@tearleads/client-sdk 0.1.75 → 0.1.77

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 (164) hide show
  1. package/data/containers/shared/mutationAcknowledgement.d.ts +38 -0
  2. package/data/{containers → persistence/container-contents}/containerBinding.js +1 -1
  3. package/data/persistence/container-contents/containerContentsPersistence.js +2 -2
  4. package/data/persistence/container-contents/containerContentsPersistence.js.map +1 -1
  5. package/data/persistence/container-contents/containerContentsPersistenceTypes.d.ts +2 -2
  6. package/data/persistence/container-contents/containerContentsPersistenceTypes.js.map +1 -1
  7. package/data/persistence/container-contents/containerDeletionPersistence.js +2 -2
  8. package/data/persistence/container-contents/containerDeletionPersistence.js.map +1 -1
  9. package/data/persistence/container-contents/containerHydrationPersistence.js +2 -2
  10. package/data/persistence/container-contents/containerHydrationPersistence.js.map +1 -1
  11. package/data/persistence/container-contents/containerMetadataMutationPersistence.js +2 -2
  12. package/data/persistence/container-contents/containerMetadataMutationPersistence.js.map +1 -1
  13. package/data/persistence/container-contents/containerMetadataRows.js +1 -1
  14. package/data/persistence/container-contents/containerMetadataRows.js.map +1 -1
  15. package/data/persistence/container-contents/containerRebindPersistence.js.map +1 -1
  16. package/data/persistence/container-contents/containerReconcilePersistence.js +2 -2
  17. package/data/persistence/container-contents/containerReconcilePersistence.js.map +1 -1
  18. package/data/persistence/container-contents/containerStructuralRepair.js +1 -1
  19. package/data/persistence/container-contents/containerStructuralRepair.js.map +1 -1
  20. package/data/persistence/container-contents/dormantMetadataSweep.js +1 -1
  21. package/data/persistence/container-contents/dormantMetadataSweep.js.map +1 -1
  22. package/data/persistence/documents/internal/containerDocumentTombstoneHolds.js +1 -1
  23. package/data/persistence/documents/internal/containerDocumentTombstoneHolds.js.map +1 -1
  24. package/data/persistence/documents/internal/containerDocumentTombstones.js +1 -1
  25. package/data/persistence/documents/internal/containerDocumentTombstones.js.map +1 -1
  26. package/data/persistence/documents/internal/discoveredDocumentPlacement.js +1 -1
  27. package/data/persistence/documents/internal/discoveredDocumentPlacement.js.map +1 -1
  28. package/data/principals/currentPolicyReferenceResolver.d.ts +3 -0
  29. package/index.d.ts +2 -2
  30. package/index.js +2 -2
  31. package/index.js.map +1 -1
  32. package/package.json +1 -1
  33. package/stores/container-contents/systemContainers/systemContainerIcon.js +1 -1
  34. package/stores/container-contents/systemContainers/systemContainerIcon.js.map +1 -1
  35. package/workflows/container-contents/container-state/create/createChild.js +1 -1
  36. package/workflows/container-contents/container-state/create/createChild.js.map +1 -1
  37. package/workflows/container-contents/container-state/purge/purgeTree.js +1 -1
  38. package/workflows/container-contents/container-state/purge/purgeTree.js.map +1 -1
  39. package/workflows/container-contents/container-state/remote.js +1 -1
  40. package/workflows/container-contents/container-state/remote.js.map +1 -1
  41. package/workflows/container-contents/container-state/share/groupGrantVerification.js +1 -1
  42. package/workflows/container-contents/container-state/share/groupGrantVerification.js.map +1 -1
  43. package/workflows/container-contents/container-state/share/groupShareEpoch.js +1 -1
  44. package/workflows/container-contents/container-state/share/groupShareEpoch.js.map +1 -1
  45. package/workflows/container-contents/container-state/types.js.map +1 -1
  46. package/workflows/container-contents/containerPersistence.d.ts +3 -3
  47. package/workflows/container-contents/containerPersistence.js +1 -1
  48. package/workflows/container-contents/containerPersistence.js.map +1 -1
  49. package/workflows/container-contents/documentLinks/documentLinkIntent.js +1 -1
  50. package/workflows/container-contents/documentLinks/documentLinkIntent.js.map +1 -1
  51. package/workflows/container-contents/documentLinks/index.js +1 -1
  52. package/workflows/container-contents/documentLinks/index.js.map +1 -1
  53. package/workflows/container-contents/documentMove/documentMoveIntent.js +1 -1
  54. package/workflows/container-contents/documentMove/documentMoveIntent.js.map +1 -1
  55. package/workflows/container-contents/documentMove/documentMoveIntentSettlement.js +2 -2
  56. package/workflows/container-contents/documentMove/documentMoveIntentSettlement.js.map +1 -1
  57. package/workflows/container-contents/documentQueries/documentSubtreeQueries.js +1 -1
  58. package/workflows/container-contents/documentQueries/documentSubtreeQueries.js.map +1 -1
  59. package/workflows/container-contents/documentQueries/index.js +3 -3
  60. package/workflows/container-contents/documentQueries/index.js.map +1 -1
  61. package/workflows/container-contents/documentQueries/pendingDownloads.js +1 -1
  62. package/workflows/container-contents/documentQueries/pendingDownloads.js.map +1 -1
  63. package/workflows/container-contents/index.d.ts +1 -1
  64. package/workflows/container-contents/index.js +1 -1
  65. package/workflows/container-contents/index.js.map +1 -1
  66. package/workflows/container-contents/info/blobInfo.js +1 -1
  67. package/workflows/container-contents/info/blobInfo.js.map +1 -1
  68. package/workflows/container-contents/info/containerInfo.js +2 -2
  69. package/workflows/container-contents/info/containerInfo.js.map +1 -1
  70. package/{data/containers → workflows/container-contents/metadata}/containerMetadataDocument.d.ts +1 -1
  71. package/{data/containers → workflows/container-contents/metadata}/containerMetadataDocument.js +2 -2
  72. package/workflows/container-contents/metadata/containerMetadataDocument.js.map +1 -0
  73. package/workflows/container-contents/metadata/metadataMutationPreparation.js +1 -1
  74. package/workflows/container-contents/metadata/metadataMutationPreparation.js.map +1 -1
  75. package/workflows/container-contents/metadata/metadataPersistence.js +1 -1
  76. package/workflows/container-contents/metadata/metadataPersistence.js.map +1 -1
  77. package/workflows/container-contents/metadata/metadataRecord.js.map +1 -1
  78. package/workflows/container-contents/metadata/metadataStateIsolation.js +1 -1
  79. package/workflows/container-contents/metadata/metadataStateIsolation.js.map +1 -1
  80. package/workflows/container-contents/metadata/metadataSyncSettlement.js +1 -1
  81. package/workflows/container-contents/metadata/metadataSyncSettlement.js.map +1 -1
  82. package/workflows/container-contents/metadata/metadataTypes.d.ts +2 -2
  83. package/workflows/container-contents/metadata/metadataTypes.js.map +1 -1
  84. package/workflows/container-contents/recovery/folderRecovery.js +1 -1
  85. package/workflows/container-contents/recovery/folderRecovery.js.map +1 -1
  86. package/workflows/container-contents/remoteHydration/destination/replacementBinding.js +1 -1
  87. package/workflows/container-contents/remoteHydration/destination/replacementBinding.js.map +1 -1
  88. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js +1 -1
  89. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js.map +1 -1
  90. package/workflows/container-contents/remoteHydration/heldContainerRebind.js +1 -1
  91. package/workflows/container-contents/remoteHydration/heldContainerRebind.js.map +1 -1
  92. package/workflows/container-contents/remoteHydration/reattachMetadata.js +1 -1
  93. package/workflows/container-contents/remoteHydration/reattachMetadata.js.map +1 -1
  94. package/workflows/container-contents/remoteHydration/remoteContainers/insertRemoteContainer.js +2 -2
  95. package/workflows/container-contents/remoteHydration/remoteContainers/insertRemoteContainer.js.map +1 -1
  96. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js +1 -1
  97. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js.map +1 -1
  98. package/workflows/container-contents/remoteHydration/types.d.ts +1 -1
  99. package/workflows/container-contents/remoteHydration/types.js.map +1 -1
  100. package/workflows/container-contents/storedContainerState.js +1 -1
  101. package/workflows/container-contents/storedContainerState.js.map +1 -1
  102. package/workflows/containers/child/mutationSubmit.d.ts +76 -0
  103. package/workflows/containers/child/rekey/carriedDescendantRekeys.d.ts +70 -0
  104. package/workflows/containers/child/share/index.d.ts +1 -38
  105. package/workflows/containers/child/share/index.js +1 -205
  106. package/workflows/containers/child/share/index.js.map +1 -1
  107. package/workflows/containers/child/share/shareAncestorRepair.d.ts +37 -0
  108. package/workflows/containers/child/share/shareProjection.d.ts +7 -0
  109. package/workflows/containers/index.d.ts +3 -2
  110. package/workflows/containers/index.js +4 -2
  111. package/workflows/containers/index.js.map +1 -1
  112. package/workflows/organizations/currentOrganizationAuthority.d.ts +21 -0
  113. package/workflows/organizations/groupMetadata/groupMetadataAccess.js +1 -1
  114. package/workflows/organizations/groupMetadata/groupMetadataAccess.js.map +1 -1
  115. package/workflows/organizations/groupMetadata/groupMetadataRuntime.d.ts +30 -0
  116. package/workflows/{containers/child/share → organizations/groupShare}/currentShareGrantMutation.js +6 -6
  117. package/workflows/organizations/groupShare/currentShareGrantMutation.js.map +1 -0
  118. package/workflows/organizations/groupShare/currentSharePrincipalPolicy.d.ts +30 -0
  119. package/workflows/{containers/child/share → organizations/groupShare}/currentSharePrincipalPolicy.js +10 -10
  120. package/workflows/organizations/groupShare/currentSharePrincipalPolicy.js.map +1 -0
  121. package/workflows/organizations/groupShare/index.d.ts +4 -0
  122. package/workflows/organizations/groupShare/index.js +7 -0
  123. package/workflows/organizations/groupShare/index.js.map +1 -0
  124. package/workflows/organizations/groupShare/runtimeCurrentGroupShare.d.ts +4 -0
  125. package/workflows/{containers/child/share → organizations/groupShare}/runtimeCurrentGroupShare.js +6 -8
  126. package/workflows/organizations/groupShare/runtimeCurrentGroupShare.js.map +1 -0
  127. package/workflows/{containers/child/share → organizations/groupShare}/sharePrincipalPolicy.d.ts +9 -9
  128. package/workflows/{containers/child/share → organizations/groupShare}/sharePrincipalPolicy.js +13 -13
  129. package/workflows/organizations/groupShare/sharePrincipalPolicy.js.map +1 -0
  130. package/workflows/organizations/groupShare/shareWithGroup.d.ts +44 -0
  131. package/workflows/organizations/groupShare/shareWithGroup.js +210 -0
  132. package/workflows/organizations/groupShare/shareWithGroup.js.map +1 -0
  133. package/workflows/organizations/index.d.ts +1 -0
  134. package/workflows/organizations/index.js +1 -0
  135. package/workflows/organizations/index.js.map +1 -1
  136. package/workflows/organizations/principalMutations/currentPrincipalMutationLease.d.ts +16 -0
  137. package/workflows/organizations/readModel/localReadModelDetails.js +1 -1
  138. package/workflows/organizations/readModel/localReadModelDetails.js.map +1 -1
  139. package/workflows/principals/runtimePolicyRecovery.d.ts +42 -0
  140. package/workflows/registration/bootstrapRootContainer.js +1 -1
  141. package/workflows/registration/bootstrapRootContainer.js.map +1 -1
  142. package/workflows/registration/provisioningBootstrapBuilders.js +1 -1
  143. package/workflows/registration/provisioningBootstrapBuilders.js.map +1 -1
  144. package/workflows/registration/rootMetadataBootstrap.js +1 -1
  145. package/workflows/registration/rootMetadataBootstrap.js.map +1 -1
  146. package/workflows/sync/remoteReset.js +1 -1
  147. package/workflows/sync/remoteReset.js.map +1 -1
  148. package/data/containers/containerMetadataDocument.js.map +0 -1
  149. package/workflows/containers/child/share/currentShareGrantMutation.js.map +0 -1
  150. package/workflows/containers/child/share/currentSharePrincipalPolicy.js.map +0 -1
  151. package/workflows/containers/child/share/runtimeCurrentGroupShare.js.map +0 -1
  152. package/workflows/containers/child/share/sharePrincipalPolicy.js.map +0 -1
  153. /package/data/{containers → persistence/container-contents}/containerBinding.d.ts +0 -0
  154. /package/data/{containers → persistence/container-contents}/containerBinding.js.map +0 -0
  155. /package/data/persistence/{containers → container-contents}/containerPersistence.d.ts +0 -0
  156. /package/data/persistence/{containers → container-contents}/containerPersistence.js +0 -0
  157. /package/data/persistence/{containers → container-contents}/containerPersistence.js.map +0 -0
  158. /package/data/persistence/{containers → container-contents}/containerSyncWatermarkPersistence.d.ts +0 -0
  159. /package/data/persistence/{containers → container-contents}/containerSyncWatermarkPersistence.js +0 -0
  160. /package/data/persistence/{containers → container-contents}/containerSyncWatermarkPersistence.js.map +0 -0
  161. /package/data/persistence/{containers → container-contents}/documentContainerProjectionPersistence.js +0 -0
  162. /package/data/persistence/{containers → container-contents}/documentContainerProjectionPersistence.js.map +0 -0
  163. /package/data/persistence/{containers → container-contents}/documentPlacement.js +0 -0
  164. /package/data/persistence/{containers → container-contents}/documentPlacement.js.map +0 -0
package/index.js CHANGED
@@ -9,9 +9,9 @@ export { createDocumentStore, discardRegisteredDocumentLocalState, getOrCreateDo
9
9
  export { Tearleads } from "./Tearleads.js";
10
10
  export { blobByteSourceInputLength, createBlobByteSource, createBlobStore, createEncryptedBlobStore, createLazyEncryptedBlobStore, createMemoryBlobStore, decryptDocumentAttachmentBlob, hydrateDocumentAttachmentBlobs, purgeOpfsBlobStore, readBlobByteSource, uploadDocumentAttachment, wrapEncryptedBlobStore, } from "./workflows/blobs/index.js";
11
11
  export { createContainerContentsDocumentsRuntime, createContainerContentsProjectionUserKeyResolver, createContainerContentsStoreWorkflowRuntime, createContainerContentsSyncLane, createContainerContentsWorkflowRuntime, createContainerParentSyncLane, createInitializedContainerMetadataDocument, defaultContainerContentsPersistence, deriveContainerSystemSlot, initializeDocumentLinksSchema, listBlobInfo, listDocumentLinkedContainerIds, loadContainerInfo, loadContainerSyncWatermark, loadDocumentAttributionRanges, loadDocumentInfo, replaceDocumentLinks, saveContainerSyncWatermark, syncedContainerDocumentObjectSyncState, } from "./workflows/container-contents/index.js";
12
- export { buildMaterializedContainerRekeyPlan, buildRootContainerCreatePlan, ContainerAuthorAccessError, ContainerKekRepairInaccessibleError, ContainerKekRepairRequiredError, ContainerKeyringOverrideStaleError, ContainerPathTooDeepError, classifyContainerWriteRefusal, containerWriterProjectionFromRekeyPlan, createRemoteContainer, fetchContainerKekLog, GroupShareNameMismatchError, HistoricalWrapUnavailableError, isProjectionVerificationCancelledError, moveRemoteContainer, rebuildKeyringEntriesFromLog, recoverKeyringEntryFromWraps, rekeyRemoteContainer, revokeRemoteContainer, rootContainerWriterProjectionFromCreatePlan, shareRemoteContainer, shareRemoteContainerWithGroup, } from "./workflows/containers/index.js";
12
+ export { buildMaterializedContainerRekeyPlan, buildRootContainerCreatePlan, ContainerAuthorAccessError, ContainerKekRepairInaccessibleError, ContainerKekRepairRequiredError, ContainerKeyringOverrideStaleError, ContainerPathTooDeepError, classifyContainerWriteRefusal, containerWriterProjectionFromRekeyPlan, createRemoteContainer, fetchContainerKekLog, HistoricalWrapUnavailableError, isProjectionVerificationCancelledError, moveRemoteContainer, rebuildKeyringEntriesFromLog, recoverKeyringEntryFromWraps, rekeyRemoteContainer, revokeRemoteContainer, rootContainerWriterProjectionFromCreatePlan, shareRemoteContainer, } from "./workflows/containers/index.js";
13
13
  export { buildMaterializedDocumentCreatePlan, createDocumentProjectionUserKeyResolver, createDocumentsWorkflowRuntime, createRemoteDocument, DOCUMENT_SYNC_TRACE_FRAGMENT, DOCUMENT_SYNC_TRACE_PATTERN, DOCUMENTS_APP_KIND, DocumentRawHistoryUnavailableError, defaultDocumentsPersistence, deletePersistedDocument, isDatabaseUnavailableError, isDocumentSyncUpdateIsolationError, persistedDocumentCreateStateFromResponse, readPullContinuation, syncRemoteDocument, unwrapContainerKekPath, unwrapDocumentContentKeyTarget, validateDocumentSyncUpdateImports, } from "./workflows/documents/index.js";
14
- export { abandonJournaledPrincipalMutation, addOrganizationGroupUser, buildInitialGroupPolicyRequest, buildInitialMemberGroupPolicyRequest, buildOrganizationGroupPolicyHistory, buildOrganizationProfileDocumentPatch, buildRosterProfileDocumentPatch, checkNativePurchaseEligibility, createInitializedRosterProfileDocument, createOrganizationGroup, DEFAULT_PERSONAL_ORGANIZATION_PROFILE_NAME, deriveOrganizationMetadataContainerSystemSlot, deriveOrganizationRosterProfileContainerSystemSlot, discardUnreadableJournaledPrincipalMutation, GroupMembershipNameMismatchError, getOrganizationProfileDocumentLocalId, getRosterProfileDocumentLocalId, importOrganizationUser, loadLocalOrganizationDataUsage, loadLocalOrganizationDirectoryAndGroups, loadOrganizationBilling, loadOrganizationBillingHistory, loadOrganizationBillingManagementUrl, ORGANIZATION_METADATA_CONTAINER_NAME, ORGANIZATION_PROFILE_DOCUMENT_KIND, ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME, PendingPrincipalMutationError, PrincipalMutationOutcomeUnknownError, ROSTER_PROFILE_DOCUMENT_KIND, readJournaledPrincipalMutation, readOrganizationProfileName, reconcileOrganizationDataUsage, reconcileOrganizationDirectoryAndGroups, recoverJournaledPrincipalMutation, removeOrganizationGroupUser, resolveOrganizationBillingView, retainAcknowledgedPrincipalCurrents, revokeOrganizationContainerGrant, startOrganizationTrial, submitJournaledPrincipalMutation, subscribeOrganizationReadModelInvalidation, UnreadablePrincipalMutationError, updateOrganizationProfile, updateOrganizationRosterEntry, } from "./workflows/organizations/index.js";
14
+ export { abandonJournaledPrincipalMutation, addOrganizationGroupUser, buildInitialGroupPolicyRequest, buildInitialMemberGroupPolicyRequest, buildOrganizationGroupPolicyHistory, buildOrganizationProfileDocumentPatch, buildRosterProfileDocumentPatch, checkNativePurchaseEligibility, createInitializedRosterProfileDocument, createOrganizationGroup, DEFAULT_PERSONAL_ORGANIZATION_PROFILE_NAME, deriveOrganizationMetadataContainerSystemSlot, deriveOrganizationRosterProfileContainerSystemSlot, discardUnreadableJournaledPrincipalMutation, GroupMembershipNameMismatchError, GroupShareNameMismatchError, getOrganizationProfileDocumentLocalId, getRosterProfileDocumentLocalId, importOrganizationUser, loadLocalOrganizationDataUsage, loadLocalOrganizationDirectoryAndGroups, loadOrganizationBilling, loadOrganizationBillingHistory, loadOrganizationBillingManagementUrl, ORGANIZATION_METADATA_CONTAINER_NAME, ORGANIZATION_PROFILE_DOCUMENT_KIND, ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME, PendingPrincipalMutationError, PrincipalMutationOutcomeUnknownError, ROSTER_PROFILE_DOCUMENT_KIND, readJournaledPrincipalMutation, readOrganizationProfileName, reconcileOrganizationDataUsage, reconcileOrganizationDirectoryAndGroups, recoverJournaledPrincipalMutation, removeOrganizationGroupUser, resolveOrganizationBillingView, retainAcknowledgedPrincipalCurrents, revokeOrganizationContainerGrant, shareRemoteContainerWithGroup, startOrganizationTrial, submitJournaledPrincipalMutation, subscribeOrganizationReadModelInvalidation, UnreadablePrincipalMutationError, updateOrganizationProfile, updateOrganizationRosterEntry, } from "./workflows/organizations/index.js";
15
15
  export { cacheReferencedPrincipalPolicies, captureAcknowledgedPrincipalPredecessor, PrincipalPolicyHistoryReadError, recoverPrincipalPolicyHistory, recoverProjectionPolicyHistory, recoverScopedPrincipalPolicyHistory, } from "./workflows/principals/index.js";
16
16
  export { bootstrapRootContainer, buildInitialOrganizationPolicyRequest, createInitialRootMetadataBootstrap, persistRegistrationBootstrap, registerIdentity, } from "./workflows/registration/index.js";
17
17
  export { listRootDataUsageReport, listRootIdentities, listRootIdentityOrganizations, listRootOrganizationIdentities, listRootOrganizations, loadRootIdentity, loadRootOrganization, loadRootOrganizationDataUsage, } from "./workflows/root/index.js";
package/index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uB,EACvB,kBAAkB,EAClB,6BAA6B,EAC7B,8BAA8B,EAC9B,qBAAqB,EACrB,gBAAgB,EAChB,oBAAoB,EACpB,6BAA6B,GAW9B,MAAM,kBAAkB,CAAC;AAe1B,OAAO,EACL,oBAAoB,EACpB,gCAAgC,EAChC,gCAAgC,EAChC,mCAAmC,EACnC,yBAAyB,EACzB,gCAAgC,EAChC,oCAAoC,GACrC,MAAM,kBAAkB,CAAC","sourcesContent":["// SDK: verified identity links, read-only pins and device-first handles.\n// Authority loaders take exact heads, including cached citations. Obsolete\n// adapters are excluded; authored policy journals survive restart. See workflows/README.md.\nexport {\n type ApiRequestCounts,\n type ApiRequestEndpointCounts,\n ApiRequestMetrics,\n type ApiRequestMetricsSnapshot,\n} from \"@tearleads/api-client\";\nexport type {\n AbandonOrganizationPolicyMutationInput,\n AddOrganizationGroupUserInput,\n BlobInfo,\n BlobInfoAttachmentKind,\n BlobInfoDocumentReference,\n BlobInfoInput,\n BlobInfoList,\n BlobInfoSort,\n BlobInfoSortDirection,\n BlobInfoSortKey,\n BrowserLocalKeyringOptions,\n ContainerContents,\n ContainerContentsContextValue,\n ContainerContentsStore,\n ContainerContentsStoreOptions,\n ContainerDocumentLinkInput,\n ContainerDocumentLinks,\n ContainerDocumentObjectSyncState,\n ContainerDocumentObjectSyncStatus,\n ContainerDocumentQueries,\n ContainerDocumentSidebarRow,\n ContainerInfo,\n ContainerInfoInput,\n ContainerItemRow,\n ContainerItemSort,\n ContainerItemSortDirection,\n ContainerItemSortKey,\n ContainerNode,\n ContainerShareAccessLevel,\n CreateOrganizationOptions,\n DatabaseListener,\n DatabaseOptions,\n DatabaseSnapshot,\n DatabaseStatus,\n DeviceFirst,\n DeviceFirstContainerContents,\n DiscardUnreadableOrganizationPolicyMutationInput,\n DocumentAttachmentStatus,\n DocumentAttachmentUpload,\n DocumentAttributionRangesInput,\n DocumentAttributionRangesPage,\n DocumentContextValue,\n DocumentInfo,\n DocumentInfoInput,\n DocumentList,\n DocumentSort,\n DocumentSortDirection,\n DocumentSortKey,\n DocumentStore,\n DocumentSubscriptionOptions,\n Documents,\n DocumentsRuntime,\n DomainScope,\n FileSaver,\n Identity,\n IdentityGenerationResult,\n IdentityKeyPackage,\n IdentityListener,\n IdentityOptions,\n IdentitySnapshot,\n ImportedOrganizationUser,\n IndexedDbLocalKeyringManifestStoreOptions,\n IndexedDbWrappingKeyKeystoreOptions,\n LinkDocumentToContainerInput,\n ListDocumentsInput,\n LocalKeyPurpose,\n LocalKeyring,\n LocalKeyringManifest,\n LocalKeyringManifestFormat,\n LocalKeyringManifestStorage,\n LocalKeyringManifestStore,\n LocalKeyringOptions,\n LocalKeyringPinCode,\n LocalKeyringScope,\n LocalKeyringSession,\n LocalOrganizationSummary,\n LocalProjectionReconciledDelta,\n LocalProjectionSnapshot,\n LocalProjectionView,\n LocalSecretContext,\n LocalStorageLocalKeyringManifestStoreOptions,\n Logger,\n MergeDocumentSummary,\n MoveDocumentToContainerInput,\n NetworkListener,\n NetworkMode,\n NetworkStatusSource,\n NormalizedLocalKeyringScope,\n OpenContainerDocumentInput,\n OpenDocumentInput,\n OpenDocumentOptions,\n OrganizationBilling,\n OrganizationBillingHistory,\n OrganizationBillingHistoryEntry,\n OrganizationBillingManagementUrl,\n OrganizationBillingView,\n OrganizationContainerGrant,\n OrganizationContainerGrants,\n OrganizationDataUsage,\n OrganizationDirectory,\n OrganizationDirectoryAndGroups,\n OrganizationDirectoryUser,\n OrganizationGrantRef,\n OrganizationGroupContainer,\n OrganizationGroupContainers,\n OrganizationGroupDetails,\n OrganizationGroupMember,\n OrganizationGroupMembers,\n OrganizationGroupMutationReceipt,\n OrganizationGroupPolicyHistory,\n OrganizationGroupSummary,\n OrganizationPolicyGrantChange,\n OrganizationPolicyGroupChange,\n /** Verified organization display page with an optional older-page cursor. */\n OrganizationPolicyHistory,\n OrganizationPolicyHistoryEntry,\n OrganizationProfile,\n Organizations,\n OrganizationUserDetail,\n PendingWriteQueueItem,\n PendingWriteQueueItemStatus,\n PendingWriteQueueObjectKind,\n PendingWriteQueueOperation,\n PendingWriteQueueOperationKind,\n PendingWriteQueueOperationStatus,\n // Persistence notifications distinguish placement changes from content saves.\n PersistedDocumentListener,\n PinCodeBrowserLocalKeyringOptions,\n PinCodeWrappingKeyKeystoreOptions,\n PurgeDocumentInput,\n PurgeDocumentResult,\n ReconciliationService,\n RemoveOrganizationGroupUserInput,\n ResolvedUserIdentity,\n SaveFileRequest,\n SecurityIncident,\n SecurityIncidentListener,\n SecurityIncidentObjectKind,\n SecurityIncidents,\n Session,\n SessionContext,\n SessionCreateOrganizationResult,\n SessionListener,\n SessionRecoverOrganizationResult,\n SessionRegistrationRefusal,\n SessionRegistrationResult,\n SessionSnapshot,\n SetActiveDocumentContainerInput,\n SetLinkedContainerIdsForDocument,\n UnlinkDocumentFromContainerInput,\n UnwrapLocalSecretInput,\n UserIdentities,\n UserSession,\n WrapLocalSecretInput,\n WrappedLocalSecretEnvelope,\n WrappedLocalSecretFormat,\n WrappingKeyHandle,\n WrappingKeyKeystore,\n WrappingKeyMaterialStorage,\n} from \"./client\";\nexport {\n type BlobStoreFactory,\n Blobs,\n createBrowserLocalKeyring,\n createBrowserLocalKeyringManifestStore,\n createBrowserNetworkStatusSource,\n createContainerDocumentObjectSyncState,\n createDomainScope,\n createIndexedDbLocalKeyringManifestStore,\n createIndexedDbWrappingKeyKeystore,\n createLocalKeyring,\n createLocalStorageLocalKeyringManifestStore,\n createMemoryLocalKeyringManifestStore,\n createMemoryWrappingKeyKeystore,\n createPinCodeBrowserLocalKeyring,\n createPinCodeWrappingKeyKeystore,\n createRevenueCatPurchases,\n createUnavailableDirectCheckout,\n createUnavailablePurchases,\n createWebViewLocalKeyring,\n Database,\n DEFAULT_DOCUMENT_ID,\n type DirectCheckoutAppearance,\n type DirectCheckoutCapability,\n type DirectCheckoutConfirmation,\n type DirectCheckoutSession,\n DirectCheckoutUnavailableError,\n decodeLocalKeyringSqliteKey,\n Events,\n type EventsListener,\n type EventsSnapshot,\n encodeLocalKeyringSqliteKey,\n enqueueReconciliationForEvents,\n IDENTITY_KEY_PACKAGE_FORMAT,\n isPinCodeWrappedLocalSecretEnvelope,\n LOCAL_KEYRING_MANIFEST_FORMAT,\n localKeyringScopeKey,\n Network,\n normalizeLocalKeyringScope,\n type PrincipalHistoryKeyProvider,\n type PrincipalHistoryKeyScope,\n PurchaseAbortedError,\n PurchaseAlreadyOwnedError,\n PurchaseCancelledError,\n PurchaseIdentityPendingError,\n PurchaseProviderStalledError,\n type PurchasesCapability,\n PurchasesUnavailableError,\n PurgedOrganizationRecoveryBillingRequiredError,\n parseLocalKeyringManifest,\n type RevenueCatBackend,\n type RevenueCatCustomerInfo,\n type RevenueCatPackage,\n type RevenueCatPurchasesConfig,\n SyncBillingGate,\n type SyncBillingGateListener,\n type SyncPurchaseResult,\n type SyncSubscriptionOption,\n serializeLocalKeyringManifest,\n WRAPPED_LOCAL_SECRET_FORMAT,\n} from \"./client\";\nexport type {\n DiscoveredDocumentInput,\n DocumentAttachment,\n DocumentClientProjectionDefinition,\n DocumentClientProjectionDeleteInput,\n DocumentClientProjectionSaveInput,\n DocumentFieldValidationIssue,\n DocumentProjection,\n DocumentProjectorDefinition,\n DocumentProjectorInput,\n DocumentProjectorRegistry,\n DocumentProjectorRegistryInput,\n DocumentRow,\n DocumentRowSummary,\n DocumentSummary,\n StoredDocumentKind,\n StoredDocumentState,\n StructuredDocumentMap,\n StructuredDocumentShape,\n StructuredDocumentText,\n ValidatedDocumentFields,\n} from \"./data/documents\";\nexport {\n addDocumentAttachments,\n createDocumentProjectorRegistry,\n createDocumentSignerDeviceId,\n DEFAULT_DOCUMENT_ACCESS_EPOCH,\n DEFAULT_DOCUMENT_KIND,\n defaultDocumentProjectorRegistry,\n deriveStoredDocumentTitle,\n ensureDocumentAttachmentStructure,\n getDocumentAttachments,\n getDocumentClientProjectionTables,\n getStoredDocumentTypeLabel,\n getUntitledDocumentTitle,\n initializeStoredDocumentKind,\n projectStoredDocumentState,\n readStoredDocumentState,\n readStringDocumentField,\n resolveOpIdAttribution,\n sameDocumentAttachments,\n summarizeDocumentContributors,\n writerByPeerId,\n writeStoredDocumentFields,\n} from \"./data/documents\";\nexport type {\n ContainerContentsSnapshot,\n ContainerContentsStoreRuntime,\n ContainerContentsStoreState,\n ContainerContentsStoreSyncAgent,\n ContainerContentsStoreSyncState,\n ContainerState,\n PurgeMoveSettlement,\n PurgeOptions,\n PurgeProgress,\n} from \"./stores/container-contents\";\nexport {\n createContainerContentsStore,\n createContainerContentsStoreState,\n createContainerContentsStoreSyncAgent,\n getOrCreateContainerContentsStore,\n isSystemContainerNode,\n requestContainerContentsDocumentPriming,\n subscribeToContainerContentsStore,\n updateContainerContentsSnapshot,\n updateContainerContentsStoreRuntime,\n} from \"./stores/container-contents\";\nexport type {\n DocumentSnapshot,\n DocumentStoreFacade,\n DocumentStoreOpenOptions,\n DocumentStoreRelinkInput,\n DocumentStructuredFieldPatch,\n} from \"./stores/documents\";\nexport {\n createDocumentStore,\n discardRegisteredDocumentLocalState,\n getOrCreateDocumentStore,\n openDocumentStore,\n requestDomainDocumentSync,\n subscribeToPersistedDocuments,\n} from \"./stores/documents\";\nexport { Tearleads } from \"./Tearleads\";\nexport type {\n TearleadsDatabaseOptions,\n TearleadsOptions,\n} from \"./TearleadsOptions\";\nexport type {\n BlobByteSource,\n BlobByteSourceInput,\n BlobBytes,\n BlobStore,\n EncryptedBlobStoreCipher,\n EncryptedBlobStoreKey,\n EncryptedBlobStoreOptions,\n WrapEncryptedBlobStoreOptions,\n} from \"./workflows/blobs\";\nexport {\n blobByteSourceInputLength,\n createBlobByteSource,\n createBlobStore,\n createEncryptedBlobStore,\n createLazyEncryptedBlobStore,\n createMemoryBlobStore,\n decryptDocumentAttachmentBlob,\n hydrateDocumentAttachmentBlobs,\n purgeOpfsBlobStore,\n readBlobByteSource,\n uploadDocumentAttachment,\n wrapEncryptedBlobStore,\n} from \"./workflows/blobs\";\nexport type {\n ContainerContentsRootAdopter,\n ContainerContentsRootAdoptionInput,\n ContainerContentsStoreWorkflowRuntime,\n ContainerContentsWorkflowRuntime,\n // Distinct from the canonical `ContainerDocumentLinkInput` (./client); the\n // documentQueries variant has a different shape, so it keeps a disambiguating\n // alias on the public surface.\n ContainerDocumentLinkInput as ContainerDocumentQueriesLinkInput,\n ContainerSystemSlotDefinition,\n PendingDownloadQueueItem,\n RecoveryFolder,\n} from \"./workflows/container-contents\";\nexport {\n createContainerContentsDocumentsRuntime,\n createContainerContentsProjectionUserKeyResolver,\n createContainerContentsStoreWorkflowRuntime,\n createContainerContentsSyncLane,\n createContainerContentsWorkflowRuntime,\n createContainerParentSyncLane,\n createInitializedContainerMetadataDocument,\n defaultContainerContentsPersistence,\n deriveContainerSystemSlot,\n initializeDocumentLinksSchema,\n listBlobInfo,\n listDocumentLinkedContainerIds,\n loadContainerInfo,\n loadContainerSyncWatermark,\n loadDocumentAttributionRanges,\n loadDocumentInfo,\n replaceDocumentLinks,\n saveContainerSyncWatermark,\n syncedContainerDocumentObjectSyncState,\n} from \"./workflows/container-contents\";\nexport type {\n AggregatedContainerKekLog,\n ContainerMutationAuthor,\n ContainerReciteApi,\n ContainerWriteRefusal,\n KeyringRebuildResult,\n MaterializedContainerRekeyPlan,\n} from \"./workflows/containers\";\nexport {\n buildMaterializedContainerRekeyPlan,\n buildRootContainerCreatePlan,\n ContainerAuthorAccessError,\n ContainerKekRepairInaccessibleError,\n ContainerKekRepairRequiredError,\n ContainerKeyringOverrideStaleError,\n ContainerPathTooDeepError,\n classifyContainerWriteRefusal,\n containerWriterProjectionFromRekeyPlan,\n createRemoteContainer,\n fetchContainerKekLog,\n GroupShareNameMismatchError,\n HistoricalWrapUnavailableError,\n type HistoricalWrapUnavailableReason,\n isProjectionVerificationCancelledError,\n moveRemoteContainer,\n rebuildKeyringEntriesFromLog,\n recoverKeyringEntryFromWraps,\n rekeyRemoteContainer,\n revokeRemoteContainer,\n rootContainerWriterProjectionFromCreatePlan,\n shareRemoteContainer,\n shareRemoteContainerWithGroup,\n} from \"./workflows/containers\";\nexport type {\n DocumentRecord,\n DocumentSyncContainerRekeyBuilder,\n DocumentSyncPullContinuation,\n DocumentSyncUpdateIsolationError,\n DocumentsPersistence,\n DocumentsWorkflowRuntime,\n DocumentsWorkflowRuntimeInput,\n IncomingDocumentSyncUpdateValidator,\n LocalAttachmentRecord,\n PendingAttachmentRecord,\n PendingUpdateInsert,\n PendingUpdateRecord,\n SyncRemoteDocumentInput,\n} from \"./workflows/documents\";\nexport {\n buildMaterializedDocumentCreatePlan,\n createDocumentProjectionUserKeyResolver,\n createDocumentsWorkflowRuntime,\n createRemoteDocument,\n DOCUMENT_SYNC_TRACE_FRAGMENT,\n DOCUMENT_SYNC_TRACE_PATTERN,\n DOCUMENTS_APP_KIND,\n DocumentRawHistoryUnavailableError,\n defaultDocumentsPersistence,\n deletePersistedDocument,\n isDatabaseUnavailableError,\n isDocumentSyncUpdateIsolationError,\n persistedDocumentCreateStateFromResponse,\n readPullContinuation,\n syncRemoteDocument,\n unwrapContainerKekPath,\n unwrapDocumentContentKeyTarget,\n validateDocumentSyncUpdateImports,\n} from \"./workflows/documents\";\n// Nominal identity constructors are available only through the testing subpath\n// for low-level runtime tests.\nexport type {\n AcknowledgedPrincipalCurrentInput,\n AcknowledgedPrincipalCurrentRetirement,\n AuthoredPrincipalMutation,\n OrganizationGroupPolicyHistoryEntry,\n OrganizationNativePurchaseEligibility,\n OrganizationPrincipalMemberChange,\n OrganizationPrincipalMemberChangeType,\n OrganizationPrincipalPolicyHistory,\n OrganizationPrincipalPolicyHistoryEntry,\n PrincipalMutationJournalContext,\n PrincipalMutationJournalScope,\n PrincipalMutationResponse,\n ReconcileOrganizationDataUsageInput,\n} from \"./workflows/organizations\";\nexport {\n abandonJournaledPrincipalMutation,\n addOrganizationGroupUser,\n buildInitialGroupPolicyRequest,\n buildInitialMemberGroupPolicyRequest,\n buildOrganizationGroupPolicyHistory,\n buildOrganizationProfileDocumentPatch,\n buildRosterProfileDocumentPatch,\n checkNativePurchaseEligibility,\n createInitializedRosterProfileDocument,\n createOrganizationGroup,\n DEFAULT_PERSONAL_ORGANIZATION_PROFILE_NAME,\n deriveOrganizationMetadataContainerSystemSlot,\n deriveOrganizationRosterProfileContainerSystemSlot,\n discardUnreadableJournaledPrincipalMutation,\n GroupMembershipNameMismatchError,\n getOrganizationProfileDocumentLocalId,\n getRosterProfileDocumentLocalId,\n importOrganizationUser,\n loadLocalOrganizationDataUsage,\n loadLocalOrganizationDirectoryAndGroups,\n loadOrganizationBilling,\n loadOrganizationBillingHistory,\n loadOrganizationBillingManagementUrl,\n ORGANIZATION_METADATA_CONTAINER_NAME,\n ORGANIZATION_PROFILE_DOCUMENT_KIND,\n ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n PendingPrincipalMutationError,\n PrincipalMutationOutcomeUnknownError,\n ROSTER_PROFILE_DOCUMENT_KIND,\n readJournaledPrincipalMutation,\n readOrganizationProfileName,\n reconcileOrganizationDataUsage,\n reconcileOrganizationDirectoryAndGroups,\n recoverJournaledPrincipalMutation,\n removeOrganizationGroupUser,\n resolveOrganizationBillingView,\n retainAcknowledgedPrincipalCurrents,\n revokeOrganizationContainerGrant,\n startOrganizationTrial,\n submitJournaledPrincipalMutation,\n subscribeOrganizationReadModelInvalidation,\n UnreadablePrincipalMutationError,\n updateOrganizationProfile,\n updateOrganizationRosterEntry,\n} from \"./workflows/organizations\";\nexport type {\n AcknowledgedPrincipalPredecessor,\n CacheReferencedPrincipalPoliciesOptions,\n PrincipalHistoryProtectionLease,\n ProjectionPolicyHistoryRecoveryOptions,\n RecoveredPrincipalPolicyHistory,\n RecoveredScopedPrincipalPolicyHistory,\n RecoverPrincipalPolicyHistoryOptions,\n RecoverScopedPrincipalPolicyHistoryOptions,\n} from \"./workflows/principals\";\nexport {\n cacheReferencedPrincipalPolicies,\n captureAcknowledgedPrincipalPredecessor,\n PrincipalPolicyHistoryReadError,\n recoverPrincipalPolicyHistory,\n recoverProjectionPolicyHistory,\n recoverScopedPrincipalPolicyHistory,\n} from \"./workflows/principals\";\nexport type {\n InitialRootMetadataBootstrap,\n ProvisionedSystemContainerSpec,\n RegisterIdentityInput,\n RegistrationApi,\n} from \"./workflows/registration\";\nexport {\n bootstrapRootContainer,\n buildInitialOrganizationPolicyRequest,\n createInitialRootMetadataBootstrap,\n persistRegistrationBootstrap,\n registerIdentity,\n} from \"./workflows/registration\";\nexport type {\n RootIdentitiesApi,\n RootIdentitiesPage,\n RootIdentitiesQueryInput,\n RootIdentity,\n RootIdentityDetail,\n RootIdentityOrganization,\n RootIdentitySession,\n RootRequestOutcome,\n} from \"./workflows/root\";\nexport {\n listRootDataUsageReport,\n listRootIdentities,\n listRootIdentityOrganizations,\n listRootOrganizationIdentities,\n listRootOrganizations,\n loadRootIdentity,\n loadRootOrganization,\n loadRootOrganizationDataUsage,\n type RootDataUsageApi,\n type RootDataUsageReportPage,\n type RootOrganization,\n type RootOrganizationDetail,\n type RootOrganizationIdentitiesPage,\n type RootOrganizationIdentity,\n type RootOrganizationPageQueryInput,\n type RootOrganizationsApi,\n type RootOrganizationsPage,\n type RootOrganizationsQueryInput,\n} from \"./workflows/root\";\nexport type {\n ClearRemoteSyncStateResult,\n DomainSyncCoordinator,\n DomainSyncSnapshot,\n RemoteResetInput,\n RemoteResetReplacement,\n SyncIdleOptions,\n SyncLane,\n SyncLaneConfig,\n SyncLaneLastAction,\n SyncLanePhase,\n SyncLaneSnapshot,\n SyncLaneStatus,\n} from \"./workflows/sync\";\nexport {\n clearRemoteSyncState,\n getDomainSyncCoordinatorSnapshot,\n getOrCreateDomainSyncCoordinator,\n hasDomainSyncCoordinatorPendingWork,\n requestAllDomainSyncLanes,\n subscribeToDomainSyncCoordinator,\n waitForDomainSyncCoordinatorToSettle,\n} from \"./workflows/sync\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,2EAA2E;AAC3E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M,kBAAkB,CAAC;AAe1B,OAAO,EACL,oBAAoB,EACpB,gCAAgC,EAChC,gCAAgC,EAChC,mCAAmC,EACnC,yBAAyB,EACzB,gCAAgC,EAChC,oCAAoC,GACrC,MAAM,kBAAkB,CAAC","sourcesContent":["// SDK: verified identity links, read-only pins and device-first handles.\n// Authority loaders take exact heads, including cached citations. Obsolete\n// adapters are excluded; authored policy journals survive restart. See workflows/README.md.\nexport {\n type ApiRequestCounts,\n type ApiRequestEndpointCounts,\n ApiRequestMetrics,\n type ApiRequestMetricsSnapshot,\n} from \"@tearleads/api-client\";\nexport type {\n AbandonOrganizationPolicyMutationInput,\n AddOrganizationGroupUserInput,\n BlobInfo,\n BlobInfoAttachmentKind,\n BlobInfoDocumentReference,\n BlobInfoInput,\n BlobInfoList,\n BlobInfoSort,\n BlobInfoSortDirection,\n BlobInfoSortKey,\n BrowserLocalKeyringOptions,\n ContainerContents,\n ContainerContentsContextValue,\n ContainerContentsStore,\n ContainerContentsStoreOptions,\n ContainerDocumentLinkInput,\n ContainerDocumentLinks,\n ContainerDocumentObjectSyncState,\n ContainerDocumentObjectSyncStatus,\n ContainerDocumentQueries,\n ContainerDocumentSidebarRow,\n ContainerInfo,\n ContainerInfoInput,\n ContainerItemRow,\n ContainerItemSort,\n ContainerItemSortDirection,\n ContainerItemSortKey,\n ContainerNode,\n ContainerShareAccessLevel,\n CreateOrganizationOptions,\n DatabaseListener,\n DatabaseOptions,\n DatabaseSnapshot,\n DatabaseStatus,\n DeviceFirst,\n DeviceFirstContainerContents,\n DiscardUnreadableOrganizationPolicyMutationInput,\n DocumentAttachmentStatus,\n DocumentAttachmentUpload,\n DocumentAttributionRangesInput,\n DocumentAttributionRangesPage,\n DocumentContextValue,\n DocumentInfo,\n DocumentInfoInput,\n DocumentList,\n DocumentSort,\n DocumentSortDirection,\n DocumentSortKey,\n DocumentStore,\n DocumentSubscriptionOptions,\n Documents,\n DocumentsRuntime,\n DomainScope,\n FileSaver,\n Identity,\n IdentityGenerationResult,\n IdentityKeyPackage,\n IdentityListener,\n IdentityOptions,\n IdentitySnapshot,\n ImportedOrganizationUser,\n IndexedDbLocalKeyringManifestStoreOptions,\n IndexedDbWrappingKeyKeystoreOptions,\n LinkDocumentToContainerInput,\n ListDocumentsInput,\n LocalKeyPurpose,\n LocalKeyring,\n LocalKeyringManifest,\n LocalKeyringManifestFormat,\n LocalKeyringManifestStorage,\n LocalKeyringManifestStore,\n LocalKeyringOptions,\n LocalKeyringPinCode,\n LocalKeyringScope,\n LocalKeyringSession,\n LocalOrganizationSummary,\n LocalProjectionReconciledDelta,\n LocalProjectionSnapshot,\n LocalProjectionView,\n LocalSecretContext,\n LocalStorageLocalKeyringManifestStoreOptions,\n Logger,\n MergeDocumentSummary,\n MoveDocumentToContainerInput,\n NetworkListener,\n NetworkMode,\n NetworkStatusSource,\n NormalizedLocalKeyringScope,\n OpenContainerDocumentInput,\n OpenDocumentInput,\n OpenDocumentOptions,\n OrganizationBilling,\n OrganizationBillingHistory,\n OrganizationBillingHistoryEntry,\n OrganizationBillingManagementUrl,\n OrganizationBillingView,\n OrganizationContainerGrant,\n OrganizationContainerGrants,\n OrganizationDataUsage,\n OrganizationDirectory,\n OrganizationDirectoryAndGroups,\n OrganizationDirectoryUser,\n OrganizationGrantRef,\n OrganizationGroupContainer,\n OrganizationGroupContainers,\n OrganizationGroupDetails,\n OrganizationGroupMember,\n OrganizationGroupMembers,\n OrganizationGroupMutationReceipt,\n OrganizationGroupPolicyHistory,\n OrganizationGroupSummary,\n OrganizationPolicyGrantChange,\n OrganizationPolicyGroupChange,\n /** Verified organization display page with an optional older-page cursor. */\n OrganizationPolicyHistory,\n OrganizationPolicyHistoryEntry,\n OrganizationProfile,\n Organizations,\n OrganizationUserDetail,\n PendingWriteQueueItem,\n PendingWriteQueueItemStatus,\n PendingWriteQueueObjectKind,\n PendingWriteQueueOperation,\n PendingWriteQueueOperationKind,\n PendingWriteQueueOperationStatus,\n // Persistence notifications distinguish placement changes from content saves.\n PersistedDocumentListener,\n PinCodeBrowserLocalKeyringOptions,\n PinCodeWrappingKeyKeystoreOptions,\n PurgeDocumentInput,\n PurgeDocumentResult,\n ReconciliationService,\n RemoveOrganizationGroupUserInput,\n ResolvedUserIdentity,\n SaveFileRequest,\n SecurityIncident,\n SecurityIncidentListener,\n SecurityIncidentObjectKind,\n SecurityIncidents,\n Session,\n SessionContext,\n SessionCreateOrganizationResult,\n SessionListener,\n SessionRecoverOrganizationResult,\n SessionRegistrationRefusal,\n SessionRegistrationResult,\n SessionSnapshot,\n SetActiveDocumentContainerInput,\n SetLinkedContainerIdsForDocument,\n UnlinkDocumentFromContainerInput,\n UnwrapLocalSecretInput,\n UserIdentities,\n UserSession,\n WrapLocalSecretInput,\n WrappedLocalSecretEnvelope,\n WrappedLocalSecretFormat,\n WrappingKeyHandle,\n WrappingKeyKeystore,\n WrappingKeyMaterialStorage,\n} from \"./client\";\nexport {\n type BlobStoreFactory,\n Blobs,\n createBrowserLocalKeyring,\n createBrowserLocalKeyringManifestStore,\n createBrowserNetworkStatusSource,\n createContainerDocumentObjectSyncState,\n createDomainScope,\n createIndexedDbLocalKeyringManifestStore,\n createIndexedDbWrappingKeyKeystore,\n createLocalKeyring,\n createLocalStorageLocalKeyringManifestStore,\n createMemoryLocalKeyringManifestStore,\n createMemoryWrappingKeyKeystore,\n createPinCodeBrowserLocalKeyring,\n createPinCodeWrappingKeyKeystore,\n createRevenueCatPurchases,\n createUnavailableDirectCheckout,\n createUnavailablePurchases,\n createWebViewLocalKeyring,\n Database,\n DEFAULT_DOCUMENT_ID,\n type DirectCheckoutAppearance,\n type DirectCheckoutCapability,\n type DirectCheckoutConfirmation,\n type DirectCheckoutSession,\n DirectCheckoutUnavailableError,\n decodeLocalKeyringSqliteKey,\n Events,\n type EventsListener,\n type EventsSnapshot,\n encodeLocalKeyringSqliteKey,\n enqueueReconciliationForEvents,\n IDENTITY_KEY_PACKAGE_FORMAT,\n isPinCodeWrappedLocalSecretEnvelope,\n LOCAL_KEYRING_MANIFEST_FORMAT,\n localKeyringScopeKey,\n Network,\n normalizeLocalKeyringScope,\n type PrincipalHistoryKeyProvider,\n type PrincipalHistoryKeyScope,\n PurchaseAbortedError,\n PurchaseAlreadyOwnedError,\n PurchaseCancelledError,\n PurchaseIdentityPendingError,\n PurchaseProviderStalledError,\n type PurchasesCapability,\n PurchasesUnavailableError,\n PurgedOrganizationRecoveryBillingRequiredError,\n parseLocalKeyringManifest,\n type RevenueCatBackend,\n type RevenueCatCustomerInfo,\n type RevenueCatPackage,\n type RevenueCatPurchasesConfig,\n SyncBillingGate,\n type SyncBillingGateListener,\n type SyncPurchaseResult,\n type SyncSubscriptionOption,\n serializeLocalKeyringManifest,\n WRAPPED_LOCAL_SECRET_FORMAT,\n} from \"./client\";\nexport type {\n DiscoveredDocumentInput,\n DocumentAttachment,\n DocumentClientProjectionDefinition,\n DocumentClientProjectionDeleteInput,\n DocumentClientProjectionSaveInput,\n DocumentFieldValidationIssue,\n DocumentProjection,\n DocumentProjectorDefinition,\n DocumentProjectorInput,\n DocumentProjectorRegistry,\n DocumentProjectorRegistryInput,\n DocumentRow,\n DocumentRowSummary,\n DocumentSummary,\n StoredDocumentKind,\n StoredDocumentState,\n StructuredDocumentMap,\n StructuredDocumentShape,\n StructuredDocumentText,\n ValidatedDocumentFields,\n} from \"./data/documents\";\nexport {\n addDocumentAttachments,\n createDocumentProjectorRegistry,\n createDocumentSignerDeviceId,\n DEFAULT_DOCUMENT_ACCESS_EPOCH,\n DEFAULT_DOCUMENT_KIND,\n defaultDocumentProjectorRegistry,\n deriveStoredDocumentTitle,\n ensureDocumentAttachmentStructure,\n getDocumentAttachments,\n getDocumentClientProjectionTables,\n getStoredDocumentTypeLabel,\n getUntitledDocumentTitle,\n initializeStoredDocumentKind,\n projectStoredDocumentState,\n readStoredDocumentState,\n readStringDocumentField,\n resolveOpIdAttribution,\n sameDocumentAttachments,\n summarizeDocumentContributors,\n writerByPeerId,\n writeStoredDocumentFields,\n} from \"./data/documents\";\nexport type {\n ContainerContentsSnapshot,\n ContainerContentsStoreRuntime,\n ContainerContentsStoreState,\n ContainerContentsStoreSyncAgent,\n ContainerContentsStoreSyncState,\n ContainerState,\n PurgeMoveSettlement,\n PurgeOptions,\n PurgeProgress,\n} from \"./stores/container-contents\";\nexport {\n createContainerContentsStore,\n createContainerContentsStoreState,\n createContainerContentsStoreSyncAgent,\n getOrCreateContainerContentsStore,\n isSystemContainerNode,\n requestContainerContentsDocumentPriming,\n subscribeToContainerContentsStore,\n updateContainerContentsSnapshot,\n updateContainerContentsStoreRuntime,\n} from \"./stores/container-contents\";\nexport type {\n DocumentSnapshot,\n DocumentStoreFacade,\n DocumentStoreOpenOptions,\n DocumentStoreRelinkInput,\n DocumentStructuredFieldPatch,\n} from \"./stores/documents\";\nexport {\n createDocumentStore,\n discardRegisteredDocumentLocalState,\n getOrCreateDocumentStore,\n openDocumentStore,\n requestDomainDocumentSync,\n subscribeToPersistedDocuments,\n} from \"./stores/documents\";\nexport { Tearleads } from \"./Tearleads\";\nexport type {\n TearleadsDatabaseOptions,\n TearleadsOptions,\n} from \"./TearleadsOptions\";\nexport type {\n BlobByteSource,\n BlobByteSourceInput,\n BlobBytes,\n BlobStore,\n EncryptedBlobStoreCipher,\n EncryptedBlobStoreKey,\n EncryptedBlobStoreOptions,\n WrapEncryptedBlobStoreOptions,\n} from \"./workflows/blobs\";\nexport {\n blobByteSourceInputLength,\n createBlobByteSource,\n createBlobStore,\n createEncryptedBlobStore,\n createLazyEncryptedBlobStore,\n createMemoryBlobStore,\n decryptDocumentAttachmentBlob,\n hydrateDocumentAttachmentBlobs,\n purgeOpfsBlobStore,\n readBlobByteSource,\n uploadDocumentAttachment,\n wrapEncryptedBlobStore,\n} from \"./workflows/blobs\";\nexport type {\n ContainerContentsRootAdopter,\n ContainerContentsRootAdoptionInput,\n ContainerContentsStoreWorkflowRuntime,\n ContainerContentsWorkflowRuntime,\n // Distinct from the canonical `ContainerDocumentLinkInput` (./client); the\n // documentQueries variant has a different shape, so it keeps a disambiguating\n // alias on the public surface.\n ContainerDocumentLinkInput as ContainerDocumentQueriesLinkInput,\n ContainerSystemSlotDefinition,\n PendingDownloadQueueItem,\n RecoveryFolder,\n} from \"./workflows/container-contents\";\nexport {\n createContainerContentsDocumentsRuntime,\n createContainerContentsProjectionUserKeyResolver,\n createContainerContentsStoreWorkflowRuntime,\n createContainerContentsSyncLane,\n createContainerContentsWorkflowRuntime,\n createContainerParentSyncLane,\n createInitializedContainerMetadataDocument,\n defaultContainerContentsPersistence,\n deriveContainerSystemSlot,\n initializeDocumentLinksSchema,\n listBlobInfo,\n listDocumentLinkedContainerIds,\n loadContainerInfo,\n loadContainerSyncWatermark,\n loadDocumentAttributionRanges,\n loadDocumentInfo,\n replaceDocumentLinks,\n saveContainerSyncWatermark,\n syncedContainerDocumentObjectSyncState,\n} from \"./workflows/container-contents\";\nexport type {\n AggregatedContainerKekLog,\n ContainerMutationAuthor,\n ContainerReciteApi,\n ContainerWriteRefusal,\n KeyringRebuildResult,\n MaterializedContainerRekeyPlan,\n} from \"./workflows/containers\";\nexport {\n buildMaterializedContainerRekeyPlan,\n buildRootContainerCreatePlan,\n ContainerAuthorAccessError,\n ContainerKekRepairInaccessibleError,\n ContainerKekRepairRequiredError,\n ContainerKeyringOverrideStaleError,\n ContainerPathTooDeepError,\n classifyContainerWriteRefusal,\n containerWriterProjectionFromRekeyPlan,\n createRemoteContainer,\n fetchContainerKekLog,\n HistoricalWrapUnavailableError,\n type HistoricalWrapUnavailableReason,\n isProjectionVerificationCancelledError,\n moveRemoteContainer,\n rebuildKeyringEntriesFromLog,\n recoverKeyringEntryFromWraps,\n rekeyRemoteContainer,\n revokeRemoteContainer,\n rootContainerWriterProjectionFromCreatePlan,\n shareRemoteContainer,\n} from \"./workflows/containers\";\nexport type {\n DocumentRecord,\n DocumentSyncContainerRekeyBuilder,\n DocumentSyncPullContinuation,\n DocumentSyncUpdateIsolationError,\n DocumentsPersistence,\n DocumentsWorkflowRuntime,\n DocumentsWorkflowRuntimeInput,\n IncomingDocumentSyncUpdateValidator,\n LocalAttachmentRecord,\n PendingAttachmentRecord,\n PendingUpdateInsert,\n PendingUpdateRecord,\n SyncRemoteDocumentInput,\n} from \"./workflows/documents\";\nexport {\n buildMaterializedDocumentCreatePlan,\n createDocumentProjectionUserKeyResolver,\n createDocumentsWorkflowRuntime,\n createRemoteDocument,\n DOCUMENT_SYNC_TRACE_FRAGMENT,\n DOCUMENT_SYNC_TRACE_PATTERN,\n DOCUMENTS_APP_KIND,\n DocumentRawHistoryUnavailableError,\n defaultDocumentsPersistence,\n deletePersistedDocument,\n isDatabaseUnavailableError,\n isDocumentSyncUpdateIsolationError,\n persistedDocumentCreateStateFromResponse,\n readPullContinuation,\n syncRemoteDocument,\n unwrapContainerKekPath,\n unwrapDocumentContentKeyTarget,\n validateDocumentSyncUpdateImports,\n} from \"./workflows/documents\";\n// Nominal identity constructors are available only through the testing subpath\n// for low-level runtime tests.\nexport type {\n AcknowledgedPrincipalCurrentInput,\n AcknowledgedPrincipalCurrentRetirement,\n AuthoredPrincipalMutation,\n OrganizationGroupPolicyHistoryEntry,\n OrganizationNativePurchaseEligibility,\n OrganizationPrincipalMemberChange,\n OrganizationPrincipalMemberChangeType,\n OrganizationPrincipalPolicyHistory,\n OrganizationPrincipalPolicyHistoryEntry,\n PrincipalMutationJournalContext,\n PrincipalMutationJournalScope,\n PrincipalMutationResponse,\n ReconcileOrganizationDataUsageInput,\n} from \"./workflows/organizations\";\nexport {\n abandonJournaledPrincipalMutation,\n addOrganizationGroupUser,\n buildInitialGroupPolicyRequest,\n buildInitialMemberGroupPolicyRequest,\n buildOrganizationGroupPolicyHistory,\n buildOrganizationProfileDocumentPatch,\n buildRosterProfileDocumentPatch,\n checkNativePurchaseEligibility,\n createInitializedRosterProfileDocument,\n createOrganizationGroup,\n DEFAULT_PERSONAL_ORGANIZATION_PROFILE_NAME,\n deriveOrganizationMetadataContainerSystemSlot,\n deriveOrganizationRosterProfileContainerSystemSlot,\n discardUnreadableJournaledPrincipalMutation,\n GroupMembershipNameMismatchError,\n GroupShareNameMismatchError,\n getOrganizationProfileDocumentLocalId,\n getRosterProfileDocumentLocalId,\n importOrganizationUser,\n loadLocalOrganizationDataUsage,\n loadLocalOrganizationDirectoryAndGroups,\n loadOrganizationBilling,\n loadOrganizationBillingHistory,\n loadOrganizationBillingManagementUrl,\n ORGANIZATION_METADATA_CONTAINER_NAME,\n ORGANIZATION_PROFILE_DOCUMENT_KIND,\n ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n PendingPrincipalMutationError,\n PrincipalMutationOutcomeUnknownError,\n ROSTER_PROFILE_DOCUMENT_KIND,\n readJournaledPrincipalMutation,\n readOrganizationProfileName,\n reconcileOrganizationDataUsage,\n reconcileOrganizationDirectoryAndGroups,\n recoverJournaledPrincipalMutation,\n removeOrganizationGroupUser,\n resolveOrganizationBillingView,\n retainAcknowledgedPrincipalCurrents,\n revokeOrganizationContainerGrant,\n shareRemoteContainerWithGroup,\n startOrganizationTrial,\n submitJournaledPrincipalMutation,\n subscribeOrganizationReadModelInvalidation,\n UnreadablePrincipalMutationError,\n updateOrganizationProfile,\n updateOrganizationRosterEntry,\n} from \"./workflows/organizations\";\nexport type {\n AcknowledgedPrincipalPredecessor,\n CacheReferencedPrincipalPoliciesOptions,\n PrincipalHistoryProtectionLease,\n ProjectionPolicyHistoryRecoveryOptions,\n RecoveredPrincipalPolicyHistory,\n RecoveredScopedPrincipalPolicyHistory,\n RecoverPrincipalPolicyHistoryOptions,\n RecoverScopedPrincipalPolicyHistoryOptions,\n} from \"./workflows/principals\";\nexport {\n cacheReferencedPrincipalPolicies,\n captureAcknowledgedPrincipalPredecessor,\n PrincipalPolicyHistoryReadError,\n recoverPrincipalPolicyHistory,\n recoverProjectionPolicyHistory,\n recoverScopedPrincipalPolicyHistory,\n} from \"./workflows/principals\";\nexport type {\n InitialRootMetadataBootstrap,\n ProvisionedSystemContainerSpec,\n RegisterIdentityInput,\n RegistrationApi,\n} from \"./workflows/registration\";\nexport {\n bootstrapRootContainer,\n buildInitialOrganizationPolicyRequest,\n createInitialRootMetadataBootstrap,\n persistRegistrationBootstrap,\n registerIdentity,\n} from \"./workflows/registration\";\nexport type {\n RootIdentitiesApi,\n RootIdentitiesPage,\n RootIdentitiesQueryInput,\n RootIdentity,\n RootIdentityDetail,\n RootIdentityOrganization,\n RootIdentitySession,\n RootRequestOutcome,\n} from \"./workflows/root\";\nexport {\n listRootDataUsageReport,\n listRootIdentities,\n listRootIdentityOrganizations,\n listRootOrganizationIdentities,\n listRootOrganizations,\n loadRootIdentity,\n loadRootOrganization,\n loadRootOrganizationDataUsage,\n type RootDataUsageApi,\n type RootDataUsageReportPage,\n type RootOrganization,\n type RootOrganizationDetail,\n type RootOrganizationIdentitiesPage,\n type RootOrganizationIdentity,\n type RootOrganizationPageQueryInput,\n type RootOrganizationsApi,\n type RootOrganizationsPage,\n type RootOrganizationsQueryInput,\n} from \"./workflows/root\";\nexport type {\n ClearRemoteSyncStateResult,\n DomainSyncCoordinator,\n DomainSyncSnapshot,\n RemoteResetInput,\n RemoteResetReplacement,\n SyncIdleOptions,\n SyncLane,\n SyncLaneConfig,\n SyncLaneLastAction,\n SyncLanePhase,\n SyncLaneSnapshot,\n SyncLaneStatus,\n} from \"./workflows/sync\";\nexport {\n clearRemoteSyncState,\n getDomainSyncCoordinatorSnapshot,\n getOrCreateDomainSyncCoordinator,\n hasDomainSyncCoordinatorPendingWork,\n requestAllDomainSyncLanes,\n subscribeToDomainSyncCoordinator,\n waitForDomainSyncCoordinatorToSettle,\n} from \"./workflows/sync\";\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tearleads/client-sdk",
3
- "version": "0.1.75",
3
+ "version": "0.1.77",
4
4
  "description": "React-free Tearleads client runtime: local SQLite persistence, keys, sync, encrypted blobs, and domain workflows.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -1,5 +1,5 @@
1
1
  import { encodeVersionVector, exportUpdatesSince } from "../../../internal/loro/index.js";
2
- import { getDefaultContainerName, readContainerMetadataValue, writeContainerMetadataValue, } from "../../../data/containers/containerMetadataDocument.js";
2
+ import { getDefaultContainerName, readContainerMetadataValue, writeContainerMetadataValue, } from "../../../workflows/container-contents/metadata/containerMetadataDocument.js";
3
3
  import { createDetachedContainerMetadataState, installDetachedContainerMetadataState, } from "../../../workflows/container-contents/metadata/metadataStateIsolation.js";
4
4
  import { removeMissingContainerState } from "../containerState/missingContainerState.js";
5
5
  import { updateContainerContentsSnapshot } from "../state.js";
@@ -1 +1 @@
1
- {"version":3,"file":"systemContainerIcon.js","sourceRoot":"","sources":["systemContainerIcon.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAC1E,OAAO,EACL,uBAAuB,EACvB,0BAA0B,EAC1B,2BAA2B,GAC5B,MAAM,oDAAoD,CAAC;AAC5D,OAAO,EACL,oCAAoC,EACpC,qCAAqC,GACtC,MAAM,uEAAuE,CAAC;AAE/E,OAAO,EAAE,2BAA2B,EAAE,MAAM,yCAAyC,CAAC;AAEtF,OAAO,EAAE,+BAA+B,EAAE,MAAM,UAAU,CAAC;AAa3D,SAAS,4BAA4B,CACnC,IAA+B;IAE/B,OAAO,IAAI,EAAE,IAAI,EAAE,IAAI,IAAI,CAAC;AAC9B,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAAC,KAO9C;IACC,MAAM,SAAS,GAAG,KAAK,CAAC,SAAS,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,CAAC;IAClD,MAAM,IAAI,GAAG,4BAA4B,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACtD,MAAM,WAAW,GAAG,KAAK,CAAC,cAAc,CAAC,SAAS,CAAC,IAAI,IAAI,IAAI,CAAC;IAChE,IAAI,WAAW,KAAK,IAAI,EAAE,CAAC;QACz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AAC;AACd,CAAC","sourcesContent":["import { encodeVersionVector, exportUpdatesSince } from \"@tearleads/loro\";\nimport {\n getDefaultContainerName,\n readContainerMetadataValue,\n writeContainerMetadataValue,\n} from \"../../../data/containers/containerMetadataDocument\";\nimport {\n createDetachedContainerMetadataState,\n installDetachedContainerMetadataState,\n} from \"../../../workflows/container-contents/metadata/metadataStateIsolation\";\nimport type { PersistContainerStateResult } from \"../../../workflows/container-contents/remoteHydration\";\nimport { removeMissingContainerState } from \"../containerState/missingContainerState\";\nimport type { ContainerWriteGuard } from \"../remoteWrites/writeGeneration\";\nimport { updateContainerContentsSnapshot } from \"../state\";\nimport type {\n ContainerContentsStoreSyncAgent,\n ContainerState,\n} from \"../syncAgent\";\nimport type { ContainerContentsStoreState } from \"../types\";\n\ntype PersistSystemContainerIcon = (\n containerState: ContainerState,\n icon: string | null,\n update: Uint8Array,\n) => Promise<PersistContainerStateResult[\"status\"]>;\n\nfunction normalizeSystemContainerIcon(\n icon: string | null | undefined,\n): string | null {\n return icon?.trim() || null;\n}\n\nexport async function applySystemContainerIcon(input: {\n readonly containerState: ContainerState;\n readonly icon: string | null | undefined;\n readonly persistIcon: PersistSystemContainerIcon;\n readonly state: ContainerContentsStoreState;\n readonly syncAgent: ContainerContentsStoreSyncAgent;\n readonly isCurrent?: ContainerWriteGuard | undefined;\n}): Promise<boolean> {\n const isCurrent = input.isCurrent ?? (() => true);\n const icon = normalizeSystemContainerIcon(input.icon);\n const currentIcon = input.containerState.container.icon ?? null;\n if (currentIcon === icon) {\n return true;\n }\n\n if (!isCurrent()) return false;\n const persistenceCandidate = await createDetachedContainerMetadataState(\n input.containerState,\n );\n if (!isCurrent()) return false;\n const metadata = readContainerMetadataValue(\n persistenceCandidate.doc,\n getDefaultContainerName(persistenceCandidate.container.parentId),\n );\n const sourceVersionVector = encodeVersionVector(persistenceCandidate.doc);\n writeContainerMetadataValue(persistenceCandidate.doc, {\n ...metadata,\n icon,\n });\n const update = exportUpdatesSince(\n persistenceCandidate.doc,\n sourceVersionVector,\n );\n const persistenceStatus = await input.persistIcon(\n persistenceCandidate,\n icon,\n update,\n );\n if (persistenceStatus === \"missing\") {\n removeMissingContainerState(input.state, input.containerState);\n }\n if (persistenceStatus !== \"persisted\" || !isCurrent()) {\n return false;\n }\n installDetachedContainerMetadataState(\n input.containerState,\n persistenceCandidate,\n { preserveConcurrentMetadataEdit: true },\n );\n updateContainerContentsSnapshot(input.state);\n if (input.containerState.record.documentId) {\n input.syncAgent.scheduleSync();\n }\n return true;\n}\n"]}
1
+ {"version":3,"file":"systemContainerIcon.js","sourceRoot":"","sources":["systemContainerIcon.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAC1E,OAAO,EACL,uBAAuB,EACvB,0BAA0B,EAC1B,2BAA2B,GAC5B,MAAM,0EAA0E,CAAC;AAClF,OAAO,EACL,oCAAoC,EACpC,qCAAqC,GACtC,MAAM,uEAAuE,CAAC;AAE/E,OAAO,EAAE,2BAA2B,EAAE,MAAM,yCAAyC,CAAC;AAEtF,OAAO,EAAE,+BAA+B,EAAE,MAAM,UAAU,CAAC;AAa3D,SAAS,4BAA4B,CACnC,IAA+B;IAE/B,OAAO,IAAI,EAAE,IAAI,EAAE,IAAI,IAAI,CAAC;AAC9B,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAAC,KAO9C;IACC,MAAM,SAAS,GAAG,KAAK,CAAC,SAAS,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,CAAC;IAClD,MAAM,IAAI,GAAG,4BAA4B,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACtD,MAAM,WAAW,GAAG,KAAK,CAAC,cAAc,CAAC,SAAS,CAAC,IAAI,IAAI,IAAI,CAAC;IAChE,IAAI,WAAW,KAAK,IAAI,EAAE,CAAC;QACzB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,IAAI,CAAC,SAAS,EAAE;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/loro\";\nimport {\n getDefaultContainerName,\n readContainerMetadataValue,\n writeContainerMetadataValue,\n} from \"../../../workflows/container-contents/metadata/containerMetadataDocument\";\nimport {\n createDetachedContainerMetadataState,\n installDetachedContainerMetadataState,\n} from \"../../../workflows/container-contents/metadata/metadataStateIsolation\";\nimport type { PersistContainerStateResult } from \"../../../workflows/container-contents/remoteHydration\";\nimport { removeMissingContainerState } from \"../containerState/missingContainerState\";\nimport type { ContainerWriteGuard } from \"../remoteWrites/writeGeneration\";\nimport { updateContainerContentsSnapshot } from \"../state\";\nimport type {\n ContainerContentsStoreSyncAgent,\n ContainerState,\n} from \"../syncAgent\";\nimport type { ContainerContentsStoreState } from \"../types\";\n\ntype PersistSystemContainerIcon = (\n containerState: ContainerState,\n icon: string | null,\n update: Uint8Array,\n) => Promise<PersistContainerStateResult[\"status\"]>;\n\nfunction normalizeSystemContainerIcon(\n icon: string | null | undefined,\n): string | null {\n return icon?.trim() || null;\n}\n\nexport async function applySystemContainerIcon(input: {\n readonly containerState: ContainerState;\n readonly icon: string | null | undefined;\n readonly persistIcon: PersistSystemContainerIcon;\n readonly state: ContainerContentsStoreState;\n readonly syncAgent: ContainerContentsStoreSyncAgent;\n readonly isCurrent?: ContainerWriteGuard | undefined;\n}): Promise<boolean> {\n const isCurrent = input.isCurrent ?? (() => true);\n const icon = normalizeSystemContainerIcon(input.icon);\n const currentIcon = input.containerState.container.icon ?? null;\n if (currentIcon === icon) {\n return true;\n }\n\n if (!isCurrent()) return false;\n const persistenceCandidate = await createDetachedContainerMetadataState(\n input.containerState,\n );\n if (!isCurrent()) return false;\n const metadata = readContainerMetadataValue(\n persistenceCandidate.doc,\n getDefaultContainerName(persistenceCandidate.container.parentId),\n );\n const sourceVersionVector = encodeVersionVector(persistenceCandidate.doc);\n writeContainerMetadataValue(persistenceCandidate.doc, {\n ...metadata,\n icon,\n });\n const update = exportUpdatesSince(\n persistenceCandidate.doc,\n sourceVersionVector,\n );\n const persistenceStatus = await input.persistIcon(\n persistenceCandidate,\n icon,\n update,\n );\n if (persistenceStatus === \"missing\") {\n removeMissingContainerState(input.state, input.containerState);\n }\n if (persistenceStatus !== \"persisted\" || !isCurrent()) {\n return false;\n }\n installDetachedContainerMetadataState(\n input.containerState,\n persistenceCandidate,\n { preserveConcurrentMetadataEdit: true },\n );\n updateContainerContentsSnapshot(input.state);\n if (input.containerState.record.documentId) {\n input.syncAgent.scheduleSync();\n }\n return true;\n}\n"]}
@@ -1,8 +1,8 @@
1
1
  import { bytesToBase64 } from "../../../../internal/encoding/index.js";
2
- import { createInitializedContainerMetadataDocument } from "../../../../data/containers/containerMetadataDocument.js";
3
2
  import { createPendingUpdateFields } from "../../../../data/documents/documentSync.js";
4
3
  import { deriveStableUuidV4Shaped } from "../../../../data/keying/stableUuid.js";
5
4
  import { defaultContainerContentsPersistence } from "../../containerPersistence.js";
5
+ import { createInitializedContainerMetadataDocument } from "../../metadata/containerMetadataDocument.js";
6
6
  import { loadContainerWriterProjectionForState } from "../projectionCache.js";
7
7
  import { createRemoteContainer } from "../remote.js";
8
8
  import { CONTAINER_ALREADY_COMMITTED } from "./createWithMetadata.js";
@@ -1 +1 @@
1
- {"version":3,"file":"createChild.js","sourceRoot":"","sources":["createChild.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,EAAE,0CAA0C,EAAE,MAAM,uDAAuD,CAAC;AACnH,OAAO,EAAE,yBAAyB,EAAE,MAAM,yCAAyC,CAAC;AACpF,OAAO,EAAE,wBAAwB,EAAE,MAAM,oCAAoC,CAAC;AAM9E,OAAO,EAAE,mCAAmC,EAAE,MAAM,4BAA4B,CAAC;AAEjF,OAAO,EAAE,qCAAqC,EAAE,MAAM,oBAAoB,CAAC;AAC3E,OAAO,EAAE,qBAAqB,EAAE,MAAM,WAAW,CAAC;AAMlD,OAAO,EAAE,2BAA2B,EAAE,MAAM,sBAAsB,CAAC;AAEnE,MAAM,mCAAmC,GAAG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C,YAAY;KACjC,CAAC,CAAC;IACH,IAAI,iBAAiB,KAAK,IAAI;QAAE,OAAO,IAAI,CAAC;IAE5C,OAAO;QACL,cAAc;QACd,aAAa;QACb,iBAAiB;KAClB,CAAC;AACJ,CAAC","sourcesContent":["import { bytesToBase64 } from \"@tearleads/encoding\";\nimport type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport { createInitializedContainerMetadataDocument } from \"../../../../data/containers/containerMetadataDocument\";\nimport { createPendingUpdateFields } from \"../../../../data/documents/documentSync\";\nimport { deriveStableUuidV4Shaped } from \"../../../../data/keying/stableUuid\";\nimport type { ProjectionUserKeyResolver } from \"../../../../data/keyingProjectionVerification\";\nimport type {\n ContainerContentsPersistence,\n ContainerDocumentRecord as DocumentRecord,\n} from \"../../containerPersistence\";\nimport { defaultContainerContentsPersistence } from \"../../containerPersistence\";\nimport type { ContainerState } from \"../../remoteHydration\";\nimport { loadContainerWriterProjectionForState } from \"../projectionCache\";\nimport { createRemoteContainer } from \"../remote\";\nimport type {\n ContainerMetadataDocumentState,\n ContainerWorkflowRuntime,\n CreatedChildContainerState,\n} from \"../types\";\nimport { CONTAINER_ALREADY_COMMITTED } from \"./createWithMetadata\";\n\nconst SYSTEM_CONTAINER_ID_NAMESPACE_BYTES = new Uint8Array([\n 0xc5, 0x5e, 0x8f, 0x2e, 0x3d, 0x82, 0x4b, 0x4d, 0x8d, 0xbd, 0x0d, 0xd2, 0xd3,\n 0x60, 0xb3, 0x6d,\n]);\n\n/**\n * Derives a stable, UUID-shaped container id for a built-in system slot.\n *\n * The namespace digest makes each slot idempotent across stale store snapshots.\n * The UUID version and variant bits are normalized to a v4 shape because remote\n * container APIs currently validate container ids with the same v4 UUID contract\n * they use for random user-created containers.\n */\nfunction deriveSystemContainerId(input: {\n parentContainerId: string;\n systemSlot: ContainerSystemSlot;\n}): Promise<string> {\n return deriveStableUuidV4Shaped(\n SYSTEM_CONTAINER_ID_NAMESPACE_BYTES,\n `${input.parentContainerId}\\u0000${input.systemSlot}`,\n );\n}\n\nasync function createChildContainerId(\n parentContainerId: string,\n systemSlot: ContainerSystemSlot | null | undefined,\n): Promise<string> {\n return systemSlot\n ? deriveSystemContainerId({ parentContainerId, systemSlot })\n : crypto.randomUUID();\n}\n\nasync function buildRemoteContainerContentsChildContainerState(input: {\n childId: string;\n icon: string | null;\n systemSlot?: ContainerSystemSlot | null | undefined;\n doc: ContainerMetadataDocumentState;\n initialRecord: DocumentRecord;\n parentState: ContainerState;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n trimmedName: string;\n}): Promise<ContainerState | null> {\n const {\n childId,\n icon,\n systemSlot,\n doc,\n initialRecord,\n parentState,\n resolveProjectionUserKey,\n runtime,\n stillCurrent,\n trimmedName,\n } = input;\n const parentProjection = await loadContainerWriterProjectionForState({\n containerState: parentState,\n runtime,\n });\n if (!parentProjection) {\n return null;\n }\n\n const created = await createRemoteContainer({\n systemSlot,\n containerId: childId,\n parentContainerId: parentState.container.id,\n parentProjection,\n resolveProjectionUserKey,\n runtime,\n stillCurrent,\n });\n\n if (!created || created === CONTAINER_ALREADY_COMMITTED) {\n // A benign manifest-exists conflict means the container is already committed\n // remotely (a lost create response). This eager path cannot rebuild its\n // committed metadata state, so leave the create intent to reconcile it via\n // hydration rather than fabricating a local record from a missing response.\n return null;\n }\n\n return {\n container: {\n id: created.containerId,\n // The creator owns a newly-created container until the server reconciles.\n effectiveAccessLevel: \"admin\",\n organizationId: created.organizationId,\n parentId: created.parentId,\n metadataDocumentId: created.metadataDocumentId,\n systemSlot: created.systemSlot,\n name: trimmedName,\n icon,\n createdAt: created.createdAt,\n serverCreatedAt: created.createdAt,\n serverUpdatedAt: created.updatedAt,\n updatedAt: created.updatedAt,\n },\n doc,\n record: {\n ...initialRecord,\n accessEpoch: 1,\n accessStateHash: created.accessManifestHash,\n ...created.persistedMetadataState,\n },\n };\n}\n\nfunction buildLocalContainerContentsChildContainerState(input: {\n childId: string;\n icon: string | null;\n systemSlot?: ContainerSystemSlot | null | undefined;\n doc: ContainerMetadataDocumentState;\n initialRecord: DocumentRecord;\n parentState: ContainerState;\n trimmedName: string;\n}): ContainerState {\n const {\n systemSlot,\n childId,\n doc,\n icon,\n initialRecord,\n parentState,\n trimmedName,\n } = input;\n\n return {\n container: {\n id: childId,\n effectiveAccessLevel: \"admin\",\n organizationId: parentState.container.organizationId,\n parentId: parentState.container.id,\n metadataDocumentId: null,\n systemSlot: systemSlot ?? null,\n name: trimmedName,\n icon,\n },\n doc,\n record: initialRecord,\n };\n}\n\nfunction createInitialChildContainerDocumentRecord(input: {\n childId: string;\n initialUpdate: Uint8Array;\n}): DocumentRecord {\n return {\n accessEpoch: 1,\n accessStateHash: null,\n contentKeyBundle: null,\n documentId: null,\n documentKekTargets: null,\n documentManifestBundle: null,\n id: input.childId,\n lastCommitLsn: null,\n metadataUpdates: bytesToBase64(input.initialUpdate),\n snapshotEndVersion: \"\",\n };\n}\n\nfunction resolveAtomicChildContainerSave(\n persistence: ContainerContentsPersistence,\n): NonNullable<\n ContainerContentsPersistence[\"saveContainerWithPendingUpdate\"]\n> | null {\n const saveContainerWithPendingUpdate =\n persistence.saveContainerWithPendingUpdate;\n if (!saveContainerWithPendingUpdate) return null;\n const inheritedSqlAtomicSave =\n saveContainerWithPendingUpdate ===\n defaultContainerContentsPersistence.saveContainerWithPendingUpdate &&\n (persistence.saveContainer !==\n defaultContainerContentsPersistence.saveContainer ||\n persistence.enqueuePendingUpdate !==\n defaultContainerContentsPersistence.enqueuePendingUpdate);\n return inheritedSqlAtomicSave ? null : saveContainerWithPendingUpdate;\n}\n\nasync function persistCreatedChildContainer(input: {\n containerState: ContainerState;\n initialUpdate: Uint8Array;\n persistence: ContainerContentsPersistence;\n queueRemoteSync: boolean;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<boolean | null> {\n const { containerState, persistence, queueRemoteSync, runtime } = input;\n const createIntent =\n queueRemoteSync &&\n !containerState.record.documentId &&\n containerState.container.parentId\n ? { parentContainerId: containerState.container.parentId }\n : undefined;\n const shouldRequestSync =\n queueRemoteSync &&\n (!containerState.record.documentId ||\n Boolean(containerState.record.contentKeyBundle));\n const saveOptions =\n createIntent || input.stillCurrent\n ? {\n ...(createIntent ? { createIntent } : {}),\n stillCurrent: input.stillCurrent,\n }\n : undefined;\n const pendingUpdate = shouldRequestSync\n ? createPendingUpdateFields(input.initialUpdate)\n : null;\n if (pendingUpdate) {\n const saveContainerWithPendingUpdate =\n resolveAtomicChildContainerSave(persistence);\n if (!saveContainerWithPendingUpdate) return null;\n containerState.container = await saveContainerWithPendingUpdate(\n runtime.infra.execSql,\n containerState.container,\n containerState.record,\n { ...saveOptions, pendingUpdate },\n );\n } else {\n containerState.container = await persistence.saveContainer(\n runtime.infra.execSql,\n containerState.container,\n containerState.record,\n saveOptions,\n );\n }\n return input.stillCurrent?.() === false ? null : shouldRequestSync;\n}\n\nexport async function createChildContainerState(input: {\n systemSlot?: ContainerSystemSlot | null | undefined;\n createRemote: boolean;\n icon?: string | null | undefined;\n name: string;\n parentState: ContainerState;\n persistence: ContainerContentsPersistence;\n queueRemoteSync?: boolean | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<CreatedChildContainerState | null> {\n const {\n createRemote,\n systemSlot,\n name,\n parentState,\n persistence,\n queueRemoteSync = true,\n resolveProjectionUserKey,\n runtime,\n } = input;\n const trimmedName = name.trim();\n if (!trimmedName) {\n return null;\n }\n\n const icon = input.icon?.trim() || null;\n const childId = await createChildContainerId(\n parentState.container.id,\n systemSlot,\n );\n const { doc, initialUpdate } =\n await createInitializedContainerMetadataDocument(childId, {\n icon,\n name: trimmedName,\n });\n const initialRecord = createInitialChildContainerDocumentRecord({\n childId,\n initialUpdate,\n });\n if (input.stillCurrent?.() === false) return null;\n // An initial metadata update and its container identity are one durable unit.\n // Refuse before any remote create when an adapter cannot provide\n // that atomic operation; a SQLite transaction cannot roll back adapter-owned\n // side effects.\n if (queueRemoteSync && !resolveAtomicChildContainerSave(persistence)) {\n return null;\n }\n\n const remoteChildState = createRemote\n ? await buildRemoteContainerContentsChildContainerState({\n childId,\n icon,\n systemSlot,\n doc,\n initialRecord,\n parentState,\n resolveProjectionUserKey,\n runtime,\n stillCurrent: input.stillCurrent,\n trimmedName,\n })\n : null;\n const containerState =\n remoteChildState ??\n buildLocalContainerContentsChildContainerState({\n childId,\n icon,\n systemSlot,\n doc,\n initialRecord,\n parentState,\n trimmedName,\n });\n const shouldRequestSync = await persistCreatedChildContainer({\n containerState,\n initialUpdate,\n persistence,\n queueRemoteSync,\n runtime,\n stillCurrent: input.stillCurrent,\n });\n if (shouldRequestSync === null) return null;\n\n return {\n containerState,\n initialUpdate,\n shouldRequestSync,\n };\n}\n"]}
1
+ {"version":3,"file":"createChild.js","sourceRoot":"","sources":["createChild.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,EAAE,yBAAyB,EAAE,MAAM,yCAAyC,CAAC;AACpF,OAAO,EAAE,wBAAwB,EAAE,MAAM,oCAAoC,CAAC;AAM9E,OAAO,EAAE,mCAAmC,EAAE,MAAM,4BAA4B,CAAC;AACjF,OAAO,EAAE,0CAA0C,EAAE,MAAM,0CAA0C,CAAC;AAEtG,OAAO,EAAE,qCAAqC,EAAE,MAAM,oBAAoB,CAAC;AAC3E,OAAO,EAAE,qBAAqB,EAAE,MAAM,WAAW,CAAC;AAMlD,OAAO,EAAE,2BAA2B,EAAE,MAAM,sBAAsB,CAAC;AAEnE,MAAM,mCAAmC,GAAG,IAAI,UAAU,CAAC;IACzD,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI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AC;AACJ,CAAC","sourcesContent":["import { bytesToBase64 } from \"@tearleads/encoding\";\nimport type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport { createPendingUpdateFields } from \"../../../../data/documents/documentSync\";\nimport { deriveStableUuidV4Shaped } from \"../../../../data/keying/stableUuid\";\nimport type { ProjectionUserKeyResolver } from \"../../../../data/keyingProjectionVerification\";\nimport type {\n ContainerContentsPersistence,\n ContainerDocumentRecord as DocumentRecord,\n} from \"../../containerPersistence\";\nimport { defaultContainerContentsPersistence } from \"../../containerPersistence\";\nimport { createInitializedContainerMetadataDocument } from \"../../metadata/containerMetadataDocument\";\nimport type { ContainerState } from \"../../remoteHydration\";\nimport { loadContainerWriterProjectionForState } from \"../projectionCache\";\nimport { createRemoteContainer } from \"../remote\";\nimport type {\n ContainerMetadataDocumentState,\n ContainerWorkflowRuntime,\n CreatedChildContainerState,\n} from \"../types\";\nimport { CONTAINER_ALREADY_COMMITTED } from \"./createWithMetadata\";\n\nconst SYSTEM_CONTAINER_ID_NAMESPACE_BYTES = new Uint8Array([\n 0xc5, 0x5e, 0x8f, 0x2e, 0x3d, 0x82, 0x4b, 0x4d, 0x8d, 0xbd, 0x0d, 0xd2, 0xd3,\n 0x60, 0xb3, 0x6d,\n]);\n\n/**\n * Derives a stable, UUID-shaped container id for a built-in system slot.\n *\n * The namespace digest makes each slot idempotent across stale store snapshots.\n * The UUID version and variant bits are normalized to a v4 shape because remote\n * container APIs currently validate container ids with the same v4 UUID contract\n * they use for random user-created containers.\n */\nfunction deriveSystemContainerId(input: {\n parentContainerId: string;\n systemSlot: ContainerSystemSlot;\n}): Promise<string> {\n return deriveStableUuidV4Shaped(\n SYSTEM_CONTAINER_ID_NAMESPACE_BYTES,\n `${input.parentContainerId}\\u0000${input.systemSlot}`,\n );\n}\n\nasync function createChildContainerId(\n parentContainerId: string,\n systemSlot: ContainerSystemSlot | null | undefined,\n): Promise<string> {\n return systemSlot\n ? deriveSystemContainerId({ parentContainerId, systemSlot })\n : crypto.randomUUID();\n}\n\nasync function buildRemoteContainerContentsChildContainerState(input: {\n childId: string;\n icon: string | null;\n systemSlot?: ContainerSystemSlot | null | undefined;\n doc: ContainerMetadataDocumentState;\n initialRecord: DocumentRecord;\n parentState: ContainerState;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n trimmedName: string;\n}): Promise<ContainerState | null> {\n const {\n childId,\n icon,\n systemSlot,\n doc,\n initialRecord,\n parentState,\n resolveProjectionUserKey,\n runtime,\n stillCurrent,\n trimmedName,\n } = input;\n const parentProjection = await loadContainerWriterProjectionForState({\n containerState: parentState,\n runtime,\n });\n if (!parentProjection) {\n return null;\n }\n\n const created = await createRemoteContainer({\n systemSlot,\n containerId: childId,\n parentContainerId: parentState.container.id,\n parentProjection,\n resolveProjectionUserKey,\n runtime,\n stillCurrent,\n });\n\n if (!created || created === CONTAINER_ALREADY_COMMITTED) {\n // A benign manifest-exists conflict means the container is already committed\n // remotely (a lost create response). This eager path cannot rebuild its\n // committed metadata state, so leave the create intent to reconcile it via\n // hydration rather than fabricating a local record from a missing response.\n return null;\n }\n\n return {\n container: {\n id: created.containerId,\n // The creator owns a newly-created container until the server reconciles.\n effectiveAccessLevel: \"admin\",\n organizationId: created.organizationId,\n parentId: created.parentId,\n metadataDocumentId: created.metadataDocumentId,\n systemSlot: created.systemSlot,\n name: trimmedName,\n icon,\n createdAt: created.createdAt,\n serverCreatedAt: created.createdAt,\n serverUpdatedAt: created.updatedAt,\n updatedAt: created.updatedAt,\n },\n doc,\n record: {\n ...initialRecord,\n accessEpoch: 1,\n accessStateHash: created.accessManifestHash,\n ...created.persistedMetadataState,\n },\n };\n}\n\nfunction buildLocalContainerContentsChildContainerState(input: {\n childId: string;\n icon: string | null;\n systemSlot?: ContainerSystemSlot | null | undefined;\n doc: ContainerMetadataDocumentState;\n initialRecord: DocumentRecord;\n parentState: ContainerState;\n trimmedName: string;\n}): ContainerState {\n const {\n systemSlot,\n childId,\n doc,\n icon,\n initialRecord,\n parentState,\n trimmedName,\n } = input;\n\n return {\n container: {\n id: childId,\n effectiveAccessLevel: \"admin\",\n organizationId: parentState.container.organizationId,\n parentId: parentState.container.id,\n metadataDocumentId: null,\n systemSlot: systemSlot ?? null,\n name: trimmedName,\n icon,\n },\n doc,\n record: initialRecord,\n };\n}\n\nfunction createInitialChildContainerDocumentRecord(input: {\n childId: string;\n initialUpdate: Uint8Array;\n}): DocumentRecord {\n return {\n accessEpoch: 1,\n accessStateHash: null,\n contentKeyBundle: null,\n documentId: null,\n documentKekTargets: null,\n documentManifestBundle: null,\n id: input.childId,\n lastCommitLsn: null,\n metadataUpdates: bytesToBase64(input.initialUpdate),\n snapshotEndVersion: \"\",\n };\n}\n\nfunction resolveAtomicChildContainerSave(\n persistence: ContainerContentsPersistence,\n): NonNullable<\n ContainerContentsPersistence[\"saveContainerWithPendingUpdate\"]\n> | null {\n const saveContainerWithPendingUpdate =\n persistence.saveContainerWithPendingUpdate;\n if (!saveContainerWithPendingUpdate) return null;\n const inheritedSqlAtomicSave =\n saveContainerWithPendingUpdate ===\n defaultContainerContentsPersistence.saveContainerWithPendingUpdate &&\n (persistence.saveContainer !==\n defaultContainerContentsPersistence.saveContainer ||\n persistence.enqueuePendingUpdate !==\n defaultContainerContentsPersistence.enqueuePendingUpdate);\n return inheritedSqlAtomicSave ? null : saveContainerWithPendingUpdate;\n}\n\nasync function persistCreatedChildContainer(input: {\n containerState: ContainerState;\n initialUpdate: Uint8Array;\n persistence: ContainerContentsPersistence;\n queueRemoteSync: boolean;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<boolean | null> {\n const { containerState, persistence, queueRemoteSync, runtime } = input;\n const createIntent =\n queueRemoteSync &&\n !containerState.record.documentId &&\n containerState.container.parentId\n ? { parentContainerId: containerState.container.parentId }\n : undefined;\n const shouldRequestSync =\n queueRemoteSync &&\n (!containerState.record.documentId ||\n Boolean(containerState.record.contentKeyBundle));\n const saveOptions =\n createIntent || input.stillCurrent\n ? {\n ...(createIntent ? { createIntent } : {}),\n stillCurrent: input.stillCurrent,\n }\n : undefined;\n const pendingUpdate = shouldRequestSync\n ? createPendingUpdateFields(input.initialUpdate)\n : null;\n if (pendingUpdate) {\n const saveContainerWithPendingUpdate =\n resolveAtomicChildContainerSave(persistence);\n if (!saveContainerWithPendingUpdate) return null;\n containerState.container = await saveContainerWithPendingUpdate(\n runtime.infra.execSql,\n containerState.container,\n containerState.record,\n { ...saveOptions, pendingUpdate },\n );\n } else {\n containerState.container = await persistence.saveContainer(\n runtime.infra.execSql,\n containerState.container,\n containerState.record,\n saveOptions,\n );\n }\n return input.stillCurrent?.() === false ? null : shouldRequestSync;\n}\n\nexport async function createChildContainerState(input: {\n systemSlot?: ContainerSystemSlot | null | undefined;\n createRemote: boolean;\n icon?: string | null | undefined;\n name: string;\n parentState: ContainerState;\n persistence: ContainerContentsPersistence;\n queueRemoteSync?: boolean | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<CreatedChildContainerState | null> {\n const {\n createRemote,\n systemSlot,\n name,\n parentState,\n persistence,\n queueRemoteSync = true,\n resolveProjectionUserKey,\n runtime,\n } = input;\n const trimmedName = name.trim();\n if (!trimmedName) {\n return null;\n }\n\n const icon = input.icon?.trim() || null;\n const childId = await createChildContainerId(\n parentState.container.id,\n systemSlot,\n );\n const { doc, initialUpdate } =\n await createInitializedContainerMetadataDocument(childId, {\n icon,\n name: trimmedName,\n });\n const initialRecord = createInitialChildContainerDocumentRecord({\n childId,\n initialUpdate,\n });\n if (input.stillCurrent?.() === false) return null;\n // An initial metadata update and its container identity are one durable unit.\n // Refuse before any remote create when an adapter cannot provide\n // that atomic operation; a SQLite transaction cannot roll back adapter-owned\n // side effects.\n if (queueRemoteSync && !resolveAtomicChildContainerSave(persistence)) {\n return null;\n }\n\n const remoteChildState = createRemote\n ? await buildRemoteContainerContentsChildContainerState({\n childId,\n icon,\n systemSlot,\n doc,\n initialRecord,\n parentState,\n resolveProjectionUserKey,\n runtime,\n stillCurrent: input.stillCurrent,\n trimmedName,\n })\n : null;\n const containerState =\n remoteChildState ??\n buildLocalContainerContentsChildContainerState({\n childId,\n icon,\n systemSlot,\n doc,\n initialRecord,\n parentState,\n trimmedName,\n });\n const shouldRequestSync = await persistCreatedChildContainer({\n containerState,\n initialUpdate,\n persistence,\n queueRemoteSync,\n runtime,\n stillCurrent: input.stillCurrent,\n });\n if (shouldRequestSync === null) return null;\n\n return {\n containerState,\n initialUpdate,\n shouldRequestSync,\n };\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { DEFAULT_DOCUMENT_KIND } from "../../../../data/documents/documentConstants.js";
2
- import { sqlDocumentContainerProjectionPersistence } from "../../../../data/persistence/containers/documentContainerProjectionPersistence.js";
2
+ import { sqlDocumentContainerProjectionPersistence } from "../../../../data/persistence/container-contents/documentContainerProjectionPersistence.js";
3
3
  import { listDocumentsByContainerIdsOrDocumentIds } from "../../../../data/persistence/documents/documentsPersistence.js";
4
4
  import { unlinkRemoteContainerDocument } from "../../documentLinks/index.js";
5
5
  import { purgeLocalContainerDocument, purgeRemoteContainerDocument, } from "../../tombstones/documentPurge.js";
@@ -1 +1 @@
1
- {"version":3,"file":"purgeTree.js","sourceRoot":"","sources":["purgeTree.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,8CAA8C,CAAC;AAGrF,OAAO,EAAE,yCAAyC,EAAE,MAAM,gFAAgF,CAAC;AAC3I,OAAO,EAAE,wCAAwC,EAAE,MAAM,6DAA6D,CAAC;AAGvH,OAAO,EAAE,6BAA6B,EAAE,MAAM,qBAAqB,CAAC;AAGpE,OAAO,EACL,2BAA2B,EAC3B,4BAA4B,GAC7B,MAAM,gCAAgC,CAAC;AAExC,OAAO,EACL,uBAAuB,EACvB,uBAAuB,G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port type { DocumentSummary } from \"../../../../data/documents/documentSummary\";\nimport type { ProjectionUserKeyResolver } from \"../../../../data/keyingProjectionVerification\";\nimport { sqlDocumentContainerProjectionPersistence } from \"../../../../data/persistence/containers/documentContainerProjectionPersistence\";\nimport { listDocumentsByContainerIdsOrDocumentIds } from \"../../../../data/persistence/documents/documentsPersistence\";\nimport type { SubtreePurgeRoot } from \"../../../documents/purge/subtreePurgeScope\";\nimport type { ContainerContentsPersistence } from \"../../containerPersistence\";\nimport { unlinkRemoteContainerDocument } from \"../../documentLinks\";\nimport type { ContainerState } from \"../../remoteHydration\";\nimport type { ContainerContentsWorkflowRuntime } from \"../../runtime\";\nimport {\n purgeLocalContainerDocument,\n purgeRemoteContainerDocument,\n} from \"../../tombstones/documentPurge\";\nimport type { PurgeProgress } from \"./purgeProgress\";\nimport {\n collectSubtreeLeafFirst,\n snapshotContainerStates,\n} from \"./purgeTreeCollection\";\nimport { deleteSubtreeContainers } from \"./purgeTreeContainerDeletion\";\nimport { createSubtreePurgeScope } from \"./purgeTreeScope\";\n\nexport { collectSubtreeLeafFirst } from \"./purgeTreeCollection\";\n\n// The store runtime satisfies the per-document purge/unlink workflows, so the\n// cascade reuses it verbatim.\ntype PurgeContainerTreeRuntime = ContainerContentsWorkflowRuntime;\n\ninterface PurgeContainerTreeInput {\n readonly containersById: ReadonlyMap<string, ContainerState>;\n readonly documentOperations?: SubtreeDocumentOperations | undefined;\n // When true, tear down everything UNDER the root (its documents plus every\n // descendant container) but never delete the root container itself. This is\n // how \"Empty Trash\" reuses the same engine: the Trash bin is a protected system\n // container that must survive while its whole contents are destroyed.\n readonly keepRootContainer?: boolean;\n readonly onProgress?: ((progress: PurgeProgress) => void) | undefined;\n readonly persistence: ContainerContentsPersistence;\n readonly prepareDocumentRotationSnapshot: (\n document: DocumentSummary,\n ) => Promise<Uint8Array | null>;\n readonly resolveProjectionUserKey: ProjectionUserKeyResolver;\n readonly rootContainerId: string;\n readonly runtime: PurgeContainerTreeRuntime;\n /** Stops a stale store generation between complete destructive units. */\n readonly stillCurrent?: (() => boolean) | undefined;\n // Checked at each unit boundary (between whole documents / whole containers),\n // never mid-remote-call, so a cancelled run stops on a consistent prefix.\n readonly signal?: AbortSignal | undefined;\n}\n\ninterface PurgeContainerTreeResult {\n readonly aborted: boolean;\n readonly completedCount: number;\n readonly failedCount: number;\n readonly purgedContainerIds: readonly string[];\n readonly remoteDeletedContainerIds: readonly string[];\n readonly totalCount: number;\n}\n\ninterface SubtreeDocumentPlan {\n // Synced documents whose every link falls inside the subtree: reduce them to\n // one retained link, as required by the purge endpoint, then destroy them.\n readonly purge: readonly {\n document: DocumentSummary;\n unlinkContainerIds: readonly string[];\n }[];\n // Synced documents also linked outside the subtree: keep them, but unlink\n // from each in-subtree container so the containers can be deleted.\n readonly unlinkByDocument: ReadonlyMap<\n string,\n { document: DocumentSummary; containerIds: readonly string[] }\n >;\n // Never-synced documents (no remote id): destroy locally only.\n readonly purgeLocal: readonly DocumentSummary[];\n}\n\ntype SubtreeDocumentDisposition =\n | { kind: \"purge\"; unlinkContainerIds: readonly string[] }\n | { kind: \"purge-local\" }\n | { kind: \"unlink\"; containerIds: readonly string[] };\n\n// Destroy local-only documents locally. Destroy synced documents only when all\n// links are in the subtree; preserve documents with an external link. The purge\n// plan reduces owned documents to the server-required sole link first.\nexport function classifySubtreeDocument(input: {\n readonly documentId: string | null;\n readonly linkedContainerIds: readonly string[];\n readonly preferredContainerId?: string | null | undefined;\n readonly subtreeContainerIds: ReadonlySet<string>;\n}): SubtreeDocumentDisposition {\n if (!input.documentId) {\n return { kind: \"purge-local\" };\n }\n const hasExternalLink = input.linkedContainerIds.some(\n (containerId) => !input.subtreeContainerIds.has(containerId),\n );\n if (!hasExternalLink) {\n const linkedContainerIds = Array.from(\n new Set(\n input.linkedContainerIds.filter((containerId) =>\n input.subtreeContainerIds.has(containerId),\n ),\n ),\n );\n const retainedContainerId =\n input.preferredContainerId &&\n linkedContainerIds.includes(input.preferredContainerId)\n ? input.preferredContainerId\n : linkedContainerIds[0];\n return {\n kind: \"purge\",\n unlinkContainerIds: linkedContainerIds.filter(\n (containerId) => containerId !== retainedContainerId,\n ),\n };\n }\n return {\n kind: \"unlink\",\n containerIds: input.linkedContainerIds.filter((containerId) =>\n input.subtreeContainerIds.has(containerId),\n ),\n };\n}\n\nasync function planSubtreeDocuments(input: {\n readonly execSql: PurgeContainerTreeRuntime[\"infra\"][\"execSql\"];\n readonly subtreeContainerIds: ReadonlySet<string>;\n}): Promise<SubtreeDocumentPlan> {\n const documents = await listDocumentsByContainerIdsOrDocumentIds(\n input.execSql,\n {\n containerIds: [...input.subtreeContainerIds],\n documentIds: [],\n },\n );\n const remoteDocumentIds = documents.flatMap((document) =>\n document.documentId ? [document.documentId] : [],\n );\n const linkedContainerIdsByDocumentId =\n await sqlDocumentContainerProjectionPersistence.listLinkedContainerIdsByDocumentIds(\n input.execSql,\n remoteDocumentIds,\n );\n\n const purge: Array<{\n document: DocumentSummary;\n unlinkContainerIds: readonly string[];\n }> = [];\n const purgeLocal: DocumentSummary[] = [];\n const unlinkByDocument = new Map<\n string,\n { document: DocumentSummary; containerIds: readonly string[] }\n >();\n for (const document of documents) {\n const disposition = classifySubtreeDocument({\n documentId: document.documentId ?? null,\n linkedContainerIds: document.documentId\n ? (linkedContainerIdsByDocumentId.get(document.documentId) ?? [])\n : [],\n preferredContainerId: document.containerId,\n subtreeContainerIds: input.subtreeContainerIds,\n });\n if (disposition.kind === \"purge-local\") {\n purgeLocal.push(document);\n } else if (disposition.kind === \"purge\") {\n purge.push({\n document,\n unlinkContainerIds: disposition.unlinkContainerIds,\n });\n } else if (document.documentId) {\n unlinkByDocument.set(document.documentId, {\n document,\n containerIds: disposition.containerIds,\n });\n }\n }\n\n return { purge, purgeLocal, unlinkByDocument };\n}\n\nasync function unlinkSubtreeDocument(input: {\n /** Rechecks the document and this exact unlink target before dispatch. */\n readonly beforeSubmit: (targetContainerId: string) => Promise<boolean>;\n readonly expectedSubtreeRoot: SubtreePurgeRoot;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly containerIds: readonly string[];\n readonly document: DocumentSummary;\n readonly prepareDocumentRotationSnapshot: PurgeContainerTreeInput[\"prepareDocumentRotationSnapshot\"];\n readonly resolveProjectionUserKey: ProjectionUserKeyResolver;\n readonly runtime: PurgeContainerTreeRuntime;\n}): Promise<boolean> {\n const documentId = input.document.documentId;\n if (!documentId) {\n return true;\n }\n let rotationSnapshot: Uint8Array | null;\n try {\n rotationSnapshot = await input.prepareDocumentRotationSnapshot(\n input.document,\n );\n } catch {\n return false;\n }\n if (!rotationSnapshot) {\n return false;\n }\n for (const containerId of input.containerIds) {\n const result = await unlinkRemoteContainerDocument({\n beforeSubmit: () => input.beforeSubmit(containerId),\n documentId,\n expectedSubtreeRoot: input.expectedSubtreeRoot,\n isCurrent: input.stillCurrent,\n noteId: input.document.id,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n rotationSnapshot,\n runtime: input.runtime,\n targetContainerId: containerId,\n });\n if (result === null) {\n return false;\n }\n }\n return true;\n}\n\ninterface SubtreeDocumentOperations {\n readonly purgeLocal: (document: DocumentSummary) => Promise<boolean>;\n readonly purgeRemote: (document: DocumentSummary) => Promise<boolean>;\n readonly unlink: (\n document: DocumentSummary,\n containerIds: readonly string[],\n ) => Promise<boolean>;\n}\n\nfunction resolveSubtreeDocumentOperations(\n input: PurgeContainerTreeInput,\n scope: ReturnType<typeof createSubtreePurgeScope>,\n): SubtreeDocumentOperations {\n const expectedSubtreeRoot = selectedSubtreeRoot(input);\n const operations: SubtreeDocumentOperations = input.documentOperations ?? {\n purgeLocal: async (document) =>\n (await purgeLocalContainerDocument({\n beforeDeleteInTransaction: (execSql) =>\n scope.assertLocalScopeInTransaction(\n execSql,\n document.containerId,\n document.id,\n ),\n noteId: document.id,\n expectedContainerId: document.containerId,\n runtime: input.runtime,\n })) !== null,\n purgeRemote: async (document) =>\n Boolean(\n document.documentId &&\n (await purgeRemoteContainerDocument({\n beforeSubmit: () => scope.allowsDocument(document),\n documentId: document.documentId,\n expectedSubtreeRoot,\n stillCurrent: input.stillCurrent,\n documentKind: document.documentKind ?? DEFAULT_DOCUMENT_KIND,\n noteId: document.id,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n runtime: input.runtime,\n })),\n ),\n unlink: (document, containerIds) =>\n unlinkSubtreeDocument({\n // Target preparation and signing can outlast the upfront checks.\n beforeSubmit: async (containerId) =>\n (await scope.allowsDocument(document)) &&\n (await scope.allowsContainer(containerId)),\n containerIds,\n document,\n expectedSubtreeRoot,\n stillCurrent: input.stillCurrent,\n prepareDocumentRotationSnapshot: input.prepareDocumentRotationSnapshot,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n runtime: input.runtime,\n }),\n };\n return {\n purgeLocal: async (document) =>\n (await scope.allowsDocument(document)) &&\n (await operations.purgeLocal(document)),\n purgeRemote: async (document) =>\n (await scope.allowsDocument(document)) &&\n (await operations.purgeRemote(document)),\n unlink: async (document, containerIds) => {\n if (!(await scope.allowsDocument(document))) return false;\n for (const containerId of containerIds) {\n if (!(await scope.allowsContainer(containerId))) return false;\n }\n return operations.unlink(document, containerIds);\n },\n };\n}\n\ninterface SubtreeTeardownResult {\n readonly aborted: boolean;\n}\n\n// Signed request paths must keep the root under the parent it was selected\n// from; a settled restore elsewhere preserves the root's own documents too.\nfunction selectedSubtreeRoot(\n input: Pick<PurgeContainerTreeInput, \"containersById\" | \"rootContainerId\">,\n): SubtreePurgeRoot {\n return {\n id: input.rootContainerId,\n parentId:\n input.containersById.get(input.rootContainerId)?.container.parentId ??\n null,\n };\n}\n\nfunction purgeWasCancelled(input: {\n readonly signal?: AbortSignal | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): boolean {\n return input.signal?.aborted === true || input.stillCurrent?.() === false;\n}\n\n// Tear down one whole document per progress step. A failed document is skipped,\n// leaving its container undeletable while the remaining subtree work continues.\n// Cancellation is honored only between complete document operations.\nasync function teardownSubtreeDocuments(input: {\n readonly documentOperations: SubtreeDocumentOperations;\n readonly plan: SubtreeDocumentPlan;\n readonly reportStep: (ok: boolean) => void;\n readonly signal?: AbortSignal | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<SubtreeTeardownResult> {\n for (const {\n document,\n containerIds,\n } of input.plan.unlinkByDocument.values()) {\n if (purgeWasCancelled(input)) {\n return { aborted: true };\n }\n const unlinked = await input.documentOperations.unlink(\n document,\n containerIds,\n );\n input.reportStep(unlinked);\n }\n for (const { document, unlinkContainerIds } of input.plan.purge) {\n if (purgeWasCancelled(input)) {\n return { aborted: true };\n }\n if (\n unlinkContainerIds.length > 0 &&\n !(await input.documentOperations.unlink(document, unlinkContainerIds))\n ) {\n input.reportStep(false);\n continue;\n }\n input.reportStep(await input.documentOperations.purgeRemote(document));\n }\n for (const document of input.plan.purgeLocal) {\n if (purgeWasCancelled(input)) {\n return { aborted: true };\n }\n input.reportStep(await input.documentOperations.purgeLocal(document));\n }\n return { aborted: false };\n}\n\n// Permanently destroy a folder that lives inside Trash, including everything\n// under it (or, with keepRootContainer, everything under the Trash bin while\n// leaving the bin in place — this is \"Empty Trash\"). Documents are destroyed only\n// when the subtree holds their last link; multi-folder documents are unlinked\n// from the subtree and preserved. Containers are deleted leaf-first so each\n// delete obeys the leaf-only constraint the store and server enforce. Every step\n// is remote-first then local (the per-document and per-container workflows handle\n// that internally), so a cancel between steps leaves local state reflecting\n// exactly the completed remote work.\n//\n// Progress is determinate: the plan (a pure read) completes before any\n// destructive step, so onProgress reports completed/failed against a total known\n// up front. A failed item is skipped rather than aborting the run, so the result\n// reports whatever prefix was actually destroyed alongside completed/failed\n// counts and whether a cancellation cut it short. Returns null only when the\n// target container is absent from the snapshot.\nexport async function purgeContainerTree(\n request: PurgeContainerTreeInput,\n): Promise<PurgeContainerTreeResult | null> {\n if (purgeWasCancelled(request)) {\n return null;\n }\n const input = {\n ...request,\n containersById: snapshotContainerStates(request.containersById),\n };\n const subtreeStates = collectSubtreeLeafFirst(\n input.containersById,\n input.rootContainerId,\n );\n if (subtreeStates.length === 0) {\n return null;\n }\n const subtreeContainerIds = new Set(\n subtreeStates.map((containerState) => containerState.container.id),\n );\n\n const plan = await planSubtreeDocuments({\n execSql: input.runtime.infra.execSql,\n subtreeContainerIds,\n });\n if (purgeWasCancelled(input)) {\n return null;\n }\n\n // Empty Trash keeps the Trash bin itself: tear down everything it holds, but\n // exclude the root from the container deletions (deleting a system container\n // would be rejected anyway).\n const containerStatesToDelete = input.keepRootContainer\n ? subtreeStates.filter(\n (containerState) =>\n containerState.container.id !== input.rootContainerId,\n )\n : subtreeStates;\n\n // The total is fully known here — planning is a pure read that completes before\n // any destructive step. Unlink work is counted per document (not per container\n // link) so completed can never exceed total even when a document has several\n // in-subtree links.\n const totalCount =\n plan.unlinkByDocument.size +\n plan.purge.length +\n plan.purgeLocal.length +\n containerStatesToDelete.length;\n\n let completedCount = 0;\n let failedCount = 0;\n const emitProgress = () => {\n input.onProgress?.({ completedCount, failedCount, totalCount });\n };\n const reportStep = (ok: boolean) => {\n if (ok) {\n completedCount += 1;\n } else {\n failedCount += 1;\n }\n emitProgress();\n };\n // Emit the initial 0/total so a determinate bar renders immediately, before the\n // first (potentially slow) remote call.\n emitProgress();\n\n const scope = createSubtreePurgeScope(input);\n const teardown = await teardownSubtreeDocuments({\n documentOperations: resolveSubtreeDocumentOperations(input, scope),\n plan,\n reportStep,\n signal: input.signal,\n stillCurrent: input.stillCurrent,\n });\n\n let purgedContainerIds: readonly string[] = [];\n let remoteDeletedContainerIds: readonly string[] = [];\n let aborted = teardown.aborted;\n if (!teardown.aborted) {\n const deletion = await deleteSubtreeContainers({\n allowsContainer: scope.allowsContainer,\n allowsLocalScopeInTransaction: scope.allowsLocalScopeInTransaction,\n root: selectedSubtreeRoot(input),\n persistence: input.persistence,\n reportStep,\n runtime: input.runtime,\n signal: input.signal,\n stillCurrent: input.stillCurrent,\n subtreeStates: containerStatesToDelete,\n });\n purgedContainerIds = deletion.purgedContainerIds;\n remoteDeletedContainerIds = deletion.remoteDeletedContainerIds;\n aborted = deletion.aborted;\n }\n\n return {\n aborted,\n completedCount,\n failedCount,\n purgedContainerIds,\n remoteDeletedContainerIds,\n totalCount,\n };\n}\n"]}
1
+ {"version":3,"file":"purgeTree.js","sourceRoot":"","sources":["purgeTree.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,8CAA8C,CAAC;AAGrF,OAAO,EAAE,yCAAyC,EAAE,MAAM,wFAAwF,CAAC;AACnJ,OAAO,EAAE,wCAAwC,EAAE,MAAM,6DAA6D,CAAC;AAGvH,OAAO,EAAE,6BAA6B,EAAE,MAAM,qBAAqB,CAAC;AAGpE,OAAO,EACL,2BAA2B,EAC3B,4BAA4B,GAC7B,MAAM,gCAAgC,CAAC;AAExC,OAAO,EACL,uBAAuB,EACvB,uBAAuB,GACxB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AACvE,OAAO,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAE3D,OAAO,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAC;AA4DhE,+EAA+E;AAC/E,gFAAgF;AAChF,uEAAuE;AACvE,MAAM,UAAU,uBAAuB,CAAC,KAKvC;IACC,IAAI,CAAC,KAAK,CAAC,UAAU,EAAE,CAAC;QACtB,OAAO,EAAE,IAAI,EAAE,aAAa,EAAE,CAAC;IACjC,CAAC;IACD,MAAM,eAAe,GAAG,KAAK,CAAC,kBAAkB,CAAC,IAAI,CACnD,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,mBAAmB,CAAC,GAAG,CAAC,WAAW,CAAC,CAC7D,CAAC;IACF,IAAI,CAAC,eAAe,EAAE,CAAC;QACrB,MAAM,kBAAkB,GAAG,KAAK,CAAC,IAAI,CACnC,IAAI,GAAG,CACL,KAAK,CAAC,kBAAkB,CAAC,MAAM,CAAC,CAAC,WAAW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CAAC,KAAK,CAAC;YAChC,WAAW,EAAE,KAAK,CAAC,WAAW;YAC9B,UAAU;YACV,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,MAAM,EAAE,KAAK,CAAC,MAAM;YACpB,YAAY,EAAE,KAAK,CAAC,YAAY;YAChC,aAAa,EAAE,uBAAuB;SACvC,CAAC,CAAC;QACH,kBAAkB,GAAG,QAAQ,CAAC,kBAAkB,CAAC;QACjD,yBAAyB,GAAG,QAAQ,CAAC,yBAAyB,CAAC;QAC/D,OAAO,GAAG,QAAQ,CAAC,OAAO,CAAC;IAC7B,CAAC;IAED,OAAO;QACL,OAAO;QACP,cAAc;QACd,WAAW;QACX,kBAAkB;QAClB,yBAAyB;QACzB,UAAU;KACX,CAAC;AACJ,CAAC","sourcesContent":["import { DEFAULT_DOCUMENT_KIND } from \"../../../../data/documents/documentConstants\";\nimport type { DocumentSummary } from \"../../../../data/documents/documentSummary\";\nimport type { ProjectionUserKeyResolver } from \"../../../../data/keyingProjectionVerification\";\nimport { sqlDocumentContainerProjectionPersistence } from \"../../../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport { listDocumentsByContainerIdsOrDocumentIds } from \"../../../../data/persistence/documents/documentsPersistence\";\nimport type { SubtreePurgeRoot } from \"../../../documents/purge/subtreePurgeScope\";\nimport type { ContainerContentsPersistence } from \"../../containerPersistence\";\nimport { unlinkRemoteContainerDocument } from \"../../documentLinks\";\nimport type { ContainerState } from \"../../remoteHydration\";\nimport type { ContainerContentsWorkflowRuntime } from \"../../runtime\";\nimport {\n purgeLocalContainerDocument,\n purgeRemoteContainerDocument,\n} from \"../../tombstones/documentPurge\";\nimport type { PurgeProgress } from \"./purgeProgress\";\nimport {\n collectSubtreeLeafFirst,\n snapshotContainerStates,\n} from \"./purgeTreeCollection\";\nimport { deleteSubtreeContainers } from \"./purgeTreeContainerDeletion\";\nimport { createSubtreePurgeScope } from \"./purgeTreeScope\";\n\nexport { collectSubtreeLeafFirst } from \"./purgeTreeCollection\";\n\n// The store runtime satisfies the per-document purge/unlink workflows, so the\n// cascade reuses it verbatim.\ntype PurgeContainerTreeRuntime = ContainerContentsWorkflowRuntime;\n\ninterface PurgeContainerTreeInput {\n readonly containersById: ReadonlyMap<string, ContainerState>;\n readonly documentOperations?: SubtreeDocumentOperations | undefined;\n // When true, tear down everything UNDER the root (its documents plus every\n // descendant container) but never delete the root container itself. This is\n // how \"Empty Trash\" reuses the same engine: the Trash bin is a protected system\n // container that must survive while its whole contents are destroyed.\n readonly keepRootContainer?: boolean;\n readonly onProgress?: ((progress: PurgeProgress) => void) | undefined;\n readonly persistence: ContainerContentsPersistence;\n readonly prepareDocumentRotationSnapshot: (\n document: DocumentSummary,\n ) => Promise<Uint8Array | null>;\n readonly resolveProjectionUserKey: ProjectionUserKeyResolver;\n readonly rootContainerId: string;\n readonly runtime: PurgeContainerTreeRuntime;\n /** Stops a stale store generation between complete destructive units. */\n readonly stillCurrent?: (() => boolean) | undefined;\n // Checked at each unit boundary (between whole documents / whole containers),\n // never mid-remote-call, so a cancelled run stops on a consistent prefix.\n readonly signal?: AbortSignal | undefined;\n}\n\ninterface PurgeContainerTreeResult {\n readonly aborted: boolean;\n readonly completedCount: number;\n readonly failedCount: number;\n readonly purgedContainerIds: readonly string[];\n readonly remoteDeletedContainerIds: readonly string[];\n readonly totalCount: number;\n}\n\ninterface SubtreeDocumentPlan {\n // Synced documents whose every link falls inside the subtree: reduce them to\n // one retained link, as required by the purge endpoint, then destroy them.\n readonly purge: readonly {\n document: DocumentSummary;\n unlinkContainerIds: readonly string[];\n }[];\n // Synced documents also linked outside the subtree: keep them, but unlink\n // from each in-subtree container so the containers can be deleted.\n readonly unlinkByDocument: ReadonlyMap<\n string,\n { document: DocumentSummary; containerIds: readonly string[] }\n >;\n // Never-synced documents (no remote id): destroy locally only.\n readonly purgeLocal: readonly DocumentSummary[];\n}\n\ntype SubtreeDocumentDisposition =\n | { kind: \"purge\"; unlinkContainerIds: readonly string[] }\n | { kind: \"purge-local\" }\n | { kind: \"unlink\"; containerIds: readonly string[] };\n\n// Destroy local-only documents locally. Destroy synced documents only when all\n// links are in the subtree; preserve documents with an external link. The purge\n// plan reduces owned documents to the server-required sole link first.\nexport function classifySubtreeDocument(input: {\n readonly documentId: string | null;\n readonly linkedContainerIds: readonly string[];\n readonly preferredContainerId?: string | null | undefined;\n readonly subtreeContainerIds: ReadonlySet<string>;\n}): SubtreeDocumentDisposition {\n if (!input.documentId) {\n return { kind: \"purge-local\" };\n }\n const hasExternalLink = input.linkedContainerIds.some(\n (containerId) => !input.subtreeContainerIds.has(containerId),\n );\n if (!hasExternalLink) {\n const linkedContainerIds = Array.from(\n new Set(\n input.linkedContainerIds.filter((containerId) =>\n input.subtreeContainerIds.has(containerId),\n ),\n ),\n );\n const retainedContainerId =\n input.preferredContainerId &&\n linkedContainerIds.includes(input.preferredContainerId)\n ? input.preferredContainerId\n : linkedContainerIds[0];\n return {\n kind: \"purge\",\n unlinkContainerIds: linkedContainerIds.filter(\n (containerId) => containerId !== retainedContainerId,\n ),\n };\n }\n return {\n kind: \"unlink\",\n containerIds: input.linkedContainerIds.filter((containerId) =>\n input.subtreeContainerIds.has(containerId),\n ),\n };\n}\n\nasync function planSubtreeDocuments(input: {\n readonly execSql: PurgeContainerTreeRuntime[\"infra\"][\"execSql\"];\n readonly subtreeContainerIds: ReadonlySet<string>;\n}): Promise<SubtreeDocumentPlan> {\n const documents = await listDocumentsByContainerIdsOrDocumentIds(\n input.execSql,\n {\n containerIds: [...input.subtreeContainerIds],\n documentIds: [],\n },\n );\n const remoteDocumentIds = documents.flatMap((document) =>\n document.documentId ? [document.documentId] : [],\n );\n const linkedContainerIdsByDocumentId =\n await sqlDocumentContainerProjectionPersistence.listLinkedContainerIdsByDocumentIds(\n input.execSql,\n remoteDocumentIds,\n );\n\n const purge: Array<{\n document: DocumentSummary;\n unlinkContainerIds: readonly string[];\n }> = [];\n const purgeLocal: DocumentSummary[] = [];\n const unlinkByDocument = new Map<\n string,\n { document: DocumentSummary; containerIds: readonly string[] }\n >();\n for (const document of documents) {\n const disposition = classifySubtreeDocument({\n documentId: document.documentId ?? null,\n linkedContainerIds: document.documentId\n ? (linkedContainerIdsByDocumentId.get(document.documentId) ?? [])\n : [],\n preferredContainerId: document.containerId,\n subtreeContainerIds: input.subtreeContainerIds,\n });\n if (disposition.kind === \"purge-local\") {\n purgeLocal.push(document);\n } else if (disposition.kind === \"purge\") {\n purge.push({\n document,\n unlinkContainerIds: disposition.unlinkContainerIds,\n });\n } else if (document.documentId) {\n unlinkByDocument.set(document.documentId, {\n document,\n containerIds: disposition.containerIds,\n });\n }\n }\n\n return { purge, purgeLocal, unlinkByDocument };\n}\n\nasync function unlinkSubtreeDocument(input: {\n /** Rechecks the document and this exact unlink target before dispatch. */\n readonly beforeSubmit: (targetContainerId: string) => Promise<boolean>;\n readonly expectedSubtreeRoot: SubtreePurgeRoot;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly containerIds: readonly string[];\n readonly document: DocumentSummary;\n readonly prepareDocumentRotationSnapshot: PurgeContainerTreeInput[\"prepareDocumentRotationSnapshot\"];\n readonly resolveProjectionUserKey: ProjectionUserKeyResolver;\n readonly runtime: PurgeContainerTreeRuntime;\n}): Promise<boolean> {\n const documentId = input.document.documentId;\n if (!documentId) {\n return true;\n }\n let rotationSnapshot: Uint8Array | null;\n try {\n rotationSnapshot = await input.prepareDocumentRotationSnapshot(\n input.document,\n );\n } catch {\n return false;\n }\n if (!rotationSnapshot) {\n return false;\n }\n for (const containerId of input.containerIds) {\n const result = await unlinkRemoteContainerDocument({\n beforeSubmit: () => input.beforeSubmit(containerId),\n documentId,\n expectedSubtreeRoot: input.expectedSubtreeRoot,\n isCurrent: input.stillCurrent,\n noteId: input.document.id,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n rotationSnapshot,\n runtime: input.runtime,\n targetContainerId: containerId,\n });\n if (result === null) {\n return false;\n }\n }\n return true;\n}\n\ninterface SubtreeDocumentOperations {\n readonly purgeLocal: (document: DocumentSummary) => Promise<boolean>;\n readonly purgeRemote: (document: DocumentSummary) => Promise<boolean>;\n readonly unlink: (\n document: DocumentSummary,\n containerIds: readonly string[],\n ) => Promise<boolean>;\n}\n\nfunction resolveSubtreeDocumentOperations(\n input: PurgeContainerTreeInput,\n scope: ReturnType<typeof createSubtreePurgeScope>,\n): SubtreeDocumentOperations {\n const expectedSubtreeRoot = selectedSubtreeRoot(input);\n const operations: SubtreeDocumentOperations = input.documentOperations ?? {\n purgeLocal: async (document) =>\n (await purgeLocalContainerDocument({\n beforeDeleteInTransaction: (execSql) =>\n scope.assertLocalScopeInTransaction(\n execSql,\n document.containerId,\n document.id,\n ),\n noteId: document.id,\n expectedContainerId: document.containerId,\n runtime: input.runtime,\n })) !== null,\n purgeRemote: async (document) =>\n Boolean(\n document.documentId &&\n (await purgeRemoteContainerDocument({\n beforeSubmit: () => scope.allowsDocument(document),\n documentId: document.documentId,\n expectedSubtreeRoot,\n stillCurrent: input.stillCurrent,\n documentKind: document.documentKind ?? DEFAULT_DOCUMENT_KIND,\n noteId: document.id,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n runtime: input.runtime,\n })),\n ),\n unlink: (document, containerIds) =>\n unlinkSubtreeDocument({\n // Target preparation and signing can outlast the upfront checks.\n beforeSubmit: async (containerId) =>\n (await scope.allowsDocument(document)) &&\n (await scope.allowsContainer(containerId)),\n containerIds,\n document,\n expectedSubtreeRoot,\n stillCurrent: input.stillCurrent,\n prepareDocumentRotationSnapshot: input.prepareDocumentRotationSnapshot,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n runtime: input.runtime,\n }),\n };\n return {\n purgeLocal: async (document) =>\n (await scope.allowsDocument(document)) &&\n (await operations.purgeLocal(document)),\n purgeRemote: async (document) =>\n (await scope.allowsDocument(document)) &&\n (await operations.purgeRemote(document)),\n unlink: async (document, containerIds) => {\n if (!(await scope.allowsDocument(document))) return false;\n for (const containerId of containerIds) {\n if (!(await scope.allowsContainer(containerId))) return false;\n }\n return operations.unlink(document, containerIds);\n },\n };\n}\n\ninterface SubtreeTeardownResult {\n readonly aborted: boolean;\n}\n\n// Signed request paths must keep the root under the parent it was selected\n// from; a settled restore elsewhere preserves the root's own documents too.\nfunction selectedSubtreeRoot(\n input: Pick<PurgeContainerTreeInput, \"containersById\" | \"rootContainerId\">,\n): SubtreePurgeRoot {\n return {\n id: input.rootContainerId,\n parentId:\n input.containersById.get(input.rootContainerId)?.container.parentId ??\n null,\n };\n}\n\nfunction purgeWasCancelled(input: {\n readonly signal?: AbortSignal | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): boolean {\n return input.signal?.aborted === true || input.stillCurrent?.() === false;\n}\n\n// Tear down one whole document per progress step. A failed document is skipped,\n// leaving its container undeletable while the remaining subtree work continues.\n// Cancellation is honored only between complete document operations.\nasync function teardownSubtreeDocuments(input: {\n readonly documentOperations: SubtreeDocumentOperations;\n readonly plan: SubtreeDocumentPlan;\n readonly reportStep: (ok: boolean) => void;\n readonly signal?: AbortSignal | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<SubtreeTeardownResult> {\n for (const {\n document,\n containerIds,\n } of input.plan.unlinkByDocument.values()) {\n if (purgeWasCancelled(input)) {\n return { aborted: true };\n }\n const unlinked = await input.documentOperations.unlink(\n document,\n containerIds,\n );\n input.reportStep(unlinked);\n }\n for (const { document, unlinkContainerIds } of input.plan.purge) {\n if (purgeWasCancelled(input)) {\n return { aborted: true };\n }\n if (\n unlinkContainerIds.length > 0 &&\n !(await input.documentOperations.unlink(document, unlinkContainerIds))\n ) {\n input.reportStep(false);\n continue;\n }\n input.reportStep(await input.documentOperations.purgeRemote(document));\n }\n for (const document of input.plan.purgeLocal) {\n if (purgeWasCancelled(input)) {\n return { aborted: true };\n }\n input.reportStep(await input.documentOperations.purgeLocal(document));\n }\n return { aborted: false };\n}\n\n// Permanently destroy a folder that lives inside Trash, including everything\n// under it (or, with keepRootContainer, everything under the Trash bin while\n// leaving the bin in place — this is \"Empty Trash\"). Documents are destroyed only\n// when the subtree holds their last link; multi-folder documents are unlinked\n// from the subtree and preserved. Containers are deleted leaf-first so each\n// delete obeys the leaf-only constraint the store and server enforce. Every step\n// is remote-first then local (the per-document and per-container workflows handle\n// that internally), so a cancel between steps leaves local state reflecting\n// exactly the completed remote work.\n//\n// Progress is determinate: the plan (a pure read) completes before any\n// destructive step, so onProgress reports completed/failed against a total known\n// up front. A failed item is skipped rather than aborting the run, so the result\n// reports whatever prefix was actually destroyed alongside completed/failed\n// counts and whether a cancellation cut it short. Returns null only when the\n// target container is absent from the snapshot.\nexport async function purgeContainerTree(\n request: PurgeContainerTreeInput,\n): Promise<PurgeContainerTreeResult | null> {\n if (purgeWasCancelled(request)) {\n return null;\n }\n const input = {\n ...request,\n containersById: snapshotContainerStates(request.containersById),\n };\n const subtreeStates = collectSubtreeLeafFirst(\n input.containersById,\n input.rootContainerId,\n );\n if (subtreeStates.length === 0) {\n return null;\n }\n const subtreeContainerIds = new Set(\n subtreeStates.map((containerState) => containerState.container.id),\n );\n\n const plan = await planSubtreeDocuments({\n execSql: input.runtime.infra.execSql,\n subtreeContainerIds,\n });\n if (purgeWasCancelled(input)) {\n return null;\n }\n\n // Empty Trash keeps the Trash bin itself: tear down everything it holds, but\n // exclude the root from the container deletions (deleting a system container\n // would be rejected anyway).\n const containerStatesToDelete = input.keepRootContainer\n ? subtreeStates.filter(\n (containerState) =>\n containerState.container.id !== input.rootContainerId,\n )\n : subtreeStates;\n\n // The total is fully known here — planning is a pure read that completes before\n // any destructive step. Unlink work is counted per document (not per container\n // link) so completed can never exceed total even when a document has several\n // in-subtree links.\n const totalCount =\n plan.unlinkByDocument.size +\n plan.purge.length +\n plan.purgeLocal.length +\n containerStatesToDelete.length;\n\n let completedCount = 0;\n let failedCount = 0;\n const emitProgress = () => {\n input.onProgress?.({ completedCount, failedCount, totalCount });\n };\n const reportStep = (ok: boolean) => {\n if (ok) {\n completedCount += 1;\n } else {\n failedCount += 1;\n }\n emitProgress();\n };\n // Emit the initial 0/total so a determinate bar renders immediately, before the\n // first (potentially slow) remote call.\n emitProgress();\n\n const scope = createSubtreePurgeScope(input);\n const teardown = await teardownSubtreeDocuments({\n documentOperations: resolveSubtreeDocumentOperations(input, scope),\n plan,\n reportStep,\n signal: input.signal,\n stillCurrent: input.stillCurrent,\n });\n\n let purgedContainerIds: readonly string[] = [];\n let remoteDeletedContainerIds: readonly string[] = [];\n let aborted = teardown.aborted;\n if (!teardown.aborted) {\n const deletion = await deleteSubtreeContainers({\n allowsContainer: scope.allowsContainer,\n allowsLocalScopeInTransaction: scope.allowsLocalScopeInTransaction,\n root: selectedSubtreeRoot(input),\n persistence: input.persistence,\n reportStep,\n runtime: input.runtime,\n signal: input.signal,\n stillCurrent: input.stillCurrent,\n subtreeStates: containerStatesToDelete,\n });\n purgedContainerIds = deletion.purgedContainerIds;\n remoteDeletedContainerIds = deletion.remoteDeletedContainerIds;\n aborted = deletion.aborted;\n }\n\n return {\n aborted,\n completedCount,\n failedCount,\n purgedContainerIds,\n remoteDeletedContainerIds,\n totalCount,\n };\n}\n"]}
@@ -2,9 +2,9 @@ import { isContainerNotFoundFailure } from "../../../data/containers/shared/muta
2
2
  import { ProjectionDependencyUnavailableError } from "../../../data/keyingProjectionVerification/dependencyUnavailable.js";
3
3
  import { errorMessage } from "../../../data/shared/errorMessage.js";
4
4
  import { readContainerMutationMetadataDocumentId, referencedPrincipalHeadsFromContainerMutationResponse, replayRemoteContainerMove, shareRemoteContainer as shareRemoteContainerMutation, } from "../../containers/index.js";
5
- import { createRuntimeCurrentGroupShare } from "../../containers/child/share/runtimeCurrentGroupShare.js";
6
5
  import { resolveDocumentCreateAuthor } from "../../documents/index.js";
7
6
  import { createRuntimeGroupMetadataAccess } from "../../organizations/groupMetadata/groupMetadataRuntime.js";
7
+ import { createRuntimeCurrentGroupShare } from "../../organizations/groupShare/index.js";
8
8
  import { createRuntimePrincipalPolicyWarmer } from "../../principals/runtimePolicyWarmer.js";
9
9
  import { createRemoteContainerWithMetadataDocument, } from "./create/createWithMetadata.js";
10
10
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"remote.js","sourceRoot":"","sources":["remote.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,0BAA0B,EAAE,MAAM,kDAAkD,CAAC;AAE9F,OAAO,EAAE,oCAAoC,EAAE,MAAM,kEAAkE,CAAC;AACxH,OAAO,EAAE,YAAY,EAAE,MAAM,mCAAmC,CAAC;AACjE,OAAO,EAEL,uCAAuC,EACvC,qDAAqD,EACrD,yBAAyB,EACzB,oBAAoB,IAAI,4BAA4B,GACrD,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,8BAA8B,EAAE,MAAM,uDAAuD,CAAC;AACvG,OAAO,EAAE,2BAA2B,EAAE,MAAM,iBAAiB,CAAC;AAC9D,OAAO,EAAE,gCAAgC,EAAE,MAAM,wDAAwD,CAAC;AAC1G,OAAO,EAAE,kCAAkC,EAAE,MAAM,sCAAsC,CAAC;AAC1F,OAAO,EAEL,yCAAyC,GAC1C,MAAM,6BAA6B,CAAC;AASrC;;;;GAIG;AACH,SAAS,6BAA6B,CACpC,OAAiC,EACjC,SAIqB;IAErB,MAAM,MAAM,GAAG,2BAA2B,CAAC,OAAO,CAAC,CAAC;IACpD,MAAM,SAAS,GAAG,OAAO,CAAC,MAAM,CAAC,oBAAoB,EAAE,SAAS,CAAC;IACjE,IAAI,CAAC,MAAM,IAAI,CAAC,SAAS,EAAE,CAAC;QAC1B,OAAO,CAAC,IAAI,CAAC,GAAG,CACd,+BAA+B,SAAS,6CAA6C,CACtF,CAAC;QACF,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO;QACL,SAAS,EAAE,OAAO,CAAC,SAAS;QAC5B,MAAM;QACN,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,OAAO;QAC9B,SAAS;KACV,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,qBAAqB,CAAC,KAW3C;IACC,OAAO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AAE,CAAC;QACrB,wEAAwE;QACxE,oEAAoE;QACpE,+CAA+C;QAC/C,OAAO,EAAE,SAAS,EAAE,0BAA0B,EAAE,CAAC;IACnD,CAAC;IAED,OAAO,EAAE,SAAS,EAAE,YAAY,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC;AACpD,CAAC;AAED,2EAA2E;AAC3E,MAAM,CAAC,KAAK,UAAU,8BAA8B,CAAC,KAIpD;IACC,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,EAAE,CAAC;QACvB,OAAO;IACT,CAAC;IACD,MAAM,cAAc,GAAG,MAAM,qBAAqB,CAAC;QACjD,WAAW,EAAE,KAAK,CAAC,OAAO,CAAC,WAAW;QACtC,cAAc,EAAE,KAAK,CAAC,OAAO,CAAC,cAAc;QAC5C,OAAO,EAAE,KAAK,CAAC,KAAK,CAAC,OAAO;KAC7B,CAAC,CAAC,IAAI,CACL,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,gCAAgC,CAAC,EAChE,CAAC,KAAc,EAAE,EAAE,CAAC,YAAY,CAAC,KAAK,CAAC,CACxC,CAAC;IACF,IAAI,KAAK,CAAC,SAAS,EAAE,IAAI,cAAc,KAAK,IAAI,EAAE,CAAC;QACjD,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAC1B,mEAAmE,KAAK,CAAC,OAAO,CAAC,WAAW,wBAAwB,cAAc,EAAE,CACrI,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type {\n ContainerMutationResponse,\n ContainerWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { isContainerNotFoundFailure } from \"../../../data/containers/shared/mutationFailures\";\nimport type { ProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { errorMessage } from \"../../../data/shared/errorMessage\";\nimport {\n type AppliedContainerMove,\n readContainerMutationMetadataDocumentId,\n referencedPrincipalHeadsFromContainerMutationResponse,\n replayRemoteContainerMove,\n shareRemoteContainer as shareRemoteContainerMutation,\n} from \"../../containers\";\nimport { createRuntimeCurrentGroupShare } from \"../../containers/child/share/runtimeCurrentGroupShare\";\nimport { resolveDocumentCreateAuthor } from \"../../documents\";\nimport { createRuntimeGroupMetadataAccess } from \"../../organizations/groupMetadata/groupMetadataRuntime\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../../principals/runtimePolicyWarmer\";\nimport {\n type ContainerAlreadyCommitted,\n createRemoteContainerWithMetadataDocument,\n} from \"./create/createWithMetadata\";\nimport type {\n ContainerCreateIntentSyncState,\n ContainerWorkflowRuntime,\n CreatedRemoteContainerState,\n RemoteContainer,\n SharedRemoteContainerState,\n} from \"./types\";\n\n/**\n * Resolve the author, api client, executor, and encapsulation secret a remote\n * container mutation needs, logging a skip for the given operation when the\n * writer context is unavailable.\n */\nfunction resolveContainerWriterContext(\n runtime: ContainerWorkflowRuntime,\n operation:\n | \"container create\"\n | \"container group share\"\n | \"container move\"\n | \"container share\",\n) {\n const author = resolveDocumentCreateAuthor(runtime);\n const secretKey = runtime.crypto.encapsulationKeyPair?.secretKey;\n if (!author || !secretKey) {\n runtime.util.log(\n `Container contents: skipped ${operation} because the writer context is unavailable.`,\n );\n return null;\n }\n\n return {\n apiClient: runtime.apiClient,\n author,\n execSql: runtime.infra.execSql,\n secretKey,\n };\n}\n\nexport async function createRemoteContainer(input: {\n systemSlot?: ContainerSystemSlot | null | undefined;\n containerId: string;\n metadataSeedUpdate?: Parameters<\n typeof createRemoteContainerWithMetadataDocument\n >[0][\"metadataSeedUpdate\"];\n parentContainerId: string;\n parentProjection?: ContainerWriterProjectionResponse | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<CreatedRemoteContainerState | ContainerAlreadyCommitted | null> {\n return createRemoteContainerWithMetadataDocument(input);\n}\n\nfunction sharedRemoteContainerStateFromMutation(\n previousProjection: ContainerWriterProjectionResponse,\n response: ContainerMutationResponse,\n): SharedRemoteContainerState {\n if (\n response.containerId !== previousProjection.containerId ||\n response.organizationId !== previousProjection.organizationId\n )\n throw new Error(\"Container mutation response projection mismatch\");\n return {\n accessManifestHash: response.manifestHead.manifestHash,\n accessEpoch: response.manifestHead.epoch,\n createdAt: response.createdAt,\n metadataDocumentId: readContainerMutationMetadataDocumentId({ response }),\n referencedPrincipalHeads:\n referencedPrincipalHeadsFromContainerMutationResponse({ response }),\n updatedAt: response.updatedAt,\n // The next read obtains the post-commit proof. A failed read cannot undo\n // acknowledgement of this successful mutation.\n writerProjection: null,\n };\n}\n\nexport async function shareRemoteContainer(input: {\n accessLevel: \"read\" | \"write\" | \"admin\";\n containerId: string;\n previousProjection: ContainerWriterProjectionResponse;\n recipientUserId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<SharedRemoteContainerState | null> {\n const writer = resolveContainerWriterContext(\n input.runtime,\n \"container share\",\n );\n if (!writer) {\n return null;\n }\n const { apiClient, author, execSql, secretKey: targetSecretKey } = writer;\n\n const shared = await shareRemoteContainerMutation({\n reportSecurityIncident: input.runtime.util.reportSecurityIncident,\n accessLevel: input.accessLevel,\n apiClient,\n author,\n containerId: input.containerId,\n execSql,\n previousProjection: input.previousProjection,\n recipientUserId: input.recipientUserId,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n targetSecretKey,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n input.runtime,\n ),\n });\n if (!shared) {\n return null;\n }\n\n return sharedRemoteContainerStateFromMutation(\n input.previousProjection,\n shared.response,\n );\n}\n\nexport async function shareRemoteContainerWithGroup(input: {\n accessLevel: \"read\" | \"write\" | \"admin\";\n containerId: string;\n expectedGroupName?: string | undefined;\n knownContainerKeks?: ReadonlyMap<string, Uint8Array> | undefined;\n previousProjection: ContainerWriterProjectionResponse;\n recipientGroupId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<SharedRemoteContainerState | null> {\n const writer = resolveContainerWriterContext(\n input.runtime,\n \"container group share\",\n );\n if (!writer) {\n return null;\n }\n const { apiClient, author, execSql, secretKey: targetSecretKey } = writer;\n\n const shareWithGroup = createRuntimeCurrentGroupShare(input.runtime);\n if (!shareWithGroup)\n throw new ProjectionDependencyUnavailableError(\n \"Group sharing requires private paged recovery\",\n );\n const shared = await shareWithGroup({\n reportSecurityIncident: input.runtime.util.reportSecurityIncident,\n accessLevel: input.accessLevel,\n apiClient,\n author,\n containerId: input.containerId,\n execSql,\n expectedGroupName: input.expectedGroupName ?? null,\n readEncryptedName: (bundle) =>\n createRuntimeGroupMetadataAccess(\n input.runtime,\n author.organizationId,\n input.stillCurrent,\n ).readName(bundle),\n knownContainerKeks: input.knownContainerKeks,\n previousProjection: input.previousProjection,\n recipientGroupId: input.recipientGroupId,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,\n signingKeyPair: input.runtime.crypto.signingKeyPair,\n stillCurrent: input.stillCurrent,\n targetSecretKey,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n input.runtime,\n ),\n });\n if (!shared) {\n return null;\n }\n\n return sharedRemoteContainerStateFromMutation(\n input.previousProjection,\n shared.response,\n );\n}\n\n/**\n * Replays a queued move. `applied` carries the verified head when the server\n * already holds the container under the destination, so nothing is posted.\n */\nexport async function moveRemoteContainer(input: {\n containerId: string;\n onAccepted?: (() => void) | undefined;\n parentContainerId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<\n { applied: AppliedContainerMove } | { moved: RemoteContainer } | null\n> {\n const writer = resolveContainerWriterContext(input.runtime, \"container move\");\n if (!writer) {\n return null;\n }\n const { apiClient, author, execSql, secretKey: targetSecretKey } = writer;\n\n const replayed = await replayRemoteContainerMove({\n reportSecurityIncident: input.runtime.util.reportSecurityIncident,\n apiClient,\n author,\n containerId: input.containerId,\n destinationParentContainerId: input.parentContainerId,\n execSql,\n onAccepted: input.onAccepted,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n targetSecretKey,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n input.runtime,\n ),\n });\n if (!replayed || \"applied\" in replayed) {\n return replayed;\n }\n\n const { response } = replayed;\n return {\n moved: {\n createdAt: response.createdAt,\n effectiveAccessLevel: \"admin\",\n id: response.containerId,\n organizationId: response.organizationId,\n parentId: response.parentId,\n metadataDocumentId: readContainerMutationMetadataDocumentId({ response }),\n metadataAccessEpoch: response.manifestHead.epoch,\n metadataAccessStateHash: response.manifestHead.manifestHash,\n metadataReferencedPrincipals:\n referencedPrincipalHeadsFromContainerMutationResponse({ response }),\n updatedAt: response.updatedAt,\n },\n };\n}\n\nexport async function deleteRemoteContainer(input: {\n containerId: string;\n organizationId: string;\n requiredAncestorId?: string | undefined;\n runtime: ContainerWorkflowRuntime;\n}): Promise<{ deletedAt: string } | null> {\n const deleteResult = await input.runtime.apiClient.deleteContainerResult(\n input.containerId,\n {\n expectedPaymentRequiredOrganizationId: input.organizationId,\n reportErrors: false,\n requiredAncestorId: input.requiredAncestorId,\n },\n );\n if (!deleteResult.ok && !isContainerNotFoundFailure(deleteResult)) {\n deleteResult.report();\n return null;\n }\n\n if (!deleteResult.ok) {\n // A 404 proves this immutable id is permanently absent, but it does not\n // carry the server deletion time. A maximal fence prevents an older\n // in-flight listing page from resurrecting it.\n return { deletedAt: \"9999-12-31T23:59:59.999Z\" };\n }\n\n return { deletedAt: deleteResult.data.deletedAt };\n}\n\n/** Best-effort delete of a remote container whose local folder is gone. */\nexport async function discardOrphanedRemoteContainer(input: {\n created: CreatedRemoteContainerState;\n isCurrent: () => boolean;\n state: Pick<ContainerCreateIntentSyncState, \"runtime\">;\n}): Promise<void> {\n if (!input.isCurrent()) {\n return;\n }\n const discardFailure = await deleteRemoteContainer({\n containerId: input.created.containerId,\n organizationId: input.created.organizationId,\n runtime: input.state.runtime,\n }).then(\n (deleted) => (deleted ? null : \"the server rejected the delete\"),\n (error: unknown) => errorMessage(error),\n );\n if (input.isCurrent() && discardFailure !== null) {\n input.state.runtime.util.log(\n `Container contents: failed to discard orphaned remote container ${input.created.containerId} after local delete: ${discardFailure}`,\n );\n }\n}\n"]}
1
+ {"version":3,"file":"remote.js","sourceRoot":"","sources":["remote.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,0BAA0B,EAAE,MAAM,kDAAkD,CAAC;AAE9F,OAAO,EAAE,oCAAoC,EAAE,MAAM,kEAAkE,CAAC;AACxH,OAAO,EAAE,YAAY,EAAE,MAAM,mCAAmC,CAAC;AACjE,OAAO,EAEL,uCAAuC,EACvC,qDAAqD,EACrD,yBAAyB,EACzB,oBAAoB,IAAI,4BAA4B,GACrD,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,2BAA2B,EAAE,MAAM,iBAAiB,CAAC;AAC9D,OAAO,EAAE,gCAAgC,EAAE,MAAM,wDAAwD,CAAC;AAC1G,OAAO,EAAE,8BAA8B,EAAE,MAAM,gCAAgC,CAAC;AAChF,OAAO,EAAE,kCAAkC,EAAE,MAAM,sCAAsC,CAAC;AAC1F,OAAO,EAEL,yCAAyC,GAC1C,MAAM,6BAA6B,CAAC;AASrC;;;;GAIG;AACH,SAAS,6BAA6B,CACpC,OAAiC,EACjC,SAIqB;IAErB,MAAM,MAAM,GAAG,2BAA2B,CAAC,OAAO,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,KAAK,IAAI,EAAE,CAAC;QACjD,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAC1B,mEAAmE,KAAK,CAAC,OAAO,CAAC,WAAW,wBAAwB,cAAc,EAAE,CACrI,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type {\n ContainerMutationResponse,\n ContainerWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { isContainerNotFoundFailure } from \"../../../data/containers/shared/mutationFailures\";\nimport type { ProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { errorMessage } from \"../../../data/shared/errorMessage\";\nimport {\n type AppliedContainerMove,\n readContainerMutationMetadataDocumentId,\n referencedPrincipalHeadsFromContainerMutationResponse,\n replayRemoteContainerMove,\n shareRemoteContainer as shareRemoteContainerMutation,\n} from \"../../containers\";\nimport { resolveDocumentCreateAuthor } from \"../../documents\";\nimport { createRuntimeGroupMetadataAccess } from \"../../organizations/groupMetadata/groupMetadataRuntime\";\nimport { createRuntimeCurrentGroupShare } from \"../../organizations/groupShare\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../../principals/runtimePolicyWarmer\";\nimport {\n type ContainerAlreadyCommitted,\n createRemoteContainerWithMetadataDocument,\n} from \"./create/createWithMetadata\";\nimport type {\n ContainerCreateIntentSyncState,\n ContainerWorkflowRuntime,\n CreatedRemoteContainerState,\n RemoteContainer,\n SharedRemoteContainerState,\n} from \"./types\";\n\n/**\n * Resolve the author, api client, executor, and encapsulation secret a remote\n * container mutation needs, logging a skip for the given operation when the\n * writer context is unavailable.\n */\nfunction resolveContainerWriterContext(\n runtime: ContainerWorkflowRuntime,\n operation:\n | \"container create\"\n | \"container group share\"\n | \"container move\"\n | \"container share\",\n) {\n const author = resolveDocumentCreateAuthor(runtime);\n const secretKey = runtime.crypto.encapsulationKeyPair?.secretKey;\n if (!author || !secretKey) {\n runtime.util.log(\n `Container contents: skipped ${operation} because the writer context is unavailable.`,\n );\n return null;\n }\n\n return {\n apiClient: runtime.apiClient,\n author,\n execSql: runtime.infra.execSql,\n secretKey,\n };\n}\n\nexport async function createRemoteContainer(input: {\n systemSlot?: ContainerSystemSlot | null | undefined;\n containerId: string;\n metadataSeedUpdate?: Parameters<\n typeof createRemoteContainerWithMetadataDocument\n >[0][\"metadataSeedUpdate\"];\n parentContainerId: string;\n parentProjection?: ContainerWriterProjectionResponse | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<CreatedRemoteContainerState | ContainerAlreadyCommitted | null> {\n return createRemoteContainerWithMetadataDocument(input);\n}\n\nfunction sharedRemoteContainerStateFromMutation(\n previousProjection: ContainerWriterProjectionResponse,\n response: ContainerMutationResponse,\n): SharedRemoteContainerState {\n if (\n response.containerId !== previousProjection.containerId ||\n response.organizationId !== previousProjection.organizationId\n )\n throw new Error(\"Container mutation response projection mismatch\");\n return {\n accessManifestHash: response.manifestHead.manifestHash,\n accessEpoch: response.manifestHead.epoch,\n createdAt: response.createdAt,\n metadataDocumentId: readContainerMutationMetadataDocumentId({ response }),\n referencedPrincipalHeads:\n referencedPrincipalHeadsFromContainerMutationResponse({ response }),\n updatedAt: response.updatedAt,\n // The next read obtains the post-commit proof. A failed read cannot undo\n // acknowledgement of this successful mutation.\n writerProjection: null,\n };\n}\n\nexport async function shareRemoteContainer(input: {\n accessLevel: \"read\" | \"write\" | \"admin\";\n containerId: string;\n previousProjection: ContainerWriterProjectionResponse;\n recipientUserId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<SharedRemoteContainerState | null> {\n const writer = resolveContainerWriterContext(\n input.runtime,\n \"container share\",\n );\n if (!writer) {\n return null;\n }\n const { apiClient, author, execSql, secretKey: targetSecretKey } = writer;\n\n const shared = await shareRemoteContainerMutation({\n reportSecurityIncident: input.runtime.util.reportSecurityIncident,\n accessLevel: input.accessLevel,\n apiClient,\n author,\n containerId: input.containerId,\n execSql,\n previousProjection: input.previousProjection,\n recipientUserId: input.recipientUserId,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n targetSecretKey,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n input.runtime,\n ),\n });\n if (!shared) {\n return null;\n }\n\n return sharedRemoteContainerStateFromMutation(\n input.previousProjection,\n shared.response,\n );\n}\n\nexport async function shareRemoteContainerWithGroup(input: {\n accessLevel: \"read\" | \"write\" | \"admin\";\n containerId: string;\n expectedGroupName?: string | undefined;\n knownContainerKeks?: ReadonlyMap<string, Uint8Array> | undefined;\n previousProjection: ContainerWriterProjectionResponse;\n recipientGroupId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<SharedRemoteContainerState | null> {\n const writer = resolveContainerWriterContext(\n input.runtime,\n \"container group share\",\n );\n if (!writer) {\n return null;\n }\n const { apiClient, author, execSql, secretKey: targetSecretKey } = writer;\n\n const shareWithGroup = createRuntimeCurrentGroupShare(input.runtime);\n if (!shareWithGroup)\n throw new ProjectionDependencyUnavailableError(\n \"Group sharing requires private paged recovery\",\n );\n const shared = await shareWithGroup({\n reportSecurityIncident: input.runtime.util.reportSecurityIncident,\n accessLevel: input.accessLevel,\n apiClient,\n author,\n containerId: input.containerId,\n execSql,\n expectedGroupName: input.expectedGroupName ?? null,\n readEncryptedName: (bundle) =>\n createRuntimeGroupMetadataAccess(\n input.runtime,\n author.organizationId,\n input.stillCurrent,\n ).readName(bundle),\n knownContainerKeks: input.knownContainerKeks,\n previousProjection: input.previousProjection,\n recipientGroupId: input.recipientGroupId,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,\n signingKeyPair: input.runtime.crypto.signingKeyPair,\n stillCurrent: input.stillCurrent,\n targetSecretKey,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n input.runtime,\n ),\n });\n if (!shared) {\n return null;\n }\n\n return sharedRemoteContainerStateFromMutation(\n input.previousProjection,\n shared.response,\n );\n}\n\n/**\n * Replays a queued move. `applied` carries the verified head when the server\n * already holds the container under the destination, so nothing is posted.\n */\nexport async function moveRemoteContainer(input: {\n containerId: string;\n onAccepted?: (() => void) | undefined;\n parentContainerId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<\n { applied: AppliedContainerMove } | { moved: RemoteContainer } | null\n> {\n const writer = resolveContainerWriterContext(input.runtime, \"container move\");\n if (!writer) {\n return null;\n }\n const { apiClient, author, execSql, secretKey: targetSecretKey } = writer;\n\n const replayed = await replayRemoteContainerMove({\n reportSecurityIncident: input.runtime.util.reportSecurityIncident,\n apiClient,\n author,\n containerId: input.containerId,\n destinationParentContainerId: input.parentContainerId,\n execSql,\n onAccepted: input.onAccepted,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n targetSecretKey,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n input.runtime,\n ),\n });\n if (!replayed || \"applied\" in replayed) {\n return replayed;\n }\n\n const { response } = replayed;\n return {\n moved: {\n createdAt: response.createdAt,\n effectiveAccessLevel: \"admin\",\n id: response.containerId,\n organizationId: response.organizationId,\n parentId: response.parentId,\n metadataDocumentId: readContainerMutationMetadataDocumentId({ response }),\n metadataAccessEpoch: response.manifestHead.epoch,\n metadataAccessStateHash: response.manifestHead.manifestHash,\n metadataReferencedPrincipals:\n referencedPrincipalHeadsFromContainerMutationResponse({ response }),\n updatedAt: response.updatedAt,\n },\n };\n}\n\nexport async function deleteRemoteContainer(input: {\n containerId: string;\n organizationId: string;\n requiredAncestorId?: string | undefined;\n runtime: ContainerWorkflowRuntime;\n}): Promise<{ deletedAt: string } | null> {\n const deleteResult = await input.runtime.apiClient.deleteContainerResult(\n input.containerId,\n {\n expectedPaymentRequiredOrganizationId: input.organizationId,\n reportErrors: false,\n requiredAncestorId: input.requiredAncestorId,\n },\n );\n if (!deleteResult.ok && !isContainerNotFoundFailure(deleteResult)) {\n deleteResult.report();\n return null;\n }\n\n if (!deleteResult.ok) {\n // A 404 proves this immutable id is permanently absent, but it does not\n // carry the server deletion time. A maximal fence prevents an older\n // in-flight listing page from resurrecting it.\n return { deletedAt: \"9999-12-31T23:59:59.999Z\" };\n }\n\n return { deletedAt: deleteResult.data.deletedAt };\n}\n\n/** Best-effort delete of a remote container whose local folder is gone. */\nexport async function discardOrphanedRemoteContainer(input: {\n created: CreatedRemoteContainerState;\n isCurrent: () => boolean;\n state: Pick<ContainerCreateIntentSyncState, \"runtime\">;\n}): Promise<void> {\n if (!input.isCurrent()) {\n return;\n }\n const discardFailure = await deleteRemoteContainer({\n containerId: input.created.containerId,\n organizationId: input.created.organizationId,\n runtime: input.state.runtime,\n }).then(\n (deleted) => (deleted ? null : \"the server rejected the delete\"),\n (error: unknown) => errorMessage(error),\n );\n if (input.isCurrent() && discardFailure !== null) {\n input.state.runtime.util.log(\n `Container contents: failed to discard orphaned remote container ${input.created.containerId} after local delete: ${discardFailure}`,\n );\n }\n}\n"]}
@@ -3,7 +3,7 @@ import { nullOnProjectionVerificationCancellation, verifyContainerWriterProjecti
3
3
  import { ProjectionDependencyUnavailableError } from "../../../../data/keyingProjectionVerification/dependencyUnavailable.js";
4
4
  import { principalPolicyCacheForVerifiedPolicies } from "../../../../data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js";
5
5
  import { referencedPrincipalHeadFromPolicy } from "../../../containers/index.js";
6
- import { createRuntimeCurrentSharePrincipalPolicy } from "../../../containers/child/share/currentSharePrincipalPolicy.js";
6
+ import { createRuntimeCurrentSharePrincipalPolicy } from "../../../organizations/groupShare/index.js";
7
7
  import { createRuntimePrincipalPolicyWarmer } from "../../../principals/runtimePolicyWarmer.js";
8
8
  import { loadContainerWriterProjectionForState } from "../projectionCache.js";
9
9
  function projectionHasCurrentGroupGrant(input) {
@@ -1 +1 @@
1
- {"version":3,"file":"groupGrantVerification.js","sourceRoot":"","sources":["groupGrantVerification.ts"],"names":[],"mappings":"AACA,OAAO,EACL,yBAAyB,EACzB,kBAAkB,GACnB,MAAM,+CAA+C,CAAC;AACvD,OAAO,EACL,wCAAwC,EAExC,+BAA+B,GAChC,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,oCAAoC,EAAE,MAAM,qEAAqE,CAAC;AAC3H,OAAO,EAAE,uCAAuC,EAAE,MAAM,oFAAoF,CAAC;AAC7I,OAAO,EAAE,iCAAiC,EAAE,MAAM,qBAAqB,CAAC;AACxE,OAAO,EAAE,wCAAwC,EAAE,MAAM,6DAA6D,CAAC;AACvH,OAAO,EAAE,kCAAkC,EAAE,MAAM,yCAAyC,CAAC;AAE7F,OAAO,EAAE,qCAAqC,EAAE,MAAM,oBAAoB,CAAC;AAK3E,SAAS,8BAA8B,CAAC,KASvC;IACC,MAAM,KAAK,GAAG,kBAAkB,CAC9B,yBAAyB,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,QAAQ,CACrD,CAAC;IACF,OAAO,CACL,KAAK,CAAC,WAAW,KAAK,KAAK,CAAC,mBAAmB;QAC/C,KAAK,CAAC,cAAc,KAAK,KAAK,CAAC,sBAAsB;QACrD,KAAK,CAAC,YAAY,CAAC,IAAI,CACrB,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,WAAW,KAAK,OAAO;YAC7B,KAAK,CAAC,SAAS,KAAK,KAAK,CAAC,OAAO;YACjC,KAAK,CAAC,WAAW,KAAK,KAAK,CAAC,WAAW,CAC1C;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C,KAAK,CAAC,OAAO,CAAC,CAAC;IAC5E,IAAI,CAAC,WAAW;QACd,MAAM,IAAI,oCAAoC,CAC5C,+CAA+C,CAChD,CAAC;IACJ,OAAO,WAAW,CAChB;QACE,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,cAAc,EAAE,KAAK,CAAC,sBAAsB;QAC5C,YAAY,EAAE,KAAK,CAAC,YAAY,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC;KACjD,EACD,KAAK,EAAE,EAAE,kBAAkB,EAAE,MAAM,EAAE,YAAY,EAAE,EAAE,EAAE;QACrD,MAAM,+BAA+B,CAAC;YACpC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO;YACpC,oBAAoB,EAClB,uCAAuC,CAAC,kBAAkB,CAAC;YAC7D,UAAU;YACV,cAAc,EAAE,KAAK,CAAC,wBAAwB;YAC9C,YAAY;YACZ,+BAA+B,EAAE,kCAAkC,CACjE,KAAK,CAAC,OAAO,CACd;SACF,CAAC,CAAC;QACH,OAAO,8BAA8B,CAAC;YACpC,WAAW,EAAE,KAAK,CAAC,WAAW;YAC9B,WAAW,EAAE,iCAAiC,CAAC,MAAM,CAAC;YACtD,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;YAC9C,sBAAsB,EAAE,KAAK,CAAC,sBAAsB;YACpD,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,UAAU;SACX,CAAC,CAAC;IACL,CAAC,CACF,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,kCAAkC,CACtD,KAAuE;IAEvE,OAAO,CACL,CAAC,MAAM,wCAAwC,CAAC,GAAG,EAAE,CACnD,0CAA0C,CAAC,KAAK,CAAC,CAClD,CAAC,IAAI,KAAK,CACZ,CAAC;AACJ,CAAC","sourcesContent":["import type { ReferencedPrincipalHead } from \"@tearleads/crypto\";\nimport {\n getTargetContainerContext,\n readContainerState,\n} from \"../../../../data/containers/shared/projection\";\nimport {\n nullOnProjectionVerificationCancellation,\n type ProjectionUserKeyResolver,\n verifyContainerWriterProjection,\n} from \"../../../../data/keyingProjectionVerification\";\nimport { ProjectionDependencyUnavailableError } from \"../../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { principalPolicyCacheForVerifiedPolicies } from \"../../../../data/keyingProjectionVerification/principalPolicy/principalPolicyCache\";\nimport { referencedPrincipalHeadFromPolicy } from \"../../../containers\";\nimport { createRuntimeCurrentSharePrincipalPolicy } from \"../../../containers/child/share/currentSharePrincipalPolicy\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../../../principals/runtimePolicyWarmer\";\nimport type { ContainerState } from \"../../remoteHydration\";\nimport { loadContainerWriterProjectionForState } from \"../projectionCache\";\nimport type { ContainerWorkflowRuntime } from \"../types\";\n\ntype GroupGrantAccessLevel = \"read\" | \"write\" | \"admin\";\n\nfunction projectionHasCurrentGroupGrant(input: {\n accessLevel: GroupGrantAccessLevel;\n expectedContainerId: string;\n expectedOrganizationId: string;\n groupId: string;\n currentHead: ReferencedPrincipalHead;\n projection: NonNullable<\n Awaited<ReturnType<typeof loadContainerWriterProjectionForState>>\n >;\n}): boolean {\n const state = readContainerState(\n getTargetContainerContext(input.projection).manifest,\n );\n return (\n state.containerId === input.expectedContainerId &&\n state.organizationId === input.expectedOrganizationId &&\n state.directGrants.some(\n (grant) =>\n grant.subjectType === \"group\" &&\n grant.subjectId === input.groupId &&\n grant.accessLevel === input.accessLevel,\n ) &&\n state.referencedPrincipalHeads.some(\n (head) =>\n head.principalType === input.currentHead.principalType &&\n head.principalId === input.currentHead.principalId &&\n head.version === input.currentHead.version &&\n head.keyEpoch === input.currentHead.keyEpoch &&\n head.stateHash === input.currentHead.stateHash &&\n head.keyFingerprint === input.currentHead.keyFingerprint,\n )\n );\n}\n\nasync function containerStateHasCurrentGroupGrantInternal(input: {\n accessLevel: GroupGrantAccessLevel;\n containerState: ContainerState;\n expectedContainerId: string;\n expectedGroupHead: ReferencedPrincipalHead;\n expectedOrganizationId: string;\n groupId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<boolean> {\n if (input.stillCurrent?.() === false) return false;\n const projection = await loadContainerWriterProjectionForState({\n containerState: input.containerState,\n runtime: input.runtime,\n });\n if (\n !projection ||\n input.stillCurrent?.() === false ||\n input.expectedGroupHead.principalType !== \"group\" ||\n input.expectedGroupHead.principalId !== input.groupId ||\n input.containerState.container.id !== input.expectedContainerId ||\n input.containerState.container.organizationId !==\n input.expectedOrganizationId ||\n projection.containerId !== input.expectedContainerId ||\n projection.organizationId !== input.expectedOrganizationId\n ) {\n return false;\n }\n\n const readCurrent = createRuntimeCurrentSharePrincipalPolicy(input.runtime);\n if (!readCurrent)\n throw new ProjectionDependencyUnavailableError(\n \"Group sharing requires private paged recovery\",\n );\n return readCurrent(\n {\n expectedGroupHead: input.expectedGroupHead,\n groupId: input.groupId,\n organizationId: input.expectedOrganizationId,\n stillCurrent: input.stillCurrent ?? (() => true),\n },\n async ({ checkpointPolicies, policy, stillCurrent }) => {\n await verifyContainerWriterProjection({\n execSql: input.runtime.infra.execSql,\n principalPolicyCache:\n principalPolicyCacheForVerifiedPolicies(checkpointPolicies),\n projection,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n input.runtime,\n ),\n });\n return projectionHasCurrentGroupGrant({\n accessLevel: input.accessLevel,\n currentHead: referencedPrincipalHeadFromPolicy(policy),\n expectedContainerId: input.expectedContainerId,\n expectedOrganizationId: input.expectedOrganizationId,\n groupId: input.groupId,\n projection,\n });\n },\n );\n}\n\nexport async function containerStateHasCurrentGroupGrant(\n input: Parameters<typeof containerStateHasCurrentGroupGrantInternal>[0],\n): Promise<boolean> {\n return (\n (await nullOnProjectionVerificationCancellation(() =>\n containerStateHasCurrentGroupGrantInternal(input),\n )) ?? false\n );\n}\n"]}
1
+ {"version":3,"file":"groupGrantVerification.js","sourceRoot":"","sources":["groupGrantVerification.ts"],"names":[],"mappings":"AACA,OAAO,EACL,yBAAyB,EACzB,kBAAkB,GACnB,MAAM,+CAA+C,CAAC;AACvD,OAAO,EACL,wCAAwC,EAExC,+BAA+B,GAChC,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,oCAAoC,EAAE,MAAM,qEAAqE,CAAC;AAC3H,OAAO,EAAE,uCAAuC,EAAE,MAAM,oFAAoF,CAAC;AAC7I,OAAO,EAAE,iCAAiC,EAAE,MAAM,qBAAqB,CAAC;AACxE,OAAO,EAAE,wCAAwC,EAAE,MAAM,mCAAmC,CAAC;AAC7F,OAAO,EAAE,kCAAkC,EAAE,MAAM,yCAAyC,CAAC;AAE7F,OAAO,EAAE,qCAAqC,EAAE,MAAM,oBAAoB,CAAC;AAK3E,SAAS,8BAA8B,CAAC,KASvC;IACC,MAAM,KAAK,GAAG,kBAAkB,CAC9B,yBAAyB,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,QAAQ,CACrD,CAAC;IACF,OAAO,CACL,KAAK,CAAC,WAAW,KAAK,KAAK,CAAC,mBAAmB;QAC/C,KAAK,CAAC,cAAc,KAAK,KAAK,CAAC,sBAAsB;QACrD,KAAK,CAAC,YAAY,CAAC,IAAI,CACrB,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,WAAW,KAAK,OAAO;YAC7B,KAAK,CAAC,SAAS,KAAK,KAAK,CAAC,OAAO;YACjC,KAAK,CAAC,WAAW,KAAK,KAAK,CAAC,WAAW,CAC1C;QACD,KAAK,CAAC,wBAAwB,CAAC,IAAI,CACjC,CAAC,IAAI,EAAE,EAAE,CACP,IAAI,CAAC,aAAa,KAAK,KAAK,CAAC,WAAW,CAAC,aAAa;YACtD,IAAI,CAAC,WAAW,KAAK,KAAK,CAAC,WAAW,CAAC,WAAW;YAClD,IAAI,CAAC,OAAO,KAAK,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,cAAc,EAAE,KAAK,CAAC,sBAAsB;QAC5C,YAAY,EAAE,KAAK,CAAC,YAAY,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC;KACjD,EACD,KAAK,EAAE,EAAE,kBAAkB,EAAE,MAAM,EAAE,YAAY,EAAE,EAAE,EAAE;QACrD,MAAM,+BAA+B,CAAC;YACpC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO;YACpC,oBAAoB,EAClB,uCAAuC,CAAC,kBAAkB,CAAC;YAC7D,UAAU;YACV,cAAc,EAAE,KAAK,CAAC,wBAAwB;YAC9C,YAAY;YACZ,+BAA+B,EAAE,kCAAkC,CACjE,KAAK,CAAC,OAAO,CACd;SACF,CAAC,CAAC;QACH,OAAO,8BAA8B,CAAC;YACpC,WAAW,EAAE,KAAK,CAAC,WAAW;YAC9B,WAAW,EAAE,iCAAiC,CAAC,MAAM,CAAC;YACtD,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;YAC9C,sBAAsB,EAAE,KAAK,CAAC,sBAAsB;YACpD,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,UAAU;SACX,CAAC,CAAC;IACL,CAAC,CACF,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,kCAAkC,CACtD,KAAuE;IAEvE,OAAO,CACL,CAAC,MAAM,wCAAwC,CAAC,GAAG,EAAE,CACnD,0CAA0C,CAAC,KAAK,CAAC,CAClD,CAAC,IAAI,KAAK,CACZ,CAAC;AACJ,CAAC","sourcesContent":["import type { ReferencedPrincipalHead } from \"@tearleads/crypto\";\nimport {\n getTargetContainerContext,\n readContainerState,\n} from \"../../../../data/containers/shared/projection\";\nimport {\n nullOnProjectionVerificationCancellation,\n type ProjectionUserKeyResolver,\n verifyContainerWriterProjection,\n} from \"../../../../data/keyingProjectionVerification\";\nimport { ProjectionDependencyUnavailableError } from \"../../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { principalPolicyCacheForVerifiedPolicies } from \"../../../../data/keyingProjectionVerification/principalPolicy/principalPolicyCache\";\nimport { referencedPrincipalHeadFromPolicy } from \"../../../containers\";\nimport { createRuntimeCurrentSharePrincipalPolicy } from \"../../../organizations/groupShare\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../../../principals/runtimePolicyWarmer\";\nimport type { ContainerState } from \"../../remoteHydration\";\nimport { loadContainerWriterProjectionForState } from \"../projectionCache\";\nimport type { ContainerWorkflowRuntime } from \"../types\";\n\ntype GroupGrantAccessLevel = \"read\" | \"write\" | \"admin\";\n\nfunction projectionHasCurrentGroupGrant(input: {\n accessLevel: GroupGrantAccessLevel;\n expectedContainerId: string;\n expectedOrganizationId: string;\n groupId: string;\n currentHead: ReferencedPrincipalHead;\n projection: NonNullable<\n Awaited<ReturnType<typeof loadContainerWriterProjectionForState>>\n >;\n}): boolean {\n const state = readContainerState(\n getTargetContainerContext(input.projection).manifest,\n );\n return (\n state.containerId === input.expectedContainerId &&\n state.organizationId === input.expectedOrganizationId &&\n state.directGrants.some(\n (grant) =>\n grant.subjectType === \"group\" &&\n grant.subjectId === input.groupId &&\n grant.accessLevel === input.accessLevel,\n ) &&\n state.referencedPrincipalHeads.some(\n (head) =>\n head.principalType === input.currentHead.principalType &&\n head.principalId === input.currentHead.principalId &&\n head.version === input.currentHead.version &&\n head.keyEpoch === input.currentHead.keyEpoch &&\n head.stateHash === input.currentHead.stateHash &&\n head.keyFingerprint === input.currentHead.keyFingerprint,\n )\n );\n}\n\nasync function containerStateHasCurrentGroupGrantInternal(input: {\n accessLevel: GroupGrantAccessLevel;\n containerState: ContainerState;\n expectedContainerId: string;\n expectedGroupHead: ReferencedPrincipalHead;\n expectedOrganizationId: string;\n groupId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<boolean> {\n if (input.stillCurrent?.() === false) return false;\n const projection = await loadContainerWriterProjectionForState({\n containerState: input.containerState,\n runtime: input.runtime,\n });\n if (\n !projection ||\n input.stillCurrent?.() === false ||\n input.expectedGroupHead.principalType !== \"group\" ||\n input.expectedGroupHead.principalId !== input.groupId ||\n input.containerState.container.id !== input.expectedContainerId ||\n input.containerState.container.organizationId !==\n input.expectedOrganizationId ||\n projection.containerId !== input.expectedContainerId ||\n projection.organizationId !== input.expectedOrganizationId\n ) {\n return false;\n }\n\n const readCurrent = createRuntimeCurrentSharePrincipalPolicy(input.runtime);\n if (!readCurrent)\n throw new ProjectionDependencyUnavailableError(\n \"Group sharing requires private paged recovery\",\n );\n return readCurrent(\n {\n expectedGroupHead: input.expectedGroupHead,\n groupId: input.groupId,\n organizationId: input.expectedOrganizationId,\n stillCurrent: input.stillCurrent ?? (() => true),\n },\n async ({ checkpointPolicies, policy, stillCurrent }) => {\n await verifyContainerWriterProjection({\n execSql: input.runtime.infra.execSql,\n principalPolicyCache:\n principalPolicyCacheForVerifiedPolicies(checkpointPolicies),\n projection,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n input.runtime,\n ),\n });\n return projectionHasCurrentGroupGrant({\n accessLevel: input.accessLevel,\n currentHead: referencedPrincipalHeadFromPolicy(policy),\n expectedContainerId: input.expectedContainerId,\n expectedOrganizationId: input.expectedOrganizationId,\n groupId: input.groupId,\n projection,\n });\n },\n );\n}\n\nexport async function containerStateHasCurrentGroupGrant(\n input: Parameters<typeof containerStateHasCurrentGroupGrantInternal>[0],\n): Promise<boolean> {\n return (\n (await nullOnProjectionVerificationCancellation(() =>\n containerStateHasCurrentGroupGrantInternal(input),\n )) ?? false\n );\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { ProjectionDependencyUnavailableError } from "../../../../data/keyingProjectionVerification/dependencyUnavailable.js";
2
- import { createRuntimeCurrentSharePrincipalPolicy } from "../../../containers/child/share/currentSharePrincipalPolicy.js";
2
+ import { createRuntimeCurrentSharePrincipalPolicy } from "../../../organizations/groupShare/index.js";
3
3
  export async function resolveCurrentGroupKeyEpoch(input) {
4
4
  if (input.stillCurrent?.() === false)
5
5
  return null;