@tearleads/client-sdk 0.1.22 → 0.1.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/client/organizations/organizationGroupHistory.js +4 -7
- package/client/organizations/organizationGroupHistory.js.map +1 -1
- package/client/organizations/organizationReadModels.js +2 -86
- package/client/organizations/organizationReadModels.js.map +1 -1
- package/client/organizations/principalMutations.js +53 -133
- package/client/organizations/principalMutations.js.map +1 -1
- package/client/principalMutationDispatch.js +2 -2
- package/client/principalMutationDispatch.js.map +1 -1
- package/data/keyingProjectionVerification/principalPolicyVerification.js +5 -5
- package/data/keyingProjectionVerification/principalPolicyVerification.js.map +1 -1
- package/data/keyingProjectionVerification/resolvedPrincipalPolicy.js +21 -7
- package/data/keyingProjectionVerification/resolvedPrincipalPolicy.js.map +1 -1
- package/data/keyingProjectionVerification/types.d.ts +1 -8
- package/data/keyingProjectionVerification/types.js +0 -9
- package/data/keyingProjectionVerification/types.js.map +1 -1
- package/data/keyingProjectionVerification.d.ts +1 -1
- package/data/keyingProjectionVerification.js.map +1 -1
- package/data/persistence/documents/documentsPersistence.js +7 -0
- package/data/persistence/documents/documentsPersistence.js.map +1 -1
- package/data/persistence/documents/orphanBlobPersistence.d.ts +13 -0
- package/data/persistence/documents/orphanBlobPersistence.js +2 -0
- package/data/persistence/documents/orphanBlobPersistence.js.map +1 -0
- package/data/persistence/documents/types.d.ts +2 -0
- package/data/persistence/documents/types.js.map +1 -1
- package/data/persistence/principalHistoryPrefixPersistence.d.ts +5 -1
- package/data/persistence/principalHistoryPrefixPersistence.js +22 -5
- package/data/persistence/principalHistoryPrefixPersistence.js.map +1 -1
- package/data/principals/principalMutationJournalShape.d.ts +1 -1
- package/data/principals/principalMutationJournalShape.js +2 -2
- package/data/principals/principalMutationJournalShape.js.map +1 -1
- package/index.js.map +1 -1
- package/package.json +1 -1
- package/stores/documents/documentStore/attachmentHydration.js +2 -2
- package/stores/documents/documentStore/attachmentHydration.js.map +1 -1
- package/stores/documents/documentStore/attachments.js +7 -5
- package/stores/documents/documentStore/attachments.js.map +1 -1
- package/stores/documents/documentStore/discard.js +3 -2
- package/stores/documents/documentStore/discard.js.map +1 -1
- package/stores/documents/documentStore/orphanMaintenance.js +3 -5
- package/stores/documents/documentStore/orphanMaintenance.js.map +1 -1
- package/stores/documents/documentStore/persistence.js +3 -4
- package/stores/documents/documentStore/persistence.js.map +1 -1
- package/stores/documents/documentStore/syncDetachedAttachments.js +3 -2
- package/stores/documents/documentStore/syncDetachedAttachments.js.map +1 -1
- package/stores/documents/documentStore/syncRequest.js +3 -4
- package/stores/documents/documentStore/syncRequest.js.map +1 -1
- package/workflows/container-contents/container-state/groupGrantVerification.js +23 -74
- package/workflows/container-contents/container-state/groupGrantVerification.js.map +1 -1
- package/workflows/container-contents/container-state/groupShareEpoch.js +6 -23
- package/workflows/container-contents/container-state/groupShareEpoch.js.map +1 -1
- package/workflows/container-contents/container-state/remote.js +5 -3
- package/workflows/container-contents/container-state/remote.js.map +1 -1
- package/workflows/container-contents/container-state/types.js.map +1 -1
- package/workflows/container-contents/documentLinks.d.ts +1 -1
- package/workflows/container-contents/documentLinks.js.map +1 -1
- package/workflows/container-contents/documentPurge.d.ts +1 -1
- package/workflows/container-contents/documentPurge.js +4 -4
- package/workflows/container-contents/documentPurge.js.map +1 -1
- package/workflows/container-contents/metadataRemoteSync.d.ts +1 -1
- package/workflows/container-contents/metadataRemoteSync.js.map +1 -1
- package/workflows/container-contents/remoteHydration/types.d.ts +2 -2
- package/workflows/container-contents/remoteHydration/types.js.map +1 -1
- package/workflows/container-contents/remoteHydration/verifiedDestination.js +6 -7
- package/workflows/container-contents/remoteHydration/verifiedDestination.js.map +1 -1
- package/workflows/containers/child/runtimeCurrentGroupShare.js +1 -1
- package/workflows/containers/child/runtimeCurrentGroupShare.js.map +1 -1
- package/workflows/documents/orphanBlobReclaimState.js +20 -0
- package/workflows/documents/orphanBlobReclaimState.js.map +1 -0
- package/workflows/documents/orphanBlobReclaims.d.ts +3 -2
- package/workflows/documents/orphanBlobReclaims.js +49 -47
- package/workflows/documents/orphanBlobReclaims.js.map +1 -1
- package/workflows/organizations/groupMetadataRuntime.js +11 -8
- package/workflows/organizations/groupMetadataRuntime.js.map +1 -1
- package/workflows/organizations/organizationGroupNames.js +8 -55
- package/workflows/organizations/organizationGroupNames.js.map +1 -1
- package/workflows/organizations/principalOperationReceipt.js +1 -1
- package/workflows/organizations/principalOperationReceipt.js.map +1 -1
- package/workflows/organizations/runtimeGroupMetadataAuthority.js +16 -0
- package/workflows/organizations/runtimeGroupMetadataAuthority.js.map +1 -0
- package/workflows/principals/runtimePolicyWarmer.js +29 -27
- package/workflows/principals/runtimePolicyWarmer.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n DocumentProjectorRegistryInput,\n StoredDocumentKind,\n} from \"../../documents/documentKinds\";\nimport type {\n DiscoveredDocumentInput,\n DocumentSummary,\n} from \"../../documents/documentSummary\";\nimport type { DocumentSyncPullContinuation } from \"../../documents/shared/pullContinuation\";\nimport type {\n DocumentRecord as BaseDocumentRecord,\n PendingUpdateFields,\n PendingUpdateRecord,\n} from \"../../sqlite/documentPersistence\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\n\nexport type { PendingUpdateRecord } from \"../../sqlite/documentPersistence\";\n\nexport interface StoredDocumentRecord extends BaseDocumentRecord {\n containerId: string | null;\n documentKind?: StoredDocumentKind;\n text: string;\n title?: string;\n}\n\nexport type DiscardDocumentToShellResult =\n | { discarded: false }\n | {\n discarded: true;\n documentKind: StoredDocumentKind;\n };\n\nexport interface PendingUpdateInsert extends PendingUpdateFields {\n localId: string;\n}\n\n/**\n * The identity a pending attachment upload reuses across attempts so a retry\n * (next sync pass or after a restart) reproduces byte-identical encrypted bytes\n * and resumes the same multipart stage instead of orphaning it. `contentKey` and\n * the chunk `nonceSeed` are base64. `partSize`/`stageId` are filled in once the\n * multipart stage has been opened and remain null before that.\n */\nexport interface PendingAttachmentUploadIdentity {\n blobId: string;\n contentKey: string;\n contentKeyEpoch: number;\n nonceSeed: string;\n partSize: number | null;\n plaintextSha256: string;\n stageId: string | null;\n}\n\nexport interface PendingAttachmentRecord {\n byteLength: number;\n contentSha256: string;\n localId: string;\n mimeType: string | null;\n name: string;\n slotId: string;\n storageKey: string;\n upload?: PendingAttachmentUploadIdentity | null;\n}\n\nexport interface LocalAttachmentRecord {\n blobId: string | null;\n byteLength: number;\n // Plaintext digest of the bytes at `storageKey`. Compared with the digest\n // the document content records for the slot: a held copy that differs is a\n // validly signed served binding the document has not recorded (yet).\n contentSha256: string;\n // Set once the slot is unlinked from a synced document and cleared when the\n // slot is written again. The record survives the unlink so the next sync can\n // still detach the remote binding; `detachedAt` is what keeps the local read\n // models from reporting the slot as a live blob reference in the meantime.\n detachedAt: string | null;\n localId: string;\n mimeType: string | null;\n slotId: string;\n storageKey: string;\n}\n\nexport interface AttachmentStagingRows {\n localAttachments: ReadonlyArray<LocalAttachmentRecord>;\n pendingAttachments: ReadonlyArray<PendingAttachmentRecord>;\n}\n\nexport interface AttachmentRemovalRows {\n mode: \"delete\" | \"detach\";\n slotId: string;\n storageKey: string;\n}\n\nexport interface DocumentHistoryRestoreState {\n snapshot: string;\n tailUpdates: readonly {\n origin: \"local\" | \"remote\";\n updateData: string;\n }[];\n}\n\nexport interface RelinkPersistedDocumentInput {\n accessEpoch: number;\n accessStateHash?: string | null;\n containerId: string;\n documentId: string | null;\n localId: string;\n}\n\nexport interface ContainerDocumentTombstoneInput {\n containerId: string;\n documentId: string;\n /** Epoch of the verified head; apply refuses a head below local state. */\n accessEpoch: number;\n /** Verified head link set (omits `containerId`); apply needs signed evidence. */\n linkedContainerIds: ReadonlyArray<string>;\n updatedAt: string;\n}\n\nexport type DocumentSummarySortDirection = \"asc\" | \"desc\";\nexport type DocumentSummarySortKey = \"kind\" | \"title\" | \"updated\";\n\nexport interface DocumentSummarySort {\n readonly direction: DocumentSummarySortDirection;\n readonly key: DocumentSummarySortKey;\n}\n\nexport interface ListDocumentSummariesInput {\n documentKind?: StoredDocumentKind | undefined;\n limit?: number | undefined;\n offset?: number | undefined;\n sort?: DocumentSummarySort | undefined;\n}\n\nexport interface DocumentSummaryList {\n readonly rows: ReadonlyArray<DocumentSummary>;\n readonly totalCount: number;\n}\n\nexport interface DocumentsPersistence {\n /**\n * The adapter guarantees that recovery checkpoint replacement, selection of\n * covered local history, rejection of unproven ordinary pending rows, and\n * quarantine of every queued checkpoint artifact share the guarded\n * `commitDocumentMutation` transaction, which also advances the canonical\n * recovery generation. An unrelated history tail not covered by the rebuild\n * must abort that transaction.\n */\n readonly supportsAtomicRecoveryHistoryPruning: boolean;\n /**\n * Atomically create the canonical row, standard projections, and birth\n * checkpoint. Returns null when another initializer already owns localId.\n */\n createDocumentWithHistoryCheckpoint: (\n execSql: ExecSql,\n document: StoredDocumentRecord,\n historyCheckpoint: {\n endVersionVector: string;\n snapshot: string;\n },\n options:\n | {\n pendingUpdate?: PendingUpdateFields;\n /** Recheck volatile caller ownership inside the create transaction. */\n stillCurrent?: (() => boolean) | undefined;\n updatedAt?: string;\n }\n | undefined,\n saveClientProjection: (\n transactionExecSql: ExecSql,\n updatedAt: string,\n ) => Promise<void>,\n ) => Promise<string | null>;\n /**\n * Conditionally commit one already-prepared mutation against the exact\n * durable record it was derived from. The identity/progress comparison,\n * attachment and history writes, accepted-queue settlement,\n * canonical/projection save, and client projection callback must share one\n * adapter transaction.\n */\n commitDocumentMutation: (\n execSql: ExecSql,\n input: {\n acceptedPendingUpdateIds: readonly string[];\n attachmentRemoval?: AttachmentRemovalRows | undefined;\n attachmentStaging?: AttachmentStagingRows | undefined;\n clearSyncFailure?: boolean | undefined;\n document: StoredDocumentRecord;\n expectedRecord: StoredDocumentRecord;\n historyCheckpoint?:\n | {\n coveredTailIds: readonly string[];\n endVersionVector: string;\n pruneCoveredLocalState: boolean;\n snapshot: string;\n }\n | undefined;\n historyUpdateOrigin?: \"local\" | \"remote\" | undefined;\n historyUpdates?: readonly string[] | undefined;\n pendingUpdate?: PendingUpdateFields | undefined;\n settleAcceptedPendingOnConflict: boolean;\n /**\n * Recheck volatile caller ownership inside the adapter transaction,\n * before any durable side effect. A false result aborts the commit.\n */\n stillCurrent?: (() => boolean) | undefined;\n updatedAt?: string | undefined;\n },\n saveClientProjection: (\n transactionExecSql: ExecSql,\n updatedAt: string,\n ) => Promise<void>,\n ) => Promise<\n | { committed: true; updatedAt: string }\n | { committed: false; currentRecord: StoredDocumentRecord | null }\n >;\n /** Settle acknowledged rows only while the response's security identity survives. */\n settleAcceptedPendingUpdates: (\n execSql: ExecSql,\n input: {\n expectedRecord: StoredDocumentRecord;\n pendingUpdateIds: readonly string[];\n },\n ) => Promise<StoredDocumentRecord | null>;\n ensureSchema: (execSql: ExecSql) => Promise<void>;\n listDocuments: (execSql: ExecSql) => Promise<DocumentSummary[]>;\n listDocumentSummaries: (\n execSql: ExecSql,\n input?: ListDocumentSummariesInput,\n ) => Promise<DocumentSummaryList>;\n listDocumentsByContainerIdsOrDocumentIds: (\n execSql: ExecSql,\n input: {\n containerIds: ReadonlyArray<string>;\n documentIds: ReadonlyArray<string>;\n },\n ) => Promise<DocumentSummary[]>;\n findDocumentLocalIdsByContainerId: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<string[]>;\n /**\n * Select one local row for a remote document identity. Prefer any row with\n * queued updates or a deferred-sync frontier, then break duplicates by\n * updatedAt and localId descending.\n */\n findLocalIdByDocumentId: (\n execSql: ExecSql,\n documentId: string,\n ) => Promise<string | null>;\n /** Canonical-row probe; false authorizes destructive orphan teardown. */\n hasDocument: (execSql: ExecSql, localId: string) => Promise<boolean>;\n /** Observe whether the canonical row still names the expected remote stream. */\n documentIdentityMatches: (\n execSql: ExecSql,\n localId: string,\n expectedDocumentId: string | null,\n expectedRecoveryGeneration: number,\n ) => Promise<boolean>;\n loadDocument: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<StoredDocumentRecord | null>;\n /** Read the canonical record and its history from one database snapshot. */\n loadDocumentWithHistoryRestoreState: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{\n document: StoredDocumentRecord | null;\n historyRestoreState: DocumentHistoryRestoreState | null;\n }>;\n /** Read every document-store startup row from one database snapshot. */\n loadDocumentStoreState: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{\n document: StoredDocumentRecord | null;\n historyRestoreState: DocumentHistoryRestoreState | null;\n localAttachments: LocalAttachmentRecord[];\n pendingAttachments: PendingAttachmentRecord[];\n }>;\n /**\n * Atomically replace the exact rejected pull continuation with the durable\n * recovery marker when every supplied sync-identity field still matches.\n * Return the authoritative current record after the compare-and-set, or\n * null when the canonical row no longer exists. A CAS loss returns the\n * winning record so the live store can adopt its newer progress.\n */\n invalidatePullContinuation: (\n execSql: ExecSql,\n input: {\n accessEpoch: number;\n accessStateHash: string | null;\n continuation: DocumentSyncPullContinuation;\n contentKeyBundle: string | null;\n documentId: string;\n documentKekTargets: string | null;\n documentManifestBundle: string | null;\n lastCommitLsn: string | null;\n localId: string;\n },\n ) => Promise<{\n historyRestoreState: DocumentHistoryRestoreState | null;\n record: StoredDocumentRecord;\n } | null>;\n // Read the authoritative container placement for a locally persisted document\n // straight from its projection row. Returns `undefined` when no projection row\n // exists yet (a first create/discovery persist), so a caller can distinguish\n // that from a row that legitimately carries a null container (a document\n // unlinked from every container). Container placement is owned by the\n // link/tombstone/discovery layer, so a content-metadata persist reads this to\n // avoid republishing a stale in-memory container.\n loadDocumentContainer: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{ containerId: string | null } | undefined>;\n saveDocument: (\n execSql: ExecSql,\n document: StoredDocumentRecord,\n options?: {\n updatedAt?: string;\n },\n ) => Promise<string>;\n /**\n * Durable full-history support (checkpoint + append-only tail) — the ONLY\n * persisted content source. REQUIRED: a persistence without these could\n * report successful writes whose documents reopen empty.\n */\n appendHistoryUpdates: (\n execSql: ExecSql,\n input: {\n localId: string;\n origin: \"local\" | \"remote\";\n updates: readonly string[];\n },\n ) => Promise<void>;\n loadHistoryRestoreState: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<DocumentHistoryRestoreState | null>;\n readHistoryTailSize: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{\n byteLength: number;\n hasCheckpoint: boolean;\n rowCount: number;\n }>;\n listHistoryTailEntries: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{ id: string; updateData: string }[]>;\n replaceHistoryCheckpoint: (\n execSql: ExecSql,\n input: {\n coveredTailIds: readonly string[];\n endVersionVector: string;\n force?: boolean;\n localId: string;\n snapshot: string;\n stillCurrent?: () => boolean;\n },\n ) => Promise<void>;\n saveDocumentAndDeletePendingUpdates: (\n execSql: ExecSql,\n document: StoredDocumentRecord,\n pendingUpdateIds: readonly string[],\n options?: {\n updatedAt?: string;\n },\n ) => Promise<string>;\n deleteDocument: (execSql: ExecSql, localId: string) => Promise<void>;\n /**\n * Delete the canonical row and every side row only when its security identity\n * still matches the captured record. The comparison, deletes, and client\n * projection callback must share one write transaction.\n */\n deleteDocumentIfMatches: (\n execSql: ExecSql,\n expectedRecord: StoredDocumentRecord,\n deleteClientProjection: (transactionExecSql: ExecSql) => Promise<void>,\n ) => Promise<boolean>;\n /**\n * Delete orphaned side rows only if the canonical document is still absent.\n * The absence check, row cleanup, and client projection callback must share\n * one write transaction so a concurrent create is preserved.\n */\n deleteDocumentSideRowsIfAbsent: (\n execSql: ExecSql,\n localId: string,\n expectedDocumentId: string | null,\n deleteClientProjection: (transactionExecSql: ExecSql) => Promise<void>,\n ) => Promise<boolean>;\n upsertDiscoveredDocument: (\n execSql: ExecSql,\n input: DiscoveredDocumentInput,\n ) => Promise<DocumentSummary>;\n relinkPersistedDocument: (\n execSql: ExecSql,\n input: RelinkPersistedDocumentInput,\n ) => Promise<DocumentSummary | null>;\n listPendingUpdates: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<PendingUpdateRecord[]>;\n rekeyPendingUpdate: (execSql: ExecSql, id: string) => Promise<string | null>;\n listPendingAttachments: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<PendingAttachmentRecord[]>;\n listLocalAttachments: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<LocalAttachmentRecord[]>;\n /**\n * Durably append the outgoing row and matching local-history tail entry.\n * When expectations are supplied, compare the document identity and recovery\n * generation with the canonical row inside that same mutation and return\n * false on absence or mismatch. Adapters must not insert either row.\n */\n enqueuePendingUpdate: (\n execSql: ExecSql,\n pendingUpdate: PendingUpdateInsert,\n options?: {\n expectedDocumentId: string | null;\n expectedRecoveryGeneration: number;\n },\n ) => Promise<boolean>;\n /** Replace a hydrated copy only if its observed durable slot and live document still match. */\n saveHydratedAttachment: (\n execSql: ExecSql,\n input: {\n attachment: LocalAttachmentRecord;\n expectedStorageKey: string | null;\n expectedSnapshotEndVersion: string | null;\n stillCurrent: () => boolean;\n },\n ) => Promise<boolean>;\n saveLocalAttachment: (\n execSql: ExecSql,\n attachment: LocalAttachmentRecord,\n ) => Promise<void>;\n deleteLocalAttachment: (\n execSql: ExecSql,\n localId: string,\n slotId: string,\n storageKey: string,\n ) => Promise<void>;\n markLocalAttachmentDetached: (\n execSql: ExecSql,\n localId: string,\n slotId: string,\n storageKey: string,\n ) => Promise<void>;\n savePendingAttachment: (\n execSql: ExecSql,\n attachment: PendingAttachmentRecord,\n ) => Promise<void>;\n deletePendingUpdate: (execSql: ExecSql, id: string) => Promise<void>;\n deletePendingUpdates: (execSql: ExecSql, localId: string) => Promise<void>;\n deletePendingAttachment: (\n execSql: ExecSql,\n localId: string,\n slotId: string,\n storageKey: string,\n ) => Promise<void>;\n deletePendingAttachments: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<void>;\n /**\n * Atomically convert a stuck document's local state to the\n * freshly-discovered-share shell (see the SQL implementation's doc\n * comment). The projector registry clears the document-kind client\n * projection in the same transaction — those tables live with the app's\n * projector definitions, so the CALLER'S registry is required (the default\n * registry knows no app kinds, and a discard that silently kept a\n * contact's or card's projected fields would leak the discarded values).\n * The method itself is optional: implementations without the full document\n * schema (container metadata, simple doubles) simply do not offer the\n * discard escape hatch.\n */\n /**\n * `expectedDocumentId` is revalidated against the loaded record inside the\n * serialized mutation: a stale caller (or a relink that raced the request)\n * must never discard a different identity's edits.\n */\n discardDocumentToShell?: (\n execSql: ExecSql,\n localId: string,\n expectedDocumentId: string,\n documentProjectors: DocumentProjectorRegistryInput,\n ) => Promise<DiscardDocumentToShellResult>;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n DocumentProjectorRegistryInput,\n StoredDocumentKind,\n} from \"../../documents/documentKinds\";\nimport type {\n DiscoveredDocumentInput,\n DocumentSummary,\n} from \"../../documents/documentSummary\";\nimport type { DocumentSyncPullContinuation } from \"../../documents/shared/pullContinuation\";\nimport type {\n DocumentRecord as BaseDocumentRecord,\n PendingUpdateFields,\n PendingUpdateRecord,\n} from \"../../sqlite/documentPersistence\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport type { DocumentOrphanBlobPersistence } from \"./orphanBlobPersistence\";\n\nexport type { PendingUpdateRecord } from \"../../sqlite/documentPersistence\";\n\nexport interface StoredDocumentRecord extends BaseDocumentRecord {\n containerId: string | null;\n documentKind?: StoredDocumentKind;\n text: string;\n title?: string;\n}\n\nexport type DiscardDocumentToShellResult =\n | { discarded: false }\n | {\n discarded: true;\n documentKind: StoredDocumentKind;\n };\n\nexport interface PendingUpdateInsert extends PendingUpdateFields {\n localId: string;\n}\n\n/**\n * The identity a pending attachment upload reuses across attempts so a retry\n * (next sync pass or after a restart) reproduces byte-identical encrypted bytes\n * and resumes the same multipart stage instead of orphaning it. `contentKey` and\n * the chunk `nonceSeed` are base64. `partSize`/`stageId` are filled in once the\n * multipart stage has been opened and remain null before that.\n */\nexport interface PendingAttachmentUploadIdentity {\n blobId: string;\n contentKey: string;\n contentKeyEpoch: number;\n nonceSeed: string;\n partSize: number | null;\n plaintextSha256: string;\n stageId: string | null;\n}\n\nexport interface PendingAttachmentRecord {\n byteLength: number;\n contentSha256: string;\n localId: string;\n mimeType: string | null;\n name: string;\n slotId: string;\n storageKey: string;\n upload?: PendingAttachmentUploadIdentity | null;\n}\n\nexport interface LocalAttachmentRecord {\n blobId: string | null;\n byteLength: number;\n // Plaintext digest of the bytes at `storageKey`. Compared with the digest\n // the document content records for the slot: a held copy that differs is a\n // validly signed served binding the document has not recorded (yet).\n contentSha256: string;\n // Set once the slot is unlinked from a synced document and cleared when the\n // slot is written again. The record survives the unlink so the next sync can\n // still detach the remote binding; `detachedAt` is what keeps the local read\n // models from reporting the slot as a live blob reference in the meantime.\n detachedAt: string | null;\n localId: string;\n mimeType: string | null;\n slotId: string;\n storageKey: string;\n}\n\nexport interface AttachmentStagingRows {\n localAttachments: ReadonlyArray<LocalAttachmentRecord>;\n pendingAttachments: ReadonlyArray<PendingAttachmentRecord>;\n}\n\nexport interface AttachmentRemovalRows {\n mode: \"delete\" | \"detach\";\n slotId: string;\n storageKey: string;\n}\n\nexport interface DocumentHistoryRestoreState {\n snapshot: string;\n tailUpdates: readonly {\n origin: \"local\" | \"remote\";\n updateData: string;\n }[];\n}\n\nexport interface RelinkPersistedDocumentInput {\n accessEpoch: number;\n accessStateHash?: string | null;\n containerId: string;\n documentId: string | null;\n localId: string;\n}\n\nexport interface ContainerDocumentTombstoneInput {\n containerId: string;\n documentId: string;\n /** Epoch of the verified head; apply refuses a head below local state. */\n accessEpoch: number;\n /** Verified head link set (omits `containerId`); apply needs signed evidence. */\n linkedContainerIds: ReadonlyArray<string>;\n updatedAt: string;\n}\n\nexport type DocumentSummarySortDirection = \"asc\" | \"desc\";\nexport type DocumentSummarySortKey = \"kind\" | \"title\" | \"updated\";\n\nexport interface DocumentSummarySort {\n readonly direction: DocumentSummarySortDirection;\n readonly key: DocumentSummarySortKey;\n}\n\nexport interface ListDocumentSummariesInput {\n documentKind?: StoredDocumentKind | undefined;\n limit?: number | undefined;\n offset?: number | undefined;\n sort?: DocumentSummarySort | undefined;\n}\n\nexport interface DocumentSummaryList {\n readonly rows: ReadonlyArray<DocumentSummary>;\n readonly totalCount: number;\n}\n\nexport interface DocumentsPersistence {\n readonly orphanBlobs: DocumentOrphanBlobPersistence;\n /**\n * The adapter guarantees that recovery checkpoint replacement, selection of\n * covered local history, rejection of unproven ordinary pending rows, and\n * quarantine of every queued checkpoint artifact share the guarded\n * `commitDocumentMutation` transaction, which also advances the canonical\n * recovery generation. An unrelated history tail not covered by the rebuild\n * must abort that transaction.\n */\n readonly supportsAtomicRecoveryHistoryPruning: boolean;\n /**\n * Atomically create the canonical row, standard projections, and birth\n * checkpoint. Returns null when another initializer already owns localId.\n */\n createDocumentWithHistoryCheckpoint: (\n execSql: ExecSql,\n document: StoredDocumentRecord,\n historyCheckpoint: {\n endVersionVector: string;\n snapshot: string;\n },\n options:\n | {\n pendingUpdate?: PendingUpdateFields;\n /** Recheck volatile caller ownership inside the create transaction. */\n stillCurrent?: (() => boolean) | undefined;\n updatedAt?: string;\n }\n | undefined,\n saveClientProjection: (\n transactionExecSql: ExecSql,\n updatedAt: string,\n ) => Promise<void>,\n ) => Promise<string | null>;\n /**\n * Conditionally commit one already-prepared mutation against the exact\n * durable record it was derived from. The identity/progress comparison,\n * attachment and history writes, accepted-queue settlement,\n * canonical/projection save, and client projection callback must share one\n * adapter transaction.\n */\n commitDocumentMutation: (\n execSql: ExecSql,\n input: {\n acceptedPendingUpdateIds: readonly string[];\n attachmentRemoval?: AttachmentRemovalRows | undefined;\n attachmentStaging?: AttachmentStagingRows | undefined;\n clearSyncFailure?: boolean | undefined;\n document: StoredDocumentRecord;\n expectedRecord: StoredDocumentRecord;\n historyCheckpoint?:\n | {\n coveredTailIds: readonly string[];\n endVersionVector: string;\n pruneCoveredLocalState: boolean;\n snapshot: string;\n }\n | undefined;\n historyUpdateOrigin?: \"local\" | \"remote\" | undefined;\n historyUpdates?: readonly string[] | undefined;\n pendingUpdate?: PendingUpdateFields | undefined;\n settleAcceptedPendingOnConflict: boolean;\n /**\n * Recheck volatile caller ownership inside the adapter transaction,\n * before any durable side effect. A false result aborts the commit.\n */\n stillCurrent?: (() => boolean) | undefined;\n updatedAt?: string | undefined;\n },\n saveClientProjection: (\n transactionExecSql: ExecSql,\n updatedAt: string,\n ) => Promise<void>,\n ) => Promise<\n | { committed: true; updatedAt: string }\n | { committed: false; currentRecord: StoredDocumentRecord | null }\n >;\n /** Settle acknowledged rows only while the response's security identity survives. */\n settleAcceptedPendingUpdates: (\n execSql: ExecSql,\n input: {\n expectedRecord: StoredDocumentRecord;\n pendingUpdateIds: readonly string[];\n },\n ) => Promise<StoredDocumentRecord | null>;\n ensureSchema: (execSql: ExecSql) => Promise<void>;\n listDocuments: (execSql: ExecSql) => Promise<DocumentSummary[]>;\n listDocumentSummaries: (\n execSql: ExecSql,\n input?: ListDocumentSummariesInput,\n ) => Promise<DocumentSummaryList>;\n listDocumentsByContainerIdsOrDocumentIds: (\n execSql: ExecSql,\n input: {\n containerIds: ReadonlyArray<string>;\n documentIds: ReadonlyArray<string>;\n },\n ) => Promise<DocumentSummary[]>;\n findDocumentLocalIdsByContainerId: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<string[]>;\n /**\n * Select one local row for a remote document identity. Prefer any row with\n * queued updates or a deferred-sync frontier, then break duplicates by\n * updatedAt and localId descending.\n */\n findLocalIdByDocumentId: (\n execSql: ExecSql,\n documentId: string,\n ) => Promise<string | null>;\n /** Canonical-row probe; false authorizes destructive orphan teardown. */\n hasDocument: (execSql: ExecSql, localId: string) => Promise<boolean>;\n /** Observe whether the canonical row still names the expected remote stream. */\n documentIdentityMatches: (\n execSql: ExecSql,\n localId: string,\n expectedDocumentId: string | null,\n expectedRecoveryGeneration: number,\n ) => Promise<boolean>;\n loadDocument: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<StoredDocumentRecord | null>;\n /** Read the canonical record and its history from one database snapshot. */\n loadDocumentWithHistoryRestoreState: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{\n document: StoredDocumentRecord | null;\n historyRestoreState: DocumentHistoryRestoreState | null;\n }>;\n /** Read every document-store startup row from one database snapshot. */\n loadDocumentStoreState: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{\n document: StoredDocumentRecord | null;\n historyRestoreState: DocumentHistoryRestoreState | null;\n localAttachments: LocalAttachmentRecord[];\n pendingAttachments: PendingAttachmentRecord[];\n }>;\n /**\n * Atomically replace the exact rejected pull continuation with the durable\n * recovery marker when every supplied sync-identity field still matches.\n * Return the authoritative current record after the compare-and-set, or\n * null when the canonical row no longer exists. A CAS loss returns the\n * winning record so the live store can adopt its newer progress.\n */\n invalidatePullContinuation: (\n execSql: ExecSql,\n input: {\n accessEpoch: number;\n accessStateHash: string | null;\n continuation: DocumentSyncPullContinuation;\n contentKeyBundle: string | null;\n documentId: string;\n documentKekTargets: string | null;\n documentManifestBundle: string | null;\n lastCommitLsn: string | null;\n localId: string;\n },\n ) => Promise<{\n historyRestoreState: DocumentHistoryRestoreState | null;\n record: StoredDocumentRecord;\n } | null>;\n // Read the authoritative container placement for a locally persisted document\n // straight from its projection row. Returns `undefined` when no projection row\n // exists yet (a first create/discovery persist), so a caller can distinguish\n // that from a row that legitimately carries a null container (a document\n // unlinked from every container). Container placement is owned by the\n // link/tombstone/discovery layer, so a content-metadata persist reads this to\n // avoid republishing a stale in-memory container.\n loadDocumentContainer: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{ containerId: string | null } | undefined>;\n saveDocument: (\n execSql: ExecSql,\n document: StoredDocumentRecord,\n options?: {\n updatedAt?: string;\n },\n ) => Promise<string>;\n /**\n * Durable full-history support (checkpoint + append-only tail) — the ONLY\n * persisted content source. REQUIRED: a persistence without these could\n * report successful writes whose documents reopen empty.\n */\n appendHistoryUpdates: (\n execSql: ExecSql,\n input: {\n localId: string;\n origin: \"local\" | \"remote\";\n updates: readonly string[];\n },\n ) => Promise<void>;\n loadHistoryRestoreState: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<DocumentHistoryRestoreState | null>;\n readHistoryTailSize: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{\n byteLength: number;\n hasCheckpoint: boolean;\n rowCount: number;\n }>;\n listHistoryTailEntries: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{ id: string; updateData: string }[]>;\n replaceHistoryCheckpoint: (\n execSql: ExecSql,\n input: {\n coveredTailIds: readonly string[];\n endVersionVector: string;\n force?: boolean;\n localId: string;\n snapshot: string;\n stillCurrent?: () => boolean;\n },\n ) => Promise<void>;\n saveDocumentAndDeletePendingUpdates: (\n execSql: ExecSql,\n document: StoredDocumentRecord,\n pendingUpdateIds: readonly string[],\n options?: {\n updatedAt?: string;\n },\n ) => Promise<string>;\n deleteDocument: (execSql: ExecSql, localId: string) => Promise<void>;\n /**\n * Delete the canonical row and every side row only when its security identity\n * still matches the captured record. The comparison, deletes, and client\n * projection callback must share one write transaction.\n */\n deleteDocumentIfMatches: (\n execSql: ExecSql,\n expectedRecord: StoredDocumentRecord,\n deleteClientProjection: (transactionExecSql: ExecSql) => Promise<void>,\n ) => Promise<boolean>;\n /**\n * Delete orphaned side rows only if the canonical document is still absent.\n * The absence check, row cleanup, and client projection callback must share\n * one write transaction so a concurrent create is preserved.\n */\n deleteDocumentSideRowsIfAbsent: (\n execSql: ExecSql,\n localId: string,\n expectedDocumentId: string | null,\n deleteClientProjection: (transactionExecSql: ExecSql) => Promise<void>,\n ) => Promise<boolean>;\n upsertDiscoveredDocument: (\n execSql: ExecSql,\n input: DiscoveredDocumentInput,\n ) => Promise<DocumentSummary>;\n relinkPersistedDocument: (\n execSql: ExecSql,\n input: RelinkPersistedDocumentInput,\n ) => Promise<DocumentSummary | null>;\n listPendingUpdates: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<PendingUpdateRecord[]>;\n rekeyPendingUpdate: (execSql: ExecSql, id: string) => Promise<string | null>;\n listPendingAttachments: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<PendingAttachmentRecord[]>;\n listLocalAttachments: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<LocalAttachmentRecord[]>;\n /**\n * Durably append the outgoing row and matching local-history tail entry.\n * When expectations are supplied, compare the document identity and recovery\n * generation with the canonical row inside that same mutation and return\n * false on absence or mismatch. Adapters must not insert either row.\n */\n enqueuePendingUpdate: (\n execSql: ExecSql,\n pendingUpdate: PendingUpdateInsert,\n options?: {\n expectedDocumentId: string | null;\n expectedRecoveryGeneration: number;\n },\n ) => Promise<boolean>;\n /** Replace a hydrated copy only if its observed durable slot and live document still match. */\n saveHydratedAttachment: (\n execSql: ExecSql,\n input: {\n attachment: LocalAttachmentRecord;\n expectedStorageKey: string | null;\n expectedSnapshotEndVersion: string | null;\n stillCurrent: () => boolean;\n },\n ) => Promise<boolean>;\n saveLocalAttachment: (\n execSql: ExecSql,\n attachment: LocalAttachmentRecord,\n ) => Promise<void>;\n deleteLocalAttachment: (\n execSql: ExecSql,\n localId: string,\n slotId: string,\n storageKey: string,\n ) => Promise<void>;\n markLocalAttachmentDetached: (\n execSql: ExecSql,\n localId: string,\n slotId: string,\n storageKey: string,\n ) => Promise<void>;\n savePendingAttachment: (\n execSql: ExecSql,\n attachment: PendingAttachmentRecord,\n ) => Promise<void>;\n deletePendingUpdate: (execSql: ExecSql, id: string) => Promise<void>;\n deletePendingUpdates: (execSql: ExecSql, localId: string) => Promise<void>;\n deletePendingAttachment: (\n execSql: ExecSql,\n localId: string,\n slotId: string,\n storageKey: string,\n ) => Promise<void>;\n deletePendingAttachments: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<void>;\n /**\n * Atomically convert a stuck document's local state to the\n * freshly-discovered-share shell (see the SQL implementation's doc\n * comment). The projector registry clears the document-kind client\n * projection in the same transaction — those tables live with the app's\n * projector definitions, so the CALLER'S registry is required (the default\n * registry knows no app kinds, and a discard that silently kept a\n * contact's or card's projected fields would leak the discarded values).\n * The method itself is optional: implementations without the full document\n * schema (container metadata, simple doubles) simply do not offer the\n * discard escape hatch.\n */\n /**\n * `expectedDocumentId` is revalidated against the loaded record inside the\n * serialized mutation: a stale caller (or a relink that raced the request)\n * must never discard a different identity's edits.\n */\n discardDocumentToShell?: (\n execSql: ExecSql,\n localId: string,\n expectedDocumentId: string,\n documentProjectors: DocumentProjectorRegistryInput,\n ) => Promise<DiscardDocumentToShellResult>;\n}\n"]}
|
|
@@ -9,7 +9,11 @@ export declare function loadPrincipalHistoryPrefix(execSql: ExecSql, scopeId: st
|
|
|
9
9
|
currentJson: string;
|
|
10
10
|
progress: string;
|
|
11
11
|
} | null>;
|
|
12
|
-
/**
|
|
12
|
+
/**
|
|
13
|
+
* Preserve identical completed progress; this sink does not authenticate hints.
|
|
14
|
+
* Callers must discard an unreadable prefix or identify it with rejectedPrefix
|
|
15
|
+
* before publishing a repair of the same head and current artifacts.
|
|
16
|
+
*/
|
|
13
17
|
export declare function savePrincipalHistoryPrefix(input: {
|
|
14
18
|
readonly execSql: ExecSql;
|
|
15
19
|
readonly prefix: PrincipalHistoryPrefix;
|
|
@@ -18,7 +18,11 @@ export async function loadPrincipalHistoryPrefix(execSql, scopeId) {
|
|
|
18
18
|
.limit(1);
|
|
19
19
|
return prefix ?? null;
|
|
20
20
|
}
|
|
21
|
-
/**
|
|
21
|
+
/**
|
|
22
|
+
* Preserve identical completed progress; this sink does not authenticate hints.
|
|
23
|
+
* Callers must discard an unreadable prefix or identify it with rejectedPrefix
|
|
24
|
+
* before publishing a repair of the same head and current artifacts.
|
|
25
|
+
*/
|
|
22
26
|
export async function savePrincipalHistoryPrefix(input) {
|
|
23
27
|
const prefix = { ...input.prefix };
|
|
24
28
|
const indexRootHash = input.indexRootHash;
|
|
@@ -34,11 +38,24 @@ export async function savePrincipalHistoryPrefix(input) {
|
|
|
34
38
|
.from(principalHistoryPrefixes)
|
|
35
39
|
.where(eq(principalHistoryPrefixes.scopeId, prefix.scopeId))
|
|
36
40
|
.limit(1);
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
+
const replacesRejected = previous &&
|
|
42
|
+
rejected?.scopeId === previous.scopeId &&
|
|
43
|
+
rejected.progress === previous.progress;
|
|
44
|
+
if (previous && previous.version > prefix.version && !replacesRejected)
|
|
41
45
|
return;
|
|
46
|
+
if (previous &&
|
|
47
|
+
previous.version === prefix.version &&
|
|
48
|
+
previous.organizationId === prefix.organizationId &&
|
|
49
|
+
previous.headJson === prefix.headJson &&
|
|
50
|
+
previous.currentJson === prefix.currentJson &&
|
|
51
|
+
!replacesRejected) {
|
|
52
|
+
// Resealing an unchanged prefix would invalidate an acknowledgement's
|
|
53
|
+
// progress CAS even though its authenticated predecessor is unchanged.
|
|
54
|
+
// Still refresh authenticated root ownership and retention below.
|
|
55
|
+
// Reuse authenticates this opaque progress; rejected hints are removed
|
|
56
|
+
// or explicitly replaced before repair can rely on the new prefix.
|
|
57
|
+
prefix.progress = previous.progress;
|
|
58
|
+
}
|
|
42
59
|
if (previous)
|
|
43
60
|
await archivePrincipalHistoryKeyEnvelopes(tx, previous);
|
|
44
61
|
await archivePrincipalHistoryKeyEnvelopes(tx, prefix);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalHistoryPrefixPersistence.js","sourceRoot":"","sources":["principalHistoryPrefixPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,mCAAmC,EAAE,MAAM,uCAAuC,CAAC;AAC5F,OAAO,EACL,8BAA8B,EAC9B,wBAAwB,GACzB,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,2BAA2B,EAAE,MAAM,uCAAuC,CAAC;AACpF,OAAO,EAAE,iCAAiC,EAAE,MAAM,oCAAoC,CAAC;AACvF,OAAO,EAAgB,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACpE,OAAO,EAAE,4B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AO,CAAC,EACpD,EAAE,CAAC,wBAAwB,CAAC,QAAQ,EAAE,MAAM,CAAC,QAAQ,CAAC,CACvD,CACF;aACA,GAAG,EAAE,CAAC;IACX,CAAC,EACD,KAAK,CAAC,YAAY,EAClB,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;IACF,mCAAmC,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;AAC9D,CAAC","sourcesContent":["import { and, eq } from \"drizzle-orm\";\nimport { assertProjectionVerificationCurrent } from \"../keyingProjectionVerification/types\";\nimport {\n principalHistoryEvidenceTables,\n principalHistoryPrefixes,\n} from \"../sqlite/principalHistoryEvidenceSchema\";\nimport { principalHistoryStageTables } from \"../sqlite/principalHistoryStageSchema\";\nimport { getClientSQLitePersistenceRuntime } from \"../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\nimport { reclaimPrincipalHistoryNodes } from \"./principalHistoryNodeRetention\";\nimport {\n releasePrincipalHistoryRoot,\n retainPrincipalHistoryRoot,\n} from \"./principalHistoryRootOwnership\";\nimport { reclaimCompletedPrincipalHistoryStages } from \"./principalHistoryStageRetention\";\nimport { archivePrincipalHistoryKeyEnvelopes } from \"./principalKeyEnvelopeArchivePersistence\";\n\nexport type PrincipalHistoryPrefix =\n typeof principalHistoryPrefixes.$inferSelect;\n\nexport async function loadPrincipalHistoryPrefix(\n execSql: ExecSql,\n scopeId: string,\n) {\n await ensureSqlTables(execSql, principalHistoryEvidenceTables);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const [prefix] = await db\n .select()\n .from(principalHistoryPrefixes)\n .where(eq(principalHistoryPrefixes.scopeId, scopeId))\n .limit(1);\n return prefix ?? null;\n}\n\n/**\n * Preserve identical completed progress; this sink does not authenticate hints.\n * Callers must discard an unreadable prefix or identify it with rejectedPrefix\n * before publishing a repair of the same head and current artifacts.\n */\nexport async function savePrincipalHistoryPrefix(input: {\n readonly execSql: ExecSql;\n readonly prefix: PrincipalHistoryPrefix;\n readonly indexRootHash: string;\n readonly stillCurrent: () => boolean;\n readonly rejectedPrefix?: PrincipalHistoryPrefix | null;\n}): Promise<void> {\n const prefix = { ...input.prefix };\n const indexRootHash = input.indexRootHash;\n const rejected = input.rejectedPrefix ? { ...input.rejectedPrefix } : null;\n await ensureSqlTables(input.execSql, [\n ...principalHistoryEvidenceTables,\n ...principalHistoryStageTables,\n ]);\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const result = await runtime.guardedTransaction(\n async (tx) => {\n const [previous] = await tx\n .select()\n .from(principalHistoryPrefixes)\n .where(eq(principalHistoryPrefixes.scopeId, prefix.scopeId))\n .limit(1);\n const replacesRejected =\n previous &&\n rejected?.scopeId === previous.scopeId &&\n rejected.progress === previous.progress;\n if (previous && previous.version > prefix.version && !replacesRejected)\n return;\n if (\n previous &&\n previous.version === prefix.version &&\n previous.organizationId === prefix.organizationId &&\n previous.headJson === prefix.headJson &&\n previous.currentJson === prefix.currentJson &&\n !replacesRejected\n ) {\n // Resealing an unchanged prefix would invalidate an acknowledgement's\n // progress CAS even though its authenticated predecessor is unchanged.\n // Still refresh authenticated root ownership and retention below.\n // Reuse authenticates this opaque progress; rejected hints are removed\n // or explicitly replaced before repair can rely on the new prefix.\n prefix.progress = previous.progress;\n }\n if (previous) await archivePrincipalHistoryKeyEnvelopes(tx, previous);\n await archivePrincipalHistoryKeyEnvelopes(tx, prefix);\n await tx\n .insert(principalHistoryPrefixes)\n .values(prefix)\n .onConflictDoUpdate({\n target: principalHistoryPrefixes.scopeId,\n set: prefix,\n })\n .run();\n await reclaimCompletedPrincipalHistoryStages(tx, prefix);\n await retainPrincipalHistoryRoot(tx, {\n id: `prefix:${prefix.scopeId}`,\n scopeId: prefix.scopeId,\n organizationId: prefix.organizationId,\n rootHash: indexRootHash,\n });\n await reclaimPrincipalHistoryNodes(tx, prefix);\n },\n input.stillCurrent,\n { behavior: \"immediate\" },\n );\n assertProjectionVerificationCurrent(() => result.committed);\n}\n\n/** Invalid hints are disposable, but a losing reader must preserve a newer hint. */\nexport async function discardPrincipalHistoryPrefix(input: {\n readonly execSql: ExecSql;\n readonly prefix: PrincipalHistoryPrefix;\n readonly stillCurrent: () => boolean;\n}): Promise<void> {\n const prefix = { ...input.prefix };\n await ensureSqlTables(input.execSql, principalHistoryEvidenceTables);\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const result = await runtime.guardedTransaction(\n async (tx) => {\n const [current] = await tx\n .select({ progress: principalHistoryPrefixes.progress })\n .from(principalHistoryPrefixes)\n .where(eq(principalHistoryPrefixes.scopeId, prefix.scopeId))\n .limit(1);\n if (current?.progress !== prefix.progress) return;\n await releasePrincipalHistoryRoot(tx, `prefix:${prefix.scopeId}`);\n await tx\n .delete(principalHistoryPrefixes)\n .where(\n and(\n eq(principalHistoryPrefixes.scopeId, prefix.scopeId),\n eq(principalHistoryPrefixes.progress, prefix.progress),\n ),\n )\n .run();\n },\n input.stillCurrent,\n { behavior: \"immediate\" },\n );\n assertProjectionVerificationCurrent(() => result.committed);\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type CommitOrganizationGroupPolicyRequest, type CreateOrganizationGroupWithPolicyRequest, type DeleteOrganizationGroupRequest, type OrganizationPrincipalPolicyRequest } from "../../internal/validators/request/index.js";
|
|
2
2
|
export type AuthoredPrincipalMutation = {
|
|
3
|
-
readonly kind
|
|
3
|
+
readonly kind: "compound";
|
|
4
4
|
readonly groupId: string;
|
|
5
5
|
readonly request: CommitOrganizationGroupPolicyRequest;
|
|
6
6
|
} | {
|
|
@@ -29,12 +29,12 @@ export function readPrincipalMutation(value, scope) {
|
|
|
29
29
|
assertStateScope(request.organizationPolicy.state, "organization", scope.organizationId, scope);
|
|
30
30
|
return { kind, groupId, request };
|
|
31
31
|
}
|
|
32
|
-
if (kind !==
|
|
32
|
+
if (kind !== "compound")
|
|
33
33
|
throw new Error("Principal mutation journal operation is unsupported");
|
|
34
34
|
const request = CommitOrganizationGroupPolicyRequestSchema.parse(body);
|
|
35
35
|
assertStateScope(request.groupPolicy.state, "group", groupId, scope);
|
|
36
36
|
assertStateScope(request.organizationPolicy.state, "organization", scope.organizationId, scope);
|
|
37
|
-
return { groupId, request };
|
|
37
|
+
return { kind, groupId, request };
|
|
38
38
|
}
|
|
39
39
|
function assertStateScope(state, principalType, principalId, scope) {
|
|
40
40
|
if (state.principalType !== principalType ||
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalMutationJournalShape.js","sourceRoot":"","sources":["principalMutationJournalShape.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,0CAA0C,EAE1C,8CAA8C,EAE9C,oCAAoC,EAEpC,wCAAwC,GACzC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;
|
|
1
|
+
{"version":3,"file":"principalMutationJournalShape.js","sourceRoot":"","sources":["principalMutationJournalShape.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,0CAA0C,EAE1C,8CAA8C,EAE9C,oCAAoC,EAEpC,wCAAwC,GACzC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AA8B5D,gFAAgF;AAChF,MAAM,UAAU,qBAAqB,CACnC,KAAc,EACd,KAAkB;IAElB,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI;QAC7C,MAAM,IAAI,KAAK,CAAC,+CAA+C,CAAC,CAAC;IACnE,MAAM,OAAO,GAAY,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;IACvD,MAAM,IAAI,GAAY,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IACjD,MAAM,IAAI,GAAY,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;IACpD,IAAI,IAAI,KAAK,cAAc,EAAE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IAAI,IAAI,KAAK,UAAU;QACrB,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;IACzE,MAAM,OAAO,GAAG,0CAA0C,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACvE,gBAAgB,CAAC,OAAO,CAAC,WAAW,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;IACrE,gBAAgB,CACd,OAAO,CAAC,kBAAkB,CAAC,KAAK,EAChC,cAAc,EACd,KAAK,CAAC,cAAc,EACpB,KAAK,CACN,CAAC;IACF,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AACpC,CAAC;AAED,SAAS,gBAAgB,CACvB,KAAkD,EAClD,aAAuC,EACvC,WAAmB,EACnB,KAAkB;IAElB,IACE,KAAK,CAAC,aAAa,KAAK,aAAa;QACrC,KAAK,CAAC,WAAW,KAAK,WAAW;QACjC,KAAK,CAAC,YAAY,KAAK,KAAK,CAAC,MAAM;QACnC,KAAK,CAAC,wBAAwB,KAAK,KAAK,CAAC,kBAAkB;QAE3D,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;AAC3E,CAAC","sourcesContent":["import {\n type CommitOrganizationGroupPolicyRequest,\n CommitOrganizationGroupPolicyRequestSchema,\n type CreateOrganizationGroupWithPolicyRequest,\n CreateOrganizationGroupWithPolicyRequestSchema,\n type DeleteOrganizationGroupRequest,\n DeleteOrganizationGroupRequestSchema,\n type OrganizationPrincipalPolicyRequest,\n OrganizationPrincipalPolicyRequestSchema,\n} from \"@tearleads/validators/request\";\nimport { isUuidV4String } from \"@tearleads/validators/util\";\n\nexport type AuthoredPrincipalMutation =\n | {\n readonly kind: \"compound\";\n readonly groupId: string;\n readonly request: CommitOrganizationGroupPolicyRequest;\n }\n | {\n readonly kind: \"group-create\";\n readonly groupId: string;\n readonly request: CreateOrganizationGroupWithPolicyRequest;\n }\n | {\n readonly kind: \"group-delete\";\n readonly groupId: string;\n readonly request: DeleteOrganizationGroupRequest;\n }\n | {\n readonly kind: \"organization\";\n readonly groupId: null;\n readonly request: OrganizationPrincipalPolicyRequest;\n };\n\ninterface SignerScope {\n readonly organizationId: string;\n readonly userId: string;\n readonly signingFingerprint: string;\n}\n\n/** Validate authored inputs; opening an existing row authenticates it first. */\nexport function readPrincipalMutation(\n value: unknown,\n scope: SignerScope,\n): AuthoredPrincipalMutation {\n if (typeof value !== \"object\" || value === null)\n throw new Error(\"Principal mutation journal payload is invalid\");\n const groupId: unknown = Reflect.get(value, \"groupId\");\n const kind: unknown = Reflect.get(value, \"kind\");\n const body: unknown = Reflect.get(value, \"request\");\n if (kind === \"organization\") {\n if (groupId !== null)\n throw new Error(\"Organization journal target differs\");\n const request = OrganizationPrincipalPolicyRequestSchema.parse(body);\n assertStateScope(\n request.state,\n \"organization\",\n scope.organizationId,\n scope,\n );\n return { kind, groupId, request };\n }\n if (typeof groupId !== \"string\" || !isUuidV4String(groupId))\n throw new Error(\"Principal mutation journal group target is invalid\");\n if (kind === \"group-create\") {\n const request = CreateOrganizationGroupWithPolicyRequestSchema.parse(body);\n if (request.groupId !== groupId)\n throw new Error(\"Group creation journal target differs\");\n assertStateScope(request.initialGroupPolicy.state, \"group\", groupId, scope);\n assertStateScope(\n request.organizationPolicy.state,\n \"organization\",\n scope.organizationId,\n scope,\n );\n return { kind, groupId, request };\n }\n if (kind === \"group-delete\") {\n const request = DeleteOrganizationGroupRequestSchema.parse(body);\n assertStateScope(\n request.organizationPolicy.state,\n \"organization\",\n scope.organizationId,\n scope,\n );\n return { kind, groupId, request };\n }\n if (kind !== \"compound\")\n throw new Error(\"Principal mutation journal operation is unsupported\");\n const request = CommitOrganizationGroupPolicyRequestSchema.parse(body);\n assertStateScope(request.groupPolicy.state, \"group\", groupId, scope);\n assertStateScope(\n request.organizationPolicy.state,\n \"organization\",\n scope.organizationId,\n scope,\n );\n return { kind, groupId, request };\n}\n\nfunction assertStateScope(\n state: OrganizationPrincipalPolicyRequest[\"state\"],\n principalType: \"organization\" | \"group\",\n principalId: string,\n scope: SignerScope,\n) {\n if (\n state.principalType !== principalType ||\n state.principalId !== principalId ||\n state.signerUserId !== scope.userId ||\n state.signerUserKeyFingerprint !== scope.signingFingerprint\n )\n throw new Error(\"Principal mutation journal target or signer differs\");\n}\n"]}
|
package/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAqKA,OAAO,EAEL,KAAK,EAEL,yBAAyB,EACzB,sCAAsC,EACtC,gCAAgC,EAChC,sCAAsC,EACtC,iBAAiB,EACjB,wCAAwC,EACxC,kCAAkC,EAClC,kBAAkB,EAClB,2CAA2C,EAC3C,qCAAqC,EACrC,+BAA+B,EAC/B,gCAAgC,EAChC,gCAAgC,EAChC,yBAAyB,EACzB,+BAA+B,EAC/B,0BAA0B,EAC1B,yBAAyB,EACzB,QAAQ,EACR,mBAAmB,EAKnB,8BAA8B,EAC9B,2BAA2B,EAC3B,MAAM,EAGN,2BAA2B,EAC3B,8BAA8B,EAC9B,2BAA2B,EAC3B,mCAAmC,EACnC,6BAA6B,EAC7B,oBAAoB,EACpB,OAAO,EACP,0BAA0B,EAG1B,oBAAoB,EACpB,yBAAyB,EACzB,sBAAsB,EACtB,4BAA4B,EAC5B,4BAA4B,EAE5B,yBAAyB,EACzB,8CAA8C,EAC9C,yBAAyB,EAKzB,eAAe,EAIf,6BAA6B,EAC7B,SAAS,EACT,2BAA2B,GAC5B,MAAM,UAAU,CAAC;AA2BlB,OAAO,EACL,sBAAsB,EACtB,yBAAyB,EACzB,oBAAoB,EACpB,+BAA+B,EAC/B,4BAA4B,EAC5B,6BAA6B,EAC7B,qBAAqB,EACrB,gCAAgC,EAChC,yBAAyB,EACzB,iCAAiC,EACjC,sBAAsB,EACtB,iCAAiC,EACjC,0BAA0B,EAC1B,wBAAwB,EACxB,4BAA4B,EAC5B,0BAA0B,EAC1B,kBAAkB,EACl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AC5B,gBAAgB,GACjB,MAAM,0BAA0B,CAAC;AAWlC,OAAO,EACL,uBAAuB,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":["// Current SDK contract: unified device-first handles and atomic revision checks.\n// Authority loaders take exact heads, including cached citations. Obsolete\n// adapters are excluded; authored policy journals survive restart. See workflows/README.md.\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 ClientDatabaseOptions,\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 type ClientOptions,\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 Tearleads,\n WRAPPED_LOCAL_SECRET_FORMAT,\n} from \"./client\";\nexport type {\n BlobByteSource,\n BlobByteSourceInput,\n BlobBytes,\n BlobStore,\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 \"./documents\";\nexport {\n addDocumentAttachments,\n blobByteSourceInputLength,\n createBlobByteSource,\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 readBlobByteSource,\n readStoredDocumentState,\n readStringDocumentField,\n resolveOpIdAttribution,\n sameDocumentAttachments,\n summarizeDocumentContributors,\n writerByPeerId,\n writeStoredDocumentFields,\n} from \"./documents\";\nexport type {\n ContainerContentsSnapshot,\n ContainerContentsStoreRuntime,\n ContainerContentsStoreState,\n ContainerContentsStoreSyncAgent,\n ContainerContentsStoreSyncState,\n ContainerState,\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 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 type {\n EncryptedBlobStoreCipher,\n EncryptedBlobStoreKey,\n EncryptedBlobStoreOptions,\n WrapEncryptedBlobStoreOptions,\n} from \"./workflows/blobs\";\nexport {\n createBlobStore,\n createEncryptedBlobStore,\n createLazyEncryptedBlobStore,\n createMemoryBlobStore,\n decryptDocumentAttachmentBlob,\n hydrateDocumentAttachmentBlobs,\n purgeOpfsBlobStore,\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 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 deliberately absent here. Integration\n// tests that compose low-level runtimes use the testing package subpath.\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 CacheReferencedPrincipalPoliciesOptions,\n PrincipalHistoryProtectionLease,\n ProjectionPolicyHistoryRecoveryOptions,\n RecoveredPrincipalPolicyHistory,\n RecoveredScopedPrincipalPolicyHistory,\n RecoverPrincipalPolicyHistoryOptions,\n RecoverScopedPrincipalPolicyHistoryOptions,\n} from \"./workflows/principals\";\nexport {\n cacheReferencedPrincipalPolicies,\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":"AAqKA,OAAO,EAEL,KAAK,EAEL,yBAAyB,EACzB,sCAAsC,EACtC,gCAAgC,EAChC,sCAAsC,EACtC,iBAAiB,EACjB,wCAAwC,EACxC,kCAAkC,EAClC,kBAAkB,EAClB,2CAA2C,EAC3C,qCAAqC,EACrC,+BAA+B,EAC/B,gCAAgC,EACh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AAuB,EACvB,0CAA0C,EAC1C,6CAA6C,EAC7C,kDAAkD,EAClD,2CAA2C,EAC3C,gCAAgC,EAChC,qCAAqC,EACrC,+BAA+B,EAC/B,sBAAsB,EACtB,8BAA8B,EAC9B,uCAAuC,EACvC,uBAAuB,EACvB,8BAA8B,EAC9B,oCAAoC,EACpC,oCAAoC,EACpC,kCAAkC,EAClC,0CAA0C,EAC1C,6BAA6B,EAC7B,oCAAoC,EACpC,4BAA4B,EAC5B,8BAA8B,EAC9B,2BAA2B,EAC3B,8BAA8B,EAC9B,uCAAuC,EACvC,iCAAiC,EACjC,2BAA2B,EAC3B,8BAA8B,EAC9B,mCAAmC,EACnC,gCAAgC,EAChC,sBAAsB,EACtB,gCAAgC,EAChC,0CAA0C,EAC1C,gCAAgC,EAChC,yBAAyB,EACzB,6BAA6B,GAC9B,MAAM,2BAA2B,CAAC;AAUnC,OAAO,EACL,gCAAgC,EAChC,+BAA+B,EAC/B,6BAA6B,EAC7B,8BAA8B,EAC9B,mCAAmC,GACpC,MAAM,wBAAwB,CAAC;AAOhC,OAAO,EACL,sBAAsB,EACtB,qCAAqC,EACrC,kCAAkC,EAClC,4BAA4B,EAC5B,gBAAgB,GACjB,MAAM,0BAA0B,CAAC;AAWlC,OAAO,EACL,uBAAuB,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":["// Current SDK contract: unified device-first handles and atomic revision checks.\n// Authority loaders take exact heads, including cached citations. Obsolete\n// adapters are excluded; authored policy journals survive restart. See workflows/README.md.\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 ClientDatabaseOptions,\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 type ClientOptions,\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 Tearleads,\n WRAPPED_LOCAL_SECRET_FORMAT,\n} from \"./client\";\nexport type {\n BlobByteSource,\n BlobByteSourceInput,\n BlobBytes,\n BlobStore,\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 \"./documents\";\nexport {\n addDocumentAttachments,\n blobByteSourceInputLength,\n createBlobByteSource,\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 readBlobByteSource,\n readStoredDocumentState,\n readStringDocumentField,\n resolveOpIdAttribution,\n sameDocumentAttachments,\n summarizeDocumentContributors,\n writerByPeerId,\n writeStoredDocumentFields,\n} from \"./documents\";\nexport type {\n ContainerContentsSnapshot,\n ContainerContentsStoreRuntime,\n ContainerContentsStoreState,\n ContainerContentsStoreSyncAgent,\n ContainerContentsStoreSyncState,\n ContainerState,\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 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 type {\n EncryptedBlobStoreCipher,\n EncryptedBlobStoreKey,\n EncryptedBlobStoreOptions,\n WrapEncryptedBlobStoreOptions,\n} from \"./workflows/blobs\";\nexport {\n createBlobStore,\n createEncryptedBlobStore,\n createLazyEncryptedBlobStore,\n createMemoryBlobStore,\n decryptDocumentAttachmentBlob,\n hydrateDocumentAttachmentBlobs,\n purgeOpfsBlobStore,\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 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 CacheReferencedPrincipalPoliciesOptions,\n PrincipalHistoryProtectionLease,\n ProjectionPolicyHistoryRecoveryOptions,\n RecoveredPrincipalPolicyHistory,\n RecoveredScopedPrincipalPolicyHistory,\n RecoverPrincipalPolicyHistoryOptions,\n RecoverScopedPrincipalPolicyHistoryOptions,\n} from \"./workflows/principals\";\nexport {\n cacheReferencedPrincipalPolicies,\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,9 +1,9 @@
|
|
|
1
1
|
/** Hydrate only bytes matching the current document's authenticated attachment intent. */
|
|
2
2
|
import { getDocumentAttachments } from "../../../data/documents/documentContent.js";
|
|
3
3
|
import { hydrateDocumentAttachmentBlobs } from "../../../workflows/blobs/index.js";
|
|
4
|
-
import { reclaimDocumentOrphanBlobs, } from "../../../workflows/documents/index.js";
|
|
5
4
|
import { createRuntimePrincipalPolicyWarmer } from "../../../workflows/principals/runtimePolicyWarmer.js";
|
|
6
5
|
import { commitHydratedAttachment } from "./attachmentHydrationCommit.js";
|
|
6
|
+
import { runDocumentOrphanMaintenance } from "./orphanMaintenance.js";
|
|
7
7
|
import { isDocumentStoreSyncGenerationCurrent as isSyncGenerationCurrent, } from "./syncGeneration.js";
|
|
8
8
|
export async function hydrateAttachmentBlobs(state, currentDoc, currentRecord, expectedGeneration) {
|
|
9
9
|
const generationIsCurrent = () => !expectedGeneration || isSyncGenerationCurrent(state, expectedGeneration);
|
|
@@ -52,6 +52,6 @@ export async function hydrateAttachmentBlobs(state, currentDoc, currentRecord, e
|
|
|
52
52
|
expectedStorageKey: expectedStorageKeys[hydratedBlob.attachment.slotId] ?? null,
|
|
53
53
|
});
|
|
54
54
|
}
|
|
55
|
-
|
|
55
|
+
void runDocumentOrphanMaintenance(state);
|
|
56
56
|
}
|
|
57
57
|
//# sourceMappingURL=attachmentHydration.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"attachmentHydration.js","sourceRoot":"","sources":["attachmentHydration.ts"],"names":[],"mappings":"AAAA,0FAA0F;AAE1F,OAAO,EAAE,sBAAsB,EAAE,MAAM,yCAAyC,CAAC;AACjF,OAAO,EAAE,8BAA8B,EAAE,MAAM,0BAA0B,CAAC;
|
|
1
|
+
{"version":3,"file":"attachmentHydration.js","sourceRoot":"","sources":["attachmentHydration.ts"],"names":[],"mappings":"AAAA,0FAA0F;AAE1F,OAAO,EAAE,sBAAsB,EAAE,MAAM,yCAAyC,CAAC;AACjF,OAAO,EAAE,8BAA8B,EAAE,MAAM,0BAA0B,CAAC;AAE1E,OAAO,EAAE,kCAAkC,EAAE,MAAM,mDAAmD,CAAC;AACvG,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AACvE,OAAO,EAAE,4BAA4B,EAAE,MAAM,qBAAqB,CAAC;AAEnE,OAAO,EAEL,oCAAoC,IAAI,uBAAuB,GAChE,MAAM,kBAAkB,CAAC;AAE1B,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAC1C,KAAyB,EACzB,UAAyB,EACzB,aAAoC,EACpC,kBAAgD;IAEhD,MAAM,mBAAmB,GAAG,GAAG,EAAE,CAC/B,CAAC,kBAAkB,IAAI,uBAAuB,CAAC,KAAK,EAAE,kBAAkB,CAAC,CAAC;IAC5E,IAAI,CAAC,mBAAmB,EAAE;QAAE,OAAO;IAEnC,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC;IAC9B,MAAM,oBAAoB,GAAG,OAAO,CAAC,MAAM,CAAC,oBAAoB,CAAC;IACjE,IACE,CAAC,oBAAoB;QACrB,CAAC,OAAO,CAAC,IAAI,CAAC,eAAe;QAC7B,CAAC,OAAO,CAAC,KAAK,CAAC,MAAM;QACrB,CAAC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AAK,CAAC,CAAC;AAC3C,CAAC","sourcesContent":["/** Hydrate only bytes matching the current document's authenticated attachment intent. */\n\nimport { getDocumentAttachments } from \"../../../data/documents/documentContent\";\nimport { hydrateDocumentAttachmentBlobs } from \"../../../workflows/blobs\";\nimport type { DocumentRecord } from \"../../../workflows/documents\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../../../workflows/principals/runtimePolicyWarmer\";\nimport { commitHydratedAttachment } from \"./attachmentHydrationCommit\";\nimport { runDocumentOrphanMaintenance } from \"./orphanMaintenance\";\nimport type { DocumentState, DocumentStoreState } from \"./state\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent as isSyncGenerationCurrent,\n} from \"./syncGeneration\";\n\nexport async function hydrateAttachmentBlobs(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n currentRecord: DocumentRecord | null,\n expectedGeneration?: DocumentStoreSyncGeneration,\n) {\n const generationIsCurrent = () =>\n !expectedGeneration || isSyncGenerationCurrent(state, expectedGeneration);\n if (!generationIsCurrent()) return;\n\n const runtime = state.runtime;\n const encapsulationKeyPair = runtime.crypto.encapsulationKeyPair;\n if (\n !encapsulationKeyPair ||\n !runtime.auth.isAuthenticated ||\n !runtime.state.online ||\n !currentRecord?.documentId\n ) {\n return;\n }\n\n const attachments = getDocumentAttachments(currentDoc);\n if (attachments.length === 0) {\n return;\n }\n\n const expectedStorageKeys = { ...state.attachmentStorageKeyBySlotId };\n const hydratedBlobs = await hydrateDocumentAttachmentBlobs({\n apiClient: runtime.apiClient,\n attachments,\n documentId: currentRecord.documentId,\n execSql: runtime.infra.execSql,\n localBlobIdBySlotId: state.attachmentBlobIdBySlotId,\n localStorageKeyBySlotId: state.attachmentStorageKeyBySlotId,\n log: runtime.util.log,\n rejectedServedBindings: state.rejectedServedAttachmentBindings,\n reportSecurityIncident: runtime.util.reportSecurityIncident,\n resolveProjectionUserKey:\n expectedGeneration?.resolveProjectionUserKey ??\n state.resolveProjectionUserKey,\n targetSecretKey: encapsulationKeyPair.secretKey,\n stillCurrent: generationIsCurrent,\n warmReferencedPrincipalPolicies:\n createRuntimePrincipalPolicyWarmer(runtime),\n });\n if (!generationIsCurrent()) return;\n if (!hydratedBlobs) {\n return;\n }\n\n for (const hydratedBlob of hydratedBlobs) {\n await commitHydratedAttachment({\n state,\n currentDoc,\n hydratedBlob,\n generationIsCurrent,\n expectedStorageKey:\n expectedStorageKeys[hydratedBlob.attachment.slotId] ?? null,\n });\n }\n void runDocumentOrphanMaintenance(state);\n}\n"]}
|
|
@@ -8,6 +8,7 @@ import { removeLocalAttachmentSlot } from "./attachmentPersistence.js";
|
|
|
8
8
|
import { deleteUnreferencedStagedAttachmentBytes, installPendingAttachmentRows, stagePendingAttachments, } from "./attachmentStaging.js";
|
|
9
9
|
import { captureAttachmentWriteGeneration, isAttachmentWriteGenerationCurrent, shouldAbortAttachmentPersistFollowup, } from "./attachmentWriteGeneration.js";
|
|
10
10
|
import { ensureDocumentStoreReady } from "./initialization.js";
|
|
11
|
+
import { runDocumentOrphanMaintenance } from "./orphanMaintenance.js";
|
|
11
12
|
import { advancePendingBaseVersion, pendingDeltaSinceBase, persistDocument, } from "./persistence.js";
|
|
12
13
|
import { reportDocumentStoreWriteFailure } from "./reportWriteFailure.js";
|
|
13
14
|
import { canAttachFiles, canWriteDocument, setReadySnapshot, } from "./state.js";
|
|
@@ -171,19 +172,20 @@ async function persistSlotAttachmentFile(state, slotId, file, writeGeneration) {
|
|
|
171
172
|
state.runtime.util.log(`Queued attachment ${file.name} for slot ${slotId}.`);
|
|
172
173
|
requestDocumentStoreSync(state);
|
|
173
174
|
}
|
|
174
|
-
|
|
175
|
+
function installCommittedAttachmentRemoval(input) {
|
|
175
176
|
const { slotId, state, storageKey } = input;
|
|
176
177
|
if (!storageKey)
|
|
177
178
|
return;
|
|
178
179
|
state.pendingAttachments = state.pendingAttachments.filter((attachment) => attachment.slotId !== slotId || attachment.storageKey !== storageKey);
|
|
180
|
+
// The committed removal queued this key. A reset can leave another document
|
|
181
|
+
// uploading from the same copy, even though this document is local-only.
|
|
182
|
+
if (!input.syncedAttachment)
|
|
183
|
+
void runDocumentOrphanMaintenance(state);
|
|
179
184
|
if (input.syncedAttachment ||
|
|
180
185
|
state.attachmentStorageKeyBySlotId[slotId] !== storageKey) {
|
|
181
186
|
return;
|
|
182
187
|
}
|
|
183
188
|
removeLocalAttachmentSlot(state, slotId);
|
|
184
|
-
await state.runtime.infra.blobStore
|
|
185
|
-
.deleteBytes(storageKey)
|
|
186
|
-
.catch(() => state.runtime.util.log(`Documents: failed to delete detached attachment bytes for ${slotId}.`));
|
|
187
189
|
setReadySnapshot(state, input.currentDoc, state.snapshot.syncing, state.snapshot.text, state.snapshot.structuredFields);
|
|
188
190
|
}
|
|
189
191
|
async function persistRemovedAttachment(state, slotId, writeGeneration) {
|
|
@@ -244,7 +246,7 @@ async function persistRemovedAttachment(state, slotId, writeGeneration) {
|
|
|
244
246
|
// See persistAttachedFiles: only durable same-identity work re-arms sync.
|
|
245
247
|
return;
|
|
246
248
|
}
|
|
247
|
-
|
|
249
|
+
installCommittedAttachmentRemoval({
|
|
248
250
|
currentDoc,
|
|
249
251
|
slotId,
|
|
250
252
|
state,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"attachments.js","sourceRoot":"","sources":["attachments.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mBAAmB,EACnB,yBAAyB,GAC1B,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,sBAAsB,EACtB,sBAAsB,EACtB,wBAAwB,GACzB,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,yBAAyB,EAAE,MAAM,sCAAsC,CAAC;AAEjF,OAAO,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AAEvD,OAAO,EACL,qBAAqB,EACrB,uBAAuB,GACxB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,+BAA+B,EAC/B,+BAA+B,GAChC,MAAM,iCAAiC,CAAC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gB,CAAC,KAAK,CAAC,EAAE,CAAC;QACrD,OAAO;IACT,CAAC;IAED,MAAM,eAAe,GAAG,gCAAgC,CAAC,KAAK,CAAC,CAAC;IAChE,IAAI,CAAC,eAAe;QAAE,OAAO;IAC7B,KAAK,CAAC,UAAU,GAAG,KAAK,CAAC,UAAU;SAChC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC;SACtB,IAAI,CAAC,KAAK,IAAI,EAAE,CACf,yBAAyB,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,eAAe,CAAC,CAChE;SACA,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;QACxB,+BAA+B,CAAC,KAAK,EAAE,0BAA0B,EAAE,KAAK,CAAC,CAAC;IAC5E,CAAC,CAAC,CAAC;IACL,OAAO,KAAK,CAAC,UAAU,CAAC;AAC1B,CAAC","sourcesContent":["import {\n encodeVersionVector,\n exportFullHistorySnapshot,\n} from \"@tearleads/loro\";\nimport {\n addDocumentAttachments,\n getDocumentAttachments,\n removeDocumentAttachment,\n} from \"../../../data/documents/documentContent\";\nimport { createPendingUpdateFields } from \"../../../data/documents/documentSync\";\nimport type { PendingAttachmentRecord } from \"../../../workflows/documents\";\nimport { requestDocumentStoreSync } from \"../registry\";\nimport type { DocumentAttachmentUpload } from \"../types\";\nimport {\n buildAttachmentIntent,\n buildPendingAttachments,\n} from \"./attachmentIntents\";\nimport {\n persistStagedAttachmentMutation,\n restoreFailedAttachmentMutation,\n} from \"./attachmentMutationPersistence\";\nimport { removeLocalAttachmentSlot } from \"./attachmentPersistence\";\nimport {\n deleteUnreferencedStagedAttachmentBytes,\n installPendingAttachmentRows,\n stagePendingAttachments,\n} from \"./attachmentStaging\";\nimport {\n type AttachmentWriteGeneration,\n captureAttachmentWriteGeneration,\n isAttachmentWriteGenerationCurrent,\n shouldAbortAttachmentPersistFollowup,\n} from \"./attachmentWriteGeneration\";\nimport { ensureDocumentStoreReady } from \"./initialization\";\nimport {\n advancePendingBaseVersion,\n pendingDeltaSinceBase,\n persistDocument,\n} from \"./persistence\";\nimport { reportDocumentStoreWriteFailure } from \"./reportWriteFailure\";\nimport {\n canAttachFiles,\n canWriteDocument,\n type DocumentStoreState,\n setReadySnapshot,\n} from \"./state\";\nimport { captureDocumentStoreSyncGeneration } from \"./syncGeneration\";\n\n// Fixed literal: a reported message must never carry file names or slot ids.\nconst ATTACHMENT_FAILURE_MESSAGE = \"Documents: attachment mutation failed\";\n\nfunction logAttachedFiles(state: DocumentStoreState, count: number) {\n state.runtime.util.log(\n state.runtime.state.online && state.runtime.auth.isAuthenticated\n ? `Attached ${count} file${count === 1 ? \"\" : \"s\"} to document ${state.localId}.`\n : `Stored ${count} attachment${count === 1 ? \"\" : \"s\"} locally for document ${state.localId}.`,\n );\n}\n\nasync function persistAttachedFiles(\n state: DocumentStoreState,\n files: ReadonlyArray<DocumentAttachmentUpload>,\n writeGeneration: AttachmentWriteGeneration,\n) {\n if (!isAttachmentWriteGenerationCurrent(state, writeGeneration)) return;\n const currentDoc = state.doc;\n\n if (!currentDoc || !canAttachFiles(state)) {\n state.runtime.util.log(\n \"Documents: attachments require a local key package.\",\n );\n return;\n }\n const generation = captureDocumentStoreSyncGeneration(state, currentDoc);\n if (!generation) {\n return;\n }\n\n const { nextAttachments, nextPendingAttachments } =\n await buildPendingAttachments(state.localId, files);\n if (\n !isAttachmentWriteGenerationCurrent(state, writeGeneration) ||\n state.doc !== currentDoc\n )\n return;\n const rollbackSnapshot = exportFullHistorySnapshot(currentDoc).slice();\n addDocumentAttachments(currentDoc, nextAttachments);\n const attachmentUpdate = pendingDeltaSinceBase(state, currentDoc);\n // Captured at delta time: the enqueued row proves coverage up to exactly\n // this version, so it is the frontier the persist below may publish.\n const coveredVersion = encodeVersionVector(currentDoc);\n\n let staged: Awaited<ReturnType<typeof stagePendingAttachments>>;\n try {\n staged = await stagePendingAttachments({\n files,\n generation,\n pendingAttachments: nextPendingAttachments,\n state,\n });\n } catch (error) {\n await restoreFailedAttachmentMutation({\n generation,\n rollbackSnapshot,\n state,\n });\n throw error;\n }\n if (!staged) {\n await restoreFailedAttachmentMutation({\n generation,\n rollbackSnapshot,\n state,\n });\n return;\n }\n // This persist changes attachments, not prose. setReadySnapshot always\n // re-derives attachments from the doc, but preserve the text/structured\n // fields so an attach that overlaps an in-flight keystroke does not republish\n // a stale doc read over the live optimistic editor value.\n const persisted = await persistStagedAttachmentMutation({\n attachmentUpdate,\n coveredVersion,\n currentDoc,\n generation,\n rollbackSnapshot,\n staged,\n state,\n });\n if (\n shouldAbortAttachmentPersistFollowup(\n state,\n writeGeneration,\n generation,\n persisted,\n )\n ) {\n await deleteUnreferencedStagedAttachmentBytes({\n generation,\n pendingAttachments: staged.pendingAttachments,\n state,\n });\n return;\n }\n installPendingAttachmentRows({ ...staged, state });\n advancePendingBaseVersion(state, currentDoc);\n logAttachedFiles(state, files.length);\n requestDocumentStoreSync(state);\n}\n\nasync function persistSlotAttachmentFile(\n state: DocumentStoreState,\n slotId: string,\n file: DocumentAttachmentUpload,\n writeGeneration: AttachmentWriteGeneration,\n) {\n if (!isAttachmentWriteGenerationCurrent(state, writeGeneration)) return;\n const currentDoc = state.doc;\n\n if (!currentDoc || !canAttachFiles(state)) {\n state.runtime.util.log(\n \"Documents: slot attachments require a local key package.\",\n );\n return;\n }\n const generation = captureDocumentStoreSyncGeneration(state, currentDoc);\n if (!generation) {\n return;\n }\n\n const replacementAttachment = await buildAttachmentIntent(slotId, file);\n if (\n !isAttachmentWriteGenerationCurrent(state, writeGeneration) ||\n state.doc !== currentDoc\n )\n return;\n const rollbackSnapshot = exportFullHistorySnapshot(currentDoc).slice();\n addDocumentAttachments(currentDoc, [replacementAttachment]);\n const attachmentUpdate = pendingDeltaSinceBase(state, currentDoc);\n const coveredVersion = encodeVersionVector(currentDoc);\n\n const storageKey = `${state.localId}-${slotId}-${crypto.randomUUID()}`;\n const pendingAttachment: PendingAttachmentRecord = {\n byteLength: replacementAttachment.byteLength,\n contentSha256: replacementAttachment.contentSha256,\n localId: state.localId,\n mimeType: replacementAttachment.mimeType,\n name: replacementAttachment.name,\n slotId,\n storageKey,\n };\n let staged: Awaited<ReturnType<typeof stagePendingAttachments>>;\n try {\n staged = await stagePendingAttachments({\n files: [file],\n generation,\n pendingAttachments: [pendingAttachment],\n state,\n });\n } catch (error) {\n await restoreFailedAttachmentMutation({\n generation,\n rollbackSnapshot,\n state,\n });\n throw error;\n }\n if (!staged) {\n await restoreFailedAttachmentMutation({\n generation,\n rollbackSnapshot,\n state,\n });\n return;\n }\n // Preserve the optimistic text/structured fields (see persistAttachedFiles):\n // a slot replacement overlapping a keystroke must not regress the editor.\n const persisted = await persistStagedAttachmentMutation({\n attachmentUpdate,\n coveredVersion,\n currentDoc,\n generation,\n rollbackSnapshot,\n staged,\n state,\n });\n if (\n shouldAbortAttachmentPersistFollowup(\n state,\n writeGeneration,\n generation,\n persisted,\n )\n ) {\n await deleteUnreferencedStagedAttachmentBytes({\n generation,\n pendingAttachments: staged.pendingAttachments,\n state,\n });\n return;\n }\n installPendingAttachmentRows({ ...staged, state });\n advancePendingBaseVersion(state, currentDoc);\n state.runtime.util.log(`Queued attachment ${file.name} for slot ${slotId}.`);\n requestDocumentStoreSync(state);\n}\n\nasync function installCommittedAttachmentRemoval(input: {\n currentDoc: NonNullable<DocumentStoreState[\"doc\"]>;\n slotId: string;\n state: DocumentStoreState;\n storageKey: string | undefined;\n syncedAttachment: boolean;\n}): Promise<void> {\n const { slotId, state, storageKey } = input;\n if (!storageKey) return;\n state.pendingAttachments = state.pendingAttachments.filter(\n (attachment) =>\n attachment.slotId !== slotId || attachment.storageKey !== storageKey,\n );\n if (\n input.syncedAttachment ||\n state.attachmentStorageKeyBySlotId[slotId] !== storageKey\n ) {\n return;\n }\n removeLocalAttachmentSlot(state, slotId);\n await state.runtime.infra.blobStore\n .deleteBytes(storageKey)\n .catch(() =>\n state.runtime.util.log(\n `Documents: failed to delete detached attachment bytes for ${slotId}.`,\n ),\n );\n setReadySnapshot(\n state,\n input.currentDoc,\n state.snapshot.syncing,\n state.snapshot.text,\n state.snapshot.structuredFields,\n );\n}\n\nasync function persistRemovedAttachment(\n state: DocumentStoreState,\n slotId: string,\n writeGeneration: AttachmentWriteGeneration,\n) {\n if (!isAttachmentWriteGenerationCurrent(state, writeGeneration)) return;\n const currentDoc = state.doc;\n if (!currentDoc) {\n return;\n }\n const generation = captureDocumentStoreSyncGeneration(state, currentDoc);\n if (!generation) {\n return;\n }\n\n const existingAttachment = getDocumentAttachments(currentDoc).find(\n (attachment) => attachment.slotId === slotId,\n );\n if (!existingAttachment) {\n return;\n }\n\n const storageKey = state.attachmentStorageKeyBySlotId[slotId];\n if (\n !isAttachmentWriteGenerationCurrent(state, writeGeneration) ||\n state.doc !== currentDoc\n )\n return;\n const rollbackSnapshot = exportFullHistorySnapshot(currentDoc).slice();\n removeDocumentAttachment(currentDoc, slotId);\n const attachmentUpdate = pendingDeltaSinceBase(state, currentDoc);\n const coveredVersion = encodeVersionVector(currentDoc);\n const pendingUpdate = createPendingUpdateFields(attachmentUpdate);\n const syncedAttachment = Boolean(state.record?.documentId);\n\n // Preserve the optimistic text/structured fields (see persistAttachedFiles):\n // removing an attachment while typing must not regress the editor.\n let persisted: Awaited<ReturnType<typeof persistDocument>>;\n try {\n persisted = await persistDocument(\n state,\n currentDoc,\n { snapshotEndVersion: coveredVersion },\n {\n ...(storageKey\n ? {\n attachmentRemoval: {\n mode: syncedAttachment\n ? (\"detach\" as const)\n : (\"delete\" as const),\n slotId,\n storageKey,\n },\n }\n : {}),\n ...(pendingUpdate ? { pendingUpdate } : {}),\n preserveSnapshotStructuredFields: true,\n preserveSnapshotText: true,\n },\n generation,\n );\n } catch (error) {\n await restoreFailedAttachmentMutation({\n generation,\n rollbackSnapshot,\n state,\n });\n throw error;\n }\n if (\n shouldAbortAttachmentPersistFollowup(\n state,\n writeGeneration,\n generation,\n persisted,\n )\n ) {\n // See persistAttachedFiles: only durable same-identity work re-arms sync.\n return;\n }\n await installCommittedAttachmentRemoval({\n currentDoc,\n slotId,\n state,\n storageKey,\n syncedAttachment,\n });\n advancePendingBaseVersion(state, currentDoc);\n state.runtime.util.log(\n `Removed attachment ${existingAttachment.name} from document ${state.localId}.`,\n );\n requestDocumentStoreSync(state);\n}\n\nexport async function attachFilesToDocumentStore(\n state: DocumentStoreState,\n scheduleSync: () => void,\n files: ReadonlyArray<DocumentAttachmentUpload>,\n) {\n if (files.length === 0) {\n return;\n }\n\n let ready: boolean;\n try {\n ready = await ensureDocumentStoreReady(state, scheduleSync);\n } catch (error) {\n reportDocumentStoreWriteFailure(state, ATTACHMENT_FAILURE_MESSAGE, error);\n return;\n }\n\n if (!ready || !state.doc || !canWriteDocument(state)) {\n return;\n }\n\n const writeGeneration = captureAttachmentWriteGeneration(state);\n if (!writeGeneration) return;\n state.writeChain = state.writeChain\n .catch(() => undefined)\n .then(async () => persistAttachedFiles(state, files, writeGeneration))\n .catch((error: unknown) => {\n reportDocumentStoreWriteFailure(state, ATTACHMENT_FAILURE_MESSAGE, error);\n });\n return state.writeChain;\n}\n\nexport async function removeAttachmentFromDocumentStore(\n state: DocumentStoreState,\n scheduleSync: () => void,\n slotId: string,\n) {\n let ready: boolean;\n try {\n ready = await ensureDocumentStoreReady(state, scheduleSync);\n } catch (error) {\n reportDocumentStoreWriteFailure(state, ATTACHMENT_FAILURE_MESSAGE, error);\n return;\n }\n\n if (!ready || !state.doc || !canWriteDocument(state)) {\n return;\n }\n\n const writeGeneration = captureAttachmentWriteGeneration(state);\n if (!writeGeneration) return;\n state.writeChain = state.writeChain\n .catch(() => undefined)\n .then(async () => persistRemovedAttachment(state, slotId, writeGeneration))\n .catch((error: unknown) => {\n reportDocumentStoreWriteFailure(state, ATTACHMENT_FAILURE_MESSAGE, error);\n });\n return state.writeChain;\n}\n\nexport async function replaceAttachmentInDocumentStore(\n state: DocumentStoreState,\n scheduleSync: () => void,\n slotId: string,\n file: DocumentAttachmentUpload,\n) {\n let ready: boolean;\n try {\n ready = await ensureDocumentStoreReady(state, scheduleSync);\n } catch (error) {\n reportDocumentStoreWriteFailure(state, ATTACHMENT_FAILURE_MESSAGE, error);\n return;\n }\n\n if (!ready || !state.doc || !canWriteDocument(state)) {\n return;\n }\n\n const writeGeneration = captureAttachmentWriteGeneration(state);\n if (!writeGeneration) return;\n state.writeChain = state.writeChain\n .catch(() => undefined)\n .then(async () =>\n persistSlotAttachmentFile(state, slotId, file, writeGeneration),\n )\n .catch((error: unknown) => {\n reportDocumentStoreWriteFailure(state, ATTACHMENT_FAILURE_MESSAGE, error);\n });\n return state.writeChain;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"attachments.js","sourceRoot":"","sources":["attachments.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mBAAmB,EACnB,yBAAyB,GAC1B,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,sBAAsB,EACtB,sBAAsB,EACtB,wBAAwB,GACzB,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,yBAAyB,EAAE,MAAM,sCAAsC,CAAC;AAEjF,OAAO,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AAEvD,OAAO,EACL,qBAAqB,EACrB,uBAAuB,GACxB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,+BAA+B,EAC/B,+BAA+B,GAChC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AACpE,OAAO,EACL,uCAAuC,EACvC,4BAA4B,EAC5B,uBAAuB,GACxB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAEL,gCAAgC,EAChC,kCAAkC,EAClC,oCAAoC,GACrC,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,wBAAwB,EAAE,MAAM,kBAAkB,CAAC;AAC5D,OAAO,EAAE,4BAA4B,EAAE,MAAM,qBAAqB,CAAC;AACnE,OAAO,EACL,yBAAyB,EACzB,qBAAqB,EACrB,eAAe,GAChB,MAAM,eAAe,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K,CAAC,CAAC;IAC5E,CAAC,CAAC,CAAC;IACL,OAAO,KAAK,CAAC,UAAU,CAAC;AAC1B,CAAC","sourcesContent":["import {\n encodeVersionVector,\n exportFullHistorySnapshot,\n} from \"@tearleads/loro\";\nimport {\n addDocumentAttachments,\n getDocumentAttachments,\n removeDocumentAttachment,\n} from \"../../../data/documents/documentContent\";\nimport { createPendingUpdateFields } from \"../../../data/documents/documentSync\";\nimport type { PendingAttachmentRecord } from \"../../../workflows/documents\";\nimport { requestDocumentStoreSync } from \"../registry\";\nimport type { DocumentAttachmentUpload } from \"../types\";\nimport {\n buildAttachmentIntent,\n buildPendingAttachments,\n} from \"./attachmentIntents\";\nimport {\n persistStagedAttachmentMutation,\n restoreFailedAttachmentMutation,\n} from \"./attachmentMutationPersistence\";\nimport { removeLocalAttachmentSlot } from \"./attachmentPersistence\";\nimport {\n deleteUnreferencedStagedAttachmentBytes,\n installPendingAttachmentRows,\n stagePendingAttachments,\n} from \"./attachmentStaging\";\nimport {\n type AttachmentWriteGeneration,\n captureAttachmentWriteGeneration,\n isAttachmentWriteGenerationCurrent,\n shouldAbortAttachmentPersistFollowup,\n} from \"./attachmentWriteGeneration\";\nimport { ensureDocumentStoreReady } from \"./initialization\";\nimport { runDocumentOrphanMaintenance } from \"./orphanMaintenance\";\nimport {\n advancePendingBaseVersion,\n pendingDeltaSinceBase,\n persistDocument,\n} from \"./persistence\";\nimport { reportDocumentStoreWriteFailure } from \"./reportWriteFailure\";\nimport {\n canAttachFiles,\n canWriteDocument,\n type DocumentStoreState,\n setReadySnapshot,\n} from \"./state\";\nimport { captureDocumentStoreSyncGeneration } from \"./syncGeneration\";\n\n// Fixed literal: a reported message must never carry file names or slot ids.\nconst ATTACHMENT_FAILURE_MESSAGE = \"Documents: attachment mutation failed\";\n\nfunction logAttachedFiles(state: DocumentStoreState, count: number) {\n state.runtime.util.log(\n state.runtime.state.online && state.runtime.auth.isAuthenticated\n ? `Attached ${count} file${count === 1 ? \"\" : \"s\"} to document ${state.localId}.`\n : `Stored ${count} attachment${count === 1 ? \"\" : \"s\"} locally for document ${state.localId}.`,\n );\n}\n\nasync function persistAttachedFiles(\n state: DocumentStoreState,\n files: ReadonlyArray<DocumentAttachmentUpload>,\n writeGeneration: AttachmentWriteGeneration,\n) {\n if (!isAttachmentWriteGenerationCurrent(state, writeGeneration)) return;\n const currentDoc = state.doc;\n\n if (!currentDoc || !canAttachFiles(state)) {\n state.runtime.util.log(\n \"Documents: attachments require a local key package.\",\n );\n return;\n }\n const generation = captureDocumentStoreSyncGeneration(state, currentDoc);\n if (!generation) {\n return;\n }\n\n const { nextAttachments, nextPendingAttachments } =\n await buildPendingAttachments(state.localId, files);\n if (\n !isAttachmentWriteGenerationCurrent(state, writeGeneration) ||\n state.doc !== currentDoc\n )\n return;\n const rollbackSnapshot = exportFullHistorySnapshot(currentDoc).slice();\n addDocumentAttachments(currentDoc, nextAttachments);\n const attachmentUpdate = pendingDeltaSinceBase(state, currentDoc);\n // Captured at delta time: the enqueued row proves coverage up to exactly\n // this version, so it is the frontier the persist below may publish.\n const coveredVersion = encodeVersionVector(currentDoc);\n\n let staged: Awaited<ReturnType<typeof stagePendingAttachments>>;\n try {\n staged = await stagePendingAttachments({\n files,\n generation,\n pendingAttachments: nextPendingAttachments,\n state,\n });\n } catch (error) {\n await restoreFailedAttachmentMutation({\n generation,\n rollbackSnapshot,\n state,\n });\n throw error;\n }\n if (!staged) {\n await restoreFailedAttachmentMutation({\n generation,\n rollbackSnapshot,\n state,\n });\n return;\n }\n // This persist changes attachments, not prose. setReadySnapshot always\n // re-derives attachments from the doc, but preserve the text/structured\n // fields so an attach that overlaps an in-flight keystroke does not republish\n // a stale doc read over the live optimistic editor value.\n const persisted = await persistStagedAttachmentMutation({\n attachmentUpdate,\n coveredVersion,\n currentDoc,\n generation,\n rollbackSnapshot,\n staged,\n state,\n });\n if (\n shouldAbortAttachmentPersistFollowup(\n state,\n writeGeneration,\n generation,\n persisted,\n )\n ) {\n await deleteUnreferencedStagedAttachmentBytes({\n generation,\n pendingAttachments: staged.pendingAttachments,\n state,\n });\n return;\n }\n installPendingAttachmentRows({ ...staged, state });\n advancePendingBaseVersion(state, currentDoc);\n logAttachedFiles(state, files.length);\n requestDocumentStoreSync(state);\n}\n\nasync function persistSlotAttachmentFile(\n state: DocumentStoreState,\n slotId: string,\n file: DocumentAttachmentUpload,\n writeGeneration: AttachmentWriteGeneration,\n) {\n if (!isAttachmentWriteGenerationCurrent(state, writeGeneration)) return;\n const currentDoc = state.doc;\n\n if (!currentDoc || !canAttachFiles(state)) {\n state.runtime.util.log(\n \"Documents: slot attachments require a local key package.\",\n );\n return;\n }\n const generation = captureDocumentStoreSyncGeneration(state, currentDoc);\n if (!generation) {\n return;\n }\n\n const replacementAttachment = await buildAttachmentIntent(slotId, file);\n if (\n !isAttachmentWriteGenerationCurrent(state, writeGeneration) ||\n state.doc !== currentDoc\n )\n return;\n const rollbackSnapshot = exportFullHistorySnapshot(currentDoc).slice();\n addDocumentAttachments(currentDoc, [replacementAttachment]);\n const attachmentUpdate = pendingDeltaSinceBase(state, currentDoc);\n const coveredVersion = encodeVersionVector(currentDoc);\n\n const storageKey = `${state.localId}-${slotId}-${crypto.randomUUID()}`;\n const pendingAttachment: PendingAttachmentRecord = {\n byteLength: replacementAttachment.byteLength,\n contentSha256: replacementAttachment.contentSha256,\n localId: state.localId,\n mimeType: replacementAttachment.mimeType,\n name: replacementAttachment.name,\n slotId,\n storageKey,\n };\n let staged: Awaited<ReturnType<typeof stagePendingAttachments>>;\n try {\n staged = await stagePendingAttachments({\n files: [file],\n generation,\n pendingAttachments: [pendingAttachment],\n state,\n });\n } catch (error) {\n await restoreFailedAttachmentMutation({\n generation,\n rollbackSnapshot,\n state,\n });\n throw error;\n }\n if (!staged) {\n await restoreFailedAttachmentMutation({\n generation,\n rollbackSnapshot,\n state,\n });\n return;\n }\n // Preserve the optimistic text/structured fields (see persistAttachedFiles):\n // a slot replacement overlapping a keystroke must not regress the editor.\n const persisted = await persistStagedAttachmentMutation({\n attachmentUpdate,\n coveredVersion,\n currentDoc,\n generation,\n rollbackSnapshot,\n staged,\n state,\n });\n if (\n shouldAbortAttachmentPersistFollowup(\n state,\n writeGeneration,\n generation,\n persisted,\n )\n ) {\n await deleteUnreferencedStagedAttachmentBytes({\n generation,\n pendingAttachments: staged.pendingAttachments,\n state,\n });\n return;\n }\n installPendingAttachmentRows({ ...staged, state });\n advancePendingBaseVersion(state, currentDoc);\n state.runtime.util.log(`Queued attachment ${file.name} for slot ${slotId}.`);\n requestDocumentStoreSync(state);\n}\n\nfunction installCommittedAttachmentRemoval(input: {\n currentDoc: NonNullable<DocumentStoreState[\"doc\"]>;\n slotId: string;\n state: DocumentStoreState;\n storageKey: string | undefined;\n syncedAttachment: boolean;\n}): void {\n const { slotId, state, storageKey } = input;\n if (!storageKey) return;\n state.pendingAttachments = state.pendingAttachments.filter(\n (attachment) =>\n attachment.slotId !== slotId || attachment.storageKey !== storageKey,\n );\n // The committed removal queued this key. A reset can leave another document\n // uploading from the same copy, even though this document is local-only.\n if (!input.syncedAttachment) void runDocumentOrphanMaintenance(state);\n if (\n input.syncedAttachment ||\n state.attachmentStorageKeyBySlotId[slotId] !== storageKey\n ) {\n return;\n }\n removeLocalAttachmentSlot(state, slotId);\n setReadySnapshot(\n state,\n input.currentDoc,\n state.snapshot.syncing,\n state.snapshot.text,\n state.snapshot.structuredFields,\n );\n}\n\nasync function persistRemovedAttachment(\n state: DocumentStoreState,\n slotId: string,\n writeGeneration: AttachmentWriteGeneration,\n) {\n if (!isAttachmentWriteGenerationCurrent(state, writeGeneration)) return;\n const currentDoc = state.doc;\n if (!currentDoc) {\n return;\n }\n const generation = captureDocumentStoreSyncGeneration(state, currentDoc);\n if (!generation) {\n return;\n }\n\n const existingAttachment = getDocumentAttachments(currentDoc).find(\n (attachment) => attachment.slotId === slotId,\n );\n if (!existingAttachment) {\n return;\n }\n\n const storageKey = state.attachmentStorageKeyBySlotId[slotId];\n if (\n !isAttachmentWriteGenerationCurrent(state, writeGeneration) ||\n state.doc !== currentDoc\n )\n return;\n const rollbackSnapshot = exportFullHistorySnapshot(currentDoc).slice();\n removeDocumentAttachment(currentDoc, slotId);\n const attachmentUpdate = pendingDeltaSinceBase(state, currentDoc);\n const coveredVersion = encodeVersionVector(currentDoc);\n const pendingUpdate = createPendingUpdateFields(attachmentUpdate);\n const syncedAttachment = Boolean(state.record?.documentId);\n\n // Preserve the optimistic text/structured fields (see persistAttachedFiles):\n // removing an attachment while typing must not regress the editor.\n let persisted: Awaited<ReturnType<typeof persistDocument>>;\n try {\n persisted = await persistDocument(\n state,\n currentDoc,\n { snapshotEndVersion: coveredVersion },\n {\n ...(storageKey\n ? {\n attachmentRemoval: {\n mode: syncedAttachment\n ? (\"detach\" as const)\n : (\"delete\" as const),\n slotId,\n storageKey,\n },\n }\n : {}),\n ...(pendingUpdate ? { pendingUpdate } : {}),\n preserveSnapshotStructuredFields: true,\n preserveSnapshotText: true,\n },\n generation,\n );\n } catch (error) {\n await restoreFailedAttachmentMutation({\n generation,\n rollbackSnapshot,\n state,\n });\n throw error;\n }\n if (\n shouldAbortAttachmentPersistFollowup(\n state,\n writeGeneration,\n generation,\n persisted,\n )\n ) {\n // See persistAttachedFiles: only durable same-identity work re-arms sync.\n return;\n }\n installCommittedAttachmentRemoval({\n currentDoc,\n slotId,\n state,\n storageKey,\n syncedAttachment,\n });\n advancePendingBaseVersion(state, currentDoc);\n state.runtime.util.log(\n `Removed attachment ${existingAttachment.name} from document ${state.localId}.`,\n );\n requestDocumentStoreSync(state);\n}\n\nexport async function attachFilesToDocumentStore(\n state: DocumentStoreState,\n scheduleSync: () => void,\n files: ReadonlyArray<DocumentAttachmentUpload>,\n) {\n if (files.length === 0) {\n return;\n }\n\n let ready: boolean;\n try {\n ready = await ensureDocumentStoreReady(state, scheduleSync);\n } catch (error) {\n reportDocumentStoreWriteFailure(state, ATTACHMENT_FAILURE_MESSAGE, error);\n return;\n }\n\n if (!ready || !state.doc || !canWriteDocument(state)) {\n return;\n }\n\n const writeGeneration = captureAttachmentWriteGeneration(state);\n if (!writeGeneration) return;\n state.writeChain = state.writeChain\n .catch(() => undefined)\n .then(async () => persistAttachedFiles(state, files, writeGeneration))\n .catch((error: unknown) => {\n reportDocumentStoreWriteFailure(state, ATTACHMENT_FAILURE_MESSAGE, error);\n });\n return state.writeChain;\n}\n\nexport async function removeAttachmentFromDocumentStore(\n state: DocumentStoreState,\n scheduleSync: () => void,\n slotId: string,\n) {\n let ready: boolean;\n try {\n ready = await ensureDocumentStoreReady(state, scheduleSync);\n } catch (error) {\n reportDocumentStoreWriteFailure(state, ATTACHMENT_FAILURE_MESSAGE, error);\n return;\n }\n\n if (!ready || !state.doc || !canWriteDocument(state)) {\n return;\n }\n\n const writeGeneration = captureAttachmentWriteGeneration(state);\n if (!writeGeneration) return;\n state.writeChain = state.writeChain\n .catch(() => undefined)\n .then(async () => persistRemovedAttachment(state, slotId, writeGeneration))\n .catch((error: unknown) => {\n reportDocumentStoreWriteFailure(state, ATTACHMENT_FAILURE_MESSAGE, error);\n });\n return state.writeChain;\n}\n\nexport async function replaceAttachmentInDocumentStore(\n state: DocumentStoreState,\n scheduleSync: () => void,\n slotId: string,\n file: DocumentAttachmentUpload,\n) {\n let ready: boolean;\n try {\n ready = await ensureDocumentStoreReady(state, scheduleSync);\n } catch (error) {\n reportDocumentStoreWriteFailure(state, ATTACHMENT_FAILURE_MESSAGE, error);\n return;\n }\n\n if (!ready || !state.doc || !canWriteDocument(state)) {\n return;\n }\n\n const writeGeneration = captureAttachmentWriteGeneration(state);\n if (!writeGeneration) return;\n state.writeChain = state.writeChain\n .catch(() => undefined)\n .then(async () =>\n persistSlotAttachmentFile(state, slotId, file, writeGeneration),\n )\n .catch((error: unknown) => {\n reportDocumentStoreWriteFailure(state, ATTACHMENT_FAILURE_MESSAGE, error);\n });\n return state.writeChain;\n}\n"]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { discardPersistedDocumentToShell
|
|
1
|
+
import { discardPersistedDocumentToShell } from "../../../workflows/documents/index.js";
|
|
2
2
|
import { chainIdentityWrite } from "./identityWriteChain.js";
|
|
3
|
+
import { runDocumentOrphanMaintenance } from "./orphanMaintenance.js";
|
|
3
4
|
import { resetDocumentStore } from "./state.js";
|
|
4
5
|
/**
|
|
5
6
|
* User-initiated escape hatch for a document whose queued local writes can no
|
|
@@ -79,7 +80,7 @@ export async function discardDocumentStoreLocalState(state, expectedDocumentId)
|
|
|
79
80
|
}
|
|
80
81
|
// The conversion queued the bytes its dropped rows pointed to; the
|
|
81
82
|
// reclaim deletes each only once no other row references it.
|
|
82
|
-
|
|
83
|
+
void runDocumentOrphanMaintenance(state);
|
|
83
84
|
resetDocumentStore(state);
|
|
84
85
|
runtime.util.log(`Documents: discarded local edits for document ${state.localId}; re-pulling the server copy`);
|
|
85
86
|
return true;
|