@tearleads/client-sdk 0.1.34 → 0.1.36

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.
@@ -91,7 +91,7 @@ class ContainerContentsService {
91
91
  const runtime = this.workflowRuntime();
92
92
  const resolveProjectionUserKey = createContainerContentsDocumentProjectionUserKeyResolver(runtime);
93
93
  const documentRuntime = (containerId) => createContainerContentsDocumentsRuntime(runtime, containerId);
94
- const openContainerDocument = (input) => openDocumentStore(runtime.state.domainScope, input.localId, documentRuntime(input.containerId), input.documentId ?? null, input.initialText, input.initialDocumentKind);
94
+ const openContainerDocument = (input) => openDocumentStore(runtime.state.domainScope, input.localId, documentRuntime(input.containerId), input.documentId ?? null, input.initialText, input.initialDocumentKind, { deferInitialUpdate: input.deferInitialUpdate });
95
95
  const documentLinks = {
96
96
  ...runtime,
97
97
  documentRuntime,
@@ -1 +1 @@
1
- {"version":3,"file":"containerContents.js","sourceRoot":"","sources":["containerContents.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,qCAAqC,CAAC;AAE5E,OAAO,EAAE,iCAAiC,EAAE,MAAM,4CAA4C,CAAC;AAC/F,OAAO,EAGL,iCAAiC,GAClC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAE,uCAAuC,EAAE,MAAM,kDAAkD,CAAC;AAC3G,OAAO,EAGL,YAAY,GACb,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAEL,iBAAiB,GAClB,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAGL,6BAA6B,GAC9B,MAAM,2DAA2D,CAAC;AACnE,OAAO,EAEL,gBAAgB,GACjB,MAAM,8CAA8C,CAAC;AACtD,OAAO,EACL,2BAA2B,EAC3B,4BAA4B,GAC7B,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAEL,yCAAyC,GAC1C,MAAM,iDAAiD,CAAC;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AsB,EAAE,OAAO,CAAC,IAAI,CAAC,sBAAsB;SAC5D,CAAC,CAAC;IACL,CAAC;IAED,2BAA2B,CACzB,UAAkB;QAElB,OAAO,IAAI,CAAC,cAAc;aACvB,aAAa,EAAE;aACf,SAAS,CAAC,0BAA0B,CAAC,UAAU,CAAC,CAAC;IACtD,CAAC;IAED,6BAA6B,CAC3B,KAAqC;QAErC,OAAO,6BAA6B,CAAC;YACnC,SAAS,EAAE,IAAI,CAAC,cAAc,CAAC,aAAa,EAAE,CAAC,SAAS;YACxD,KAAK,EAAE,KAAK;SACb,CAAC,CAAC;IACL,CAAC;IAED,YAAY,CAAC,QAAuB,EAAE;QACpC,MAAM,OAAO,GAAG,IAAI,CAAC,cAAc,CAAC,aAAa,EAAE,CAAC;QACpD,OAAO,YAAY,CAAC;YAClB,GAAG,KAAK;YACR,OAAO,EAAE,YAAY,CAAC,OAAO,CAAC;SAC/B,CAAC,CAAC;IACL,CAAC;IAED,eAAe;QACb,OAAO,2CAA2C,CAChD,IAAI,CAAC,cAAc,CAAC,aAAa,EAAE,EACnC,IAAI,CAAC,cAAc,CAAC,kBAAkB,CACvC,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { DEFAULT_DOCUMENT_KIND } from \"../data/documents/documentConstants\";\nimport type { DocumentSummary } from \"../data/documents/documentSummary\";\nimport { inheritPrincipalHistoryProtection } from \"../data/principals/principalHistoryRuntime\";\nimport {\n type ContainerContentsStore,\n type ContainerContentsStoreOptions,\n getOrCreateContainerContentsStore,\n} from \"../stores/container-contents\";\nimport { openDocumentStore } from \"../stores/documents\";\nimport { relinkDocumentStoreWithCommitSideEffect } from \"../stores/documents/documentStore/internalRelink\";\nimport {\n type BlobInfoInput,\n type BlobInfoList,\n listBlobInfo,\n} from \"../workflows/container-contents/blobInfo\";\nimport {\n type ContainerInfo,\n loadContainerInfo,\n} from \"../workflows/container-contents/containerInfo\";\nimport {\n type DocumentAttributionRangesInput,\n type DocumentAttributionRangesPage,\n loadDocumentAttributionRanges,\n} from \"../workflows/container-contents/documentAttributionRanges\";\nimport {\n type DocumentInfo,\n loadDocumentInfo,\n} from \"../workflows/container-contents/documentInfo\";\nimport {\n purgeLocalContainerDocument,\n purgeRemoteContainerDocument,\n} from \"../workflows/container-contents/documentPurge\";\nimport {\n type ContainerDocumentQueries,\n createContainerDocumentQueriesFromRuntime,\n} from \"../workflows/container-contents/documentQueries\";\nimport {\n activateDocumentLink,\n addDocumentLink,\n canMutateDocumentLink,\n canMutateLocalDocumentLink,\n type DocumentStructuralMutationHost,\n moveDocumentLink,\n removeDocumentLink,\n} from \"../workflows/container-contents/documentStructure\";\nimport { createContainerContentsDocumentProjectionUserKeyResolver } from \"../workflows/container-contents/projectionKeys\";\nimport {\n type ContainerContentsStoreWorkflowRuntime,\n createContainerContentsDocumentsRuntime,\n createContainerContentsStoreWorkflowRuntime,\n} from \"../workflows/container-contents/runtime\";\nimport { createContainerDocumentObjectSyncState } from \"../workflows/container-contents/syncState\";\nimport type { DocumentsWorkflowRuntime } from \"../workflows/documents\";\nimport type {\n ContainerContents,\n ContainerDocumentLinks,\n ContainerInfoInput,\n DocumentInfoInput,\n MergeDocumentSummary,\n MoveDocumentToContainerInput,\n OpenContainerDocumentInput,\n} from \"./containerContentsTypes\";\nimport { discoverContainerDocumentsForRuntime } from \"./containerDocumentDiscovery\";\nimport {\n createOrganizationReadModelCoordinator,\n type OrganizationReadModelCoordinator,\n} from \"./organizations/organizationReadModels\";\nimport type {\n InternalRuntime,\n InternalWorkflowRuntimeInput,\n} from \"./workflowRuntime\";\n\nexport type {\n ContainerContentsContextValue,\n ContainerContentsStore,\n ContainerContentsStoreOptions,\n ContainerNode,\n} from \"../stores/container-contents\";\nexport type {\n BlobInfo,\n BlobInfoAttachmentKind,\n BlobInfoDocumentReference,\n BlobInfoInput,\n BlobInfoList,\n BlobInfoSort,\n BlobInfoSortDirection,\n BlobInfoSortKey,\n} from \"../workflows/container-contents/blobInfo\";\nexport type {\n ContainerInfo,\n ContainerShareAccessLevel,\n} from \"../workflows/container-contents/containerInfo\";\nexport type {\n DocumentAttributionRangesInput,\n DocumentAttributionRangesPage,\n} from \"../workflows/container-contents/documentAttributionRanges\";\nexport type { DocumentInfo } from \"../workflows/container-contents/documentInfo\";\nexport type {\n ContainerDocumentQueries,\n ContainerDocumentSidebarRow,\n ContainerItemRow,\n ContainerItemSort,\n ContainerItemSortDirection,\n ContainerItemSortKey,\n} from \"../workflows/container-contents/documentQueries\";\nexport type { SetLinkedContainerIdsForDocument } from \"../workflows/container-contents/documentStructure\";\nexport type {\n PendingWriteQueueItem,\n PendingWriteQueueItemStatus,\n PendingWriteQueueObjectKind,\n PendingWriteQueueOperation,\n PendingWriteQueueOperationKind,\n PendingWriteQueueOperationStatus,\n} from \"../workflows/container-contents/pendingWrites\";\nexport type {\n ContainerDocumentObjectSyncState,\n ContainerDocumentObjectSyncStatus,\n} from \"../workflows/container-contents/syncState\";\nexport type {\n ContainerContents,\n ContainerDocumentLinkInput,\n ContainerDocumentLinks,\n ContainerInfoInput,\n DocumentInfoInput,\n LinkDocumentToContainerInput,\n MergeDocumentSummary,\n MoveDocumentToContainerInput,\n OpenContainerDocumentInput,\n PurgeDocumentInput,\n PurgeDocumentResult,\n SetActiveDocumentContainerInput,\n UnlinkDocumentFromContainerInput,\n} from \"./containerContentsTypes\";\n\nexport { createContainerDocumentObjectSyncState };\n\nexport function createContainerContents(\n runtime: InternalRuntime,\n): ContainerContents {\n return new ContainerContentsService(runtime);\n}\n\nfunction createDocumentLinkHost(\n runtime: ContainerDocumentLinks,\n mergeDocumentSummary: MergeDocumentSummary,\n): DocumentStructuralMutationHost<DocumentsWorkflowRuntime> {\n return {\n documentWorkflowRuntime: runtime.documentRuntime,\n mergeDocumentSummary,\n openDocumentStore: (input) => {\n const store = runtime.openDocument({\n containerId: input.containerId,\n documentId: input.documentId,\n localId: input.localId,\n });\n return {\n ...store,\n relink: ({ commitSideEffect, ...relinkInput }) =>\n commitSideEffect\n ? relinkDocumentStoreWithCommitSideEffect(\n store,\n relinkInput,\n commitSideEffect,\n )\n : store.relink(relinkInput),\n };\n },\n };\n}\n\nfunction moveDocumentLinkNote(\n input: Pick<MoveDocumentToContainerInput, \"note\" | \"sourceContainerId\">,\n): DocumentSummary {\n if (\n input.note.documentId &&\n input.sourceContainerId &&\n input.sourceContainerId !== input.note.containerId\n ) {\n return { ...input.note, containerId: input.sourceContainerId };\n }\n\n return input.note;\n}\n\ninterface ContainerInfoOrganizationScope {\n readonly domainScope: InternalWorkflowRuntimeInput[\"state\"][\"domainScope\"];\n readonly organizationId: string;\n readonly userId: string;\n}\n\nfunction readyExecSql(\n runtime: InternalWorkflowRuntimeInput,\n): InternalWorkflowRuntimeInput[\"infra\"][\"execSql\"] | null {\n return runtime.infra.dbStatus === \"ready\" ? runtime.infra.execSql : null;\n}\n\nfunction isActiveContainerInfoOrganizationScope(\n runtime: InternalWorkflowRuntimeInput,\n scope: ContainerInfoOrganizationScope,\n): boolean {\n return (\n runtime.auth.isAuthenticated &&\n runtime.auth.organizationId === scope.organizationId &&\n runtime.auth.userId === scope.userId &&\n runtime.state.domainScope === scope.domainScope\n );\n}\n\nfunction purgeDocumentFromLinks(input: {\n readonly document: Parameters<ContainerDocumentLinks[\"purgeDocument\"]>[0];\n readonly resolveProjectionUserKey: ContainerDocumentLinks[\"resolveProjectionUserKey\"];\n readonly runtime: ContainerDocumentLinks;\n}) {\n const { note } = input.document;\n if (!note.documentId) {\n return purgeLocalContainerDocument({\n noteId: note.id,\n runtime: input.runtime,\n });\n }\n return purgeRemoteContainerDocument({\n documentId: note.documentId,\n documentKind: note.documentKind ?? DEFAULT_DOCUMENT_KIND,\n noteId: note.id,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n runtime: input.runtime,\n });\n}\n\nclass ContainerContentsService implements ContainerContents {\n private readonly organizationReadModels: OrganizationReadModelCoordinator;\n\n constructor(private readonly runtimeService: InternalRuntime) {\n this.organizationReadModels =\n createOrganizationReadModelCoordinator(runtimeService);\n }\n\n openTree(\n options?: ContainerContentsStoreOptions | undefined,\n ): ContainerContentsStore {\n const runtime = this.workflowRuntime();\n const store = getOrCreateContainerContentsStore(\n runtime.state.domainScope,\n runtime,\n options,\n );\n return store;\n }\n\n documentQueries(): ContainerDocumentQueries {\n return createContainerDocumentQueriesFromRuntime(this.workflowRuntime());\n }\n\n documentLinks(): ContainerDocumentLinks {\n const runtime = this.workflowRuntime();\n const resolveProjectionUserKey =\n createContainerContentsDocumentProjectionUserKeyResolver(runtime);\n const documentRuntime = (containerId: string | null) =>\n createContainerContentsDocumentsRuntime(runtime, containerId);\n const openContainerDocument = (input: OpenContainerDocumentInput) =>\n openDocumentStore(\n runtime.state.domainScope,\n input.localId,\n documentRuntime(input.containerId),\n input.documentId ?? null,\n input.initialText,\n input.initialDocumentKind,\n );\n const documentLinks: ContainerDocumentLinks = {\n ...runtime,\n documentRuntime,\n openDocument: openContainerDocument,\n setActiveDocumentContainer: (input) =>\n activateDocumentLink({\n host: createDocumentLinkHost(\n documentLinks,\n input.mergeDocumentSummary,\n ),\n note: input.note,\n runtime: documentLinks,\n targetContainerId: input.targetContainerId,\n }),\n canMutateDocumentLinks: canMutateDocumentLink(runtime),\n canMutateUnsyncedDocumentLinks: canMutateLocalDocumentLink(runtime),\n linkDocumentToContainer: (input) =>\n addDocumentLink({\n host: createDocumentLinkHost(\n documentLinks,\n input.mergeDocumentSummary,\n ),\n note: input.note,\n runtime: documentLinks,\n scheduleSync: () => this.openTree().requestSync(),\n setLinkedContainerIdsForDocument:\n input.setLinkedContainerIdsForDocument,\n targetContainerId: input.targetContainerId,\n }),\n moveDocumentToContainer: (input) =>\n moveDocumentLink({\n expandNode: input.expandNode,\n host: createDocumentLinkHost(\n documentLinks,\n input.mergeDocumentSummary,\n ),\n note: moveDocumentLinkNote(input),\n replaceLinkedContainers: input.replaceLinkedContainers,\n runtime: documentLinks,\n scheduleSync: () => this.openTree().requestSync(),\n setLinkedContainerIdsForDocument:\n input.setLinkedContainerIdsForDocument,\n targetContainerId: input.targetContainerId,\n }),\n purgeDocument: (document) =>\n purgeDocumentFromLinks({\n document,\n resolveProjectionUserKey,\n runtime: documentLinks,\n }),\n resolveProjectionUserKey,\n unlinkDocumentFromContainer: (input) =>\n removeDocumentLink({\n host: createDocumentLinkHost(\n documentLinks,\n input.mergeDocumentSummary,\n ),\n note: input.note,\n removedContainerId: input.removedContainerId,\n runtime: documentLinks,\n scheduleSync: () => this.openTree().requestSync(),\n setLinkedContainerIdsForDocument:\n input.setLinkedContainerIdsForDocument,\n }),\n };\n\n return inheritPrincipalHistoryProtection(runtime, documentLinks);\n }\n\n discoverContainerDocuments(\n containerId: string,\n ): Promise<ReadonlyArray<DocumentSummary> | null> {\n return discoverContainerDocumentsForRuntime({\n containerId,\n runtimeService: this.runtimeService,\n });\n }\n\n pullDocumentContent(input: {\n containerId: string;\n localId: string;\n documentId?: string | null | undefined;\n }): void {\n const runtime = this.workflowRuntime();\n const store = openDocumentStore(\n runtime.state.domainScope,\n input.localId,\n createContainerContentsDocumentsRuntime(runtime, input.containerId),\n input.documentId ?? null,\n );\n store.requestRemoteSync();\n }\n\n loadContainerInfo(input: ContainerInfoInput): Promise<ContainerInfo> {\n const runtime = this.runtimeService.workflowInput();\n const organizationScope =\n runtime.auth.isAuthenticated &&\n runtime.auth.organizationId &&\n runtime.auth.userId\n ? {\n domainScope: runtime.state.domainScope,\n organizationId: runtime.auth.organizationId,\n userId: runtime.auth.userId,\n }\n : null;\n const cachedContainerProjection =\n input.remoteInfoMode === \"always\"\n ? null\n : this.openTree().getCachedContainerWriterProjection(input.containerId);\n return loadContainerInfo({\n ...input,\n apiClient: runtime.apiClient,\n containerProjection: cachedContainerProjection,\n execSql: readyExecSql(runtime),\n loadOrganizationGroups: async () => {\n if (\n !organizationScope ||\n !isActiveContainerInfoOrganizationScope(\n this.runtimeService.workflowInput(),\n organizationScope,\n )\n ) {\n return [];\n }\n // Organization groups are disposable presentation data. Container\n // writer projections remain the authority for grants and access.\n const projection = await this.organizationReadModels.loadLocal(\n organizationScope.organizationId,\n );\n return isActiveContainerInfoOrganizationScope(\n this.runtimeService.workflowInput(),\n organizationScope,\n )\n ? (projection?.groups ?? [])\n : [];\n },\n parentId: input.parentId ?? null,\n });\n }\n\n loadDocumentInfo(input: DocumentInfoInput): Promise<DocumentInfo> {\n const runtime = this.runtimeService.workflowInput();\n return loadDocumentInfo({\n ...input,\n apiClient: runtime.apiClient,\n execSql: readyExecSql(runtime),\n reportSecurityIncident: runtime.util.reportSecurityIncident,\n });\n }\n\n loadDocumentEditAttribution(\n documentId: string,\n ): ReturnType<ContainerContents[\"loadDocumentEditAttribution\"]> {\n return this.runtimeService\n .workflowInput()\n .apiClient.getDocumentEditAttribution(documentId);\n }\n\n loadDocumentAttributionRanges(\n input: DocumentAttributionRangesInput,\n ): Promise<DocumentAttributionRangesPage> {\n return loadDocumentAttributionRanges({\n apiClient: this.runtimeService.workflowInput().apiClient,\n query: input,\n });\n }\n\n listBlobInfo(input: BlobInfoInput = {}): Promise<BlobInfoList> {\n const runtime = this.runtimeService.workflowInput();\n return listBlobInfo({\n ...input,\n execSql: readyExecSql(runtime),\n });\n }\n\n workflowRuntime(): ContainerContentsStoreWorkflowRuntime {\n return createContainerContentsStoreWorkflowRuntime(\n this.runtimeService.workflowInput(),\n this.runtimeService.adoptRootContainer,\n );\n }\n}\n"]}
1
+ {"version":3,"file":"containerContents.js","sourceRoot":"","sources":["containerContents.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,qCAAqC,CAAC;AAE5E,OAAO,EAAE,iCAAiC,EAAE,MAAM,4CAA4C,CAAC;AAC/F,OAAO,EAGL,iCAAiC,GAClC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAE,uCAAuC,EAAE,MAAM,kDAAkD,CAAC;AAC3G,OAAO,EAGL,YAAY,GACb,MAAM,0CAA0C,CA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AAC,CAAC,EAAE,CAAC;YACT,CAAC;YACD,QAAQ,EAAE,KAAK,CAAC,QAAQ,IAAI,IAAI;SACjC,CAAC,CAAC;IACL,CAAC;IAED,gBAAgB,CAAC,KAAwB;QACvC,MAAM,OAAO,GAAG,IAAI,CAAC,cAAc,CAAC,aAAa,EAAE,CAAC;QACpD,OAAO,gBAAgB,CAAC;YACtB,GAAG,KAAK;YACR,SAAS,EAAE,OAAO,CAAC,SAAS;YAC5B,OAAO,EAAE,YAAY,CAAC,OAAO,CAAC;YAC9B,sBAAsB,EAAE,OAAO,CAAC,IAAI,CAAC,sBAAsB;SAC5D,CAAC,CAAC;IACL,CAAC;IAED,2BAA2B,CACzB,UAAkB;QAElB,OAAO,IAAI,CAAC,cAAc;aACvB,aAAa,EAAE;aACf,SAAS,CAAC,0BAA0B,CAAC,UAAU,CAAC,CAAC;IACtD,CAAC;IAED,6BAA6B,CAC3B,KAAqC;QAErC,OAAO,6BAA6B,CAAC;YACnC,SAAS,EAAE,IAAI,CAAC,cAAc,CAAC,aAAa,EAAE,CAAC,SAAS;YACxD,KAAK,EAAE,KAAK;SACb,CAAC,CAAC;IACL,CAAC;IAED,YAAY,CAAC,QAAuB,EAAE;QACpC,MAAM,OAAO,GAAG,IAAI,CAAC,cAAc,CAAC,aAAa,EAAE,CAAC;QACpD,OAAO,YAAY,CAAC;YAClB,GAAG,KAAK;YACR,OAAO,EAAE,YAAY,CAAC,OAAO,CAAC;SAC/B,CAAC,CAAC;IACL,CAAC;IAED,eAAe;QACb,OAAO,2CAA2C,CAChD,IAAI,CAAC,cAAc,CAAC,aAAa,EAAE,EACnC,IAAI,CAAC,cAAc,CAAC,kBAAkB,CACvC,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { DEFAULT_DOCUMENT_KIND } from \"../data/documents/documentConstants\";\nimport type { DocumentSummary } from \"../data/documents/documentSummary\";\nimport { inheritPrincipalHistoryProtection } from \"../data/principals/principalHistoryRuntime\";\nimport {\n type ContainerContentsStore,\n type ContainerContentsStoreOptions,\n getOrCreateContainerContentsStore,\n} from \"../stores/container-contents\";\nimport { openDocumentStore } from \"../stores/documents\";\nimport { relinkDocumentStoreWithCommitSideEffect } from \"../stores/documents/documentStore/internalRelink\";\nimport {\n type BlobInfoInput,\n type BlobInfoList,\n listBlobInfo,\n} from \"../workflows/container-contents/blobInfo\";\nimport {\n type ContainerInfo,\n loadContainerInfo,\n} from \"../workflows/container-contents/containerInfo\";\nimport {\n type DocumentAttributionRangesInput,\n type DocumentAttributionRangesPage,\n loadDocumentAttributionRanges,\n} from \"../workflows/container-contents/documentAttributionRanges\";\nimport {\n type DocumentInfo,\n loadDocumentInfo,\n} from \"../workflows/container-contents/documentInfo\";\nimport {\n purgeLocalContainerDocument,\n purgeRemoteContainerDocument,\n} from \"../workflows/container-contents/documentPurge\";\nimport {\n type ContainerDocumentQueries,\n createContainerDocumentQueriesFromRuntime,\n} from \"../workflows/container-contents/documentQueries\";\nimport {\n activateDocumentLink,\n addDocumentLink,\n canMutateDocumentLink,\n canMutateLocalDocumentLink,\n type DocumentStructuralMutationHost,\n moveDocumentLink,\n removeDocumentLink,\n} from \"../workflows/container-contents/documentStructure\";\nimport { createContainerContentsDocumentProjectionUserKeyResolver } from \"../workflows/container-contents/projectionKeys\";\nimport {\n type ContainerContentsStoreWorkflowRuntime,\n createContainerContentsDocumentsRuntime,\n createContainerContentsStoreWorkflowRuntime,\n} from \"../workflows/container-contents/runtime\";\nimport { createContainerDocumentObjectSyncState } from \"../workflows/container-contents/syncState\";\nimport type { DocumentsWorkflowRuntime } from \"../workflows/documents\";\nimport type {\n ContainerContents,\n ContainerDocumentLinks,\n ContainerInfoInput,\n DocumentInfoInput,\n MergeDocumentSummary,\n MoveDocumentToContainerInput,\n OpenContainerDocumentInput,\n} from \"./containerContentsTypes\";\nimport { discoverContainerDocumentsForRuntime } from \"./containerDocumentDiscovery\";\nimport {\n createOrganizationReadModelCoordinator,\n type OrganizationReadModelCoordinator,\n} from \"./organizations/organizationReadModels\";\nimport type {\n InternalRuntime,\n InternalWorkflowRuntimeInput,\n} from \"./workflowRuntime\";\n\nexport type {\n ContainerContentsContextValue,\n ContainerContentsStore,\n ContainerContentsStoreOptions,\n ContainerNode,\n} from \"../stores/container-contents\";\nexport type {\n BlobInfo,\n BlobInfoAttachmentKind,\n BlobInfoDocumentReference,\n BlobInfoInput,\n BlobInfoList,\n BlobInfoSort,\n BlobInfoSortDirection,\n BlobInfoSortKey,\n} from \"../workflows/container-contents/blobInfo\";\nexport type {\n ContainerInfo,\n ContainerShareAccessLevel,\n} from \"../workflows/container-contents/containerInfo\";\nexport type {\n DocumentAttributionRangesInput,\n DocumentAttributionRangesPage,\n} from \"../workflows/container-contents/documentAttributionRanges\";\nexport type { DocumentInfo } from \"../workflows/container-contents/documentInfo\";\nexport type {\n ContainerDocumentQueries,\n ContainerDocumentSidebarRow,\n ContainerItemRow,\n ContainerItemSort,\n ContainerItemSortDirection,\n ContainerItemSortKey,\n} from \"../workflows/container-contents/documentQueries\";\nexport type { SetLinkedContainerIdsForDocument } from \"../workflows/container-contents/documentStructure\";\nexport type {\n PendingWriteQueueItem,\n PendingWriteQueueItemStatus,\n PendingWriteQueueObjectKind,\n PendingWriteQueueOperation,\n PendingWriteQueueOperationKind,\n PendingWriteQueueOperationStatus,\n} from \"../workflows/container-contents/pendingWrites\";\nexport type {\n ContainerDocumentObjectSyncState,\n ContainerDocumentObjectSyncStatus,\n} from \"../workflows/container-contents/syncState\";\nexport type {\n ContainerContents,\n ContainerDocumentLinkInput,\n ContainerDocumentLinks,\n ContainerInfoInput,\n DocumentInfoInput,\n LinkDocumentToContainerInput,\n MergeDocumentSummary,\n MoveDocumentToContainerInput,\n OpenContainerDocumentInput,\n PurgeDocumentInput,\n PurgeDocumentResult,\n SetActiveDocumentContainerInput,\n UnlinkDocumentFromContainerInput,\n} from \"./containerContentsTypes\";\n\nexport { createContainerDocumentObjectSyncState };\n\nexport function createContainerContents(\n runtime: InternalRuntime,\n): ContainerContents {\n return new ContainerContentsService(runtime);\n}\n\nfunction createDocumentLinkHost(\n runtime: ContainerDocumentLinks,\n mergeDocumentSummary: MergeDocumentSummary,\n): DocumentStructuralMutationHost<DocumentsWorkflowRuntime> {\n return {\n documentWorkflowRuntime: runtime.documentRuntime,\n mergeDocumentSummary,\n openDocumentStore: (input) => {\n const store = runtime.openDocument({\n containerId: input.containerId,\n documentId: input.documentId,\n localId: input.localId,\n });\n return {\n ...store,\n relink: ({ commitSideEffect, ...relinkInput }) =>\n commitSideEffect\n ? relinkDocumentStoreWithCommitSideEffect(\n store,\n relinkInput,\n commitSideEffect,\n )\n : store.relink(relinkInput),\n };\n },\n };\n}\n\nfunction moveDocumentLinkNote(\n input: Pick<MoveDocumentToContainerInput, \"note\" | \"sourceContainerId\">,\n): DocumentSummary {\n if (\n input.note.documentId &&\n input.sourceContainerId &&\n input.sourceContainerId !== input.note.containerId\n ) {\n return { ...input.note, containerId: input.sourceContainerId };\n }\n\n return input.note;\n}\n\ninterface ContainerInfoOrganizationScope {\n readonly domainScope: InternalWorkflowRuntimeInput[\"state\"][\"domainScope\"];\n readonly organizationId: string;\n readonly userId: string;\n}\n\nfunction readyExecSql(\n runtime: InternalWorkflowRuntimeInput,\n): InternalWorkflowRuntimeInput[\"infra\"][\"execSql\"] | null {\n return runtime.infra.dbStatus === \"ready\" ? runtime.infra.execSql : null;\n}\n\nfunction isActiveContainerInfoOrganizationScope(\n runtime: InternalWorkflowRuntimeInput,\n scope: ContainerInfoOrganizationScope,\n): boolean {\n return (\n runtime.auth.isAuthenticated &&\n runtime.auth.organizationId === scope.organizationId &&\n runtime.auth.userId === scope.userId &&\n runtime.state.domainScope === scope.domainScope\n );\n}\n\nfunction purgeDocumentFromLinks(input: {\n readonly document: Parameters<ContainerDocumentLinks[\"purgeDocument\"]>[0];\n readonly resolveProjectionUserKey: ContainerDocumentLinks[\"resolveProjectionUserKey\"];\n readonly runtime: ContainerDocumentLinks;\n}) {\n const { note } = input.document;\n if (!note.documentId) {\n return purgeLocalContainerDocument({\n noteId: note.id,\n runtime: input.runtime,\n });\n }\n return purgeRemoteContainerDocument({\n documentId: note.documentId,\n documentKind: note.documentKind ?? DEFAULT_DOCUMENT_KIND,\n noteId: note.id,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n runtime: input.runtime,\n });\n}\n\nclass ContainerContentsService implements ContainerContents {\n private readonly organizationReadModels: OrganizationReadModelCoordinator;\n\n constructor(private readonly runtimeService: InternalRuntime) {\n this.organizationReadModels =\n createOrganizationReadModelCoordinator(runtimeService);\n }\n\n openTree(\n options?: ContainerContentsStoreOptions | undefined,\n ): ContainerContentsStore {\n const runtime = this.workflowRuntime();\n const store = getOrCreateContainerContentsStore(\n runtime.state.domainScope,\n runtime,\n options,\n );\n return store;\n }\n\n documentQueries(): ContainerDocumentQueries {\n return createContainerDocumentQueriesFromRuntime(this.workflowRuntime());\n }\n\n documentLinks(): ContainerDocumentLinks {\n const runtime = this.workflowRuntime();\n const resolveProjectionUserKey =\n createContainerContentsDocumentProjectionUserKeyResolver(runtime);\n const documentRuntime = (containerId: string | null) =>\n createContainerContentsDocumentsRuntime(runtime, containerId);\n const openContainerDocument = (input: OpenContainerDocumentInput) =>\n openDocumentStore(\n runtime.state.domainScope,\n input.localId,\n documentRuntime(input.containerId),\n input.documentId ?? null,\n input.initialText,\n input.initialDocumentKind,\n { deferInitialUpdate: input.deferInitialUpdate },\n );\n const documentLinks: ContainerDocumentLinks = {\n ...runtime,\n documentRuntime,\n openDocument: openContainerDocument,\n setActiveDocumentContainer: (input) =>\n activateDocumentLink({\n host: createDocumentLinkHost(\n documentLinks,\n input.mergeDocumentSummary,\n ),\n note: input.note,\n runtime: documentLinks,\n targetContainerId: input.targetContainerId,\n }),\n canMutateDocumentLinks: canMutateDocumentLink(runtime),\n canMutateUnsyncedDocumentLinks: canMutateLocalDocumentLink(runtime),\n linkDocumentToContainer: (input) =>\n addDocumentLink({\n host: createDocumentLinkHost(\n documentLinks,\n input.mergeDocumentSummary,\n ),\n note: input.note,\n runtime: documentLinks,\n scheduleSync: () => this.openTree().requestSync(),\n setLinkedContainerIdsForDocument:\n input.setLinkedContainerIdsForDocument,\n targetContainerId: input.targetContainerId,\n }),\n moveDocumentToContainer: (input) =>\n moveDocumentLink({\n expandNode: input.expandNode,\n host: createDocumentLinkHost(\n documentLinks,\n input.mergeDocumentSummary,\n ),\n note: moveDocumentLinkNote(input),\n replaceLinkedContainers: input.replaceLinkedContainers,\n runtime: documentLinks,\n scheduleSync: () => this.openTree().requestSync(),\n setLinkedContainerIdsForDocument:\n input.setLinkedContainerIdsForDocument,\n targetContainerId: input.targetContainerId,\n }),\n purgeDocument: (document) =>\n purgeDocumentFromLinks({\n document,\n resolveProjectionUserKey,\n runtime: documentLinks,\n }),\n resolveProjectionUserKey,\n unlinkDocumentFromContainer: (input) =>\n removeDocumentLink({\n host: createDocumentLinkHost(\n documentLinks,\n input.mergeDocumentSummary,\n ),\n note: input.note,\n removedContainerId: input.removedContainerId,\n runtime: documentLinks,\n scheduleSync: () => this.openTree().requestSync(),\n setLinkedContainerIdsForDocument:\n input.setLinkedContainerIdsForDocument,\n }),\n };\n\n return inheritPrincipalHistoryProtection(runtime, documentLinks);\n }\n\n discoverContainerDocuments(\n containerId: string,\n ): Promise<ReadonlyArray<DocumentSummary> | null> {\n return discoverContainerDocumentsForRuntime({\n containerId,\n runtimeService: this.runtimeService,\n });\n }\n\n pullDocumentContent(input: {\n containerId: string;\n localId: string;\n documentId?: string | null | undefined;\n }): void {\n const runtime = this.workflowRuntime();\n const store = openDocumentStore(\n runtime.state.domainScope,\n input.localId,\n createContainerContentsDocumentsRuntime(runtime, input.containerId),\n input.documentId ?? null,\n );\n store.requestRemoteSync();\n }\n\n loadContainerInfo(input: ContainerInfoInput): Promise<ContainerInfo> {\n const runtime = this.runtimeService.workflowInput();\n const organizationScope =\n runtime.auth.isAuthenticated &&\n runtime.auth.organizationId &&\n runtime.auth.userId\n ? {\n domainScope: runtime.state.domainScope,\n organizationId: runtime.auth.organizationId,\n userId: runtime.auth.userId,\n }\n : null;\n const cachedContainerProjection =\n input.remoteInfoMode === \"always\"\n ? null\n : this.openTree().getCachedContainerWriterProjection(input.containerId);\n return loadContainerInfo({\n ...input,\n apiClient: runtime.apiClient,\n containerProjection: cachedContainerProjection,\n execSql: readyExecSql(runtime),\n loadOrganizationGroups: async () => {\n if (\n !organizationScope ||\n !isActiveContainerInfoOrganizationScope(\n this.runtimeService.workflowInput(),\n organizationScope,\n )\n ) {\n return [];\n }\n // Organization groups are disposable presentation data. Container\n // writer projections remain the authority for grants and access.\n const projection = await this.organizationReadModels.loadLocal(\n organizationScope.organizationId,\n );\n return isActiveContainerInfoOrganizationScope(\n this.runtimeService.workflowInput(),\n organizationScope,\n )\n ? (projection?.groups ?? [])\n : [];\n },\n parentId: input.parentId ?? null,\n });\n }\n\n loadDocumentInfo(input: DocumentInfoInput): Promise<DocumentInfo> {\n const runtime = this.runtimeService.workflowInput();\n return loadDocumentInfo({\n ...input,\n apiClient: runtime.apiClient,\n execSql: readyExecSql(runtime),\n reportSecurityIncident: runtime.util.reportSecurityIncident,\n });\n }\n\n loadDocumentEditAttribution(\n documentId: string,\n ): ReturnType<ContainerContents[\"loadDocumentEditAttribution\"]> {\n return this.runtimeService\n .workflowInput()\n .apiClient.getDocumentEditAttribution(documentId);\n }\n\n loadDocumentAttributionRanges(\n input: DocumentAttributionRangesInput,\n ): Promise<DocumentAttributionRangesPage> {\n return loadDocumentAttributionRanges({\n apiClient: this.runtimeService.workflowInput().apiClient,\n query: input,\n });\n }\n\n listBlobInfo(input: BlobInfoInput = {}): Promise<BlobInfoList> {\n const runtime = this.runtimeService.workflowInput();\n return listBlobInfo({\n ...input,\n execSql: readyExecSql(runtime),\n });\n }\n\n workflowRuntime(): ContainerContentsStoreWorkflowRuntime {\n return createContainerContentsStoreWorkflowRuntime(\n this.runtimeService.workflowInput(),\n this.runtimeService.adoptRootContainer,\n );\n }\n}\n"]}
@@ -51,6 +51,8 @@ export interface DocumentInfoInput {
51
51
  export type MergeDocumentSummary = (nextDocument: DocumentSummary) => void;
52
52
  export interface OpenContainerDocumentInput {
53
53
  readonly containerId: string | null;
54
+ /** A file attach follows creation and carries the birth; see the store. */
55
+ readonly deferInitialUpdate?: boolean | undefined;
54
56
  readonly documentId?: string | null | undefined;
55
57
  readonly initialDocumentKind?: StoredDocumentKind | undefined;
56
58
  readonly initialText?: string | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"containerContentsTypes.js","sourceRoot":"","sources":["containerContentsTypes.ts"],"names":[],"mappings":"","sourcesContent":["import type { DocumentEditAttributionResponse } from \"@tearleads/validators/response\";\nimport type { StoredDocumentKind } from \"../data/documents/documentKinds\";\nimport type { DocumentSummary } from \"../data/documents/documentSummary\";\nimport type {\n ContainerContentsStore,\n ContainerContentsStoreOptions,\n ContainerContentsStoreRuntime,\n} from \"../stores/container-contents\";\nimport type { DocumentStore } from \"../stores/documents\";\nimport type {\n BlobInfoInput,\n BlobInfoList,\n} from \"../workflows/container-contents/blobInfo\";\nimport type {\n ContainerInfo,\n ContainerInfoRemoteMode,\n} from \"../workflows/container-contents/containerInfo\";\nimport type {\n DocumentAttributionRangesInput,\n DocumentAttributionRangesPage,\n} from \"../workflows/container-contents/documentAttributionRanges\";\nimport type {\n DocumentInfo,\n DocumentInfoRemoteMode,\n} from \"../workflows/container-contents/documentInfo\";\nimport type { ContainerDocumentQueries } from \"../workflows/container-contents/documentQueries\";\nimport type { SetLinkedContainerIdsForDocument } from \"../workflows/container-contents/documentStructure\";\nimport type { ContainerContentsProjectionUserKeyResolver } from \"../workflows/container-contents/projectionKeys\";\nimport type { ContainerContentsWorkflowRuntime } from \"../workflows/container-contents/runtime\";\nimport type { DocumentsWorkflowRuntime } from \"../workflows/documents\";\n\n/**\n * Selects the container to inspect.\n *\n * Container info combines local SQLite timestamps with optional remote writer\n * projection details. Remote details include direct and inherited grants,\n * organization groups, security-path metadata, and sync watermarks for the\n * parent, child-container, and document lanes.\n *\n * Fields:\n * - `containerId`: Container id to inspect.\n * - `parentId`: Known parent id used when the container has not been synced\n * locally yet. Synced local state wins when available.\n * - `remoteInfoMode`: Controls whether remote projection details are fetched.\n */\nexport interface ContainerInfoInput {\n containerId: string;\n parentId?: string | null | undefined;\n remoteInfoMode?: ContainerInfoRemoteMode | undefined;\n}\n\n/**\n * Selects the document to inspect.\n *\n * Document info combines local document state, local and pending attachment\n * rows, and optional remote writer projection details.\n *\n * Fields:\n * - `attributionRequestKey`: Optional freshness generation used to coalesce\n * duplicate attribution reads without joining requests across invalidation.\n * - `localId`: Local document id stored in the client database.\n * - `remoteInfoMode`: Controls whether remote projection details are fetched.\n */\nexport interface DocumentInfoInput {\n attributionRequestKey?: string | undefined;\n localId: string;\n remoteInfoMode?: DocumentInfoRemoteMode | undefined;\n}\n\nexport type MergeDocumentSummary = (nextDocument: DocumentSummary) => void;\n\nexport interface OpenContainerDocumentInput {\n readonly containerId: string | null;\n readonly documentId?: string | null | undefined;\n readonly initialDocumentKind?: StoredDocumentKind | undefined;\n readonly initialText?: string | undefined;\n readonly localId: string;\n}\n\nexport interface ContainerDocumentLinkInput {\n readonly mergeDocumentSummary: MergeDocumentSummary;\n readonly note: DocumentSummary;\n}\n\nexport interface MoveDocumentToContainerInput\n extends ContainerDocumentLinkInput {\n readonly expandNode: (nodeId: string) => void;\n readonly replaceLinkedContainers?: boolean | undefined;\n readonly setLinkedContainerIdsForDocument: SetLinkedContainerIdsForDocument;\n readonly sourceContainerId?: string | null | undefined;\n readonly targetContainerId: string;\n}\n\nexport interface LinkDocumentToContainerInput\n extends ContainerDocumentLinkInput {\n readonly setLinkedContainerIdsForDocument: SetLinkedContainerIdsForDocument;\n readonly targetContainerId: string;\n}\n\nexport interface UnlinkDocumentFromContainerInput\n extends ContainerDocumentLinkInput {\n readonly removedContainerId: string;\n readonly setLinkedContainerIdsForDocument: SetLinkedContainerIdsForDocument;\n}\n\nexport interface SetActiveDocumentContainerInput\n extends ContainerDocumentLinkInput {\n readonly targetContainerId: string;\n}\n\nexport interface PurgeDocumentInput {\n /** The current local summary of the document to destroy. */\n readonly note: DocumentSummary;\n}\n\nexport interface PurgeDocumentResult {\n readonly documentId: string;\n readonly purgedAt: string;\n readonly reclaimedBlobStorageKeys: ReadonlyArray<string>;\n}\n\nexport interface ContainerDocumentLinks\n extends ContainerContentsWorkflowRuntime {\n documentRuntime(containerId: string | null): DocumentsWorkflowRuntime;\n openDocument(input: OpenContainerDocumentInput): DocumentStore;\n setActiveDocumentContainer(\n input: SetActiveDocumentContainerInput,\n ): Promise<DocumentSummary | null>;\n readonly canMutateDocumentLinks: boolean;\n readonly canMutateUnsyncedDocumentLinks: boolean;\n linkDocumentToContainer(\n input: LinkDocumentToContainerInput,\n ): Promise<DocumentSummary | null>;\n moveDocumentToContainer(\n input: MoveDocumentToContainerInput,\n ): Promise<{ linksChanged: boolean; note: DocumentSummary | null }>;\n /**\n * Permanently destroy a local-only document, or submit and verify a signed\n * terminal purge for a remote document. Remote purge requires exactly one\n * remaining container link and returns null on refusal or verification\n * failure.\n */\n purgeDocument(input: PurgeDocumentInput): Promise<PurgeDocumentResult | null>;\n readonly resolveProjectionUserKey: ContainerContentsProjectionUserKeyResolver;\n unlinkDocumentFromContainer(\n input: UnlinkDocumentFromContainerInput,\n ): Promise<DocumentSummary | null>;\n}\n\n/**\n * High-level container-content service for tree state, document lists, document\n * links, discovery, and diagnostics.\n *\n * The facade owns the normal SDK protocol: it supplies the API client,\n * referenced-principal policy cache, local document query helpers, link\n * projection, tombstone handling, and sync watermarks. Consumers that need a\n * custom persistence protocol can call the lower-level workflows directly from\n * `@tearleads/client-sdk`.\n */\nexport interface ContainerContents {\n /**\n * Open the container tree state store for the current SDK runtime.\n *\n * The store is cached per domain scope and created from the current runtime\n * snapshot. Long-lived hosts should call `updateRuntime` after runtime\n * changes, such as from a React effect.\n */\n openTree(\n options?: ContainerContentsStoreOptions | undefined,\n ): ContainerContentsStore;\n\n /**\n * Create local document query helpers for container contents.\n *\n * The facade is bound to the current SDK runtime snapshot, including the\n * active SQLite executor. Recreate it when the SDK runtime version changes.\n */\n documentQueries(): ContainerDocumentQueries;\n\n /**\n * Create the default document-link workflow helper.\n *\n * The returned object includes the current container-contents runtime,\n * the document projection-key resolver, mutation readiness, document store\n * priming, and container document-link mutations. Product stores can pass\n * this bundle around without rebuilding SDK runtime plumbing themselves.\n */\n documentLinks(): ContainerDocumentLinks;\n\n /**\n * Discover remote documents linked to one container.\n *\n * The method pages the remote container-document lane, writes discovered\n * document summaries into local SQLite, replaces the local link projection for\n * each discovered document, applies applicable tombstones, caches referenced\n * principal policies needed by newly visible documents, and advances the\n * container-document watermark after the local apply completes.\n *\n * One call verifies a bounded batch. Pending evidence is durable; a later\n * explicit call or background reconciliation resumes it.\n *\n * Returns the summaries touched by the apply, or `null` when the database or\n * listing is unavailable, a trust reset cancels the pass, or all evidence is\n * pending. Pending evidence may advance the watermark after durable staging.\n *\n * Parameters:\n * - `containerId`: Remote container id whose document lane should be listed.\n */\n discoverContainerDocuments(\n containerId: string,\n ): Promise<ReadonlyArray<DocumentSummary> | null>;\n\n /**\n * Sync the content of a single document that no mini-app has opened.\n *\n * Discovery only records a document's metadata + an empty content shell, and a\n * document's locally authored content is only pushed once its store syncs; both\n * normally happen lazily when a mini-app opens the document. Some documents are\n * never opened yet still need to sync — notably the organization profile\n * document, which lives in an org's Members-granted metadata container and\n * holds the org display name. This opens a transient document store (registered\n * under the container's keys, so it can decrypt) and schedules a remote sync\n * pass. The pass both pushes the store's pending updates and merges + persists\n * any remote body, so the same call lets an owning device publish its profile\n * content and a member device pull it. `documentId` may be omitted; the store\n * then resolves it from the persisted record (the owning device keys the\n * document under a local alias, not its server id).\n */\n pullDocumentContent(input: {\n containerId: string;\n localId: string;\n documentId?: string | null | undefined;\n }): void;\n\n /**\n * Load diagnostic information for one local document.\n *\n * Local details are available when SQLite is ready. Remote details are loaded\n * from the document writer projection according to `remoteInfoMode`; the\n * default is `\"if-synced\"`.\n */\n loadDocumentInfo(input: DocumentInfoInput): Promise<DocumentInfo>;\n\n /**\n * Fetch a synced document's compact edit-attribution segments (peer -> writer\n * intervals) on their own, without the writer-projection/attachment work\n * `loadDocumentInfo` also does. Resolves to `null` on any request failure.\n * Callers must ignore the segments when `truncated` is set — a truncated\n * interval list can drop a peer's segments and mis-resolve it.\n */\n loadDocumentEditAttribution(\n documentId: string,\n ): Promise<DocumentEditAttributionResponse | null>;\n\n /** Load one revision-bound page of detailed per-upload edit attribution. */\n loadDocumentAttributionRanges(\n input: DocumentAttributionRangesInput,\n ): Promise<DocumentAttributionRangesPage>;\n\n /**\n * List local blob projections and pending attachment bytes grouped by blob.\n *\n * This is a reverse lookup query: callers can search by server blob id,\n * local storage key, document id/title, attachment slot, or MIME metadata and\n * then traverse matching blobs back to their owning local documents.\n */\n listBlobInfo(input?: BlobInfoInput | undefined): Promise<BlobInfoList>;\n\n /**\n * Load diagnostic information for one container.\n *\n * Local details include synced timestamps. Remote details are loaded from the\n * container writer projection according to `remoteInfoMode`; the default is\n * `\"always\"`. Pass `parentId` when inspecting a container before its local row\n * has been synced.\n */\n loadContainerInfo(input: ContainerInfoInput): Promise<ContainerInfo>;\n\n /**\n * Create a workflow runtime for advanced container-content workflows.\n *\n * Prefer the high-level methods on this service for the default SDK protocol.\n * Use this when constructing lower-level stores or custom workflows that need\n * access to the current runtime snapshot.\n */\n workflowRuntime(): ContainerContentsStoreRuntime;\n}\n"]}
1
+ {"version":3,"file":"containerContentsTypes.js","sourceRoot":"","sources":["containerContentsTypes.ts"],"names":[],"mappings":"","sourcesContent":["import type { DocumentEditAttributionResponse } from \"@tearleads/validators/response\";\nimport type { StoredDocumentKind } from \"../data/documents/documentKinds\";\nimport type { DocumentSummary } from \"../data/documents/documentSummary\";\nimport type {\n ContainerContentsStore,\n ContainerContentsStoreOptions,\n ContainerContentsStoreRuntime,\n} from \"../stores/container-contents\";\nimport type { DocumentStore } from \"../stores/documents\";\nimport type {\n BlobInfoInput,\n BlobInfoList,\n} from \"../workflows/container-contents/blobInfo\";\nimport type {\n ContainerInfo,\n ContainerInfoRemoteMode,\n} from \"../workflows/container-contents/containerInfo\";\nimport type {\n DocumentAttributionRangesInput,\n DocumentAttributionRangesPage,\n} from \"../workflows/container-contents/documentAttributionRanges\";\nimport type {\n DocumentInfo,\n DocumentInfoRemoteMode,\n} from \"../workflows/container-contents/documentInfo\";\nimport type { ContainerDocumentQueries } from \"../workflows/container-contents/documentQueries\";\nimport type { SetLinkedContainerIdsForDocument } from \"../workflows/container-contents/documentStructure\";\nimport type { ContainerContentsProjectionUserKeyResolver } from \"../workflows/container-contents/projectionKeys\";\nimport type { ContainerContentsWorkflowRuntime } from \"../workflows/container-contents/runtime\";\nimport type { DocumentsWorkflowRuntime } from \"../workflows/documents\";\n\n/**\n * Selects the container to inspect.\n *\n * Container info combines local SQLite timestamps with optional remote writer\n * projection details. Remote details include direct and inherited grants,\n * organization groups, security-path metadata, and sync watermarks for the\n * parent, child-container, and document lanes.\n *\n * Fields:\n * - `containerId`: Container id to inspect.\n * - `parentId`: Known parent id used when the container has not been synced\n * locally yet. Synced local state wins when available.\n * - `remoteInfoMode`: Controls whether remote projection details are fetched.\n */\nexport interface ContainerInfoInput {\n containerId: string;\n parentId?: string | null | undefined;\n remoteInfoMode?: ContainerInfoRemoteMode | undefined;\n}\n\n/**\n * Selects the document to inspect.\n *\n * Document info combines local document state, local and pending attachment\n * rows, and optional remote writer projection details.\n *\n * Fields:\n * - `attributionRequestKey`: Optional freshness generation used to coalesce\n * duplicate attribution reads without joining requests across invalidation.\n * - `localId`: Local document id stored in the client database.\n * - `remoteInfoMode`: Controls whether remote projection details are fetched.\n */\nexport interface DocumentInfoInput {\n attributionRequestKey?: string | undefined;\n localId: string;\n remoteInfoMode?: DocumentInfoRemoteMode | undefined;\n}\n\nexport type MergeDocumentSummary = (nextDocument: DocumentSummary) => void;\n\nexport interface OpenContainerDocumentInput {\n readonly containerId: string | null;\n /** A file attach follows creation and carries the birth; see the store. */\n readonly deferInitialUpdate?: boolean | undefined;\n readonly documentId?: string | null | undefined;\n readonly initialDocumentKind?: StoredDocumentKind | undefined;\n readonly initialText?: string | undefined;\n readonly localId: string;\n}\n\nexport interface ContainerDocumentLinkInput {\n readonly mergeDocumentSummary: MergeDocumentSummary;\n readonly note: DocumentSummary;\n}\n\nexport interface MoveDocumentToContainerInput\n extends ContainerDocumentLinkInput {\n readonly expandNode: (nodeId: string) => void;\n readonly replaceLinkedContainers?: boolean | undefined;\n readonly setLinkedContainerIdsForDocument: SetLinkedContainerIdsForDocument;\n readonly sourceContainerId?: string | null | undefined;\n readonly targetContainerId: string;\n}\n\nexport interface LinkDocumentToContainerInput\n extends ContainerDocumentLinkInput {\n readonly setLinkedContainerIdsForDocument: SetLinkedContainerIdsForDocument;\n readonly targetContainerId: string;\n}\n\nexport interface UnlinkDocumentFromContainerInput\n extends ContainerDocumentLinkInput {\n readonly removedContainerId: string;\n readonly setLinkedContainerIdsForDocument: SetLinkedContainerIdsForDocument;\n}\n\nexport interface SetActiveDocumentContainerInput\n extends ContainerDocumentLinkInput {\n readonly targetContainerId: string;\n}\n\nexport interface PurgeDocumentInput {\n /** The current local summary of the document to destroy. */\n readonly note: DocumentSummary;\n}\n\nexport interface PurgeDocumentResult {\n readonly documentId: string;\n readonly purgedAt: string;\n readonly reclaimedBlobStorageKeys: ReadonlyArray<string>;\n}\n\nexport interface ContainerDocumentLinks\n extends ContainerContentsWorkflowRuntime {\n documentRuntime(containerId: string | null): DocumentsWorkflowRuntime;\n openDocument(input: OpenContainerDocumentInput): DocumentStore;\n setActiveDocumentContainer(\n input: SetActiveDocumentContainerInput,\n ): Promise<DocumentSummary | null>;\n readonly canMutateDocumentLinks: boolean;\n readonly canMutateUnsyncedDocumentLinks: boolean;\n linkDocumentToContainer(\n input: LinkDocumentToContainerInput,\n ): Promise<DocumentSummary | null>;\n moveDocumentToContainer(\n input: MoveDocumentToContainerInput,\n ): Promise<{ linksChanged: boolean; note: DocumentSummary | null }>;\n /**\n * Permanently destroy a local-only document, or submit and verify a signed\n * terminal purge for a remote document. Remote purge requires exactly one\n * remaining container link and returns null on refusal or verification\n * failure.\n */\n purgeDocument(input: PurgeDocumentInput): Promise<PurgeDocumentResult | null>;\n readonly resolveProjectionUserKey: ContainerContentsProjectionUserKeyResolver;\n unlinkDocumentFromContainer(\n input: UnlinkDocumentFromContainerInput,\n ): Promise<DocumentSummary | null>;\n}\n\n/**\n * High-level container-content service for tree state, document lists, document\n * links, discovery, and diagnostics.\n *\n * The facade owns the normal SDK protocol: it supplies the API client,\n * referenced-principal policy cache, local document query helpers, link\n * projection, tombstone handling, and sync watermarks. Consumers that need a\n * custom persistence protocol can call the lower-level workflows directly from\n * `@tearleads/client-sdk`.\n */\nexport interface ContainerContents {\n /**\n * Open the container tree state store for the current SDK runtime.\n *\n * The store is cached per domain scope and created from the current runtime\n * snapshot. Long-lived hosts should call `updateRuntime` after runtime\n * changes, such as from a React effect.\n */\n openTree(\n options?: ContainerContentsStoreOptions | undefined,\n ): ContainerContentsStore;\n\n /**\n * Create local document query helpers for container contents.\n *\n * The facade is bound to the current SDK runtime snapshot, including the\n * active SQLite executor. Recreate it when the SDK runtime version changes.\n */\n documentQueries(): ContainerDocumentQueries;\n\n /**\n * Create the default document-link workflow helper.\n *\n * The returned object includes the current container-contents runtime,\n * the document projection-key resolver, mutation readiness, document store\n * priming, and container document-link mutations. Product stores can pass\n * this bundle around without rebuilding SDK runtime plumbing themselves.\n */\n documentLinks(): ContainerDocumentLinks;\n\n /**\n * Discover remote documents linked to one container.\n *\n * The method pages the remote container-document lane, writes discovered\n * document summaries into local SQLite, replaces the local link projection for\n * each discovered document, applies applicable tombstones, caches referenced\n * principal policies needed by newly visible documents, and advances the\n * container-document watermark after the local apply completes.\n *\n * One call verifies a bounded batch. Pending evidence is durable; a later\n * explicit call or background reconciliation resumes it.\n *\n * Returns the summaries touched by the apply, or `null` when the database or\n * listing is unavailable, a trust reset cancels the pass, or all evidence is\n * pending. Pending evidence may advance the watermark after durable staging.\n *\n * Parameters:\n * - `containerId`: Remote container id whose document lane should be listed.\n */\n discoverContainerDocuments(\n containerId: string,\n ): Promise<ReadonlyArray<DocumentSummary> | null>;\n\n /**\n * Sync the content of a single document that no mini-app has opened.\n *\n * Discovery only records a document's metadata + an empty content shell, and a\n * document's locally authored content is only pushed once its store syncs; both\n * normally happen lazily when a mini-app opens the document. Some documents are\n * never opened yet still need to sync — notably the organization profile\n * document, which lives in an org's Members-granted metadata container and\n * holds the org display name. This opens a transient document store (registered\n * under the container's keys, so it can decrypt) and schedules a remote sync\n * pass. The pass both pushes the store's pending updates and merges + persists\n * any remote body, so the same call lets an owning device publish its profile\n * content and a member device pull it. `documentId` may be omitted; the store\n * then resolves it from the persisted record (the owning device keys the\n * document under a local alias, not its server id).\n */\n pullDocumentContent(input: {\n containerId: string;\n localId: string;\n documentId?: string | null | undefined;\n }): void;\n\n /**\n * Load diagnostic information for one local document.\n *\n * Local details are available when SQLite is ready. Remote details are loaded\n * from the document writer projection according to `remoteInfoMode`; the\n * default is `\"if-synced\"`.\n */\n loadDocumentInfo(input: DocumentInfoInput): Promise<DocumentInfo>;\n\n /**\n * Fetch a synced document's compact edit-attribution segments (peer -> writer\n * intervals) on their own, without the writer-projection/attachment work\n * `loadDocumentInfo` also does. Resolves to `null` on any request failure.\n * Callers must ignore the segments when `truncated` is set — a truncated\n * interval list can drop a peer's segments and mis-resolve it.\n */\n loadDocumentEditAttribution(\n documentId: string,\n ): Promise<DocumentEditAttributionResponse | null>;\n\n /** Load one revision-bound page of detailed per-upload edit attribution. */\n loadDocumentAttributionRanges(\n input: DocumentAttributionRangesInput,\n ): Promise<DocumentAttributionRangesPage>;\n\n /**\n * List local blob projections and pending attachment bytes grouped by blob.\n *\n * This is a reverse lookup query: callers can search by server blob id,\n * local storage key, document id/title, attachment slot, or MIME metadata and\n * then traverse matching blobs back to their owning local documents.\n */\n listBlobInfo(input?: BlobInfoInput | undefined): Promise<BlobInfoList>;\n\n /**\n * Load diagnostic information for one container.\n *\n * Local details include synced timestamps. Remote details are loaded from the\n * container writer projection according to `remoteInfoMode`; the default is\n * `\"always\"`. Pass `parentId` when inspecting a container before its local row\n * has been synced.\n */\n loadContainerInfo(input: ContainerInfoInput): Promise<ContainerInfo>;\n\n /**\n * Create a workflow runtime for advanced container-content workflows.\n *\n * Prefer the high-level methods on this service for the default SDK protocol.\n * Use this when constructing lower-level stores or custom workflows that need\n * access to the current runtime snapshot.\n */\n workflowRuntime(): ContainerContentsStoreRuntime;\n}\n"]}
@@ -52,7 +52,7 @@ class DocumentsService {
52
52
  open(input = {}, options = {}) {
53
53
  const { containerId, documentId = null, initialDocumentKind = DEFAULT_DOCUMENT_KIND, initialText = "", localId = DEFAULT_LOCAL_DOCUMENT_ID, } = input;
54
54
  const runtime = options.workflowRuntime ?? this.workflowRuntime(containerId);
55
- return openDocumentStore(runtime.state.domainScope, localId, runtime, documentId, initialText, initialDocumentKind, options.remoteSyncMode ?? "startup");
55
+ return openDocumentStore(runtime.state.domainScope, localId, runtime, documentId, initialText, initialDocumentKind, { remoteSyncMode: options.remoteSyncMode });
56
56
  }
57
57
  subscribe(listener, options = {}) {
58
58
  return subscribeToPersistedDocuments(this.dependencies.runtime.workflowInput(options.containerId).state
@@ -1 +1 @@
1
- {"version":3,"file":"documents.js","sourceRoot":"","sources":["documents.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,qCAAqC,CAAC;AAU5E,OAAO,EACL,mBAAmB,IAAI,yBAAyB,EAGhD,iBAAiB,EAEjB,6BAA6B,GAC9B,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,6BAA6B,EAAE,MAAM,8BAA8B,CAAC;AAC7E,OAAO,EACL,8BAA8B,EAC9B,2BAA2B,EAC3B,uBAAuB,EACvB,0BAA0B,GAC3B,MAAM,wBAAwB,CAAC;AAqBhC,OAAO,EAAE,yBAAyB,IAAI,mBAAmB,EAAE,CAAC;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AAC,WAAW,CAAC,CAAC,KAAK;aAC/D,WAAW,EACd,QAAQ,CACT,CAAC;IACJ,CAAC;IAEO,YAAY,CAAC,OAAgB;QACnC,MAAM,QAAQ,GAAG,IAAI,CAAC,sBAAsB,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QAC1D,IAAI,QAAQ,EAAE,CAAC;YACb,OAAO,QAAQ,CAAC;QAClB,CAAC;QAED,MAAM,MAAM,GAAG,2BAA2B;aACvC,YAAY,CAAC,OAAO,CAAC;aACrB,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;YACxB,IAAI,CAAC,sBAAsB,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;YAC5C,MAAM,KAAK,CAAC;QACd,CAAC,CAAC,CAAC;QACL,IAAI,CAAC,sBAAsB,CAAC,GAAG,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QACjD,OAAO,MAAM,CAAC;IAChB,CAAC;CACF","sourcesContent":["import { DEFAULT_DOCUMENT_KIND } from \"../data/documents/documentConstants\";\nimport type { StoredDocumentKind } from \"../data/documents/documentKinds\";\nimport type {\n DocumentSummaryList,\n DocumentSummarySort,\n DocumentSummarySortDirection,\n DocumentSummarySortKey,\n ListDocumentSummariesInput,\n} from \"../data/persistence/documents/types\";\nimport type { ExecSql } from \"../data/sqlite/sqlSchema\";\nimport {\n DEFAULT_DOCUMENT_ID as DEFAULT_LOCAL_DOCUMENT_ID,\n type DocumentStore,\n type DocumentsRuntime,\n openDocumentStore,\n type PersistedDocumentListener,\n subscribeToPersistedDocuments,\n} from \"../stores/documents\";\nimport { emitPersistedDocumentDeletion } from \"../stores/documents/registry\";\nimport {\n createDocumentsWorkflowRuntime,\n defaultDocumentsPersistence,\n deletePersistedDocument,\n reclaimDocumentOrphanBlobs,\n} from \"../workflows/documents\";\nimport type { InternalRuntime } from \"./workflowRuntime\";\n\nexport type {\n DocumentAttachmentStatus,\n DocumentAttachmentUpload,\n DocumentContextValue,\n DocumentStore,\n DocumentsRuntime,\n PersistedDocumentListener,\n} from \"../stores/documents\";\n\nexport type DocumentSortDirection = DocumentSummarySortDirection;\nexport type DocumentSortKey = DocumentSummarySortKey;\n\nexport type DocumentSort = DocumentSummarySort;\n\nexport interface ListDocumentsInput extends ListDocumentSummariesInput {}\n\nexport type DocumentList = DocumentSummaryList;\n\nexport { DEFAULT_LOCAL_DOCUMENT_ID as DEFAULT_DOCUMENT_ID };\n\nexport interface OpenDocumentInput {\n readonly containerId?: string | null | undefined;\n readonly documentId?: string | null | undefined;\n readonly initialDocumentKind?: StoredDocumentKind | undefined;\n readonly initialText?: string | undefined;\n readonly localId?: string | undefined;\n}\n\nexport interface OpenDocumentOptions {\n readonly remoteSyncMode?: \"on-demand\" | \"startup\" | undefined;\n readonly workflowRuntime?: DocumentsRuntime | undefined;\n}\n\nexport interface DocumentSubscriptionOptions {\n readonly containerId?: string | null | undefined;\n}\n\nexport interface Documents {\n delete(localId: string): Promise<boolean>;\n findLocalIdByDocumentId(documentId: string): Promise<string | null>;\n list(input?: ListDocumentsInput | undefined): Promise<DocumentList | null>;\n open(\n input?: OpenDocumentInput | undefined,\n options?: OpenDocumentOptions | undefined,\n ): DocumentStore;\n subscribe(\n listener: PersistedDocumentListener,\n options?: DocumentSubscriptionOptions | undefined,\n ): () => void;\n workflowRuntime(containerId?: string | null | undefined): DocumentsRuntime;\n}\n\ninterface DocumentsDependencies {\n getDefaultContainerId: () => string | null;\n runtime: InternalRuntime;\n}\n\nexport function createDocuments(\n dependencies: DocumentsDependencies,\n): Documents {\n return new DocumentsService(dependencies);\n}\n\nclass DocumentsService implements Documents {\n private readonly schemaEnsuresByExecSql = new WeakMap<\n ExecSql,\n Promise<void>\n >();\n\n constructor(private readonly dependencies: DocumentsDependencies) {}\n\n async delete(localId: string): Promise<boolean> {\n const runtime = this.workflowRuntime();\n if (runtime.infra.dbStatus !== \"ready\") {\n return false;\n }\n\n const deleted = await deletePersistedDocument({\n documentProjectors: runtime.infra.documentProjectors,\n execSql: runtime.infra.execSql,\n localId,\n persistence: defaultDocumentsPersistence,\n });\n if (!deleted) return false;\n void reclaimDocumentOrphanBlobs(runtime);\n emitPersistedDocumentDeletion(runtime.state.domainScope, localId);\n return true;\n }\n\n async findLocalIdByDocumentId(documentId: string): Promise<string | null> {\n const runtime = this.dependencies.runtime.workflowInput();\n if (runtime.infra.dbStatus !== \"ready\") {\n return null;\n }\n\n await this.ensureSchema(runtime.infra.execSql);\n return defaultDocumentsPersistence.findLocalIdByDocumentId(\n runtime.infra.execSql,\n documentId,\n );\n }\n\n async list(input: ListDocumentsInput = {}): Promise<DocumentList | null> {\n const runtime = this.dependencies.runtime.workflowInput();\n if (runtime.infra.dbStatus !== \"ready\") {\n return null;\n }\n\n await this.ensureSchema(runtime.infra.execSql);\n return defaultDocumentsPersistence.listDocumentSummaries(\n runtime.infra.execSql,\n input,\n );\n }\n\n workflowRuntime(\n containerId = this.dependencies.getDefaultContainerId(),\n ): DocumentsRuntime {\n const input = this.dependencies.runtime.workflowInput(containerId);\n return createDocumentsWorkflowRuntime(input);\n }\n\n open(\n input: OpenDocumentInput = {},\n options: OpenDocumentOptions = {},\n ): DocumentStore {\n const {\n containerId,\n documentId = null,\n initialDocumentKind = DEFAULT_DOCUMENT_KIND,\n initialText = \"\",\n localId = DEFAULT_LOCAL_DOCUMENT_ID,\n } = input;\n const runtime =\n options.workflowRuntime ?? this.workflowRuntime(containerId);\n return openDocumentStore(\n runtime.state.domainScope,\n localId,\n runtime,\n documentId,\n initialText,\n initialDocumentKind,\n options.remoteSyncMode ?? \"startup\",\n );\n }\n\n subscribe(\n listener: PersistedDocumentListener,\n options: DocumentSubscriptionOptions = {},\n ): () => void {\n return subscribeToPersistedDocuments(\n this.dependencies.runtime.workflowInput(options.containerId).state\n .domainScope,\n listener,\n );\n }\n\n private ensureSchema(execSql: ExecSql): Promise<void> {\n const existing = this.schemaEnsuresByExecSql.get(execSql);\n if (existing) {\n return existing;\n }\n\n const ensure = defaultDocumentsPersistence\n .ensureSchema(execSql)\n .catch((error: unknown) => {\n this.schemaEnsuresByExecSql.delete(execSql);\n throw error;\n });\n this.schemaEnsuresByExecSql.set(execSql, ensure);\n return ensure;\n }\n}\n"]}
1
+ {"version":3,"file":"documents.js","sourceRoot":"","sources":["documents.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,qCAAqC,CAAC;AAU5E,OAAO,EACL,mBAAmB,IAAI,yBAAyB,EAGhD,iBAAiB,EAEjB,6BAA6B,GAC9B,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,6BAA6B,EAAE,MAAM,8BAA8B,CAAC;AAC7E,OAAO,EACL,8BAA8B,EAC9B,2BAA2B,EAC3B,uBAAuB,EACvB,0BAA0B,GAC3B,MAAM,wBAAwB,CAAC;AAqBhC,OAAO,EAAE,yBAAyB,IAAI,mBAAmB,EAAE,CAAC;AAuC5D,MAAM,UAAU,eAAe,CAC7B,YAAmC;IAEnC,OAAO,IAAI,gBAAgB,CAAC,YAAY,CAAC,CAAC;AAC5C,CAAC;AAED,MAAM,gBAAgB;IAMS;IALZ,sBAAsB,GAAG,IAAI,OAAO,EAGlD,CAAC;IAEJ,YAA6B,YAAmC;QAAnC,iBAAY,GAAZ,YAAY,CAAuB;IAAG,CAAC;IAEpE,KAAK,CAAC,MAAM,CAAC,OAAe;QAC1B,MAAM,OAAO,GAAG,IAAI,CAAC,eAAe,EAAE,CAAC;QACvC,IAAI,OAAO,CAAC,KAAK,CAAC,QAAQ,KAAK,OAAO,EAAE,CAAC;YACvC,OAAO,KAAK,CAAC;QACf,CAAC;QAED,MAAM,OAAO,GAAG,MAAM,uBAAuB,CAAC;YAC5C,kBAAkB,EAAE,OAAO,CAAC,KAAK,CAAC,kBAAkB;YACpD,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,OAAO;YAC9B,OAAO;YACP,WAAW,EAAE,2BAA2B;SACzC,CAAC,CAAC;QACH,IAAI,CAAC,OAAO;YAAE,OAAO,KAAK,CAA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AE;QAEjC,MAAM,EACJ,WAAW,EACX,UAAU,GAAG,IAAI,EACjB,mBAAmB,GAAG,qBAAqB,EAC3C,WAAW,GAAG,EAAE,EAChB,OAAO,GAAG,yBAAyB,GACpC,GAAG,KAAK,CAAC;QACV,MAAM,OAAO,GACX,OAAO,CAAC,eAAe,IAAI,IAAI,CAAC,eAAe,CAAC,WAAW,CAAC,CAAC;QAC/D,OAAO,iBAAiB,CACtB,OAAO,CAAC,KAAK,CAAC,WAAW,EACzB,OAAO,EACP,OAAO,EACP,UAAU,EACV,WAAW,EACX,mBAAmB,EACnB,EAAE,cAAc,EAAE,OAAO,CAAC,cAAc,EAAE,CAC3C,CAAC;IACJ,CAAC;IAED,SAAS,CACP,QAAmC,EACnC,UAAuC,EAAE;QAEzC,OAAO,6BAA6B,CAClC,IAAI,CAAC,YAAY,CAAC,OAAO,CAAC,aAAa,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,KAAK;aAC/D,WAAW,EACd,QAAQ,CACT,CAAC;IACJ,CAAC;IAEO,YAAY,CAAC,OAAgB;QACnC,MAAM,QAAQ,GAAG,IAAI,CAAC,sBAAsB,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QAC1D,IAAI,QAAQ,EAAE,CAAC;YACb,OAAO,QAAQ,CAAC;QAClB,CAAC;QAED,MAAM,MAAM,GAAG,2BAA2B;aACvC,YAAY,CAAC,OAAO,CAAC;aACrB,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;YACxB,IAAI,CAAC,sBAAsB,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;YAC5C,MAAM,KAAK,CAAC;QACd,CAAC,CAAC,CAAC;QACL,IAAI,CAAC,sBAAsB,CAAC,GAAG,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QACjD,OAAO,MAAM,CAAC;IAChB,CAAC;CACF","sourcesContent":["import { DEFAULT_DOCUMENT_KIND } from \"../data/documents/documentConstants\";\nimport type { StoredDocumentKind } from \"../data/documents/documentKinds\";\nimport type {\n DocumentSummaryList,\n DocumentSummarySort,\n DocumentSummarySortDirection,\n DocumentSummarySortKey,\n ListDocumentSummariesInput,\n} from \"../data/persistence/documents/types\";\nimport type { ExecSql } from \"../data/sqlite/sqlSchema\";\nimport {\n DEFAULT_DOCUMENT_ID as DEFAULT_LOCAL_DOCUMENT_ID,\n type DocumentStore,\n type DocumentsRuntime,\n openDocumentStore,\n type PersistedDocumentListener,\n subscribeToPersistedDocuments,\n} from \"../stores/documents\";\nimport { emitPersistedDocumentDeletion } from \"../stores/documents/registry\";\nimport {\n createDocumentsWorkflowRuntime,\n defaultDocumentsPersistence,\n deletePersistedDocument,\n reclaimDocumentOrphanBlobs,\n} from \"../workflows/documents\";\nimport type { InternalRuntime } from \"./workflowRuntime\";\n\nexport type {\n DocumentAttachmentStatus,\n DocumentAttachmentUpload,\n DocumentContextValue,\n DocumentStore,\n DocumentsRuntime,\n PersistedDocumentListener,\n} from \"../stores/documents\";\n\nexport type DocumentSortDirection = DocumentSummarySortDirection;\nexport type DocumentSortKey = DocumentSummarySortKey;\n\nexport type DocumentSort = DocumentSummarySort;\n\nexport interface ListDocumentsInput extends ListDocumentSummariesInput {}\n\nexport type DocumentList = DocumentSummaryList;\n\nexport { DEFAULT_LOCAL_DOCUMENT_ID as DEFAULT_DOCUMENT_ID };\n\nexport interface OpenDocumentInput {\n readonly containerId?: string | null | undefined;\n readonly documentId?: string | null | undefined;\n readonly initialDocumentKind?: StoredDocumentKind | undefined;\n readonly initialText?: string | undefined;\n readonly localId?: string | undefined;\n}\n\nexport interface OpenDocumentOptions {\n readonly remoteSyncMode?: \"on-demand\" | \"startup\" | undefined;\n readonly workflowRuntime?: DocumentsRuntime | undefined;\n}\n\nexport interface DocumentSubscriptionOptions {\n readonly containerId?: string | null | undefined;\n}\n\nexport interface Documents {\n delete(localId: string): Promise<boolean>;\n findLocalIdByDocumentId(documentId: string): Promise<string | null>;\n list(input?: ListDocumentsInput | undefined): Promise<DocumentList | null>;\n open(\n input?: OpenDocumentInput | undefined,\n options?: OpenDocumentOptions | undefined,\n ): DocumentStore;\n subscribe(\n listener: PersistedDocumentListener,\n options?: DocumentSubscriptionOptions | undefined,\n ): () => void;\n workflowRuntime(containerId?: string | null | undefined): DocumentsRuntime;\n}\n\ninterface DocumentsDependencies {\n getDefaultContainerId: () => string | null;\n runtime: InternalRuntime;\n}\n\nexport function createDocuments(\n dependencies: DocumentsDependencies,\n): Documents {\n return new DocumentsService(dependencies);\n}\n\nclass DocumentsService implements Documents {\n private readonly schemaEnsuresByExecSql = new WeakMap<\n ExecSql,\n Promise<void>\n >();\n\n constructor(private readonly dependencies: DocumentsDependencies) {}\n\n async delete(localId: string): Promise<boolean> {\n const runtime = this.workflowRuntime();\n if (runtime.infra.dbStatus !== \"ready\") {\n return false;\n }\n\n const deleted = await deletePersistedDocument({\n documentProjectors: runtime.infra.documentProjectors,\n execSql: runtime.infra.execSql,\n localId,\n persistence: defaultDocumentsPersistence,\n });\n if (!deleted) return false;\n void reclaimDocumentOrphanBlobs(runtime);\n emitPersistedDocumentDeletion(runtime.state.domainScope, localId);\n return true;\n }\n\n async findLocalIdByDocumentId(documentId: string): Promise<string | null> {\n const runtime = this.dependencies.runtime.workflowInput();\n if (runtime.infra.dbStatus !== \"ready\") {\n return null;\n }\n\n await this.ensureSchema(runtime.infra.execSql);\n return defaultDocumentsPersistence.findLocalIdByDocumentId(\n runtime.infra.execSql,\n documentId,\n );\n }\n\n async list(input: ListDocumentsInput = {}): Promise<DocumentList | null> {\n const runtime = this.dependencies.runtime.workflowInput();\n if (runtime.infra.dbStatus !== \"ready\") {\n return null;\n }\n\n await this.ensureSchema(runtime.infra.execSql);\n return defaultDocumentsPersistence.listDocumentSummaries(\n runtime.infra.execSql,\n input,\n );\n }\n\n workflowRuntime(\n containerId = this.dependencies.getDefaultContainerId(),\n ): DocumentsRuntime {\n const input = this.dependencies.runtime.workflowInput(containerId);\n return createDocumentsWorkflowRuntime(input);\n }\n\n open(\n input: OpenDocumentInput = {},\n options: OpenDocumentOptions = {},\n ): DocumentStore {\n const {\n containerId,\n documentId = null,\n initialDocumentKind = DEFAULT_DOCUMENT_KIND,\n initialText = \"\",\n localId = DEFAULT_LOCAL_DOCUMENT_ID,\n } = input;\n const runtime =\n options.workflowRuntime ?? this.workflowRuntime(containerId);\n return openDocumentStore(\n runtime.state.domainScope,\n localId,\n runtime,\n documentId,\n initialText,\n initialDocumentKind,\n { remoteSyncMode: options.remoteSyncMode },\n );\n }\n\n subscribe(\n listener: PersistedDocumentListener,\n options: DocumentSubscriptionOptions = {},\n ): () => void {\n return subscribeToPersistedDocuments(\n this.dependencies.runtime.workflowInput(options.containerId).state\n .domainScope,\n listener,\n );\n }\n\n private ensureSchema(execSql: ExecSql): Promise<void> {\n const existing = this.schemaEnsuresByExecSql.get(execSql);\n if (existing) {\n return existing;\n }\n\n const ensure = defaultDocumentsPersistence\n .ensureSchema(execSql)\n .catch((error: unknown) => {\n this.schemaEnsuresByExecSql.delete(execSql);\n throw error;\n });\n this.schemaEnsuresByExecSql.set(execSql, ensure);\n return ensure;\n }\n}\n"]}
package/index.d.ts CHANGED
@@ -7,7 +7,7 @@ export type { BlobByteSource, BlobByteSourceInput, BlobBytes, BlobStore, Discove
7
7
  export { addDocumentAttachments, blobByteSourceInputLength, createBlobByteSource, createDocumentProjectorRegistry, createDocumentSignerDeviceId, DEFAULT_DOCUMENT_ACCESS_EPOCH, DEFAULT_DOCUMENT_KIND, defaultDocumentProjectorRegistry, deriveStoredDocumentTitle, ensureDocumentAttachmentStructure, getDocumentAttachments, getDocumentClientProjectionTables, getStoredDocumentTypeLabel, getUntitledDocumentTitle, initializeStoredDocumentKind, projectStoredDocumentState, readBlobByteSource, readStoredDocumentState, readStringDocumentField, resolveOpIdAttribution, sameDocumentAttachments, summarizeDocumentContributors, writerByPeerId, writeStoredDocumentFields, } from "./documents.js";
8
8
  export type { ContainerContentsSnapshot, ContainerContentsStoreRuntime, ContainerContentsStoreState, ContainerContentsStoreSyncAgent, ContainerContentsStoreSyncState, ContainerState, PurgeOptions, PurgeProgress, } from "./stores/container-contents/index.js";
9
9
  export { createContainerContentsStore, createContainerContentsStoreState, createContainerContentsStoreSyncAgent, getOrCreateContainerContentsStore, isSystemContainerNode, requestContainerContentsDocumentPriming, subscribeToContainerContentsStore, updateContainerContentsSnapshot, updateContainerContentsStoreRuntime, } from "./stores/container-contents/index.js";
10
- export type { DocumentSnapshot, DocumentStoreFacade, DocumentStoreRelinkInput, DocumentStructuredFieldPatch, } from "./stores/documents/index.js";
10
+ export type { DocumentSnapshot, DocumentStoreFacade, DocumentStoreOpenOptions, DocumentStoreRelinkInput, DocumentStructuredFieldPatch, } from "./stores/documents/index.js";
11
11
  export { createDocumentStore, discardRegisteredDocumentLocalState, getOrCreateDocumentStore, openDocumentStore, requestDomainDocumentSync, subscribeToPersistedDocuments, } from "./stores/documents/index.js";
12
12
  export type { EncryptedBlobStoreCipher, EncryptedBlobStoreKey, EncryptedBlobStoreOptions, WrapEncryptedBlobStoreOptions, } from "./workflows/blobs/index.js";
13
13
  export { createBlobStore, createEncryptedBlobStore, createLazyEncryptedBlobStore, createMemoryBlobStore, decryptDocumentAttachmentBlob, hydrateDocumentAttachmentBlobs, purgeOpfsBlobStore, uploadDocumentAttachment, wrapEncryptedBlobStore, } from "./workflows/blobs/index.js";
package/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,iFAAiF;AACjF,2EAA2E;AAC3E,4FAA4F;AAC5F,OAAO,EAGL,iBAAiB,GAElB,MAAM,uBAAuB,CAAC;AAmK/B,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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AuB,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 {\n type ApiRequestCounts,\n type ApiRequestEndpointCounts,\n ApiRequestMetrics,\n type ApiRequestMetricsSnapshot,\n} from \"@tearleads/api-client\";\nexport type {\n AbandonOrganizationPolicyMutationInput,\n AddOrganizationGroupUserInput,\n BlobInfo,\n BlobInfoAttachmentKind,\n BlobInfoDocumentReference,\n BlobInfoInput,\n BlobInfoList,\n BlobInfoSort,\n BlobInfoSortDirection,\n BlobInfoSortKey,\n BrowserLocalKeyringOptions,\n 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 PendingDownloadQueueItem,\n RecoveryFolder,\n} from \"./workflows/container-contents\";\nexport {\n createContainerContentsDocumentsRuntime,\n createContainerContentsProjectionUserKeyResolver,\n createContainerContentsStoreWorkflowRuntime,\n createContainerContentsSyncLane,\n createContainerContentsWorkflowRuntime,\n createContainerParentSyncLane,\n createInitializedContainerMetadataDocument,\n defaultContainerContentsPersistence,\n deriveContainerSystemSlot,\n initializeDocumentLinksSchema,\n listBlobInfo,\n listDocumentLinkedContainerIds,\n loadContainerInfo,\n loadContainerSyncWatermark,\n loadDocumentAttributionRanges,\n loadDocumentInfo,\n replaceDocumentLinks,\n saveContainerSyncWatermark,\n syncedContainerDocumentObjectSyncState,\n} from \"./workflows/container-contents\";\nexport type {\n AggregatedContainerKekLog,\n ContainerMutationAuthor,\n ContainerReciteApi,\n ContainerWriteRefusal,\n KeyringRebuildResult,\n MaterializedContainerRekeyPlan,\n} from \"./workflows/containers\";\nexport {\n buildMaterializedContainerRekeyPlan,\n buildRootContainerCreatePlan,\n ContainerAuthorAccessError,\n ContainerKekRepairInaccessibleError,\n ContainerKekRepairRequiredError,\n ContainerKeyringOverrideStaleError,\n ContainerPathTooDeepError,\n classifyContainerWriteRefusal,\n containerWriterProjectionFromRekeyPlan,\n createRemoteContainer,\n fetchContainerKekLog,\n GroupShareNameMismatchError,\n HistoricalWrapUnavailableError,\n type HistoricalWrapUnavailableReason,\n isProjectionVerificationCancelledError,\n moveRemoteContainer,\n rebuildKeyringEntriesFromLog,\n recoverKeyringEntryFromWraps,\n rekeyRemoteContainer,\n revokeRemoteContainer,\n rootContainerWriterProjectionFromCreatePlan,\n shareRemoteContainer,\n shareRemoteContainerWithGroup,\n} from \"./workflows/containers\";\nexport type {\n DocumentRecord,\n DocumentSyncContainerRekeyBuilder,\n DocumentSyncPullContinuation,\n DocumentSyncUpdateIsolationError,\n DocumentsPersistence,\n DocumentsWorkflowRuntime,\n DocumentsWorkflowRuntimeInput,\n IncomingDocumentSyncUpdateValidator,\n LocalAttachmentRecord,\n PendingAttachmentRecord,\n PendingUpdateInsert,\n PendingUpdateRecord,\n SyncRemoteDocumentInput,\n} from \"./workflows/documents\";\nexport {\n buildMaterializedDocumentCreatePlan,\n createDocumentProjectionUserKeyResolver,\n createDocumentsWorkflowRuntime,\n createRemoteDocument,\n DOCUMENT_SYNC_TRACE_FRAGMENT,\n DOCUMENT_SYNC_TRACE_PATTERN,\n DOCUMENTS_APP_KIND,\n DocumentRawHistoryUnavailableError,\n defaultDocumentsPersistence,\n deletePersistedDocument,\n isDatabaseUnavailableError,\n isDocumentSyncUpdateIsolationError,\n persistedDocumentCreateStateFromResponse,\n readPullContinuation,\n syncRemoteDocument,\n unwrapContainerKekPath,\n unwrapDocumentContentKeyTarget,\n validateDocumentSyncUpdateImports,\n} from \"./workflows/documents\";\n// Nominal identity constructors are available only through the testing subpath\n// for low-level runtime tests.\nexport type {\n AcknowledgedPrincipalCurrentInput,\n AcknowledgedPrincipalCurrentRetirement,\n AcknowledgedPrincipalPredecessor,\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 captureAcknowledgedPrincipalPredecessor,\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":"AAAA,iFAAiF;AACjF,2EAA2E;AAC3E,4FAA4F;AAC5F,OAAO,EAGL,iBAAiB,GAElB,MAAM,uBAAuB,CAAC;AAmK/B,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,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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 {\n type ApiRequestCounts,\n type ApiRequestEndpointCounts,\n ApiRequestMetrics,\n type ApiRequestMetricsSnapshot,\n} from \"@tearleads/api-client\";\nexport type {\n AbandonOrganizationPolicyMutationInput,\n AddOrganizationGroupUserInput,\n BlobInfo,\n BlobInfoAttachmentKind,\n BlobInfoDocumentReference,\n BlobInfoInput,\n BlobInfoList,\n BlobInfoSort,\n BlobInfoSortDirection,\n BlobInfoSortKey,\n BrowserLocalKeyringOptions,\n 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 DocumentStoreOpenOptions,\n DocumentStoreRelinkInput,\n DocumentStructuredFieldPatch,\n} from \"./stores/documents\";\nexport {\n createDocumentStore,\n discardRegisteredDocumentLocalState,\n getOrCreateDocumentStore,\n openDocumentStore,\n requestDomainDocumentSync,\n subscribeToPersistedDocuments,\n} from \"./stores/documents\";\nexport 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 PendingDownloadQueueItem,\n RecoveryFolder,\n} from \"./workflows/container-contents\";\nexport {\n createContainerContentsDocumentsRuntime,\n createContainerContentsProjectionUserKeyResolver,\n createContainerContentsStoreWorkflowRuntime,\n createContainerContentsSyncLane,\n createContainerContentsWorkflowRuntime,\n createContainerParentSyncLane,\n createInitializedContainerMetadataDocument,\n defaultContainerContentsPersistence,\n deriveContainerSystemSlot,\n initializeDocumentLinksSchema,\n listBlobInfo,\n listDocumentLinkedContainerIds,\n loadContainerInfo,\n loadContainerSyncWatermark,\n loadDocumentAttributionRanges,\n loadDocumentInfo,\n replaceDocumentLinks,\n saveContainerSyncWatermark,\n syncedContainerDocumentObjectSyncState,\n} from \"./workflows/container-contents\";\nexport type {\n AggregatedContainerKekLog,\n ContainerMutationAuthor,\n ContainerReciteApi,\n ContainerWriteRefusal,\n KeyringRebuildResult,\n MaterializedContainerRekeyPlan,\n} from \"./workflows/containers\";\nexport {\n buildMaterializedContainerRekeyPlan,\n buildRootContainerCreatePlan,\n ContainerAuthorAccessError,\n ContainerKekRepairInaccessibleError,\n ContainerKekRepairRequiredError,\n ContainerKeyringOverrideStaleError,\n ContainerPathTooDeepError,\n classifyContainerWriteRefusal,\n containerWriterProjectionFromRekeyPlan,\n createRemoteContainer,\n fetchContainerKekLog,\n GroupShareNameMismatchError,\n HistoricalWrapUnavailableError,\n type HistoricalWrapUnavailableReason,\n isProjectionVerificationCancelledError,\n moveRemoteContainer,\n rebuildKeyringEntriesFromLog,\n recoverKeyringEntryFromWraps,\n rekeyRemoteContainer,\n revokeRemoteContainer,\n rootContainerWriterProjectionFromCreatePlan,\n shareRemoteContainer,\n shareRemoteContainerWithGroup,\n} from \"./workflows/containers\";\nexport type {\n DocumentRecord,\n DocumentSyncContainerRekeyBuilder,\n DocumentSyncPullContinuation,\n DocumentSyncUpdateIsolationError,\n DocumentsPersistence,\n DocumentsWorkflowRuntime,\n DocumentsWorkflowRuntimeInput,\n IncomingDocumentSyncUpdateValidator,\n LocalAttachmentRecord,\n PendingAttachmentRecord,\n PendingUpdateInsert,\n PendingUpdateRecord,\n SyncRemoteDocumentInput,\n} from \"./workflows/documents\";\nexport {\n buildMaterializedDocumentCreatePlan,\n createDocumentProjectionUserKeyResolver,\n createDocumentsWorkflowRuntime,\n createRemoteDocument,\n DOCUMENT_SYNC_TRACE_FRAGMENT,\n DOCUMENT_SYNC_TRACE_PATTERN,\n DOCUMENTS_APP_KIND,\n DocumentRawHistoryUnavailableError,\n defaultDocumentsPersistence,\n deletePersistedDocument,\n isDatabaseUnavailableError,\n isDocumentSyncUpdateIsolationError,\n persistedDocumentCreateStateFromResponse,\n readPullContinuation,\n syncRemoteDocument,\n unwrapContainerKekPath,\n unwrapDocumentContentKeyTarget,\n validateDocumentSyncUpdateImports,\n} from \"./workflows/documents\";\n// Nominal identity constructors are available only through the testing subpath\n// for low-level runtime tests.\nexport type {\n AcknowledgedPrincipalCurrentInput,\n AcknowledgedPrincipalCurrentRetirement,\n AcknowledgedPrincipalPredecessor,\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 captureAcknowledgedPrincipalPredecessor,\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,6 +1,6 @@
1
1
  {
2
2
  "name": "@tearleads/client-sdk",
3
- "version": "0.1.34",
3
+ "version": "0.1.36",
4
4
  "description": "React-free Tearleads client runtime: local SQLite persistence, keys, sync, encrypted blobs, and domain workflows.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -0,0 +1,136 @@
1
+ import { encodeVersionVector, exportFullHistorySnapshot, } from "../../../internal/loro/index.js";
2
+ import { getDocumentAttachments, removeDocumentAttachment, } from "../../../data/documents/documentContent.js";
3
+ import { createPendingUpdateFields } from "../../../data/documents/documentSync.js";
4
+ import { requestDocumentStoreSync } from "../registry.js";
5
+ import { restoreFailedAttachmentMutation } from "./attachmentMutationPersistence.js";
6
+ import { assignLocalAttachmentSlots, removeLocalAttachmentSlot, } from "./attachmentPersistence.js";
7
+ import { ATTACHMENT_FAILURE_MESSAGE } from "./attachments.js";
8
+ import { captureAttachmentWriteGeneration, isAttachmentWriteGenerationCurrent, shouldAbortAttachmentPersistFollowup, } from "./attachmentWriteGeneration.js";
9
+ import { ensureDocumentStoreReady } from "./initialization.js";
10
+ import { runDocumentOrphanMaintenance } from "./orphanMaintenance.js";
11
+ import { advancePendingBaseVersion, pendingDeltaSinceBase, persistDocument, } from "./persistence.js";
12
+ import { reportDocumentStoreWriteFailure } from "./reportWriteFailure.js";
13
+ import { canWriteDocument, setReadySnapshot, } from "./state.js";
14
+ import { captureDocumentStoreSyncGeneration } from "./syncGeneration.js";
15
+ function installCommittedAttachmentRemoval(input) {
16
+ const { slotId, state, storageKey } = input;
17
+ if (!storageKey)
18
+ return;
19
+ const pending = state.pendingAttachments.find((attachment) => attachment.slotId === slotId && attachment.storageKey === storageKey);
20
+ if (input.syncedAttachment && pending?.upload) {
21
+ assignLocalAttachmentSlots(state, [
22
+ {
23
+ slotId,
24
+ storageKey,
25
+ blobId: pending.upload.blobId,
26
+ contentSha256: pending.contentSha256,
27
+ },
28
+ ]);
29
+ }
30
+ state.pendingAttachments = state.pendingAttachments.filter((attachment) => attachment.slotId !== slotId || attachment.storageKey !== storageKey);
31
+ // The committed removal queued this key. A reset can leave another document
32
+ // uploading from the same copy; a detached marker keeps it until sync.
33
+ void runDocumentOrphanMaintenance(state);
34
+ if (input.syncedAttachment ||
35
+ state.attachmentStorageKeyBySlotId[slotId] !== storageKey) {
36
+ return;
37
+ }
38
+ removeLocalAttachmentSlot(state, slotId);
39
+ setReadySnapshot(state, input.currentDoc, state.snapshot.syncing, state.snapshot.text, state.snapshot.structuredFields);
40
+ }
41
+ async function persistRemovedAttachment(state, slotId, writeGeneration) {
42
+ if (!isAttachmentWriteGenerationCurrent(state, writeGeneration))
43
+ return;
44
+ const currentDoc = state.doc;
45
+ if (!currentDoc) {
46
+ return;
47
+ }
48
+ const generation = captureDocumentStoreSyncGeneration(state, currentDoc);
49
+ if (!generation) {
50
+ return;
51
+ }
52
+ const existingAttachment = getDocumentAttachments(currentDoc).find((attachment) => attachment.slotId === slotId);
53
+ if (!existingAttachment) {
54
+ return;
55
+ }
56
+ // After a reset, a store opened cold holds the slot only as a pending upload.
57
+ const storageKey = state.attachmentStorageKeyBySlotId[slotId] ??
58
+ state.pendingAttachments.find((attachment) => attachment.slotId === slotId)
59
+ ?.storageKey;
60
+ if (!isAttachmentWriteGenerationCurrent(state, writeGeneration) ||
61
+ state.doc !== currentDoc)
62
+ return;
63
+ const rollbackSnapshot = exportFullHistorySnapshot(currentDoc).slice();
64
+ removeDocumentAttachment(currentDoc, slotId);
65
+ const attachmentUpdate = pendingDeltaSinceBase(state, currentDoc);
66
+ const coveredVersion = encodeVersionVector(currentDoc);
67
+ const pendingUpdate = createPendingUpdateFields(attachmentUpdate);
68
+ const syncedAttachment = Boolean(state.record?.documentId);
69
+ // Preserve the optimistic text/structured fields (see persistAttachedFiles):
70
+ // removing an attachment while typing must not regress the editor.
71
+ let persisted;
72
+ try {
73
+ persisted = await persistDocument(state, currentDoc, { snapshotEndVersion: coveredVersion }, {
74
+ ...(storageKey
75
+ ? {
76
+ attachmentRemoval: {
77
+ mode: syncedAttachment
78
+ ? "detach"
79
+ : "delete",
80
+ slotId,
81
+ storageKey,
82
+ },
83
+ }
84
+ : {}),
85
+ ...(pendingUpdate ? { pendingUpdate } : {}),
86
+ preserveSnapshotStructuredFields: true,
87
+ preserveSnapshotText: true,
88
+ }, generation);
89
+ }
90
+ catch (error) {
91
+ await restoreFailedAttachmentMutation({
92
+ generation,
93
+ rollbackSnapshot,
94
+ state,
95
+ });
96
+ throw error;
97
+ }
98
+ if (shouldAbortAttachmentPersistFollowup(state, writeGeneration, generation, persisted)) {
99
+ // See persistAttachedFiles: only durable same-identity work re-arms sync.
100
+ return;
101
+ }
102
+ installCommittedAttachmentRemoval({
103
+ currentDoc,
104
+ slotId,
105
+ state,
106
+ storageKey,
107
+ syncedAttachment,
108
+ });
109
+ advancePendingBaseVersion(state, currentDoc);
110
+ state.runtime.util.log(`Removed attachment ${existingAttachment.name} from document ${state.localId}.`);
111
+ requestDocumentStoreSync(state);
112
+ }
113
+ export async function removeAttachmentFromDocumentStore(state, scheduleSync, slotId) {
114
+ let ready;
115
+ try {
116
+ ready = await ensureDocumentStoreReady(state, scheduleSync);
117
+ }
118
+ catch (error) {
119
+ reportDocumentStoreWriteFailure(state, ATTACHMENT_FAILURE_MESSAGE, error);
120
+ return;
121
+ }
122
+ if (!ready || !state.doc || !canWriteDocument(state)) {
123
+ return;
124
+ }
125
+ const writeGeneration = captureAttachmentWriteGeneration(state);
126
+ if (!writeGeneration)
127
+ return;
128
+ state.writeChain = state.writeChain
129
+ .catch(() => undefined)
130
+ .then(async () => persistRemovedAttachment(state, slotId, writeGeneration))
131
+ .catch((error) => {
132
+ reportDocumentStoreWriteFailure(state, ATTACHMENT_FAILURE_MESSAGE, error);
133
+ });
134
+ return state.writeChain;
135
+ }
136
+ //# sourceMappingURL=attachmentRemoval.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"attachmentRemoval.js","sourceRoot":"","sources":["attachmentRemoval.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mBAAmB,EACnB,yBAAyB,GAC1B,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,sBAAsB,EACtB,wBAAwB,GACzB,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,yBAAyB,EAAE,MAAM,sCAAsC,CAAC;AACjF,OAAO,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AACvD,OAAO,EAAE,+BAA+B,EAAE,MAAM,iCAAiC,CAAC;AAClF,OAAO,EACL,0BAA0B,EAC1B,yBAAyB,GAC1B,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,0BAA0B,EAAE,MAAM,eAAe,CAAC;AAC3D,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,CAAC;AACvB,OAAO,EAAE,+BAA+B,EAAE,MAAM,sBAAsB,CAAC;AACvE,OAAO,EACL,gBAAgB,EAEhB,gBAAgB,GACjB,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,kCAAkC,EAAE,MAA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AEd,IAAI,KAAc,CAAC;IACnB,IAAI,CAAC;QACH,KAAK,GAAG,MAAM,wBAAwB,CAAC,KAAK,EAAE,YAAY,CAAC,CAAC;IAC9D,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,+BAA+B,CAAC,KAAK,EAAE,0BAA0B,EAAE,KAAK,CAAC,CAAC;QAC1E,OAAO;IACT,CAAC;IAED,IAAI,CAAC,KAAK,IAAI,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,gBAAgB,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,CAAC,wBAAwB,CAAC,KAAK,EAAE,MAAM,EAAE,eAAe,CAAC,CAAC;SAC1E,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 getDocumentAttachments,\n removeDocumentAttachment,\n} from \"../../../data/documents/documentContent\";\nimport { createPendingUpdateFields } from \"../../../data/documents/documentSync\";\nimport { requestDocumentStoreSync } from \"../registry\";\nimport { restoreFailedAttachmentMutation } from \"./attachmentMutationPersistence\";\nimport {\n assignLocalAttachmentSlots,\n removeLocalAttachmentSlot,\n} from \"./attachmentPersistence\";\nimport { ATTACHMENT_FAILURE_MESSAGE } from \"./attachments\";\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 canWriteDocument,\n type DocumentStoreState,\n setReadySnapshot,\n} from \"./state\";\nimport { captureDocumentStoreSyncGeneration } from \"./syncGeneration\";\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 const pending = state.pendingAttachments.find(\n (attachment) =>\n attachment.slotId === slotId && attachment.storageKey === storageKey,\n );\n if (input.syncedAttachment && pending?.upload) {\n assignLocalAttachmentSlots(state, [\n {\n slotId,\n storageKey,\n blobId: pending.upload.blobId,\n contentSha256: pending.contentSha256,\n },\n ]);\n }\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; a detached marker keeps it until sync.\n 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 // After a reset, a store opened cold holds the slot only as a pending upload.\n const storageKey =\n state.attachmentStorageKeyBySlotId[slotId] ??\n state.pendingAttachments.find((attachment) => attachment.slotId === slotId)\n ?.storageKey;\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 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"]}