@tearleads/client-sdk 0.1.260 → 0.1.262

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.
@@ -28,6 +28,10 @@ export interface OpenDocumentOptions {
28
28
  readonly remoteSyncMode?: "on-demand" | "startup" | undefined;
29
29
  readonly workflowRuntime?: DocumentsRuntime | undefined;
30
30
  }
31
+ export interface RetryDocumentDownloadInput {
32
+ readonly documentId: string;
33
+ readonly localId: string;
34
+ }
31
35
  export interface DocumentSubscriptionOptions {
32
36
  readonly containerId?: string | null | undefined;
33
37
  }
@@ -43,6 +47,13 @@ export interface Documents {
43
47
  * The caller must `close()` the result.
44
48
  */
45
49
  openHistory(localId: string): Promise<DocumentHistory | null>;
50
+ /**
51
+ * Pull a synced document again and re-list its attachment bindings, e.g.
52
+ * to retry a pending first download. Resolves false, without syncing, when
53
+ * the database is not ready or the local record no longer carries
54
+ * `documentId`; an already-open store keeps its runtime and draft.
55
+ */
56
+ retryDownload(input: RetryDocumentDownloadInput): Promise<boolean>;
46
57
  subscribe(listener: PersistedDocumentListener, options?: DocumentSubscriptionOptions | undefined): () => void;
47
58
  workflowRuntime(containerId?: string | null | undefined): DocumentsRuntime;
48
59
  }
@@ -1,5 +1,5 @@
1
1
  import { DEFAULT_DOCUMENT_KIND } from "../../data/documents/documentConstants.js";
2
- import { createSeededDocument, DEFAULT_DOCUMENT_ID as DEFAULT_LOCAL_DOCUMENT_ID, openDocumentStore, subscribeToPersistedDocuments, } from "../../stores/documents/index.js";
2
+ import { createSeededDocument, DEFAULT_DOCUMENT_ID as DEFAULT_LOCAL_DOCUMENT_ID, openDocumentStore, retryDocumentDownload, subscribeToPersistedDocuments, } from "../../stores/documents/index.js";
3
3
  import { emitPersistedDocumentDeletion } from "../../stores/documents/registry.js";
4
4
  import { createDocumentsWorkflowRuntimeFromSnapshot, defaultDocumentsPersistence, deletePersistedDocument, openDocumentHistory, reclaimDocumentOrphanBlobs, } from "../../workflows/documents/index.js";
5
5
  export { DEFAULT_LOCAL_DOCUMENT_ID as DEFAULT_DOCUMENT_ID };
@@ -80,6 +80,12 @@ class DocumentsService {
80
80
  persistence: defaultDocumentsPersistence,
81
81
  });
82
82
  }
83
+ retryDownload(input) {
84
+ return retryDocumentDownload({
85
+ ...input,
86
+ workflowRuntime: (containerId) => this.workflowRuntime(containerId),
87
+ });
88
+ }
83
89
  subscribe(listener, options = {}) {
84
90
  return subscribeToPersistedDocuments(this.dependencies.runtime.workflowInput(options.containerId).state
85
91
  .domainScope, listener);
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,wCAAwC,CAAC;AAW/E,OAAO,EACL,oBAAoB,EACpB,mBAAmB,IAAI,yBAAyB,EAIhD,iBAAiB,EAGjB,6BAA6B,GAC9B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,6BAA6B,EAAE,MAAM,iCAAiC,CAAC;AAChF,OAAO,EACL,0CAA0C,EAE1C,2BAA2B,EAC3B,uBAAuB,EACvB,mBAAmB,EACnB,0BAA0B,GAC3B,MAAM,2BAA2B,CAAC;AA2CnC,OAAO,EAAE,yBAAyB,IAAI,mBAAmB,EAAE,CAAC;AAwC5D,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,YAAY,CAAC,KAA0B;QACrC,MAAM,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC,YAAY,CAAC;QACtC,MAAM,UAAU,GAAG,OAAO,CAAC,eAAe,CAAC;QAC3C,OAAO,oBAAoB,CACzB,IAAI,CAAC,eAAe,CAAC,KAA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OAAO,CAAC,KAAK,CAAC,QAAQ,KAAK,OAAO,EAAE,CAAC;YACvC,OAAO,IAAI,CAAC;QACd,CAAC;QAED,MAAM,IAAI,CAAC,YAAY,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QAC/C,OAAO,mBAAmB,CAAC;YACzB,kBAAkB,EAAE,OAAO,CAAC,KAAK,CAAC,kBAAkB;YACpD,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,OAAO;YAC9B,OAAO;YACP,WAAW,EAAE,2BAA2B;SACzC,CAAC,CAAC;IACL,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 { DiscoveredDocumentInput } from \"../../data/documents/documentSummary\";\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 createSeededDocument,\n DEFAULT_DOCUMENT_ID as DEFAULT_LOCAL_DOCUMENT_ID,\n type DocumentStore,\n type DocumentStoreOpenOptions,\n type DocumentsRuntime,\n openDocumentStore,\n type PersistedDocumentListener,\n type SeededDocumentInput,\n subscribeToPersistedDocuments,\n} from \"../../stores/documents\";\nimport { emitPersistedDocumentDeletion } from \"../../stores/documents/registry\";\nimport {\n createDocumentsWorkflowRuntimeFromSnapshot,\n type DocumentHistory,\n defaultDocumentsPersistence,\n deletePersistedDocument,\n openDocumentHistory,\n reclaimDocumentOrphanBlobs,\n} from \"../../workflows/documents\";\nimport type { InternalRuntime } from \"../runtime/workflowRuntime\";\n\nexport type {\n DocumentAttachmentStatus,\n DocumentAttachmentUpload,\n DocumentContextValue,\n DocumentStore,\n DocumentsRuntime,\n PersistedDocumentListener,\n} from \"../../stores/documents\";\n\nexport type {\n DocumentHistory,\n DocumentHistoryChange,\n DocumentHistoryRowChange,\n DocumentHistoryStop,\n DocumentHistoryTextChange,\n DocumentHistoryVersion,\n DocumentHistoryVersionEntry,\n DocumentHistoryView,\n} from \"../../workflows/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 type { SeededDocumentInput } from \"../../stores/documents\";\nexport interface OpenDocumentInput {\n readonly containerId?: string | null | undefined;\n readonly documentId?: string | null | undefined;\n readonly initialDocumentKind?: StoredDocumentKind | undefined;\n /** Birth content of a created record; see `DocumentStoreOpenOptions`. */\n readonly initialRows?: DocumentStoreOpenOptions[\"initialRows\"];\n readonly initialStructuredFields?: DocumentStoreOpenOptions[\"initialStructuredFields\"];\n readonly initialText?: string | undefined;\n readonly localId?: string | undefined;\n}\nexport { DEFAULT_LOCAL_DOCUMENT_ID as DEFAULT_DOCUMENT_ID };\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 createSeeded(\n input: SeededDocumentInput,\n ): Promise<DiscoveredDocumentInput | \"purged\">;\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 /**\n * Open a read-only replay of a document's durable local history. Resolves to\n * null while the database is not ready or the document has no history yet.\n * The caller must `close()` the result.\n */\n openHistory(localId: string): Promise<DocumentHistory | null>;\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 createSeeded(input: SeededDocumentInput) {\n const { runtime } = this.dependencies;\n const generation = runtime.scopeGeneration;\n return createSeededDocument(\n this.workflowRuntime(input.containerId),\n input,\n () => runtime.scopeGeneration === generation,\n );\n }\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 deleteDocumentPlacements: runtime.deleteDocumentPlacements,\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 { runtime } = this.dependencies;\n return createDocumentsWorkflowRuntimeFromSnapshot({\n ...runtime.workflowInput(containerId),\n deleteDocumentPlacements: runtime.deleteDocumentPlacements,\n });\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 initialRows,\n initialStructuredFields,\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 {\n initialRows,\n initialStructuredFields,\n remoteSyncMode: options.remoteSyncMode,\n },\n );\n }\n\n async openHistory(localId: string): Promise<DocumentHistory | null> {\n const runtime = this.workflowRuntime();\n if (runtime.infra.dbStatus !== \"ready\") {\n return null;\n }\n\n await this.ensureSchema(runtime.infra.execSql);\n return openDocumentHistory({\n documentProjectors: runtime.infra.documentProjectors,\n execSql: runtime.infra.execSql,\n localId,\n persistence: defaultDocumentsPersistence,\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":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,wCAAwC,CAAC;AAW/E,OAAO,EACL,oBAAoB,EACpB,mBAAmB,IAAI,yBAAyB,EAIhD,iBAAiB,EAEjB,qBAAqB,EAErB,6BAA6B,GAC9B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,6BAA6B,EAAE,MAAM,iCAAiC,CAAC;AAChF,OAAO,EACL,0CAA0C,EAE1C,2BAA2B,EAC3B,uBAAuB,EACvB,mBAAmB,EACnB,0BAA0B,GAC3B,MAAM,2BAA2B,CAAC;AA2CnC,OAAO,EAAE,yBAAyB,IAAI,mBAAmB,EAAE,CAAC;AAoD5D,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;IAEp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BAAsB,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 { DiscoveredDocumentInput } from \"../../data/documents/documentSummary\";\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 createSeededDocument,\n DEFAULT_DOCUMENT_ID as DEFAULT_LOCAL_DOCUMENT_ID,\n type DocumentStore,\n type DocumentStoreOpenOptions,\n type DocumentsRuntime,\n openDocumentStore,\n type PersistedDocumentListener,\n retryDocumentDownload,\n type SeededDocumentInput,\n subscribeToPersistedDocuments,\n} from \"../../stores/documents\";\nimport { emitPersistedDocumentDeletion } from \"../../stores/documents/registry\";\nimport {\n createDocumentsWorkflowRuntimeFromSnapshot,\n type DocumentHistory,\n defaultDocumentsPersistence,\n deletePersistedDocument,\n openDocumentHistory,\n reclaimDocumentOrphanBlobs,\n} from \"../../workflows/documents\";\nimport type { InternalRuntime } from \"../runtime/workflowRuntime\";\n\nexport type {\n DocumentAttachmentStatus,\n DocumentAttachmentUpload,\n DocumentContextValue,\n DocumentStore,\n DocumentsRuntime,\n PersistedDocumentListener,\n} from \"../../stores/documents\";\n\nexport type {\n DocumentHistory,\n DocumentHistoryChange,\n DocumentHistoryRowChange,\n DocumentHistoryStop,\n DocumentHistoryTextChange,\n DocumentHistoryVersion,\n DocumentHistoryVersionEntry,\n DocumentHistoryView,\n} from \"../../workflows/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 type { SeededDocumentInput } from \"../../stores/documents\";\nexport interface OpenDocumentInput {\n readonly containerId?: string | null | undefined;\n readonly documentId?: string | null | undefined;\n readonly initialDocumentKind?: StoredDocumentKind | undefined;\n /** Birth content of a created record; see `DocumentStoreOpenOptions`. */\n readonly initialRows?: DocumentStoreOpenOptions[\"initialRows\"];\n readonly initialStructuredFields?: DocumentStoreOpenOptions[\"initialStructuredFields\"];\n readonly initialText?: string | undefined;\n readonly localId?: string | undefined;\n}\nexport { DEFAULT_LOCAL_DOCUMENT_ID as DEFAULT_DOCUMENT_ID };\n\nexport interface OpenDocumentOptions {\n readonly remoteSyncMode?: \"on-demand\" | \"startup\" | undefined;\n readonly workflowRuntime?: DocumentsRuntime | undefined;\n}\n\nexport interface RetryDocumentDownloadInput {\n readonly documentId: string;\n readonly localId: string;\n}\n\nexport interface DocumentSubscriptionOptions {\n readonly containerId?: string | null | undefined;\n}\n\nexport interface Documents {\n createSeeded(\n input: SeededDocumentInput,\n ): Promise<DiscoveredDocumentInput | \"purged\">;\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 /**\n * Open a read-only replay of a document's durable local history. Resolves to\n * null while the database is not ready or the document has no history yet.\n * The caller must `close()` the result.\n */\n openHistory(localId: string): Promise<DocumentHistory | null>;\n /**\n * Pull a synced document again and re-list its attachment bindings, e.g.\n * to retry a pending first download. Resolves false, without syncing, when\n * the database is not ready or the local record no longer carries\n * `documentId`; an already-open store keeps its runtime and draft.\n */\n retryDownload(input: RetryDocumentDownloadInput): Promise<boolean>;\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 createSeeded(input: SeededDocumentInput) {\n const { runtime } = this.dependencies;\n const generation = runtime.scopeGeneration;\n return createSeededDocument(\n this.workflowRuntime(input.containerId),\n input,\n () => runtime.scopeGeneration === generation,\n );\n }\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 deleteDocumentPlacements: runtime.deleteDocumentPlacements,\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 { runtime } = this.dependencies;\n return createDocumentsWorkflowRuntimeFromSnapshot({\n ...runtime.workflowInput(containerId),\n deleteDocumentPlacements: runtime.deleteDocumentPlacements,\n });\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 initialRows,\n initialStructuredFields,\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 {\n initialRows,\n initialStructuredFields,\n remoteSyncMode: options.remoteSyncMode,\n },\n );\n }\n\n async openHistory(localId: string): Promise<DocumentHistory | null> {\n const runtime = this.workflowRuntime();\n if (runtime.infra.dbStatus !== \"ready\") {\n return null;\n }\n\n await this.ensureSchema(runtime.infra.execSql);\n return openDocumentHistory({\n documentProjectors: runtime.infra.documentProjectors,\n execSql: runtime.infra.execSql,\n localId,\n persistence: defaultDocumentsPersistence,\n });\n }\n\n retryDownload(input: RetryDocumentDownloadInput): Promise<boolean> {\n return retryDocumentDownload({\n ...input,\n workflowRuntime: (containerId) => this.workflowRuntime(containerId),\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/client/index.d.ts CHANGED
@@ -7,7 +7,7 @@ export { type BlobStoreFactory, Blobs } from "./blobs/index.js";
7
7
  export type { BlobInfo, BlobInfoAttachmentKind, BlobInfoDocumentReference, BlobInfoInput, BlobInfoList, BlobInfoSort, BlobInfoSortDirection, BlobInfoSortKey, ContainerContents, ContainerContentsContextValue, ContainerContentsStore, ContainerContentsStoreOptions, ContainerDocumentLinkInput, ContainerDocumentLinks, ContainerDocumentObjectSyncState, ContainerDocumentObjectSyncStatus, ContainerDocumentQueries, ContainerDocumentSidebarRow, ContainerInfo, ContainerInfoInput, ContainerItemRow, ContainerItemSort, ContainerItemSortDirection, ContainerItemSortKey, ContainerNode, ContainerShareAccessLevel, DocumentAttributionRangesInput, DocumentAttributionRangesPage, DocumentInfo, DocumentInfoInput, LinkDocumentToContainerInput, MergeDocumentSummary, MoveDocumentToContainerInput, OpenContainerDocumentInput, PendingWriteQueueItem, PendingWriteQueueItemStatus, PendingWriteQueueObjectKind, PendingWriteQueueOperation, PendingWriteQueueOperationKind, PendingWriteQueueOperationStatus, PurgeDocumentInput, PurgeDocumentResult, SetActiveDocumentContainerInput, SetLinkedContainerIdsForDocument, UnlinkDocumentFromContainerInput, } from "./containerContents/index.js";
8
8
  export { createContainerDocumentObjectSyncState } from "./containerContents/index.js";
9
9
  export type { DeviceFirst, DeviceFirstContainerContents, LocalProjectionView, } from "./deviceFirst/index.js";
10
- export type { DocumentAttachmentStatus, DocumentAttachmentUpload, DocumentContextValue, DocumentHistory, DocumentHistoryChange, DocumentHistoryRowChange, DocumentHistoryStop, DocumentHistoryTextChange, DocumentHistoryVersion, DocumentHistoryVersionEntry, DocumentHistoryView, DocumentList, DocumentSort, DocumentSortDirection, DocumentSortKey, DocumentStore, DocumentSubscriptionOptions, Documents, DocumentsRuntime, ListDocumentsInput, OpenDocumentInput, OpenDocumentOptions, PersistedDocumentListener, SeededDocumentInput, } from "./documents/index.js";
10
+ export type { DocumentAttachmentStatus, DocumentAttachmentUpload, DocumentContextValue, DocumentHistory, DocumentHistoryChange, DocumentHistoryRowChange, DocumentHistoryStop, DocumentHistoryTextChange, DocumentHistoryVersion, DocumentHistoryVersionEntry, DocumentHistoryView, DocumentList, DocumentSort, DocumentSortDirection, DocumentSortKey, DocumentStore, DocumentSubscriptionOptions, Documents, DocumentsRuntime, ListDocumentsInput, OpenDocumentInput, OpenDocumentOptions, PersistedDocumentListener, RetryDocumentDownloadInput, SeededDocumentInput, } from "./documents/index.js";
11
11
  export { DEFAULT_DOCUMENT_ID } from "./documents/index.js";
12
12
  export type { FileSaver, SaveFileRequest } from "./host/fileSaver.js";
13
13
  export type { Logger } from "./host/logger.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,GAElB,MAAM,4BAA4B,CAAC;AAKpC,OAAO,EACL,8BAA8B,GAE/B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACL,+BAA+B,EAK/B,8BAA8B,GAC/B,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,yBAAyB,EACzB,0BAA0B,EAC1B,oBAAoB,EACpB,yBAAyB,EACzB,sBAAsB,EACtB,4BAA4B,EAC5B,4BAA4B,EAE5B,yBAAyB,GAO1B,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAyB,KAAK,EAAE,MAAM,SAAS,CAAC;AAgDvD,OAAO,EAAE,sCAAsC,EAAE,MAAM,qBAAqB,CAAC;AAgC7E,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAUlD,OAAO,EACL,2BAA2B,GAE5B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAEL,2BAA2B,GAE5B,MAAM,2BAA2B,CAAC;AAyBnC,OAAO,EACL,yBAAyB,EACzB,sCAAsC,EACtC,wCAAwC,EACxC,kCAAkC,EAClC,kBAAkB,EAClB,2CAA2C,EAC3C,qCAAqC,EACrC,+BAA+B,EAC/B,yBAAyB,EACzB,2BAA2B,EAC3B,2BAA2B,EAC3B,6BAA6B,EAC7B,oBAAoB,EACpB,0BAA0B,EAC1B,yBAAyB,EACzB,6BAA6B,EAC7B,2BAA2B,GAC5B,MAAM,gBAAgB,CAAC;AAMxB,OAAO,EACL,gCAAgC,EAChC,gCAAgC,EAChC,mCAAmC,GACpC,MAAM,oCAAoC,CAAC;AA0C5C,OAAO,EACL,2CAA2C,EAC3C,sCAAsC,GACvC,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EACL,QAAQ,GAKT,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACL,8BAA8B,GAE/B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,MAAM,GAGP,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,gCAAgC,EAChC,OAAO,GAIR,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EACL,eAAe,GAEhB,MAAM,2BAA2B,CAAC;AAOnC,OAAO,EAAE,8CAA8C,EAAE,MAAM,iCAAiC,CAAC","sourcesContent":["export {\n createDomainScope,\n type DomainScope,\n} from \"../data/shared/domainScope\";\nexport type {\n LocalProjectionReconciledDelta,\n LocalProjectionSnapshot,\n} from \"../stores/local-projection\";\nexport {\n enqueueReconciliationForEvents,\n type ReconciliationService,\n} from \"../sync/reconciliation\";\nexport {\n createUnavailableDirectCheckout,\n type DirectCheckoutAppearance,\n type DirectCheckoutCapability,\n type DirectCheckoutConfirmation,\n type DirectCheckoutSession,\n DirectCheckoutUnavailableError,\n} from \"./billing/directCheckout\";\nexport {\n createRevenueCatPurchases,\n createUnavailablePurchases,\n PurchaseAbortedError,\n PurchaseAlreadyOwnedError,\n PurchaseCancelledError,\n PurchaseIdentityPendingError,\n PurchaseProviderStalledError,\n type PurchasesCapability,\n PurchasesUnavailableError,\n type RevenueCatBackend,\n type RevenueCatCustomerInfo,\n type RevenueCatPackage,\n type RevenueCatPurchasesConfig,\n type SyncPurchaseResult,\n type SyncSubscriptionOption,\n} from \"./billing/purchases\";\nexport { type BlobStoreFactory, Blobs } from \"./blobs\";\nexport type {\n BlobInfo,\n BlobInfoAttachmentKind,\n BlobInfoDocumentReference,\n BlobInfoInput,\n BlobInfoList,\n BlobInfoSort,\n BlobInfoSortDirection,\n BlobInfoSortKey,\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 DocumentAttributionRangesInput,\n DocumentAttributionRangesPage,\n DocumentInfo,\n DocumentInfoInput,\n LinkDocumentToContainerInput,\n MergeDocumentSummary,\n MoveDocumentToContainerInput,\n OpenContainerDocumentInput,\n PendingWriteQueueItem,\n PendingWriteQueueItemStatus,\n PendingWriteQueueObjectKind,\n PendingWriteQueueOperation,\n PendingWriteQueueOperationKind,\n PendingWriteQueueOperationStatus,\n PurgeDocumentInput,\n PurgeDocumentResult,\n SetActiveDocumentContainerInput,\n SetLinkedContainerIdsForDocument,\n UnlinkDocumentFromContainerInput,\n} from \"./containerContents\";\nexport { createContainerDocumentObjectSyncState } from \"./containerContents\";\nexport type {\n DeviceFirst,\n DeviceFirstContainerContents,\n LocalProjectionView,\n} from \"./deviceFirst\";\nexport type {\n DocumentAttachmentStatus,\n DocumentAttachmentUpload,\n DocumentContextValue,\n DocumentHistory,\n DocumentHistoryChange,\n DocumentHistoryRowChange,\n DocumentHistoryStop,\n DocumentHistoryTextChange,\n DocumentHistoryVersion,\n DocumentHistoryVersionEntry,\n DocumentHistoryView,\n DocumentList,\n DocumentSort,\n DocumentSortDirection,\n DocumentSortKey,\n DocumentStore,\n DocumentSubscriptionOptions,\n Documents,\n DocumentsRuntime,\n ListDocumentsInput,\n OpenDocumentInput,\n OpenDocumentOptions,\n PersistedDocumentListener,\n SeededDocumentInput,\n} from \"./documents\";\nexport { DEFAULT_DOCUMENT_ID } from \"./documents\";\nexport type { FileSaver, SaveFileRequest } from \"./host/fileSaver\";\nexport type { Logger } from \"./host/logger\";\nexport type {\n Identity,\n IdentityGenerationResult,\n IdentityListener,\n IdentityOptions,\n IdentitySnapshot,\n} from \"./identity\";\nexport {\n IDENTITY_KEY_PACKAGE_FORMAT,\n type IdentityKeyPackage,\n} from \"./identity/keyPackage\";\nexport {\n type ResolvedUserIdentity,\n UnverifiedUserIdentityError,\n type UserIdentities,\n} from \"./identity/userIdentities\";\nexport type {\n BrowserLocalKeyringOptions,\n IndexedDbLocalKeyringManifestStoreOptions,\n IndexedDbWrappingKeyKeystoreOptions,\n LocalKeyPurpose,\n LocalKeyring,\n LocalKeyringManifest,\n LocalKeyringManifestFormat,\n LocalKeyringManifestStorage,\n LocalKeyringManifestStore,\n LocalKeyringOptions,\n LocalKeyringScope,\n LocalKeyringSession,\n LocalSecretContext,\n LocalStorageLocalKeyringManifestStoreOptions,\n NormalizedLocalKeyringScope,\n UnwrapLocalSecretInput,\n WrapLocalSecretInput,\n WrappedLocalSecretEnvelope,\n WrappedLocalSecretFormat,\n WrappingKeyHandle,\n WrappingKeyKeystore,\n WrappingKeyMaterialStorage,\n} from \"./localKeyring\";\nexport {\n createBrowserLocalKeyring,\n createBrowserLocalKeyringManifestStore,\n createIndexedDbLocalKeyringManifestStore,\n createIndexedDbWrappingKeyKeystore,\n createLocalKeyring,\n createLocalStorageLocalKeyringManifestStore,\n createMemoryLocalKeyringManifestStore,\n createMemoryWrappingKeyKeystore,\n createWebViewLocalKeyring,\n decodeLocalKeyringSqliteKey,\n encodeLocalKeyringSqliteKey,\n LOCAL_KEYRING_MANIFEST_FORMAT,\n localKeyringScopeKey,\n normalizeLocalKeyringScope,\n parseLocalKeyringManifest,\n serializeLocalKeyringManifest,\n WRAPPED_LOCAL_SECRET_FORMAT,\n} from \"./localKeyring\";\nexport type {\n LocalKeyringPinCode,\n PinCodeBrowserLocalKeyringOptions,\n PinCodeWrappingKeyKeystoreOptions,\n} from \"./localKeyring/localKeyringPinCode\";\nexport {\n createPinCodeBrowserLocalKeyring,\n createPinCodeWrappingKeyKeystore,\n isPinCodeWrappedLocalSecretEnvelope,\n} from \"./localKeyring/localKeyringPinCode\";\nexport type {\n AbandonOrganizationPolicyMutationInput,\n AddOrganizationGroupUserInput,\n DiscardUnreadableOrganizationPolicyMutationInput,\n LocalOrganizationSummary,\n OrganizationBilling,\n OrganizationBillingHistory,\n OrganizationBillingHistoryEntry,\n OrganizationBillingManagementUrl,\n OrganizationBillingView,\n OrganizationContainerGrant,\n OrganizationContainerGrants,\n OrganizationDataUsage,\n OrganizationDeviceDataUsage,\n OrganizationDeviceDocumentUsageCategoryBreakdown,\n OrganizationDirectory,\n OrganizationDirectoryAndGroups,\n OrganizationDirectoryUser,\n OrganizationGrantRef,\n OrganizationGroupContainer,\n OrganizationGroupContainers,\n OrganizationGroupDetails,\n OrganizationGroupMember,\n OrganizationGroupMembers,\n OrganizationGroupMutationReceipt,\n OrganizationGroupMutationResult,\n OrganizationGroupPolicyHistory,\n OrganizationGroupSummary,\n OrganizationLeaveRequestResult,\n OrganizationMembership,\n OrganizationMemberships,\n OrganizationPolicyGrantChange,\n OrganizationPolicyGroupChange,\n OrganizationPolicyHistory,\n OrganizationPolicyHistoryEntry,\n OrganizationProfile,\n OrganizationSyncPauseResult,\n Organizations,\n OrganizationUserDetail,\n RemoveOrganizationGroupUserInput,\n} from \"./organizations\";\nexport {\n createContainerContentsStoreWorkflowRuntime,\n createContainerContentsWorkflowRuntime,\n} from \"./runtime/containerContentsRuntime\";\nexport {\n Database,\n type DatabaseListener,\n type DatabaseOptions,\n type DatabaseSnapshot,\n type DatabaseStatus,\n} from \"./runtime/database\";\nexport {\n createDocumentsWorkflowRuntime,\n type DocumentsWorkflowRuntimeInput,\n} from \"./runtime/documentsRuntime\";\nexport {\n Events,\n type EventsListener,\n type EventsSnapshot,\n} from \"./runtime/events\";\nexport {\n createBrowserNetworkStatusSource,\n Network,\n type NetworkListener,\n type NetworkMode,\n type NetworkStatusSource,\n} from \"./runtime/network\";\nexport type {\n PrincipalHistoryKeyProvider,\n PrincipalHistoryKeyScope,\n} from \"./runtime/principalHistoryProtection\";\nexport {\n SyncBillingGate,\n type SyncBillingGateListener,\n} from \"./runtime/syncBillingGate\";\nexport type {\n SecurityIncident,\n SecurityIncidentListener,\n SecurityIncidentObjectKind,\n SecurityIncidents,\n} from \"./securityIncidents\";\nexport { PurgedOrganizationRecoveryBillingRequiredError } from \"./session/sessionRecoveryErrors\";\nexport type {\n CreateOrganizationOptions,\n Session,\n SessionContext,\n SessionCreateOrganizationResult,\n SessionListener,\n SessionRecoverOrganizationResult,\n SessionRegistrationRefusal,\n SessionRegistrationResult,\n SessionSnapshot,\n UserSession,\n} from \"./session/sessionTypes\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,GAElB,MAAM,4BAA4B,CAAC;AAKpC,OAAO,EACL,8BAA8B,GAE/B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACL,+BAA+B,EAK/B,8BAA8B,GAC/B,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,yBAAyB,EACzB,0BAA0B,EAC1B,oBAAoB,EACpB,yBAAyB,EACzB,sBAAsB,EACtB,4BAA4B,EAC5B,4BAA4B,EAE5B,yBAAyB,GAO1B,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAyB,KAAK,EAAE,MAAM,SAAS,CAAC;AAgDvD,OAAO,EAAE,sCAAsC,EAAE,MAAM,qBAAqB,CAAC;AAiC7E,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAUlD,OAAO,EACL,2BAA2B,GAE5B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAEL,2BAA2B,GAE5B,MAAM,2BAA2B,CAAC;AAyBnC,OAAO,EACL,yBAAyB,EACzB,sCAAsC,EACtC,wCAAwC,EACxC,kCAAkC,EAClC,kBAAkB,EAClB,2CAA2C,EAC3C,qCAAqC,EACrC,+BAA+B,EAC/B,yBAAyB,EACzB,2BAA2B,EAC3B,2BAA2B,EAC3B,6BAA6B,EAC7B,oBAAoB,EACpB,0BAA0B,EAC1B,yBAAyB,EACzB,6BAA6B,EAC7B,2BAA2B,GAC5B,MAAM,gBAAgB,CAAC;AAMxB,OAAO,EACL,gCAAgC,EAChC,gCAAgC,EAChC,mCAAmC,GACpC,MAAM,oCAAoC,CAAC;AA0C5C,OAAO,EACL,2CAA2C,EAC3C,sCAAsC,GACvC,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EACL,QAAQ,GAKT,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACL,8BAA8B,GAE/B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,MAAM,GAGP,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,gCAAgC,EAChC,OAAO,GAIR,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EACL,eAAe,GAEhB,MAAM,2BAA2B,CAAC;AAOnC,OAAO,EAAE,8CAA8C,EAAE,MAAM,iCAAiC,CAAC","sourcesContent":["export {\n createDomainScope,\n type DomainScope,\n} from \"../data/shared/domainScope\";\nexport type {\n LocalProjectionReconciledDelta,\n LocalProjectionSnapshot,\n} from \"../stores/local-projection\";\nexport {\n enqueueReconciliationForEvents,\n type ReconciliationService,\n} from \"../sync/reconciliation\";\nexport {\n createUnavailableDirectCheckout,\n type DirectCheckoutAppearance,\n type DirectCheckoutCapability,\n type DirectCheckoutConfirmation,\n type DirectCheckoutSession,\n DirectCheckoutUnavailableError,\n} from \"./billing/directCheckout\";\nexport {\n createRevenueCatPurchases,\n createUnavailablePurchases,\n PurchaseAbortedError,\n PurchaseAlreadyOwnedError,\n PurchaseCancelledError,\n PurchaseIdentityPendingError,\n PurchaseProviderStalledError,\n type PurchasesCapability,\n PurchasesUnavailableError,\n type RevenueCatBackend,\n type RevenueCatCustomerInfo,\n type RevenueCatPackage,\n type RevenueCatPurchasesConfig,\n type SyncPurchaseResult,\n type SyncSubscriptionOption,\n} from \"./billing/purchases\";\nexport { type BlobStoreFactory, Blobs } from \"./blobs\";\nexport type {\n BlobInfo,\n BlobInfoAttachmentKind,\n BlobInfoDocumentReference,\n BlobInfoInput,\n BlobInfoList,\n BlobInfoSort,\n BlobInfoSortDirection,\n BlobInfoSortKey,\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 DocumentAttributionRangesInput,\n DocumentAttributionRangesPage,\n DocumentInfo,\n DocumentInfoInput,\n LinkDocumentToContainerInput,\n MergeDocumentSummary,\n MoveDocumentToContainerInput,\n OpenContainerDocumentInput,\n PendingWriteQueueItem,\n PendingWriteQueueItemStatus,\n PendingWriteQueueObjectKind,\n PendingWriteQueueOperation,\n PendingWriteQueueOperationKind,\n PendingWriteQueueOperationStatus,\n PurgeDocumentInput,\n PurgeDocumentResult,\n SetActiveDocumentContainerInput,\n SetLinkedContainerIdsForDocument,\n UnlinkDocumentFromContainerInput,\n} from \"./containerContents\";\nexport { createContainerDocumentObjectSyncState } from \"./containerContents\";\nexport type {\n DeviceFirst,\n DeviceFirstContainerContents,\n LocalProjectionView,\n} from \"./deviceFirst\";\nexport type {\n DocumentAttachmentStatus,\n DocumentAttachmentUpload,\n DocumentContextValue,\n DocumentHistory,\n DocumentHistoryChange,\n DocumentHistoryRowChange,\n DocumentHistoryStop,\n DocumentHistoryTextChange,\n DocumentHistoryVersion,\n DocumentHistoryVersionEntry,\n DocumentHistoryView,\n DocumentList,\n DocumentSort,\n DocumentSortDirection,\n DocumentSortKey,\n DocumentStore,\n DocumentSubscriptionOptions,\n Documents,\n DocumentsRuntime,\n ListDocumentsInput,\n OpenDocumentInput,\n OpenDocumentOptions,\n PersistedDocumentListener,\n RetryDocumentDownloadInput,\n SeededDocumentInput,\n} from \"./documents\";\nexport { DEFAULT_DOCUMENT_ID } from \"./documents\";\nexport type { FileSaver, SaveFileRequest } from \"./host/fileSaver\";\nexport type { Logger } from \"./host/logger\";\nexport type {\n Identity,\n IdentityGenerationResult,\n IdentityListener,\n IdentityOptions,\n IdentitySnapshot,\n} from \"./identity\";\nexport {\n IDENTITY_KEY_PACKAGE_FORMAT,\n type IdentityKeyPackage,\n} from \"./identity/keyPackage\";\nexport {\n type ResolvedUserIdentity,\n UnverifiedUserIdentityError,\n type UserIdentities,\n} from \"./identity/userIdentities\";\nexport type {\n BrowserLocalKeyringOptions,\n IndexedDbLocalKeyringManifestStoreOptions,\n IndexedDbWrappingKeyKeystoreOptions,\n LocalKeyPurpose,\n LocalKeyring,\n LocalKeyringManifest,\n LocalKeyringManifestFormat,\n LocalKeyringManifestStorage,\n LocalKeyringManifestStore,\n LocalKeyringOptions,\n LocalKeyringScope,\n LocalKeyringSession,\n LocalSecretContext,\n LocalStorageLocalKeyringManifestStoreOptions,\n NormalizedLocalKeyringScope,\n UnwrapLocalSecretInput,\n WrapLocalSecretInput,\n WrappedLocalSecretEnvelope,\n WrappedLocalSecretFormat,\n WrappingKeyHandle,\n WrappingKeyKeystore,\n WrappingKeyMaterialStorage,\n} from \"./localKeyring\";\nexport {\n createBrowserLocalKeyring,\n createBrowserLocalKeyringManifestStore,\n createIndexedDbLocalKeyringManifestStore,\n createIndexedDbWrappingKeyKeystore,\n createLocalKeyring,\n createLocalStorageLocalKeyringManifestStore,\n createMemoryLocalKeyringManifestStore,\n createMemoryWrappingKeyKeystore,\n createWebViewLocalKeyring,\n decodeLocalKeyringSqliteKey,\n encodeLocalKeyringSqliteKey,\n LOCAL_KEYRING_MANIFEST_FORMAT,\n localKeyringScopeKey,\n normalizeLocalKeyringScope,\n parseLocalKeyringManifest,\n serializeLocalKeyringManifest,\n WRAPPED_LOCAL_SECRET_FORMAT,\n} from \"./localKeyring\";\nexport type {\n LocalKeyringPinCode,\n PinCodeBrowserLocalKeyringOptions,\n PinCodeWrappingKeyKeystoreOptions,\n} from \"./localKeyring/localKeyringPinCode\";\nexport {\n createPinCodeBrowserLocalKeyring,\n createPinCodeWrappingKeyKeystore,\n isPinCodeWrappedLocalSecretEnvelope,\n} from \"./localKeyring/localKeyringPinCode\";\nexport type {\n AbandonOrganizationPolicyMutationInput,\n AddOrganizationGroupUserInput,\n DiscardUnreadableOrganizationPolicyMutationInput,\n LocalOrganizationSummary,\n OrganizationBilling,\n OrganizationBillingHistory,\n OrganizationBillingHistoryEntry,\n OrganizationBillingManagementUrl,\n OrganizationBillingView,\n OrganizationContainerGrant,\n OrganizationContainerGrants,\n OrganizationDataUsage,\n OrganizationDeviceDataUsage,\n OrganizationDeviceDocumentUsageCategoryBreakdown,\n OrganizationDirectory,\n OrganizationDirectoryAndGroups,\n OrganizationDirectoryUser,\n OrganizationGrantRef,\n OrganizationGroupContainer,\n OrganizationGroupContainers,\n OrganizationGroupDetails,\n OrganizationGroupMember,\n OrganizationGroupMembers,\n OrganizationGroupMutationReceipt,\n OrganizationGroupMutationResult,\n OrganizationGroupPolicyHistory,\n OrganizationGroupSummary,\n OrganizationLeaveRequestResult,\n OrganizationMembership,\n OrganizationMemberships,\n OrganizationPolicyGrantChange,\n OrganizationPolicyGroupChange,\n OrganizationPolicyHistory,\n OrganizationPolicyHistoryEntry,\n OrganizationProfile,\n OrganizationSyncPauseResult,\n Organizations,\n OrganizationUserDetail,\n RemoveOrganizationGroupUserInput,\n} from \"./organizations\";\nexport {\n createContainerContentsStoreWorkflowRuntime,\n createContainerContentsWorkflowRuntime,\n} from \"./runtime/containerContentsRuntime\";\nexport {\n Database,\n type DatabaseListener,\n type DatabaseOptions,\n type DatabaseSnapshot,\n type DatabaseStatus,\n} from \"./runtime/database\";\nexport {\n createDocumentsWorkflowRuntime,\n type DocumentsWorkflowRuntimeInput,\n} from \"./runtime/documentsRuntime\";\nexport {\n Events,\n type EventsListener,\n type EventsSnapshot,\n} from \"./runtime/events\";\nexport {\n createBrowserNetworkStatusSource,\n Network,\n type NetworkListener,\n type NetworkMode,\n type NetworkStatusSource,\n} from \"./runtime/network\";\nexport type {\n PrincipalHistoryKeyProvider,\n PrincipalHistoryKeyScope,\n} from \"./runtime/principalHistoryProtection\";\nexport {\n SyncBillingGate,\n type SyncBillingGateListener,\n} from \"./runtime/syncBillingGate\";\nexport type {\n SecurityIncident,\n SecurityIncidentListener,\n SecurityIncidentObjectKind,\n SecurityIncidents,\n} from \"./securityIncidents\";\nexport { PurgedOrganizationRecoveryBillingRequiredError } from \"./session/sessionRecoveryErrors\";\nexport type {\n CreateOrganizationOptions,\n Session,\n SessionContext,\n SessionCreateOrganizationResult,\n SessionListener,\n SessionRecoverOrganizationResult,\n SessionRegistrationRefusal,\n SessionRegistrationResult,\n SessionSnapshot,\n UserSession,\n} from \"./session/sessionTypes\";\n"]}
@@ -41,7 +41,9 @@ export interface DocumentAttachmentHydrationApi {
41
41
  evictDocumentWriterProjection?(documentId: string): void;
42
42
  getBlobBytes(blobId: string, options?: RequestResultOptions): Promise<BlobBytesResponse | null>;
43
43
  getDocumentWriterProjection(documentId: string): Promise<DocumentWriterProjectionResponse | null>;
44
- listDocumentAttachments(documentId: string): Promise<ListDocumentAttachmentsResponse | null>;
44
+ listDocumentAttachments(documentId: string, options?: {
45
+ readonly refresh?: boolean;
46
+ }): Promise<ListDocumentAttachmentsResponse | null>;
45
47
  }
46
48
  export type { BlobContentKeyTarget };
47
49
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"AAqCA,MAAM,CAAC,MAAM,mCAAmC,GAC9C,wCAAwC,CAAC;AAC3C,MAAM,CAAC,MAAM,8BAA8B,GACzC,mCAAmC,CAAC;AACtC,MAAM,CAAC,MAAM,gCAAgC,GAC3C,qCAAqC,CAAC;AACxC,MAAM,CAAC,MAAM,6BAA6B,GACxC,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,yCAAyC,CAAC,CAAC;AACtE,MAAM,CAAC,MAAM,YAAY,GAAG,IAAI,WAAW,EAAE,CAAC","sourcesContent":["import type {\n BlobBytesResponse,\n RequestFailureKind,\n RequestResultOptions,\n UploadMultipartBlobPartBytesRequest,\n} from \"@tearleads/api-client\";\nimport type {\n BlobContentKeyTarget,\n BlobEnvelopeHeaderRecord,\n BlobEnvelopeRecord,\n WriteHeader,\n} from \"@tearleads/crypto\";\nimport type {\n BlobAttachmentBindRequest,\n BlobAttachmentDetachRequest,\n BlobContentKeyBundleRequest,\n DocumentSyncRequest,\n InitiateMultipartBlobStageRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n BlobAttachmentBindResponse,\n BlobAttachmentDetachResponse,\n BlobAttachmentSummary,\n DocumentWriterProjectionResponse,\n InitiateMultipartBlobStageResponse,\n ListDocumentAttachmentsResponse,\n MultipartBlobStageStatusResponse,\n UploadMultipartBlobPartResponse,\n} from \"@tearleads/validators/response\";\nimport type { DocumentCreateAuthor } from \"../../documents/shared/types\";\nimport type {\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../../keyingProjectionVerification\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport type { BlobByteSourceInput, BlobBytes } from \"../blobContracts\";\n\nexport const BLOB_CONTENT_RECORD_KEY_INFO_DOMAIN =\n \"tearleads.blob.content-record-key-info\";\nexport const BLOB_CONTENT_RECORD_AAD_DOMAIN =\n \"tearleads.blob.content-record-aad\";\nexport const BLOB_CONTENT_RECORD_NONCE_DOMAIN =\n \"tearleads.blob.content-record-nonce\";\nexport const BLOB_CONTENT_RECORD_HKDF_SALT: Uint8Array<ArrayBuffer> =\n new TextEncoder().encode(\"tearleads.blob.content-record-hkdf-salt\");\nexport const TEXT_ENCODER = new TextEncoder();\n\nexport interface BlobAttachmentRequestOptions {\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly expectedPaymentRequiredOrganizationId?: string | undefined;\n}\n\nexport interface BlobAttachmentApi {\n bindBlobAttachment(\n blobId: string,\n input: BlobAttachmentBindRequest,\n options?: BlobAttachmentRequestOptions,\n ): Promise<BlobAttachmentBindResponse | null>;\n clearWriterProjectionCaches?(): void;\n evictDocumentWriterProjection?(documentId: string): void;\n getRequestFailure?(input: {\n method: \"DELETE\" | \"GET\" | \"POST\" | \"PUT\";\n path: string;\n }): {\n readonly code?: string | undefined;\n readonly kind: RequestFailureKind;\n readonly message: string;\n readonly status: number | null;\n } | null;\n getDocumentWriterProjection(\n documentId: string,\n ): Promise<DocumentWriterProjectionResponse | null>;\n getMultipartBlobStage(\n stageId: string,\n options?: RequestResultOptions,\n ): Promise<MultipartBlobStageStatusResponse | null>;\n initiateMultipartBlobStage(\n input: InitiateMultipartBlobStageRequest,\n options?: RequestResultOptions,\n ): Promise<InitiateMultipartBlobStageResponse | null>;\n uploadMultipartBlobPartBytes(\n stageId: string,\n partNumber: number,\n input: UploadMultipartBlobPartBytesRequest,\n options?: RequestResultOptions,\n ): Promise<UploadMultipartBlobPartResponse | null>;\n}\n\nexport interface BlobAttachmentDetachApi {\n detachBlobAttachment(\n blobId: string,\n bindingId: string,\n input: BlobAttachmentDetachRequest,\n options?: BlobAttachmentRequestOptions,\n ): Promise<BlobAttachmentDetachResponse | null>;\n getDocumentWriterProjection(\n documentId: string,\n ): Promise<DocumentWriterProjectionResponse | null>;\n}\n\nexport interface DocumentAttachmentHydrationApi {\n evictDocumentWriterProjection?(documentId: string): void;\n getBlobBytes(\n blobId: string,\n options?: RequestResultOptions,\n ): Promise<BlobBytesResponse | null>;\n getDocumentWriterProjection(\n documentId: string,\n ): Promise<DocumentWriterProjectionResponse | null>;\n listDocumentAttachments(\n documentId: string,\n ): Promise<ListDocumentAttachmentsResponse | null>;\n}\n\nexport type { BlobContentKeyTarget };\n\n/**\n * Aliases of the crypto parser's own types. The parser is shared with the API,\n * so restating these shapes here would let the two drift apart silently.\n */\nexport type BlobEncryptedBytesRecord = BlobEnvelopeRecord;\n\n/**\n * The envelope as the header establishes it. Streaming readers hold this\n * before any ciphertext is read, so it has no `chunks`: an empty array there\n * would read as an empty object rather than an unread one.\n */\nexport type BlobEncryptedBytesHeader = BlobEnvelopeHeaderRecord;\n\nexport type BlobEncryptedChunk = BlobEnvelopeRecord[\"chunks\"][number];\n\nexport interface BlobSourceSnapshot {\n readonly byteLength: number;\n readonly chunkSha256: readonly string[];\n readonly chunkSize: number;\n readonly sha256: string;\n}\n\nexport interface BlobEncryptionPlan {\n readonly byteLength: number;\n readonly chunkSize: number;\n readonly metadataHash: string;\n readonly partCount: number;\n readonly plaintextByteLength: number;\n readonly plaintextSha256: string;\n readonly sha256: string;\n encryptPart(index: number): Promise<BlobBytes>;\n getPartByteLength(index: number): number;\n}\n\nexport interface DocumentManifestIdentity {\n documentId: string;\n manifestHash: string;\n organizationId: string;\n}\n\nexport interface BlobAttachmentMaterial {\n blobAccessManifestHash: string;\n contentKeyBundle: BlobContentKeyBundleRequest;\n encrypted: BlobEncryptionPlan;\n manifestIdentity: DocumentManifestIdentity;\n targetHash: string;\n targets: BlobContentKeyTarget[];\n writerProjection: DocumentWriterProjectionResponse;\n}\n\n/**\n * Progress for an in-flight multipart blob upload.\n */\nexport interface MultipartUploadProgress {\n readonly bytesTotal: number;\n readonly bytesUploaded: number;\n readonly partsCompleted: number;\n readonly partsTotal: number;\n}\n\nexport type MultipartUploadProgressListener = (\n progress: MultipartUploadProgress,\n) => void;\n\n/**\n * Fires once a multipart stage has been opened (or resumed), with its id and\n * plaintext chunk size. Callers persist both so a later attempt can reproduce\n * the same encrypted parts and resume instead of orphaning the partial upload.\n */\nexport type MultipartStageResolvedListener = (input: {\n readonly partSize: number;\n readonly stageId: string;\n}) => void | Promise<void>;\n\n/** One upload; the service supplies the API, executor, and secret key. */\nexport interface UploadDocumentAttachmentRequest {\n author: DocumentCreateAuthor;\n blobId?: string | undefined;\n bindingId?: string | undefined;\n bytes: BlobByteSourceInput;\n contentKey?: Uint8Array | undefined;\n contentKeyEpoch?: number | undefined;\n documentId: string;\n /**\n * The document's deferred first update for the bind to commit after its\n * binding. A bind refused with it is sent once more without it, and the\n * caller's queued row then syncs on its own.\n */\n documentSync?: DocumentSyncRequest | undefined;\n eventId?: string | undefined;\n expectedBindingId: string | null;\n isRemoteSyncBlocked?: ((organizationId: string) => boolean) | undefined;\n // A persisted nonce seed. The plaintext digest derives the envelope IV from\n // it, then each chunk derives a unique IV. Same-source retries reproduce the\n // encrypted parts; changed bytes cannot reuse their AES-GCM nonces.\n nonceSeed?: Uint8Array | undefined;\n multipart?: MultipartBlobUploadOptions | undefined;\n onMultipartProgress?: MultipartUploadProgressListener | undefined;\n onStageResolved?: MultipartStageResolvedListener | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n signedAt?: string | undefined;\n slotId: string;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n writerProjection?: DocumentWriterProjectionResponse | undefined;\n}\n\nexport interface MultipartBlobUploadOptions {\n /** Exactly 5 MiB per plaintext encryption chunk; transport parts include envelope overhead. */\n readonly partSize: number;\n // The id of a previously opened stage to resume. When set, the upload refetches\n // that stage and skips parts the server already has instead of opening a new\n // one; if the stage is gone (expired), it falls back to a fresh stage.\n readonly resumeStageId?: string | undefined;\n readonly uploadConcurrency?: number | undefined;\n}\n\nexport interface UploadDocumentAttachmentResult {\n blobId: string;\n bindingId: string;\n request: BlobAttachmentBindRequest;\n response: BlobAttachmentBindResponse;\n sha256: string;\n byteLength: number;\n writeHeader: WriteHeader;\n writeHeaderHash: string;\n writerProjection: DocumentWriterProjectionResponse;\n}\n\n/** One detach; the service supplies the API and executor. */\nexport interface DetachDocumentAttachmentRequest {\n author: DocumentCreateAuthor;\n bindingId: string;\n blobId: string;\n documentId: string;\n eventId?: string | undefined;\n isRemoteSyncBlocked?: ((organizationId: string) => boolean) | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n signedAt?: string | undefined;\n slotId: string;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n writerProjection?: DocumentWriterProjectionResponse | undefined;\n}\n\nexport interface DetachDocumentAttachmentResult {\n request: BlobAttachmentDetachRequest;\n response: BlobAttachmentDetachResponse;\n writerProjection: DocumentWriterProjectionResponse;\n}\n\nexport interface DecryptDocumentAttachmentBlobInput {\n binding: BlobAttachmentSummary;\n encryptedBytes: BlobBytes;\n expectedDocumentId: string;\n expectedSlotId: string;\n execSql: ExecSql;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n targetSecretKey: Uint8Array;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n writerProjection: DocumentWriterProjectionResponse;\n}\n\n/** One decrypt; the service supplies the executor and its secret key. */\nexport type DecryptDocumentAttachmentBlobRequest = Omit<\n DecryptDocumentAttachmentBlobInput,\n \"execSql\" | \"targetSecretKey\"\n>;\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"AAqCA,MAAM,CAAC,MAAM,mCAAmC,GAC9C,wCAAwC,CAAC;AAC3C,MAAM,CAAC,MAAM,8BAA8B,GACzC,mCAAmC,CAAC;AACtC,MAAM,CAAC,MAAM,gCAAgC,GAC3C,qCAAqC,CAAC;AACxC,MAAM,CAAC,MAAM,6BAA6B,GACxC,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,yCAAyC,CAAC,CAAC;AACtE,MAAM,CAAC,MAAM,YAAY,GAAG,IAAI,WAAW,EAAE,CAAC","sourcesContent":["import type {\n BlobBytesResponse,\n RequestFailureKind,\n RequestResultOptions,\n UploadMultipartBlobPartBytesRequest,\n} from \"@tearleads/api-client\";\nimport type {\n BlobContentKeyTarget,\n BlobEnvelopeHeaderRecord,\n BlobEnvelopeRecord,\n WriteHeader,\n} from \"@tearleads/crypto\";\nimport type {\n BlobAttachmentBindRequest,\n BlobAttachmentDetachRequest,\n BlobContentKeyBundleRequest,\n DocumentSyncRequest,\n InitiateMultipartBlobStageRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n BlobAttachmentBindResponse,\n BlobAttachmentDetachResponse,\n BlobAttachmentSummary,\n DocumentWriterProjectionResponse,\n InitiateMultipartBlobStageResponse,\n ListDocumentAttachmentsResponse,\n MultipartBlobStageStatusResponse,\n UploadMultipartBlobPartResponse,\n} from \"@tearleads/validators/response\";\nimport type { DocumentCreateAuthor } from \"../../documents/shared/types\";\nimport type {\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../../keyingProjectionVerification\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport type { BlobByteSourceInput, BlobBytes } from \"../blobContracts\";\n\nexport const BLOB_CONTENT_RECORD_KEY_INFO_DOMAIN =\n \"tearleads.blob.content-record-key-info\";\nexport const BLOB_CONTENT_RECORD_AAD_DOMAIN =\n \"tearleads.blob.content-record-aad\";\nexport const BLOB_CONTENT_RECORD_NONCE_DOMAIN =\n \"tearleads.blob.content-record-nonce\";\nexport const BLOB_CONTENT_RECORD_HKDF_SALT: Uint8Array<ArrayBuffer> =\n new TextEncoder().encode(\"tearleads.blob.content-record-hkdf-salt\");\nexport const TEXT_ENCODER = new TextEncoder();\n\nexport interface BlobAttachmentRequestOptions {\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly expectedPaymentRequiredOrganizationId?: string | undefined;\n}\n\nexport interface BlobAttachmentApi {\n bindBlobAttachment(\n blobId: string,\n input: BlobAttachmentBindRequest,\n options?: BlobAttachmentRequestOptions,\n ): Promise<BlobAttachmentBindResponse | null>;\n clearWriterProjectionCaches?(): void;\n evictDocumentWriterProjection?(documentId: string): void;\n getRequestFailure?(input: {\n method: \"DELETE\" | \"GET\" | \"POST\" | \"PUT\";\n path: string;\n }): {\n readonly code?: string | undefined;\n readonly kind: RequestFailureKind;\n readonly message: string;\n readonly status: number | null;\n } | null;\n getDocumentWriterProjection(\n documentId: string,\n ): Promise<DocumentWriterProjectionResponse | null>;\n getMultipartBlobStage(\n stageId: string,\n options?: RequestResultOptions,\n ): Promise<MultipartBlobStageStatusResponse | null>;\n initiateMultipartBlobStage(\n input: InitiateMultipartBlobStageRequest,\n options?: RequestResultOptions,\n ): Promise<InitiateMultipartBlobStageResponse | null>;\n uploadMultipartBlobPartBytes(\n stageId: string,\n partNumber: number,\n input: UploadMultipartBlobPartBytesRequest,\n options?: RequestResultOptions,\n ): Promise<UploadMultipartBlobPartResponse | null>;\n}\n\nexport interface BlobAttachmentDetachApi {\n detachBlobAttachment(\n blobId: string,\n bindingId: string,\n input: BlobAttachmentDetachRequest,\n options?: BlobAttachmentRequestOptions,\n ): Promise<BlobAttachmentDetachResponse | null>;\n getDocumentWriterProjection(\n documentId: string,\n ): Promise<DocumentWriterProjectionResponse | null>;\n}\n\nexport interface DocumentAttachmentHydrationApi {\n evictDocumentWriterProjection?(documentId: string): void;\n getBlobBytes(\n blobId: string,\n options?: RequestResultOptions,\n ): Promise<BlobBytesResponse | null>;\n getDocumentWriterProjection(\n documentId: string,\n ): Promise<DocumentWriterProjectionResponse | null>;\n listDocumentAttachments(\n documentId: string,\n options?: { readonly refresh?: boolean },\n ): Promise<ListDocumentAttachmentsResponse | null>;\n}\n\nexport type { BlobContentKeyTarget };\n\n/**\n * Aliases of the crypto parser's own types. The parser is shared with the API,\n * so restating these shapes here would let the two drift apart silently.\n */\nexport type BlobEncryptedBytesRecord = BlobEnvelopeRecord;\n\n/**\n * The envelope as the header establishes it. Streaming readers hold this\n * before any ciphertext is read, so it has no `chunks`: an empty array there\n * would read as an empty object rather than an unread one.\n */\nexport type BlobEncryptedBytesHeader = BlobEnvelopeHeaderRecord;\n\nexport type BlobEncryptedChunk = BlobEnvelopeRecord[\"chunks\"][number];\n\nexport interface BlobSourceSnapshot {\n readonly byteLength: number;\n readonly chunkSha256: readonly string[];\n readonly chunkSize: number;\n readonly sha256: string;\n}\n\nexport interface BlobEncryptionPlan {\n readonly byteLength: number;\n readonly chunkSize: number;\n readonly metadataHash: string;\n readonly partCount: number;\n readonly plaintextByteLength: number;\n readonly plaintextSha256: string;\n readonly sha256: string;\n encryptPart(index: number): Promise<BlobBytes>;\n getPartByteLength(index: number): number;\n}\n\nexport interface DocumentManifestIdentity {\n documentId: string;\n manifestHash: string;\n organizationId: string;\n}\n\nexport interface BlobAttachmentMaterial {\n blobAccessManifestHash: string;\n contentKeyBundle: BlobContentKeyBundleRequest;\n encrypted: BlobEncryptionPlan;\n manifestIdentity: DocumentManifestIdentity;\n targetHash: string;\n targets: BlobContentKeyTarget[];\n writerProjection: DocumentWriterProjectionResponse;\n}\n\n/**\n * Progress for an in-flight multipart blob upload.\n */\nexport interface MultipartUploadProgress {\n readonly bytesTotal: number;\n readonly bytesUploaded: number;\n readonly partsCompleted: number;\n readonly partsTotal: number;\n}\n\nexport type MultipartUploadProgressListener = (\n progress: MultipartUploadProgress,\n) => void;\n\n/**\n * Fires once a multipart stage has been opened (or resumed), with its id and\n * plaintext chunk size. Callers persist both so a later attempt can reproduce\n * the same encrypted parts and resume instead of orphaning the partial upload.\n */\nexport type MultipartStageResolvedListener = (input: {\n readonly partSize: number;\n readonly stageId: string;\n}) => void | Promise<void>;\n\n/** One upload; the service supplies the API, executor, and secret key. */\nexport interface UploadDocumentAttachmentRequest {\n author: DocumentCreateAuthor;\n blobId?: string | undefined;\n bindingId?: string | undefined;\n bytes: BlobByteSourceInput;\n contentKey?: Uint8Array | undefined;\n contentKeyEpoch?: number | undefined;\n documentId: string;\n /**\n * The document's deferred first update for the bind to commit after its\n * binding. A bind refused with it is sent once more without it, and the\n * caller's queued row then syncs on its own.\n */\n documentSync?: DocumentSyncRequest | undefined;\n eventId?: string | undefined;\n expectedBindingId: string | null;\n isRemoteSyncBlocked?: ((organizationId: string) => boolean) | undefined;\n // A persisted nonce seed. The plaintext digest derives the envelope IV from\n // it, then each chunk derives a unique IV. Same-source retries reproduce the\n // encrypted parts; changed bytes cannot reuse their AES-GCM nonces.\n nonceSeed?: Uint8Array | undefined;\n multipart?: MultipartBlobUploadOptions | undefined;\n onMultipartProgress?: MultipartUploadProgressListener | undefined;\n onStageResolved?: MultipartStageResolvedListener | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n signedAt?: string | undefined;\n slotId: string;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n writerProjection?: DocumentWriterProjectionResponse | undefined;\n}\n\nexport interface MultipartBlobUploadOptions {\n /** Exactly 5 MiB per plaintext encryption chunk; transport parts include envelope overhead. */\n readonly partSize: number;\n // The id of a previously opened stage to resume. When set, the upload refetches\n // that stage and skips parts the server already has instead of opening a new\n // one; if the stage is gone (expired), it falls back to a fresh stage.\n readonly resumeStageId?: string | undefined;\n readonly uploadConcurrency?: number | undefined;\n}\n\nexport interface UploadDocumentAttachmentResult {\n blobId: string;\n bindingId: string;\n request: BlobAttachmentBindRequest;\n response: BlobAttachmentBindResponse;\n sha256: string;\n byteLength: number;\n writeHeader: WriteHeader;\n writeHeaderHash: string;\n writerProjection: DocumentWriterProjectionResponse;\n}\n\n/** One detach; the service supplies the API and executor. */\nexport interface DetachDocumentAttachmentRequest {\n author: DocumentCreateAuthor;\n bindingId: string;\n blobId: string;\n documentId: string;\n eventId?: string | undefined;\n isRemoteSyncBlocked?: ((organizationId: string) => boolean) | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n signedAt?: string | undefined;\n slotId: string;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n writerProjection?: DocumentWriterProjectionResponse | undefined;\n}\n\nexport interface DetachDocumentAttachmentResult {\n request: BlobAttachmentDetachRequest;\n response: BlobAttachmentDetachResponse;\n writerProjection: DocumentWriterProjectionResponse;\n}\n\nexport interface DecryptDocumentAttachmentBlobInput {\n binding: BlobAttachmentSummary;\n encryptedBytes: BlobBytes;\n expectedDocumentId: string;\n expectedSlotId: string;\n execSql: ExecSql;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n targetSecretKey: Uint8Array;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n writerProjection: DocumentWriterProjectionResponse;\n}\n\n/** One decrypt; the service supplies the executor and its secret key. */\nexport type DecryptDocumentAttachmentBlobRequest = Omit<\n DecryptDocumentAttachmentBlobInput,\n \"execSql\" | \"targetSecretKey\"\n>;\n"]}
package/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export { type ApiRequestCounts, type ApiRequestEndpointCounts, ApiRequestMetrics, type ApiRequestMetricsSnapshot, } from "./internal/api-client/index.js";
2
2
  export type { AbandonOrganizationPolicyMutationInput, AddOrganizationGroupUserInput, BlobInfo, BlobInfoAttachmentKind, BlobInfoDocumentReference, BlobInfoInput, BlobInfoList, BlobInfoSort, BlobInfoSortDirection, BlobInfoSortKey, BrowserLocalKeyringOptions, ContainerContents, ContainerContentsContextValue, ContainerContentsStore, ContainerContentsStoreOptions, ContainerDocumentLinkInput, ContainerDocumentLinks, ContainerDocumentObjectSyncState, ContainerDocumentObjectSyncStatus, ContainerDocumentQueries, ContainerDocumentSidebarRow, ContainerInfo, ContainerInfoInput, ContainerItemRow, ContainerItemSort, ContainerItemSortDirection, ContainerItemSortKey, ContainerNode, ContainerShareAccessLevel, CreateOrganizationOptions, DatabaseListener, DatabaseOptions, DatabaseSnapshot, DatabaseStatus, DeviceFirst, DeviceFirstContainerContents, DiscardUnreadableOrganizationPolicyMutationInput, DocumentAttachmentStatus, DocumentAttachmentUpload, DocumentAttributionRangesInput, DocumentAttributionRangesPage, DocumentContextValue, DocumentHistory, DocumentHistoryChange, DocumentHistoryRowChange, DocumentHistoryStop, DocumentHistoryTextChange, DocumentHistoryVersion, DocumentHistoryVersionEntry, DocumentHistoryView, DocumentInfo, DocumentInfoInput, DocumentList, DocumentSort, DocumentSortDirection, DocumentSortKey, DocumentStore, DocumentSubscriptionOptions, Documents, DocumentsRuntime, DocumentsWorkflowRuntimeInput, DomainScope, FileSaver, Identity, IdentityGenerationResult, IdentityKeyPackage, IdentityListener, IdentityOptions, IdentitySnapshot, IndexedDbLocalKeyringManifestStoreOptions, IndexedDbWrappingKeyKeystoreOptions, LinkDocumentToContainerInput, ListDocumentsInput, LocalKeyPurpose, LocalKeyring, LocalKeyringManifest, LocalKeyringManifestFormat, LocalKeyringManifestStorage, LocalKeyringManifestStore, LocalKeyringOptions, LocalKeyringPinCode, LocalKeyringScope, LocalKeyringSession, LocalOrganizationSummary, LocalProjectionReconciledDelta, LocalProjectionSnapshot, LocalProjectionView, LocalSecretContext, LocalStorageLocalKeyringManifestStoreOptions, Logger, MergeDocumentSummary, MoveDocumentToContainerInput, NetworkListener, NetworkMode, NetworkStatusSource, NormalizedLocalKeyringScope, OpenContainerDocumentInput, OpenDocumentInput, OpenDocumentOptions, OrganizationBilling, OrganizationBillingHistory, OrganizationBillingHistoryEntry, OrganizationBillingManagementUrl, OrganizationBillingView, OrganizationContainerGrant, OrganizationContainerGrants, OrganizationDataUsage, OrganizationDeviceDataUsage, OrganizationDeviceDocumentUsageCategoryBreakdown, OrganizationDirectory, OrganizationDirectoryAndGroups, OrganizationDirectoryUser, OrganizationGrantRef, OrganizationGroupContainer, OrganizationGroupContainers, OrganizationGroupDetails, OrganizationGroupMember, OrganizationGroupMembers, OrganizationGroupMutationReceipt, OrganizationGroupMutationResult, OrganizationGroupPolicyHistory, OrganizationGroupSummary, OrganizationLeaveRequestResult, OrganizationMembership, OrganizationMemberships, OrganizationPolicyGrantChange, OrganizationPolicyGroupChange,
3
3
  /** Verified organization display page with an optional older-page cursor. */
4
- OrganizationPolicyHistory, OrganizationPolicyHistoryEntry, OrganizationProfile, OrganizationSyncPauseResult, Organizations, OrganizationUserDetail, PendingWriteQueueItem, PendingWriteQueueItemStatus, PendingWriteQueueObjectKind, PendingWriteQueueOperation, PendingWriteQueueOperationKind, PendingWriteQueueOperationStatus, PersistedDocumentListener, PinCodeBrowserLocalKeyringOptions, PinCodeWrappingKeyKeystoreOptions, PurgeDocumentInput, PurgeDocumentResult, ReconciliationService, RemoveOrganizationGroupUserInput, ResolvedUserIdentity, SaveFileRequest, SecurityIncident, SecurityIncidentListener, SecurityIncidentObjectKind, SecurityIncidents, SeededDocumentInput, Session, SessionContext, SessionCreateOrganizationResult, SessionListener, SessionRecoverOrganizationResult, SessionRegistrationRefusal, SessionRegistrationResult, SessionSnapshot, SetActiveDocumentContainerInput, SetLinkedContainerIdsForDocument, UnlinkDocumentFromContainerInput, UnwrapLocalSecretInput, UserIdentities, UserSession, WrapLocalSecretInput, WrappedLocalSecretEnvelope, WrappedLocalSecretFormat, WrappingKeyHandle, WrappingKeyKeystore, WrappingKeyMaterialStorage, } from "./client/index.js";
4
+ OrganizationPolicyHistory, OrganizationPolicyHistoryEntry, OrganizationProfile, OrganizationSyncPauseResult, Organizations, OrganizationUserDetail, PendingWriteQueueItem, PendingWriteQueueItemStatus, PendingWriteQueueObjectKind, PendingWriteQueueOperation, PendingWriteQueueOperationKind, PendingWriteQueueOperationStatus, PersistedDocumentListener, PinCodeBrowserLocalKeyringOptions, PinCodeWrappingKeyKeystoreOptions, PurgeDocumentInput, PurgeDocumentResult, ReconciliationService, RemoveOrganizationGroupUserInput, ResolvedUserIdentity, RetryDocumentDownloadInput, SaveFileRequest, SecurityIncident, SecurityIncidentListener, SecurityIncidentObjectKind, SecurityIncidents, SeededDocumentInput, Session, SessionContext, SessionCreateOrganizationResult, SessionListener, SessionRecoverOrganizationResult, SessionRegistrationRefusal, SessionRegistrationResult, SessionSnapshot, SetActiveDocumentContainerInput, SetLinkedContainerIdsForDocument, UnlinkDocumentFromContainerInput, UnwrapLocalSecretInput, UserIdentities, UserSession, WrapLocalSecretInput, WrappedLocalSecretEnvelope, WrappedLocalSecretFormat, WrappingKeyHandle, WrappingKeyKeystore, WrappingKeyMaterialStorage, } from "./client/index.js";
5
5
  export { type BlobStoreFactory, Blobs, createBrowserLocalKeyring, createBrowserLocalKeyringManifestStore, createBrowserNetworkStatusSource, createContainerContentsStoreWorkflowRuntime, createContainerContentsWorkflowRuntime, createContainerDocumentObjectSyncState, createDocumentsWorkflowRuntime, createDomainScope, createIndexedDbLocalKeyringManifestStore, createIndexedDbWrappingKeyKeystore, createLocalKeyring, createLocalStorageLocalKeyringManifestStore, createMemoryLocalKeyringManifestStore, createMemoryWrappingKeyKeystore, createPinCodeBrowserLocalKeyring, createPinCodeWrappingKeyKeystore, createRevenueCatPurchases, createUnavailableDirectCheckout, createUnavailablePurchases, createWebViewLocalKeyring, Database, DEFAULT_DOCUMENT_ID, type DirectCheckoutAppearance, type DirectCheckoutCapability, type DirectCheckoutConfirmation, type DirectCheckoutSession, DirectCheckoutUnavailableError, decodeLocalKeyringSqliteKey, Events, type EventsListener, type EventsSnapshot, encodeLocalKeyringSqliteKey, enqueueReconciliationForEvents, IDENTITY_KEY_PACKAGE_FORMAT, isPinCodeWrappedLocalSecretEnvelope, LOCAL_KEYRING_MANIFEST_FORMAT, localKeyringScopeKey, Network, normalizeLocalKeyringScope, type PrincipalHistoryKeyProvider, type PrincipalHistoryKeyScope, PurchaseAbortedError, PurchaseAlreadyOwnedError, PurchaseCancelledError, PurchaseIdentityPendingError, PurchaseProviderStalledError, type PurchasesCapability, PurchasesUnavailableError, PurgedOrganizationRecoveryBillingRequiredError, parseLocalKeyringManifest, type RevenueCatBackend, type RevenueCatCustomerInfo, type RevenueCatPackage, type RevenueCatPurchasesConfig, SyncBillingGate, type SyncBillingGateListener, type SyncPurchaseResult, type SyncSubscriptionOption, serializeLocalKeyringManifest, UnverifiedUserIdentityError, WRAPPED_LOCAL_SECRET_FORMAT, } from "./client/index.js";
6
6
  export type { DiscoveredDocumentInput, DocumentAttachment, DocumentClientProjectionDefinition, DocumentClientProjectionDeleteInput, DocumentClientProjectionSaveInput, DocumentFieldValidationIssue, DocumentProjection, DocumentProjectorDefinition, DocumentProjectorInput, DocumentProjectorRegistry, DocumentProjectorRegistryInput, DocumentRestoreContent, DocumentRow, DocumentRowSummary, DocumentSummary, EnvFileVariable, StoredDocumentKind, StoredDocumentState, StructuredDocumentMap, StructuredDocumentShape, StructuredDocumentText, ValidatedDocumentFields, } from "./data/documents/index.js";
7
7
  export { addDocumentAttachments, createDocumentProjectorRegistry, createDocumentSignerDeviceId, DEFAULT_DOCUMENT_ACCESS_EPOCH, DEFAULT_DOCUMENT_KIND, defaultDocumentProjectorRegistry, deriveStoredDocumentTitle, ENV_FILE_DOCUMENT_KIND, ENV_FILE_NAME_FIELD, ENV_FILE_VARIABLE_KEY_FIELD, ENV_FILE_VARIABLE_NAME_PATTERN, ENV_FILE_VARIABLE_VALUE_FIELD, ensureDocumentAttachmentStructure, getDocumentAttachments, getDocumentClientProjectionTables, getStoredDocumentTypeLabel, getUntitledDocumentTitle, initializeStoredDocumentKind, isValidEnvFileVariableName, parseEnvFileText, projectStoredDocumentState, readStoredDocumentState, readStringDocumentField, resolveOpIdAttribution, sameDocumentAttachments, summarizeDocumentContributors, writerByPeerId, writeStoredDocumentFields, } from "./data/documents/index.js";
package/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,iEAAiE;AACjE,yEAAyE;AACzE,gEAAgE;AAChE,OAAO,EAGL,iBAAiB,GAElB,MAAM,uBAAuB,CAAC;AAkL/B,OAAO,EAEL,KAAK,EACL,yBAAyB,EACzB,sCAAsC,EACtC,gCAAgC,EAChC,2CAA2C,EAC3C,sCAAsC,EAC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CAAC;AAe1B,OAAO,EACL,oBAAoB,EACpB,gCAAgC,EAChC,gCAAgC,EAChC,mCAAmC,EACnC,yBAAyB,EACzB,gCAAgC,EAChC,oCAAoC,GACrC,MAAM,kBAAkB,CAAC","sourcesContent":["// SDK: full-bundle identity trust and bounded Members admission.\n// Exact-head authority; canonical writer domains; restart-safe journals.\n// No pin promotion or legacy adapters. See workflows/README.md.\nexport {\n type ApiRequestCounts,\n type ApiRequestEndpointCounts,\n ApiRequestMetrics,\n type ApiRequestMetricsSnapshot,\n} from \"@tearleads/api-client\";\nexport type {\n AbandonOrganizationPolicyMutationInput,\n AddOrganizationGroupUserInput,\n BlobInfo,\n BlobInfoAttachmentKind,\n BlobInfoDocumentReference,\n BlobInfoInput,\n BlobInfoList,\n BlobInfoSort,\n BlobInfoSortDirection,\n BlobInfoSortKey,\n BrowserLocalKeyringOptions,\n ContainerContents,\n ContainerContentsContextValue,\n ContainerContentsStore,\n ContainerContentsStoreOptions,\n ContainerDocumentLinkInput,\n ContainerDocumentLinks,\n ContainerDocumentObjectSyncState,\n ContainerDocumentObjectSyncStatus,\n ContainerDocumentQueries,\n ContainerDocumentSidebarRow,\n ContainerInfo,\n ContainerInfoInput,\n ContainerItemRow,\n ContainerItemSort,\n ContainerItemSortDirection,\n ContainerItemSortKey,\n ContainerNode,\n ContainerShareAccessLevel,\n CreateOrganizationOptions,\n DatabaseListener,\n DatabaseOptions,\n DatabaseSnapshot,\n DatabaseStatus,\n DeviceFirst,\n DeviceFirstContainerContents,\n DiscardUnreadableOrganizationPolicyMutationInput,\n DocumentAttachmentStatus,\n DocumentAttachmentUpload,\n DocumentAttributionRangesInput,\n DocumentAttributionRangesPage,\n DocumentContextValue,\n DocumentHistory,\n DocumentHistoryChange,\n DocumentHistoryRowChange,\n DocumentHistoryStop,\n DocumentHistoryTextChange,\n DocumentHistoryVersion,\n DocumentHistoryVersionEntry,\n DocumentHistoryView,\n DocumentInfo,\n DocumentInfoInput,\n DocumentList,\n DocumentSort,\n DocumentSortDirection,\n DocumentSortKey,\n DocumentStore,\n DocumentSubscriptionOptions,\n Documents,\n DocumentsRuntime,\n DocumentsWorkflowRuntimeInput,\n DomainScope,\n FileSaver,\n Identity,\n IdentityGenerationResult,\n IdentityKeyPackage,\n IdentityListener,\n IdentityOptions,\n IdentitySnapshot,\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 OrganizationDeviceDataUsage,\n OrganizationDeviceDocumentUsageCategoryBreakdown,\n OrganizationDirectory,\n OrganizationDirectoryAndGroups,\n OrganizationDirectoryUser,\n OrganizationGrantRef,\n OrganizationGroupContainer,\n OrganizationGroupContainers,\n OrganizationGroupDetails,\n OrganizationGroupMember,\n OrganizationGroupMembers,\n OrganizationGroupMutationReceipt,\n OrganizationGroupMutationResult,\n OrganizationGroupPolicyHistory,\n OrganizationGroupSummary,\n OrganizationLeaveRequestResult,\n OrganizationMembership,\n OrganizationMemberships,\n OrganizationPolicyGrantChange,\n OrganizationPolicyGroupChange,\n /** Verified organization display page with an optional older-page cursor. */\n OrganizationPolicyHistory,\n OrganizationPolicyHistoryEntry,\n OrganizationProfile,\n OrganizationSyncPauseResult,\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 SeededDocumentInput,\n Session,\n SessionContext,\n SessionCreateOrganizationResult,\n SessionListener,\n SessionRecoverOrganizationResult,\n SessionRegistrationRefusal,\n SessionRegistrationResult,\n SessionSnapshot,\n SetActiveDocumentContainerInput,\n SetLinkedContainerIdsForDocument,\n UnlinkDocumentFromContainerInput,\n UnwrapLocalSecretInput,\n UserIdentities,\n UserSession,\n WrapLocalSecretInput,\n WrappedLocalSecretEnvelope,\n WrappedLocalSecretFormat,\n WrappingKeyHandle,\n WrappingKeyKeystore,\n WrappingKeyMaterialStorage,\n} from \"./client\";\nexport {\n type BlobStoreFactory,\n Blobs,\n createBrowserLocalKeyring,\n createBrowserLocalKeyringManifestStore,\n createBrowserNetworkStatusSource,\n createContainerContentsStoreWorkflowRuntime,\n createContainerContentsWorkflowRuntime,\n createContainerDocumentObjectSyncState,\n createDocumentsWorkflowRuntime,\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 UnverifiedUserIdentityError,\n WRAPPED_LOCAL_SECRET_FORMAT,\n} from \"./client\";\nexport type {\n DiscoveredDocumentInput,\n DocumentAttachment,\n DocumentClientProjectionDefinition,\n DocumentClientProjectionDeleteInput,\n DocumentClientProjectionSaveInput,\n DocumentFieldValidationIssue,\n DocumentProjection,\n DocumentProjectorDefinition,\n DocumentProjectorInput,\n DocumentProjectorRegistry,\n DocumentProjectorRegistryInput,\n DocumentRestoreContent,\n DocumentRow,\n DocumentRowSummary,\n DocumentSummary,\n EnvFileVariable,\n StoredDocumentKind,\n StoredDocumentState,\n StructuredDocumentMap,\n StructuredDocumentShape,\n StructuredDocumentText,\n ValidatedDocumentFields,\n} from \"./data/documents\";\nexport {\n addDocumentAttachments,\n createDocumentProjectorRegistry,\n createDocumentSignerDeviceId,\n DEFAULT_DOCUMENT_ACCESS_EPOCH,\n DEFAULT_DOCUMENT_KIND,\n defaultDocumentProjectorRegistry,\n deriveStoredDocumentTitle,\n ENV_FILE_DOCUMENT_KIND,\n ENV_FILE_NAME_FIELD,\n ENV_FILE_VARIABLE_KEY_FIELD,\n ENV_FILE_VARIABLE_NAME_PATTERN,\n ENV_FILE_VARIABLE_VALUE_FIELD,\n ensureDocumentAttachmentStructure,\n getDocumentAttachments,\n getDocumentClientProjectionTables,\n getStoredDocumentTypeLabel,\n getUntitledDocumentTitle,\n initializeStoredDocumentKind,\n isValidEnvFileVariableName,\n parseEnvFileText,\n projectStoredDocumentState,\n readStoredDocumentState,\n readStringDocumentField,\n resolveOpIdAttribution,\n sameDocumentAttachments,\n summarizeDocumentContributors,\n writerByPeerId,\n writeStoredDocumentFields,\n} from \"./data/documents\";\nexport type {\n ContainerContentsSnapshot,\n ContainerContentsStoreRuntime,\n ContainerContentsStoreState,\n ContainerContentsStoreSyncAgent,\n ContainerContentsStoreSyncState,\n ContainerState,\n PurgeMoveSettlement,\n PurgeOptions,\n PurgeProgress,\n} from \"./stores/container-contents\";\nexport {\n createContainerContentsStore,\n createContainerContentsStoreState,\n createContainerContentsStoreSyncAgent,\n getOrCreateContainerContentsStore,\n isSystemContainerNode,\n requestContainerContentsDocumentPriming,\n subscribeToContainerContentsStore,\n updateContainerContentsSnapshot,\n updateContainerContentsStoreRuntime,\n} from \"./stores/container-contents\";\nexport type {\n DocumentMutationGuard,\n DocumentMutationOptions,\n DocumentSnapshot,\n DocumentStoreFacade,\n DocumentStoreOpenOptions,\n DocumentStoreRelinkInput,\n DocumentStructuredFieldPatch,\n} from \"./stores/documents\";\nexport {\n createDocumentStore,\n discardRegisteredDocumentLocalState,\n getOrCreateDocumentStore,\n hasPendingLocalDocumentWrites,\n openDocumentStore,\n requestDomainDocumentSync,\n subscribeToPersistedDocuments,\n} from \"./stores/documents\";\nexport { Tearleads } from \"./Tearleads\";\nexport type {\n TearleadsDatabaseOptions,\n TearleadsOptions,\n} from \"./TearleadsOptions\";\nexport type {\n BlobAttachmentCollaborators,\n BlobAttachmentServiceApi,\n BlobByteSource,\n BlobByteSourceInput,\n BlobBytes,\n BlobStore,\n DecryptDocumentAttachmentBlobRequest,\n DetachDocumentAttachmentRequest,\n DetachDocumentAttachmentResult,\n EncryptedBlobStoreCipher,\n EncryptedBlobStoreKey,\n EncryptedBlobStoreOptions,\n HydrateDocumentAttachmentBlobsRequest,\n HydratedDocumentAttachmentBlob,\n UploadDocumentAttachmentRequest,\n UploadDocumentAttachmentResult,\n WrapEncryptedBlobStoreOptions,\n} from \"./workflows/blobs\";\nexport {\n BlobAttachmentService,\n blobByteSourceInputLength,\n createBlobByteSource,\n createBlobStore,\n createEncryptedBlobStore,\n createLazyEncryptedBlobStore,\n createMemoryBlobStore,\n purgeOpfsBlobStore,\n readBlobByteSource,\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 ContainerSyncWatermarkRepository,\n createContainerContentsDocumentsRuntime,\n createContainerContentsProjectionUserKeyResolver,\n createContainerContentsSyncLane,\n createContainerParentSyncLane,\n createDocumentHeadLinkSetLoader,\n createInitializedContainerMetadataDocument,\n DocumentContainerProjectionRepository,\n defaultContainerContentsPersistence,\n deriveContainerSystemSlot,\n listBlobInfo,\n loadContainerInfo,\n loadDocumentAttributionRanges,\n loadDocumentInfo,\n syncedContainerDocumentObjectSyncState,\n} from \"./workflows/container-contents\";\nexport type {\n AggregatedContainerKekLog,\n ContainerMutationAuthor,\n ContainerMutationCollaborators,\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 ContainerMutationService,\n ContainerPathTooDeepError,\n classifyContainerWriteRefusal,\n containerWriterProjectionFromRekeyPlan,\n fetchContainerKekLog,\n HistoricalWrapUnavailableError,\n type HistoricalWrapUnavailableReason,\n isProjectionVerificationCancelledError,\n rebuildKeyringEntriesFromLog,\n recoverKeyringEntryFromWraps,\n rootContainerWriterProjectionFromCreatePlan,\n} from \"./workflows/containers\";\nexport type {\n CreateRemoteDocumentRequest,\n CreateRemoteDocumentResult,\n DocumentBirthResult,\n DocumentRecord,\n DocumentSyncContainerRekeyBuilder,\n DocumentSyncPullContinuation,\n DocumentSyncUpdateIsolationError,\n DocumentsPersistence,\n DocumentsWorkflowRuntime,\n IncomingDocumentSyncUpdateValidator,\n LocalAttachmentRecord,\n PendingAttachmentRecord,\n PendingUpdateInsert,\n PendingUpdateRecord,\n QueuedPendingUpdateRecord,\n RemoteDocumentServiceApi,\n SyncRemoteDocumentRequest,\n SyncRemoteDocumentResult,\n} from \"./workflows/documents\";\nexport {\n buildMaterializedDocumentCreatePlan,\n createDocumentProjectionUserKeyResolver,\n DOCUMENT_SYNC_TRACE_FRAGMENT,\n DOCUMENT_SYNC_TRACE_PATTERN,\n DOCUMENTS_APP_KIND,\n DocumentRawHistoryUnavailableError,\n defaultDocumentsPersistence,\n deletePersistedDocument,\n deriveStableDocumentId,\n isDatabaseUnavailableError,\n isDocumentSyncUpdateIsolationError,\n isEmptyDocumentHistoryChange,\n persistedDocumentCreateStateFromResponse,\n RemoteDocumentService,\n readPullContinuation,\n resolveDocumentCreateAuthor,\n unwrapContainerKekPath,\n unwrapDocumentContentKeyTarget,\n validateDocumentSyncUpdateImports,\n} from \"./workflows/documents\";\n// Nominal identity constructors are available only through the testing subpath\n// for low-level runtime tests.\nexport type {\n AcknowledgedPrincipalCurrentInput,\n AcknowledgedPrincipalCurrentRetirement,\n AuthoredPrincipalMutation,\n OrganizationDocumentUsageCategory,\n OrganizationGroupPolicyHistoryEntry,\n OrganizationNativePurchaseEligibility,\n OrganizationPrincipalMemberChange,\n OrganizationPrincipalMemberChangeType,\n OrganizationPrincipalPolicyHistory,\n OrganizationPrincipalPolicyHistoryEntry,\n PrincipalMutationJournalContext,\n PrincipalMutationJournalScope,\n PrincipalMutationResponse,\n ReconcileOrganizationDataUsageInput,\n} from \"./workflows/organizations\";\nexport {\n abandonJournaledPrincipalMutation,\n addOrganizationGroupUser,\n buildInitialGroupPolicyRequest,\n buildInitialMemberGroupPolicyRequest,\n buildOrganizationGroupPolicyHistory,\n buildOrganizationProfileDocumentPatch,\n buildRosterProfileDocumentPatch,\n checkNativePurchaseEligibility,\n createInitializedRosterProfileDocument,\n createOrganizationGroup,\n DEFAULT_PERSONAL_ORGANIZATION_PROFILE_NAME,\n deriveOrganizationMetadataContainerSystemSlot,\n deriveOrganizationRosterProfileContainerSystemSlot,\n discardUnreadableJournaledPrincipalMutation,\n GroupMembershipNameMismatchError,\n GroupShareNameMismatchError,\n getOrganizationProfileDocumentLocalId,\n getRosterProfileDocumentLocalId,\n loadLocalOrganizationDataUsage,\n loadLocalOrganizationDirectoryAndGroups,\n loadOrganizationBilling,\n loadOrganizationBillingHistory,\n loadOrganizationBillingManagementUrl,\n ORGANIZATION_DOCUMENT_USAGE_CATEGORIES,\n ORGANIZATION_METADATA_CONTAINER_NAME,\n ORGANIZATION_PROFILE_DOCUMENT_KIND,\n ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n PendingPrincipalMutationError,\n PrincipalMutationOutcomeUnknownError,\n ROSTER_PROFILE_DOCUMENT_KIND,\n readJournaledPrincipalMutation,\n readOrganizationProfileName,\n reconcileOrganizationDataUsage,\n reconcileOrganizationDirectoryAndGroups,\n recoverJournaledPrincipalMutation,\n removeOrganizationGroupUser,\n resolveOrganizationBillingView,\n retainAcknowledgedPrincipalCurrents,\n revokeOrganizationContainerGrant,\n shareRemoteContainerWithGroup,\n startOrganizationTrial,\n submitJournaledPrincipalMutation,\n subscribeOrganizationReadModelInvalidation,\n UnreadablePrincipalMutationError,\n updateOrganizationProfile,\n updateOrganizationRosterEntry,\n} from \"./workflows/organizations\";\nexport type {\n AcknowledgedPrincipalPredecessor,\n CacheReferencedPrincipalPoliciesOptions,\n PrincipalHistoryProtectionLease,\n PrincipalPolicyService,\n ProjectionPolicyHistoryRecoveryOptions,\n RecoveredPrincipalPolicyHistory,\n RecoveredScopedPrincipalPolicyHistory,\n RecoverPrincipalPolicyHistoryOptions,\n RecoverScopedPrincipalPolicyHistoryOptions,\n} from \"./workflows/principals\";\nexport {\n cacheReferencedPrincipalPolicies,\n captureAcknowledgedPrincipalPredecessor,\n PrincipalPolicyHistoryReadError,\n recoverPrincipalPolicyHistory,\n recoverProjectionPolicyHistory,\n recoverScopedPrincipalPolicyHistory,\n} from \"./workflows/principals\";\nexport type {\n InitialRootMetadataBootstrap,\n ProvisionedSystemContainerSpec,\n RegisterIdentityInput,\n RegistrationApi,\n} from \"./workflows/registration\";\nexport {\n bootstrapRootContainer,\n buildInitialOrganizationPolicyRequest,\n createInitialRootMetadataBootstrap,\n deriveRegistrationOrganizationId,\n persistRegistrationBootstrap,\n registerIdentity,\n} from \"./workflows/registration\";\nexport type {\n PendingBlobDeletion,\n PendingBlobDeletionsPage,\n PendingBlobDeletionsQueryInput,\n RootIdentitiesApi,\n RootIdentitiesPage,\n RootIdentitiesQueryInput,\n RootIdentity,\n RootIdentityDetail,\n RootIdentityOrganization,\n RootIdentitySession,\n RootPendingBlobDeletionsQueryInput,\n RootRequestOutcome,\n} from \"./workflows/root\";\nexport {\n liftRootIdentitySuspension,\n listRootAuditEvents,\n listRootDataUsageReport,\n listRootIdentities,\n listRootIdentityOrganizations,\n listRootOrganizationIdentities,\n listRootOrganizationRevenuecatEvents,\n listRootOrganizations,\n listRootRevenuecatEventsReport,\n loadRootIdentity,\n loadRootOpsHealthReport,\n loadRootOrganization,\n loadRootOrganizationDataUsage,\n type RootAuditApi,\n type RootAuditEvent,\n type RootAuditEventsPage,\n type RootAuditEventsQueryInput,\n type RootDataUsageApi,\n type RootDataUsageReportPage,\n type RootOpsHealthApi,\n type RootOpsHealthReport,\n type RootOrganization,\n type RootOrganizationDetail,\n type RootOrganizationIdentitiesPage,\n type RootOrganizationIdentity,\n type RootOrganizationPageQueryInput,\n type RootOrganizationRevenuecatEvent,\n type RootOrganizationRevenuecatEventsPage,\n type RootOrganizationsApi,\n type RootOrganizationsPage,\n type RootOrganizationsQueryInput,\n type RootRevenuecatApi,\n type RootRevenuecatEvent,\n type RootRevenuecatEventsQueryInput,\n type RootRevenuecatEventsReportPage,\n type RootRevenuecatEventsReportQueryInput,\n type RootSuspensionApi,\n suspendRootIdentity,\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,iEAAiE;AACjE,yEAAyE;AACzE,gEAAgE;AAChE,OAAO,EAGL,iB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oCAAoC,EACpC,qBAAqB,EACrB,8BAA8B,EAC9B,gBAAgB,EAChB,uBAAuB,EACvB,oBAAoB,EACpB,6BAA6B,EAyB7B,mBAAmB,GACpB,MAAM,kBAAkB,CAAC;AAe1B,OAAO,EACL,oBAAoB,EACpB,gCAAgC,EAChC,gCAAgC,EAChC,mCAAmC,EACnC,yBAAyB,EACzB,gCAAgC,EAChC,oCAAoC,GACrC,MAAM,kBAAkB,CAAC","sourcesContent":["// SDK: full-bundle identity trust and bounded Members admission.\n// Exact-head authority; canonical writer domains; restart-safe journals.\n// No pin promotion or legacy adapters. See workflows/README.md.\nexport {\n type ApiRequestCounts,\n type ApiRequestEndpointCounts,\n ApiRequestMetrics,\n type ApiRequestMetricsSnapshot,\n} from \"@tearleads/api-client\";\nexport type {\n AbandonOrganizationPolicyMutationInput,\n AddOrganizationGroupUserInput,\n BlobInfo,\n BlobInfoAttachmentKind,\n BlobInfoDocumentReference,\n BlobInfoInput,\n BlobInfoList,\n BlobInfoSort,\n BlobInfoSortDirection,\n BlobInfoSortKey,\n BrowserLocalKeyringOptions,\n ContainerContents,\n ContainerContentsContextValue,\n ContainerContentsStore,\n ContainerContentsStoreOptions,\n ContainerDocumentLinkInput,\n ContainerDocumentLinks,\n ContainerDocumentObjectSyncState,\n ContainerDocumentObjectSyncStatus,\n ContainerDocumentQueries,\n ContainerDocumentSidebarRow,\n ContainerInfo,\n ContainerInfoInput,\n ContainerItemRow,\n ContainerItemSort,\n ContainerItemSortDirection,\n ContainerItemSortKey,\n ContainerNode,\n ContainerShareAccessLevel,\n CreateOrganizationOptions,\n DatabaseListener,\n DatabaseOptions,\n DatabaseSnapshot,\n DatabaseStatus,\n DeviceFirst,\n DeviceFirstContainerContents,\n DiscardUnreadableOrganizationPolicyMutationInput,\n DocumentAttachmentStatus,\n DocumentAttachmentUpload,\n DocumentAttributionRangesInput,\n DocumentAttributionRangesPage,\n DocumentContextValue,\n DocumentHistory,\n DocumentHistoryChange,\n DocumentHistoryRowChange,\n DocumentHistoryStop,\n DocumentHistoryTextChange,\n DocumentHistoryVersion,\n DocumentHistoryVersionEntry,\n DocumentHistoryView,\n DocumentInfo,\n DocumentInfoInput,\n DocumentList,\n DocumentSort,\n DocumentSortDirection,\n DocumentSortKey,\n DocumentStore,\n DocumentSubscriptionOptions,\n Documents,\n DocumentsRuntime,\n DocumentsWorkflowRuntimeInput,\n DomainScope,\n FileSaver,\n Identity,\n IdentityGenerationResult,\n IdentityKeyPackage,\n IdentityListener,\n IdentityOptions,\n IdentitySnapshot,\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 OrganizationDeviceDataUsage,\n OrganizationDeviceDocumentUsageCategoryBreakdown,\n OrganizationDirectory,\n OrganizationDirectoryAndGroups,\n OrganizationDirectoryUser,\n OrganizationGrantRef,\n OrganizationGroupContainer,\n OrganizationGroupContainers,\n OrganizationGroupDetails,\n OrganizationGroupMember,\n OrganizationGroupMembers,\n OrganizationGroupMutationReceipt,\n OrganizationGroupMutationResult,\n OrganizationGroupPolicyHistory,\n OrganizationGroupSummary,\n OrganizationLeaveRequestResult,\n OrganizationMembership,\n OrganizationMemberships,\n OrganizationPolicyGrantChange,\n OrganizationPolicyGroupChange,\n /** Verified organization display page with an optional older-page cursor. */\n OrganizationPolicyHistory,\n OrganizationPolicyHistoryEntry,\n OrganizationProfile,\n OrganizationSyncPauseResult,\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 RetryDocumentDownloadInput,\n SaveFileRequest,\n SecurityIncident,\n SecurityIncidentListener,\n SecurityIncidentObjectKind,\n SecurityIncidents,\n SeededDocumentInput,\n Session,\n SessionContext,\n SessionCreateOrganizationResult,\n SessionListener,\n SessionRecoverOrganizationResult,\n SessionRegistrationRefusal,\n SessionRegistrationResult,\n SessionSnapshot,\n SetActiveDocumentContainerInput,\n SetLinkedContainerIdsForDocument,\n UnlinkDocumentFromContainerInput,\n UnwrapLocalSecretInput,\n UserIdentities,\n UserSession,\n WrapLocalSecretInput,\n WrappedLocalSecretEnvelope,\n WrappedLocalSecretFormat,\n WrappingKeyHandle,\n WrappingKeyKeystore,\n WrappingKeyMaterialStorage,\n} from \"./client\";\nexport {\n type BlobStoreFactory,\n Blobs,\n createBrowserLocalKeyring,\n createBrowserLocalKeyringManifestStore,\n createBrowserNetworkStatusSource,\n createContainerContentsStoreWorkflowRuntime,\n createContainerContentsWorkflowRuntime,\n createContainerDocumentObjectSyncState,\n createDocumentsWorkflowRuntime,\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 UnverifiedUserIdentityError,\n WRAPPED_LOCAL_SECRET_FORMAT,\n} from \"./client\";\nexport type {\n DiscoveredDocumentInput,\n DocumentAttachment,\n DocumentClientProjectionDefinition,\n DocumentClientProjectionDeleteInput,\n DocumentClientProjectionSaveInput,\n DocumentFieldValidationIssue,\n DocumentProjection,\n DocumentProjectorDefinition,\n DocumentProjectorInput,\n DocumentProjectorRegistry,\n DocumentProjectorRegistryInput,\n DocumentRestoreContent,\n DocumentRow,\n DocumentRowSummary,\n DocumentSummary,\n EnvFileVariable,\n StoredDocumentKind,\n StoredDocumentState,\n StructuredDocumentMap,\n StructuredDocumentShape,\n StructuredDocumentText,\n ValidatedDocumentFields,\n} from \"./data/documents\";\nexport {\n addDocumentAttachments,\n createDocumentProjectorRegistry,\n createDocumentSignerDeviceId,\n DEFAULT_DOCUMENT_ACCESS_EPOCH,\n DEFAULT_DOCUMENT_KIND,\n defaultDocumentProjectorRegistry,\n deriveStoredDocumentTitle,\n ENV_FILE_DOCUMENT_KIND,\n ENV_FILE_NAME_FIELD,\n ENV_FILE_VARIABLE_KEY_FIELD,\n ENV_FILE_VARIABLE_NAME_PATTERN,\n ENV_FILE_VARIABLE_VALUE_FIELD,\n ensureDocumentAttachmentStructure,\n getDocumentAttachments,\n getDocumentClientProjectionTables,\n getStoredDocumentTypeLabel,\n getUntitledDocumentTitle,\n initializeStoredDocumentKind,\n isValidEnvFileVariableName,\n parseEnvFileText,\n projectStoredDocumentState,\n readStoredDocumentState,\n readStringDocumentField,\n resolveOpIdAttribution,\n sameDocumentAttachments,\n summarizeDocumentContributors,\n writerByPeerId,\n writeStoredDocumentFields,\n} from \"./data/documents\";\nexport type {\n ContainerContentsSnapshot,\n ContainerContentsStoreRuntime,\n ContainerContentsStoreState,\n ContainerContentsStoreSyncAgent,\n ContainerContentsStoreSyncState,\n ContainerState,\n PurgeMoveSettlement,\n PurgeOptions,\n PurgeProgress,\n} from \"./stores/container-contents\";\nexport {\n createContainerContentsStore,\n createContainerContentsStoreState,\n createContainerContentsStoreSyncAgent,\n getOrCreateContainerContentsStore,\n isSystemContainerNode,\n requestContainerContentsDocumentPriming,\n subscribeToContainerContentsStore,\n updateContainerContentsSnapshot,\n updateContainerContentsStoreRuntime,\n} from \"./stores/container-contents\";\nexport type {\n DocumentMutationGuard,\n DocumentMutationOptions,\n DocumentSnapshot,\n DocumentStoreFacade,\n DocumentStoreOpenOptions,\n DocumentStoreRelinkInput,\n DocumentStructuredFieldPatch,\n} from \"./stores/documents\";\nexport {\n createDocumentStore,\n discardRegisteredDocumentLocalState,\n getOrCreateDocumentStore,\n hasPendingLocalDocumentWrites,\n openDocumentStore,\n requestDomainDocumentSync,\n subscribeToPersistedDocuments,\n} from \"./stores/documents\";\nexport { Tearleads } from \"./Tearleads\";\nexport type {\n TearleadsDatabaseOptions,\n TearleadsOptions,\n} from \"./TearleadsOptions\";\nexport type {\n BlobAttachmentCollaborators,\n BlobAttachmentServiceApi,\n BlobByteSource,\n BlobByteSourceInput,\n BlobBytes,\n BlobStore,\n DecryptDocumentAttachmentBlobRequest,\n DetachDocumentAttachmentRequest,\n DetachDocumentAttachmentResult,\n EncryptedBlobStoreCipher,\n EncryptedBlobStoreKey,\n EncryptedBlobStoreOptions,\n HydrateDocumentAttachmentBlobsRequest,\n HydratedDocumentAttachmentBlob,\n UploadDocumentAttachmentRequest,\n UploadDocumentAttachmentResult,\n WrapEncryptedBlobStoreOptions,\n} from \"./workflows/blobs\";\nexport {\n BlobAttachmentService,\n blobByteSourceInputLength,\n createBlobByteSource,\n createBlobStore,\n createEncryptedBlobStore,\n createLazyEncryptedBlobStore,\n createMemoryBlobStore,\n purgeOpfsBlobStore,\n readBlobByteSource,\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 ContainerSyncWatermarkRepository,\n createContainerContentsDocumentsRuntime,\n createContainerContentsProjectionUserKeyResolver,\n createContainerContentsSyncLane,\n createContainerParentSyncLane,\n createDocumentHeadLinkSetLoader,\n createInitializedContainerMetadataDocument,\n DocumentContainerProjectionRepository,\n defaultContainerContentsPersistence,\n deriveContainerSystemSlot,\n listBlobInfo,\n loadContainerInfo,\n loadDocumentAttributionRanges,\n loadDocumentInfo,\n syncedContainerDocumentObjectSyncState,\n} from \"./workflows/container-contents\";\nexport type {\n AggregatedContainerKekLog,\n ContainerMutationAuthor,\n ContainerMutationCollaborators,\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 ContainerMutationService,\n ContainerPathTooDeepError,\n classifyContainerWriteRefusal,\n containerWriterProjectionFromRekeyPlan,\n fetchContainerKekLog,\n HistoricalWrapUnavailableError,\n type HistoricalWrapUnavailableReason,\n isProjectionVerificationCancelledError,\n rebuildKeyringEntriesFromLog,\n recoverKeyringEntryFromWraps,\n rootContainerWriterProjectionFromCreatePlan,\n} from \"./workflows/containers\";\nexport type {\n CreateRemoteDocumentRequest,\n CreateRemoteDocumentResult,\n DocumentBirthResult,\n DocumentRecord,\n DocumentSyncContainerRekeyBuilder,\n DocumentSyncPullContinuation,\n DocumentSyncUpdateIsolationError,\n DocumentsPersistence,\n DocumentsWorkflowRuntime,\n IncomingDocumentSyncUpdateValidator,\n LocalAttachmentRecord,\n PendingAttachmentRecord,\n PendingUpdateInsert,\n PendingUpdateRecord,\n QueuedPendingUpdateRecord,\n RemoteDocumentServiceApi,\n SyncRemoteDocumentRequest,\n SyncRemoteDocumentResult,\n} from \"./workflows/documents\";\nexport {\n buildMaterializedDocumentCreatePlan,\n createDocumentProjectionUserKeyResolver,\n DOCUMENT_SYNC_TRACE_FRAGMENT,\n DOCUMENT_SYNC_TRACE_PATTERN,\n DOCUMENTS_APP_KIND,\n DocumentRawHistoryUnavailableError,\n defaultDocumentsPersistence,\n deletePersistedDocument,\n deriveStableDocumentId,\n isDatabaseUnavailableError,\n isDocumentSyncUpdateIsolationError,\n isEmptyDocumentHistoryChange,\n persistedDocumentCreateStateFromResponse,\n RemoteDocumentService,\n readPullContinuation,\n resolveDocumentCreateAuthor,\n unwrapContainerKekPath,\n unwrapDocumentContentKeyTarget,\n validateDocumentSyncUpdateImports,\n} from \"./workflows/documents\";\n// Nominal identity constructors are available only through the testing subpath\n// for low-level runtime tests.\nexport type {\n AcknowledgedPrincipalCurrentInput,\n AcknowledgedPrincipalCurrentRetirement,\n AuthoredPrincipalMutation,\n OrganizationDocumentUsageCategory,\n OrganizationGroupPolicyHistoryEntry,\n OrganizationNativePurchaseEligibility,\n OrganizationPrincipalMemberChange,\n OrganizationPrincipalMemberChangeType,\n OrganizationPrincipalPolicyHistory,\n OrganizationPrincipalPolicyHistoryEntry,\n PrincipalMutationJournalContext,\n PrincipalMutationJournalScope,\n PrincipalMutationResponse,\n ReconcileOrganizationDataUsageInput,\n} from \"./workflows/organizations\";\nexport {\n abandonJournaledPrincipalMutation,\n addOrganizationGroupUser,\n buildInitialGroupPolicyRequest,\n buildInitialMemberGroupPolicyRequest,\n buildOrganizationGroupPolicyHistory,\n buildOrganizationProfileDocumentPatch,\n buildRosterProfileDocumentPatch,\n checkNativePurchaseEligibility,\n createInitializedRosterProfileDocument,\n createOrganizationGroup,\n DEFAULT_PERSONAL_ORGANIZATION_PROFILE_NAME,\n deriveOrganizationMetadataContainerSystemSlot,\n deriveOrganizationRosterProfileContainerSystemSlot,\n discardUnreadableJournaledPrincipalMutation,\n GroupMembershipNameMismatchError,\n GroupShareNameMismatchError,\n getOrganizationProfileDocumentLocalId,\n getRosterProfileDocumentLocalId,\n loadLocalOrganizationDataUsage,\n loadLocalOrganizationDirectoryAndGroups,\n loadOrganizationBilling,\n loadOrganizationBillingHistory,\n loadOrganizationBillingManagementUrl,\n ORGANIZATION_DOCUMENT_USAGE_CATEGORIES,\n ORGANIZATION_METADATA_CONTAINER_NAME,\n ORGANIZATION_PROFILE_DOCUMENT_KIND,\n ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n PendingPrincipalMutationError,\n PrincipalMutationOutcomeUnknownError,\n ROSTER_PROFILE_DOCUMENT_KIND,\n readJournaledPrincipalMutation,\n readOrganizationProfileName,\n reconcileOrganizationDataUsage,\n reconcileOrganizationDirectoryAndGroups,\n recoverJournaledPrincipalMutation,\n removeOrganizationGroupUser,\n resolveOrganizationBillingView,\n retainAcknowledgedPrincipalCurrents,\n revokeOrganizationContainerGrant,\n shareRemoteContainerWithGroup,\n startOrganizationTrial,\n submitJournaledPrincipalMutation,\n subscribeOrganizationReadModelInvalidation,\n UnreadablePrincipalMutationError,\n updateOrganizationProfile,\n updateOrganizationRosterEntry,\n} from \"./workflows/organizations\";\nexport type {\n AcknowledgedPrincipalPredecessor,\n CacheReferencedPrincipalPoliciesOptions,\n PrincipalHistoryProtectionLease,\n PrincipalPolicyService,\n ProjectionPolicyHistoryRecoveryOptions,\n RecoveredPrincipalPolicyHistory,\n RecoveredScopedPrincipalPolicyHistory,\n RecoverPrincipalPolicyHistoryOptions,\n RecoverScopedPrincipalPolicyHistoryOptions,\n} from \"./workflows/principals\";\nexport {\n cacheReferencedPrincipalPolicies,\n captureAcknowledgedPrincipalPredecessor,\n PrincipalPolicyHistoryReadError,\n recoverPrincipalPolicyHistory,\n recoverProjectionPolicyHistory,\n recoverScopedPrincipalPolicyHistory,\n} from \"./workflows/principals\";\nexport type {\n InitialRootMetadataBootstrap,\n ProvisionedSystemContainerSpec,\n RegisterIdentityInput,\n RegistrationApi,\n} from \"./workflows/registration\";\nexport {\n bootstrapRootContainer,\n buildInitialOrganizationPolicyRequest,\n createInitialRootMetadataBootstrap,\n deriveRegistrationOrganizationId,\n persistRegistrationBootstrap,\n registerIdentity,\n} from \"./workflows/registration\";\nexport type {\n PendingBlobDeletion,\n PendingBlobDeletionsPage,\n PendingBlobDeletionsQueryInput,\n RootIdentitiesApi,\n RootIdentitiesPage,\n RootIdentitiesQueryInput,\n RootIdentity,\n RootIdentityDetail,\n RootIdentityOrganization,\n RootIdentitySession,\n RootPendingBlobDeletionsQueryInput,\n RootRequestOutcome,\n} from \"./workflows/root\";\nexport {\n liftRootIdentitySuspension,\n listRootAuditEvents,\n listRootDataUsageReport,\n listRootIdentities,\n listRootIdentityOrganizations,\n listRootOrganizationIdentities,\n listRootOrganizationRevenuecatEvents,\n listRootOrganizations,\n listRootRevenuecatEventsReport,\n loadRootIdentity,\n loadRootOpsHealthReport,\n loadRootOrganization,\n loadRootOrganizationDataUsage,\n type RootAuditApi,\n type RootAuditEvent,\n type RootAuditEventsPage,\n type RootAuditEventsQueryInput,\n type RootDataUsageApi,\n type RootDataUsageReportPage,\n type RootOpsHealthApi,\n type RootOpsHealthReport,\n type RootOrganization,\n type RootOrganizationDetail,\n type RootOrganizationIdentitiesPage,\n type RootOrganizationIdentity,\n type RootOrganizationPageQueryInput,\n type RootOrganizationRevenuecatEvent,\n type RootOrganizationRevenuecatEventsPage,\n type RootOrganizationsApi,\n type RootOrganizationsPage,\n type RootOrganizationsQueryInput,\n type RootRevenuecatApi,\n type RootRevenuecatEvent,\n type RootRevenuecatEventsQueryInput,\n type RootRevenuecatEventsReportPage,\n type RootRevenuecatEventsReportQueryInput,\n type RootSuspensionApi,\n suspendRootIdentity,\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.260",
3
+ "version": "0.1.262",
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,16 @@
1
+ import type { DocumentsRuntime } from "./types.js";
2
+ /**
3
+ * Ask one synced document to pull again and re-list its attachment bindings,
4
+ * e.g. for a pending first download in Explorer. The request names the
5
+ * document id it was read with: when the local record has since been relinked
6
+ * to another document, nothing runs and the caller re-reads its queue.
7
+ *
8
+ * The store is resolved by local id only, so an already-open store is reused
9
+ * as-is (its runtime, draft and identity untouched) and a retry never maps one
10
+ * local record onto another document's store.
11
+ */
12
+ export declare function retryDocumentDownload(input: {
13
+ documentId: string;
14
+ localId: string;
15
+ workflowRuntime: (containerId: string | null) => DocumentsRuntime;
16
+ }): Promise<boolean>;
@@ -0,0 +1,28 @@
1
+ import { defaultDocumentsPersistence } from "../../workflows/documents/index.js";
2
+ import { getOrCreateDocumentStore } from "./documentStore/index.js";
3
+ /**
4
+ * Ask one synced document to pull again and re-list its attachment bindings,
5
+ * e.g. for a pending first download in Explorer. The request names the
6
+ * document id it was read with: when the local record has since been relinked
7
+ * to another document, nothing runs and the caller re-reads its queue.
8
+ *
9
+ * The store is resolved by local id only, so an already-open store is reused
10
+ * as-is (its runtime, draft and identity untouched) and a retry never maps one
11
+ * local record onto another document's store.
12
+ */
13
+ export async function retryDocumentDownload(input) {
14
+ const { execSql, dbStatus } = input.workflowRuntime(null).infra;
15
+ if (dbStatus !== "ready")
16
+ return false;
17
+ const record = await defaultDocumentsPersistence.loadDocument(execSql, input.localId);
18
+ if (!record || record.documentId !== input.documentId)
19
+ return false;
20
+ const runtime = input.workflowRuntime(record.containerId);
21
+ const store = getOrCreateDocumentStore(runtime.state.domainScope, input.localId, runtime, null, "", record.documentKind);
22
+ // A store nothing has opened yet loads its record before it can sync.
23
+ if (!(await store.ensureInitialized()))
24
+ return false;
25
+ store.requestRemoteSync();
26
+ return true;
27
+ }
28
+ //# sourceMappingURL=downloadRetry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"downloadRetry.js","sourceRoot":"","sources":["downloadRetry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,2BAA2B,EAAE,MAAM,2BAA2B,CAAC;AACxE,OAAO,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAC;AAG3D;;;;;;;;;GASG;AACH,MAAM,CAAC,KAAK,UAAU,qBAAqB,CAAC,KAI3C;IACC,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,GAAG,KAAK,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC;IAChE,IAAI,QAAQ,KAAK,OAAO;QAAE,OAAO,KAAK,CAAC;IACvC,MAAM,MAAM,GAAG,MAAM,2BAA2B,CAAC,YAAY,CAC3D,OAAO,EACP,KAAK,CAAC,OAAO,CACd,CAAC;IACF,IAAI,CAAC,MAAM,IAAI,MAAM,CAAC,UAAU,KAAK,KAAK,CAAC,UAAU;QAAE,OAAO,KAAK,CAAC;IACpE,MAAM,OAAO,GAAG,KAAK,CAAC,eAAe,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;IAC1D,MAAM,KAAK,GAAG,wBAAwB,CACpC,OAAO,CAAC,KAAK,CAAC,WAAW,EACzB,KAAK,CAAC,OAAO,EACb,OAAO,EACP,IAAI,EACJ,EAAE,EACF,MAAM,CAAC,YAAY,CACpB,CAAC;IACF,sEAAsE;IACtE,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,iBAAiB,EAAE,CAAC;QAAE,OAAO,KAAK,CAAC;IACrD,KAAK,CAAC,iBAAiB,EAAE,CAAC;IAC1B,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { defaultDocumentsPersistence } from \"../../workflows/documents\";\nimport { getOrCreateDocumentStore } from \"./documentStore\";\nimport type { DocumentsRuntime } from \"./types\";\n\n/**\n * Ask one synced document to pull again and re-list its attachment bindings,\n * e.g. for a pending first download in Explorer. The request names the\n * document id it was read with: when the local record has since been relinked\n * to another document, nothing runs and the caller re-reads its queue.\n *\n * The store is resolved by local id only, so an already-open store is reused\n * as-is (its runtime, draft and identity untouched) and a retry never maps one\n * local record onto another document's store.\n */\nexport async function retryDocumentDownload(input: {\n documentId: string;\n localId: string;\n workflowRuntime: (containerId: string | null) => DocumentsRuntime;\n}): Promise<boolean> {\n const { execSql, dbStatus } = input.workflowRuntime(null).infra;\n if (dbStatus !== \"ready\") return false;\n const record = await defaultDocumentsPersistence.loadDocument(\n execSql,\n input.localId,\n );\n if (!record || record.documentId !== input.documentId) return false;\n const runtime = input.workflowRuntime(record.containerId);\n const store = getOrCreateDocumentStore(\n runtime.state.domainScope,\n input.localId,\n runtime,\n null,\n \"\",\n record.documentKind,\n );\n // A store nothing has opened yet loads its record before it can sync.\n if (!(await store.ensureInitialized())) return false;\n store.requestRemoteSync();\n return true;\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  export * from "./documentStore/index.js";
2
2
  export { createSeededDocument, type SeededDocumentInput, } from "./documentStore/initialization/createSeededDocument.js";
3
+ export { retryDocumentDownload } from "./downloadRetry.js";
3
4
  export { hasPendingLocalDocumentWrites } from "./registry.js";
4
5
  export * from "./types.js";
@@ -1,5 +1,6 @@
1
1
  export * from "./documentStore/index.js";
2
2
  export { createSeededDocument, } from "./documentStore/initialization/createSeededDocument.js";
3
+ export { retryDocumentDownload } from "./downloadRetry.js";
3
4
  export { hasPendingLocalDocumentWrites } from "./registry.js";
4
5
  export * from "./types.js";
5
6
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,cAAc,iBAAiB,CAAC;AAChC,OAAO,EACL,oBAAoB,GAErB,MAAM,qDAAqD,CAAC;AAC7D,OAAO,EAAE,6BAA6B,EAAE,MAAM,YAAY,CAAC;AAC3D,cAAc,SAAS,CAAC","sourcesContent":["export * from \"./documentStore\";\nexport {\n createSeededDocument,\n type SeededDocumentInput,\n} from \"./documentStore/initialization/createSeededDocument\";\nexport { hasPendingLocalDocumentWrites } from \"./registry\";\nexport * from \"./types\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,cAAc,iBAAiB,CAAC;AAChC,OAAO,EACL,oBAAoB,GAErB,MAAM,qDAAqD,CAAC;AAC7D,OAAO,EAAE,qBAAqB,EAAE,MAAM,iBAAiB,CAAC;AACxD,OAAO,EAAE,6BAA6B,EAAE,MAAM,YAAY,CAAC;AAC3D,cAAc,SAAS,CAAC","sourcesContent":["export * from \"./documentStore\";\nexport {\n createSeededDocument,\n type SeededDocumentInput,\n} from \"./documentStore/initialization/createSeededDocument\";\nexport { retryDocumentDownload } from \"./downloadRetry\";\nexport { hasPendingLocalDocumentWrites } from \"./registry\";\nexport * from \"./types\";\n"]}
@@ -141,7 +141,9 @@ export async function hydrateDocumentAttachmentBlobs(blobs, request) {
141
141
  reportSecurityIncident: blobs.reportSecurityIncident,
142
142
  targetSecretKey: requireEncapsulationSecretKey(blobs, "Document attachment hydration"),
143
143
  };
144
- const attachmentBindings = await input.apiClient.listDocumentAttachments(input.documentId);
144
+ // The writer can bind a file after publishing its document. An earlier
145
+ // cached list cannot tell a reader whether the file is now available.
146
+ const attachmentBindings = await input.apiClient.listDocumentAttachments(input.documentId, { refresh: true });
145
147
  if (!attachmentBindings) {
146
148
  return null;
147
149
  }
@@ -1 +1 @@
1
- {"version":3,"file":"hydrate.js","sourceRoot":"","sources":["hydrate.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAK/C,OAAO,EAAE,uBAAuB,EAAE,MAAM,+CAA+C,CAAC;AACxF,OAAO,EAEL,6BAA6B,GAC9B,MAAM,+CAA+C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ACN,gBAAgB;aACjB,CAAC;SACL,CAAC,CAAC;KACJ,CAAC,CAAC;IACH,MAAM,QAAQ,GAAG,QAAQ,CAAC,MAAM,CAC9B,CAAC,IAAI,EAA0C,EAAE,CAAC,IAAI,KAAK,IAAI,CAChE,CAAC;IACF,IAAI,QAAQ,CAAC,MAAM,KAAK,gBAAgB,CAAC,MAAM;QAAE,KAAK,CAAC,iBAAiB,EAAE,EAAE,CAAC;IAC7E,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import type { BlobBytesResponse } from \"@tearleads/api-client\";\nimport { bytesToHex } from \"@tearleads/crypto\";\nimport type {\n BlobAttachmentSummary,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { attachmentContentSha256 } from \"../../../data/blobs/attachmentContentIdentity\";\nimport {\n type BlobAttachmentCollaborators,\n requireEncapsulationSecretKey,\n} from \"../../../data/blobs/attachments/collaborators\";\nimport type { DocumentAttachmentHydrationApi } from \"../../../data/blobs/attachments/types\";\nimport type { BlobBytes } from \"../../../data/blobs/blobContracts\";\nimport { runBlobTransfer } from \"../../../data/blobs/transferPool\";\nimport type { DocumentAttachment } from \"../../../data/documents\";\nimport type {\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../../../data/keyingProjectionVerification\";\nimport { errorMessage } from \"../../../data/shared/errorMessage\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { createAttachmentDecryptor } from \"../verification/attachmentDecryptor\";\nimport { collectHydrationResults } from \"./hydrationResults\";\nimport { readAttachmentTransfer } from \"./readAttachmentTransfer\";\n\nexport interface HydratedDocumentAttachmentBlob {\n attachment: DocumentAttachment;\n binding: BlobAttachmentSummary;\n bytes: BlobBytes;\n /** Plaintext digest of `bytes`. */\n contentSha256: string;\n /**\n * The served binding is validly signed but its plaintext digest differs\n * from the digest the document content records for the slot. Set only when\n * the slot held no local bytes: the bind and the content update carrying\n * its digest are two server writes, and an uploader lost between them must\n * not leave the attachment permanently invisible. Never a security incident;\n * an honest crash window is indistinguishable from a served rollback.\n */\n intentMismatch: boolean;\n storageKey: string;\n}\n\n/** One hydration pass; the service supplies the API, executor, and key. */\nexport interface HydrateDocumentAttachmentBlobsRequest {\n attachments: ReadonlyArray<DocumentAttachment>;\n documentId: string;\n localBlobIdBySlotId?:\n | Readonly<Record<string, string | null | undefined>>\n | undefined;\n localStorageKeyBySlotId?: Readonly<Record<string, string | undefined>>;\n /** No binding target remains unchecked or unavailable in this pass. */\n onBindingsChecked?: (() => void) | undefined;\n /**\n * Served bindings already downloaded and refused for a held copy, keyed per\n * (slot, binding, intent). Populated here; a later pass skips the download\n * until the binding or the document intent changes.\n */\n rejectedServedBindings?: Set<string> | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}\n\ninterface DocumentAttachmentHydrationContext\n extends Omit<\n HydrateDocumentAttachmentBlobsRequest,\n \"attachments\" | \"onBindingsChecked\"\n > {\n apiClient: DocumentAttachmentHydrationApi;\n execSql: ExecSql;\n log?: ((message: string) => void) | undefined;\n reportSecurityIncident?: SecurityIncidentReporter | undefined;\n targetSecretKey: Uint8Array;\n}\n\nfunction servedBindingRejectionKey(\n attachment: DocumentAttachment,\n binding: BlobAttachmentSummary,\n): string {\n return JSON.stringify([\n attachment.slotId,\n binding.bindingId,\n attachment.contentSha256,\n ]);\n}\n\ninterface DocumentAttachmentHydrationTarget {\n attachment: DocumentAttachment;\n binding: BlobAttachmentSummary;\n}\n\ninterface LoadedDocumentAttachmentBlob\n extends DocumentAttachmentHydrationTarget {\n encryptedBytes: Uint8Array<ArrayBuffer>;\n}\n\ninterface LoadedDocumentAttachmentBlobBytes {\n blobId: string;\n encryptedBytes: Uint8Array<ArrayBuffer>;\n}\n\nasync function hasExpectedBlobSha256(\n blob: BlobBytesResponse,\n encryptedBytes: Uint8Array<ArrayBuffer>,\n): Promise<boolean> {\n const blobDigest = new Uint8Array(\n await crypto.subtle.digest(\"SHA-256\", encryptedBytes),\n );\n\n return bytesToHex(blobDigest) === blob.sha256;\n}\n\nfunction shouldHydrateAttachment(input: {\n attachment: DocumentAttachment;\n binding: BlobAttachmentSummary;\n localBlobIdBySlotId:\n | Readonly<Record<string, string | null | undefined>>\n | undefined;\n localStorageKeyBySlotId:\n | Readonly<Record<string, string | undefined>>\n | undefined;\n rejectedServedBindings: ReadonlySet<string> | undefined;\n}): boolean {\n const slotId = input.attachment.slotId;\n const localStorageKey = input.localStorageKeyBySlotId?.[slotId];\n // An empty slot always hydrates: a rejection only ever protected a held\n // copy, so once that copy is gone the served binding is shown (flagged).\n if (!localStorageKey) {\n return true;\n }\n if (\n input.rejectedServedBindings?.has(\n servedBindingRejectionKey(input.attachment, input.binding),\n )\n ) {\n return false;\n }\n\n const localBlobId = input.localBlobIdBySlotId?.[slotId];\n return localBlobId !== null && localBlobId !== input.binding.blobId;\n}\n\nasync function loadDocumentAttachmentBlob(\n input: DocumentAttachmentHydrationContext & {\n binding: BlobAttachmentSummary;\n signal: AbortSignal;\n progress: () => void;\n },\n): Promise<LoadedDocumentAttachmentBlobBytes | null> {\n const { apiClient, binding, log } = input;\n if (input.stillCurrent?.() === false) return null;\n input.signal.throwIfAborted();\n const blob = await apiClient.getBlobBytes(binding.blobId, {\n signal: input.signal,\n });\n if (!blob) {\n return null;\n }\n\n let encryptedBytes: Uint8Array<ArrayBuffer>;\n try {\n encryptedBytes = await readAttachmentTransfer(\n blob,\n input.signal,\n input.progress,\n );\n } catch (error) {\n log?.(\n `Documents: blob ${binding.blobId} failed to stream during hydration: ${errorMessage(\n error,\n )}`,\n );\n return null;\n }\n\n if (encryptedBytes.byteLength !== blob.byteLength) {\n log?.(\n `Documents: blob ${binding.blobId} byte length mismatch during hydration.`,\n );\n return null;\n }\n\n if (!(await hasExpectedBlobSha256(blob, encryptedBytes))) {\n log?.(\n `Documents: blob ${binding.blobId} sha256 mismatch during hydration.`,\n );\n return null;\n }\n\n input.signal.throwIfAborted();\n return {\n blobId: binding.blobId,\n encryptedBytes,\n };\n}\n\nasync function loadUniqueDocumentAttachmentBlobs(\n input: DocumentAttachmentHydrationContext & {\n hydrationTargets: ReadonlyArray<DocumentAttachmentHydrationTarget>;\n },\n): Promise<ReadonlyMap<string, LoadedDocumentAttachmentBlobBytes>> {\n const targetsByBlobId = new Map<string, DocumentAttachmentHydrationTarget>();\n for (const target of input.hydrationTargets) {\n if (!targetsByBlobId.has(target.binding.blobId)) {\n targetsByBlobId.set(target.binding.blobId, target);\n }\n }\n\n const loadedBlobs = await collectHydrationResults({\n ...input,\n tasks: Array.from(targetsByBlobId.values()).map((target) => ({\n blobId: target.binding.blobId,\n run: () =>\n runBlobTransfer(input.apiClient, (signal, progress) =>\n loadDocumentAttachmentBlob({\n ...input,\n binding: target.binding,\n signal,\n progress,\n }),\n ),\n })),\n });\n\n return new Map(\n loadedBlobs.flatMap((loaded) =>\n loaded ? [[loaded.blobId, loaded] as const] : [],\n ),\n );\n}\n\nfunction applyLoadedBlobBytesToHydrationTargets(\n hydrationTargets: ReadonlyArray<DocumentAttachmentHydrationTarget>,\n loadedBlobsByBlobId: ReadonlyMap<string, LoadedDocumentAttachmentBlobBytes>,\n): LoadedDocumentAttachmentBlob[] {\n return hydrationTargets.flatMap((target) => {\n const loaded = loadedBlobsByBlobId.get(target.binding.blobId);\n return loaded\n ? [\n {\n ...target,\n encryptedBytes: loaded.encryptedBytes,\n },\n ]\n : [];\n });\n}\n\nasync function decryptLoadedDocumentAttachmentBlob(\n input: DocumentAttachmentHydrationContext & {\n loaded: LoadedDocumentAttachmentBlob;\n decryptAttachment: ReturnType<typeof createAttachmentDecryptor>;\n writerProjection: DocumentWriterProjectionResponse;\n },\n): Promise<HydratedDocumentAttachmentBlob | null> {\n const bytes = await input.decryptAttachment({\n binding: input.loaded.binding,\n encryptedBytes: input.loaded.encryptedBytes,\n expectedDocumentId: input.documentId,\n expectedSlotId: input.loaded.attachment.slotId,\n execSql: input.execSql,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n targetSecretKey: input.targetSecretKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n writerProjection: input.writerProjection,\n });\n\n const { attachment, binding } = input.loaded;\n const contentSha256 = await attachmentContentSha256(bytes);\n const intentMismatch = contentSha256 !== attachment.contentSha256;\n if (intentMismatch && input.localStorageKeyBySlotId?.[attachment.slotId]) {\n // Never replace a held copy with bytes the document does not record.\n input.rejectedServedBindings?.add(\n servedBindingRejectionKey(attachment, binding),\n );\n input.log?.(\n \"Documents: served attachment bytes differ from the current document content; keeping the held copy.\",\n );\n return null;\n }\n if (intentMismatch) {\n input.log?.(\n \"Documents: served attachment bytes differ from the current document content; showing them flagged.\",\n );\n }\n return {\n attachment,\n binding,\n bytes,\n contentSha256,\n intentMismatch,\n storageKey: `blob-${binding.blobId}`,\n };\n}\n\nexport async function hydrateDocumentAttachmentBlobs(\n blobs: BlobAttachmentCollaborators,\n request: HydrateDocumentAttachmentBlobsRequest,\n): Promise<HydratedDocumentAttachmentBlob[] | null> {\n const input = {\n ...request,\n apiClient: blobs.api,\n execSql: blobs.execSql,\n log: blobs.log,\n reportSecurityIncident: blobs.reportSecurityIncident,\n targetSecretKey: requireEncapsulationSecretKey(\n blobs,\n \"Document attachment hydration\",\n ),\n };\n const attachmentBindings = await input.apiClient.listDocumentAttachments(\n input.documentId,\n );\n if (!attachmentBindings) {\n return null;\n }\n\n const bindingBySlotId = new Map(\n attachmentBindings.map((binding) => [binding.slotId, binding]),\n );\n const hydrationTargets: DocumentAttachmentHydrationTarget[] =\n input.attachments.flatMap((attachment) => {\n const binding = bindingBySlotId.get(attachment.slotId);\n return binding &&\n shouldHydrateAttachment({\n attachment,\n binding,\n localBlobIdBySlotId: input.localBlobIdBySlotId,\n localStorageKeyBySlotId: input.localStorageKeyBySlotId,\n rejectedServedBindings: input.rejectedServedBindings,\n })\n ? [{ attachment, binding }]\n : [];\n });\n if (hydrationTargets.length === 0) {\n input.onBindingsChecked?.();\n return [];\n }\n\n const loadedBlobs = applyLoadedBlobBytesToHydrationTargets(\n hydrationTargets,\n await loadUniqueDocumentAttachmentBlobs({\n ...input,\n hydrationTargets,\n }),\n );\n if (loadedBlobs.length === 0) {\n return [];\n }\n\n const writerProjection = await input.apiClient.getDocumentWriterProjection(\n input.documentId,\n );\n if (!writerProjection) {\n input.log?.(\n `Documents: cannot hydrate attachments for document ${input.documentId} without a writer projection.`,\n );\n return [];\n }\n\n const decryptAttachment = createAttachmentDecryptor(\n input.apiClient,\n input.documentId,\n );\n const hydrated = await collectHydrationResults({\n ...input,\n tasks: loadedBlobs.map((loaded) => ({\n blobId: loaded.binding.blobId,\n run: () =>\n decryptLoadedDocumentAttachmentBlob({\n ...input,\n decryptAttachment,\n loaded,\n writerProjection,\n }),\n })),\n });\n const complete = hydrated.filter(\n (item): item is HydratedDocumentAttachmentBlob => item !== null,\n );\n if (complete.length === hydrationTargets.length) input.onBindingsChecked?.();\n return complete;\n}\n"]}
1
+ {"version":3,"file":"hydrate.js","sourceRoot":"","sources":["hydrate.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAK/C,OAAO,EAAE,uBAAuB,EAAE,MAAM,+CAA+C,CAAC;AACxF,OAAO,EAEL,6BAA6B,GAC9B,MAAM,+CAA+C,CAAC;AAGvD,OAAO,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AAMnE,OAAO,EAAE,YAAY,EAAE,MAAM,mCAAmC,CAAC;AAGjE,OAAO,EAAE,yBAAyB,EAAE,MAAM,qCAAqC,CAAC;AAChF,OAAO,EAAE,uBAAuB,EAAE,MAAM,oBAAoB,CAAC;AAC7D,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAqDlE,SAAS,yBA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M;QAAE,KAAK,CAAC,iBAAiB,EAAE,EAAE,CAAC;IAC7E,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import type { BlobBytesResponse } from \"@tearleads/api-client\";\nimport { bytesToHex } from \"@tearleads/crypto\";\nimport type {\n BlobAttachmentSummary,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { attachmentContentSha256 } from \"../../../data/blobs/attachmentContentIdentity\";\nimport {\n type BlobAttachmentCollaborators,\n requireEncapsulationSecretKey,\n} from \"../../../data/blobs/attachments/collaborators\";\nimport type { DocumentAttachmentHydrationApi } from \"../../../data/blobs/attachments/types\";\nimport type { BlobBytes } from \"../../../data/blobs/blobContracts\";\nimport { runBlobTransfer } from \"../../../data/blobs/transferPool\";\nimport type { DocumentAttachment } from \"../../../data/documents\";\nimport type {\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../../../data/keyingProjectionVerification\";\nimport { errorMessage } from \"../../../data/shared/errorMessage\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { createAttachmentDecryptor } from \"../verification/attachmentDecryptor\";\nimport { collectHydrationResults } from \"./hydrationResults\";\nimport { readAttachmentTransfer } from \"./readAttachmentTransfer\";\n\nexport interface HydratedDocumentAttachmentBlob {\n attachment: DocumentAttachment;\n binding: BlobAttachmentSummary;\n bytes: BlobBytes;\n /** Plaintext digest of `bytes`. */\n contentSha256: string;\n /**\n * The served binding is validly signed but its plaintext digest differs\n * from the digest the document content records for the slot. Set only when\n * the slot held no local bytes: the bind and the content update carrying\n * its digest are two server writes, and an uploader lost between them must\n * not leave the attachment permanently invisible. Never a security incident;\n * an honest crash window is indistinguishable from a served rollback.\n */\n intentMismatch: boolean;\n storageKey: string;\n}\n\n/** One hydration pass; the service supplies the API, executor, and key. */\nexport interface HydrateDocumentAttachmentBlobsRequest {\n attachments: ReadonlyArray<DocumentAttachment>;\n documentId: string;\n localBlobIdBySlotId?:\n | Readonly<Record<string, string | null | undefined>>\n | undefined;\n localStorageKeyBySlotId?: Readonly<Record<string, string | undefined>>;\n /** No binding target remains unchecked or unavailable in this pass. */\n onBindingsChecked?: (() => void) | undefined;\n /**\n * Served bindings already downloaded and refused for a held copy, keyed per\n * (slot, binding, intent). Populated here; a later pass skips the download\n * until the binding or the document intent changes.\n */\n rejectedServedBindings?: Set<string> | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}\n\ninterface DocumentAttachmentHydrationContext\n extends Omit<\n HydrateDocumentAttachmentBlobsRequest,\n \"attachments\" | \"onBindingsChecked\"\n > {\n apiClient: DocumentAttachmentHydrationApi;\n execSql: ExecSql;\n log?: ((message: string) => void) | undefined;\n reportSecurityIncident?: SecurityIncidentReporter | undefined;\n targetSecretKey: Uint8Array;\n}\n\nfunction servedBindingRejectionKey(\n attachment: DocumentAttachment,\n binding: BlobAttachmentSummary,\n): string {\n return JSON.stringify([\n attachment.slotId,\n binding.bindingId,\n attachment.contentSha256,\n ]);\n}\n\ninterface DocumentAttachmentHydrationTarget {\n attachment: DocumentAttachment;\n binding: BlobAttachmentSummary;\n}\n\ninterface LoadedDocumentAttachmentBlob\n extends DocumentAttachmentHydrationTarget {\n encryptedBytes: Uint8Array<ArrayBuffer>;\n}\n\ninterface LoadedDocumentAttachmentBlobBytes {\n blobId: string;\n encryptedBytes: Uint8Array<ArrayBuffer>;\n}\n\nasync function hasExpectedBlobSha256(\n blob: BlobBytesResponse,\n encryptedBytes: Uint8Array<ArrayBuffer>,\n): Promise<boolean> {\n const blobDigest = new Uint8Array(\n await crypto.subtle.digest(\"SHA-256\", encryptedBytes),\n );\n\n return bytesToHex(blobDigest) === blob.sha256;\n}\n\nfunction shouldHydrateAttachment(input: {\n attachment: DocumentAttachment;\n binding: BlobAttachmentSummary;\n localBlobIdBySlotId:\n | Readonly<Record<string, string | null | undefined>>\n | undefined;\n localStorageKeyBySlotId:\n | Readonly<Record<string, string | undefined>>\n | undefined;\n rejectedServedBindings: ReadonlySet<string> | undefined;\n}): boolean {\n const slotId = input.attachment.slotId;\n const localStorageKey = input.localStorageKeyBySlotId?.[slotId];\n // An empty slot always hydrates: a rejection only ever protected a held\n // copy, so once that copy is gone the served binding is shown (flagged).\n if (!localStorageKey) {\n return true;\n }\n if (\n input.rejectedServedBindings?.has(\n servedBindingRejectionKey(input.attachment, input.binding),\n )\n ) {\n return false;\n }\n\n const localBlobId = input.localBlobIdBySlotId?.[slotId];\n return localBlobId !== null && localBlobId !== input.binding.blobId;\n}\n\nasync function loadDocumentAttachmentBlob(\n input: DocumentAttachmentHydrationContext & {\n binding: BlobAttachmentSummary;\n signal: AbortSignal;\n progress: () => void;\n },\n): Promise<LoadedDocumentAttachmentBlobBytes | null> {\n const { apiClient, binding, log } = input;\n if (input.stillCurrent?.() === false) return null;\n input.signal.throwIfAborted();\n const blob = await apiClient.getBlobBytes(binding.blobId, {\n signal: input.signal,\n });\n if (!blob) {\n return null;\n }\n\n let encryptedBytes: Uint8Array<ArrayBuffer>;\n try {\n encryptedBytes = await readAttachmentTransfer(\n blob,\n input.signal,\n input.progress,\n );\n } catch (error) {\n log?.(\n `Documents: blob ${binding.blobId} failed to stream during hydration: ${errorMessage(\n error,\n )}`,\n );\n return null;\n }\n\n if (encryptedBytes.byteLength !== blob.byteLength) {\n log?.(\n `Documents: blob ${binding.blobId} byte length mismatch during hydration.`,\n );\n return null;\n }\n\n if (!(await hasExpectedBlobSha256(blob, encryptedBytes))) {\n log?.(\n `Documents: blob ${binding.blobId} sha256 mismatch during hydration.`,\n );\n return null;\n }\n\n input.signal.throwIfAborted();\n return {\n blobId: binding.blobId,\n encryptedBytes,\n };\n}\n\nasync function loadUniqueDocumentAttachmentBlobs(\n input: DocumentAttachmentHydrationContext & {\n hydrationTargets: ReadonlyArray<DocumentAttachmentHydrationTarget>;\n },\n): Promise<ReadonlyMap<string, LoadedDocumentAttachmentBlobBytes>> {\n const targetsByBlobId = new Map<string, DocumentAttachmentHydrationTarget>();\n for (const target of input.hydrationTargets) {\n if (!targetsByBlobId.has(target.binding.blobId)) {\n targetsByBlobId.set(target.binding.blobId, target);\n }\n }\n\n const loadedBlobs = await collectHydrationResults({\n ...input,\n tasks: Array.from(targetsByBlobId.values()).map((target) => ({\n blobId: target.binding.blobId,\n run: () =>\n runBlobTransfer(input.apiClient, (signal, progress) =>\n loadDocumentAttachmentBlob({\n ...input,\n binding: target.binding,\n signal,\n progress,\n }),\n ),\n })),\n });\n\n return new Map(\n loadedBlobs.flatMap((loaded) =>\n loaded ? [[loaded.blobId, loaded] as const] : [],\n ),\n );\n}\n\nfunction applyLoadedBlobBytesToHydrationTargets(\n hydrationTargets: ReadonlyArray<DocumentAttachmentHydrationTarget>,\n loadedBlobsByBlobId: ReadonlyMap<string, LoadedDocumentAttachmentBlobBytes>,\n): LoadedDocumentAttachmentBlob[] {\n return hydrationTargets.flatMap((target) => {\n const loaded = loadedBlobsByBlobId.get(target.binding.blobId);\n return loaded\n ? [\n {\n ...target,\n encryptedBytes: loaded.encryptedBytes,\n },\n ]\n : [];\n });\n}\n\nasync function decryptLoadedDocumentAttachmentBlob(\n input: DocumentAttachmentHydrationContext & {\n loaded: LoadedDocumentAttachmentBlob;\n decryptAttachment: ReturnType<typeof createAttachmentDecryptor>;\n writerProjection: DocumentWriterProjectionResponse;\n },\n): Promise<HydratedDocumentAttachmentBlob | null> {\n const bytes = await input.decryptAttachment({\n binding: input.loaded.binding,\n encryptedBytes: input.loaded.encryptedBytes,\n expectedDocumentId: input.documentId,\n expectedSlotId: input.loaded.attachment.slotId,\n execSql: input.execSql,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n targetSecretKey: input.targetSecretKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n writerProjection: input.writerProjection,\n });\n\n const { attachment, binding } = input.loaded;\n const contentSha256 = await attachmentContentSha256(bytes);\n const intentMismatch = contentSha256 !== attachment.contentSha256;\n if (intentMismatch && input.localStorageKeyBySlotId?.[attachment.slotId]) {\n // Never replace a held copy with bytes the document does not record.\n input.rejectedServedBindings?.add(\n servedBindingRejectionKey(attachment, binding),\n );\n input.log?.(\n \"Documents: served attachment bytes differ from the current document content; keeping the held copy.\",\n );\n return null;\n }\n if (intentMismatch) {\n input.log?.(\n \"Documents: served attachment bytes differ from the current document content; showing them flagged.\",\n );\n }\n return {\n attachment,\n binding,\n bytes,\n contentSha256,\n intentMismatch,\n storageKey: `blob-${binding.blobId}`,\n };\n}\n\nexport async function hydrateDocumentAttachmentBlobs(\n blobs: BlobAttachmentCollaborators,\n request: HydrateDocumentAttachmentBlobsRequest,\n): Promise<HydratedDocumentAttachmentBlob[] | null> {\n const input = {\n ...request,\n apiClient: blobs.api,\n execSql: blobs.execSql,\n log: blobs.log,\n reportSecurityIncident: blobs.reportSecurityIncident,\n targetSecretKey: requireEncapsulationSecretKey(\n blobs,\n \"Document attachment hydration\",\n ),\n };\n // The writer can bind a file after publishing its document. An earlier\n // cached list cannot tell a reader whether the file is now available.\n const attachmentBindings = await input.apiClient.listDocumentAttachments(\n input.documentId,\n { refresh: true },\n );\n if (!attachmentBindings) {\n return null;\n }\n\n const bindingBySlotId = new Map(\n attachmentBindings.map((binding) => [binding.slotId, binding]),\n );\n const hydrationTargets: DocumentAttachmentHydrationTarget[] =\n input.attachments.flatMap((attachment) => {\n const binding = bindingBySlotId.get(attachment.slotId);\n return binding &&\n shouldHydrateAttachment({\n attachment,\n binding,\n localBlobIdBySlotId: input.localBlobIdBySlotId,\n localStorageKeyBySlotId: input.localStorageKeyBySlotId,\n rejectedServedBindings: input.rejectedServedBindings,\n })\n ? [{ attachment, binding }]\n : [];\n });\n if (hydrationTargets.length === 0) {\n input.onBindingsChecked?.();\n return [];\n }\n\n const loadedBlobs = applyLoadedBlobBytesToHydrationTargets(\n hydrationTargets,\n await loadUniqueDocumentAttachmentBlobs({\n ...input,\n hydrationTargets,\n }),\n );\n if (loadedBlobs.length === 0) {\n return [];\n }\n\n const writerProjection = await input.apiClient.getDocumentWriterProjection(\n input.documentId,\n );\n if (!writerProjection) {\n input.log?.(\n `Documents: cannot hydrate attachments for document ${input.documentId} without a writer projection.`,\n );\n return [];\n }\n\n const decryptAttachment = createAttachmentDecryptor(\n input.apiClient,\n input.documentId,\n );\n const hydrated = await collectHydrationResults({\n ...input,\n tasks: loadedBlobs.map((loaded) => ({\n blobId: loaded.binding.blobId,\n run: () =>\n decryptLoadedDocumentAttachmentBlob({\n ...input,\n decryptAttachment,\n loaded,\n writerProjection,\n }),\n })),\n });\n const complete = hydrated.filter(\n (item): item is HydratedDocumentAttachmentBlob => item !== null,\n );\n if (complete.length === hydrationTargets.length) input.onBindingsChecked?.();\n return complete;\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import type { ExecSql } from "../../../data/sqlite/sqlSchema.js";
2
- export interface PendingDownloadQueueItem {
2
+ interface PendingContentDownload {
3
3
  localId: string;
4
4
  documentId: string;
5
5
  objectKind: "document" | "container";
@@ -8,5 +8,26 @@ export interface PendingDownloadQueueItem {
8
8
  reason: "initial" | "continuation";
9
9
  lastError: string | null;
10
10
  }
11
- /** Durable, already-discovered content pulls, including folder metadata. */
11
+ /**
12
+ * The first download of a file a synced document records for a slot. The row
13
+ * carries the identity hydration fetches with: the slot and the stored
14
+ * record's document id.
15
+ */
16
+ interface PendingAttachmentDownload {
17
+ localId: string;
18
+ documentId: string;
19
+ objectKind: "attachment";
20
+ /** The owning document's projected title. */
21
+ title: string;
22
+ reason: "initial";
23
+ lastError: string | null;
24
+ slotId: string;
25
+ fileName: string;
26
+ }
27
+ export type PendingDownloadQueueItem = PendingContentDownload | PendingAttachmentDownload;
28
+ /**
29
+ * Durable, already-discovered content pulls, including folder metadata, then
30
+ * the first downloads of files recorded by synced documents.
31
+ */
12
32
  export declare function listPendingDownloads(execSql: ExecSql): Promise<ReadonlyArray<PendingDownloadQueueItem>>;
33
+ export {};
@@ -1,10 +1,18 @@
1
1
  import { ensureContainerTables } from "../../../data/persistence/container-contents/containerPersistence.js";
2
2
  import { sqlDocumentsPersistence } from "../../../data/persistence/documents/documentsPersistence.js";
3
3
  import { emptyContentFrontierSql } from "./hydrationSql.js";
4
- /** Durable, already-discovered content pulls, including folder metadata. */
4
+ /**
5
+ * Durable, already-discovered content pulls, including folder metadata, then
6
+ * the first downloads of files recorded by synced documents.
7
+ */
5
8
  export async function listPendingDownloads(execSql) {
6
9
  await ensureContainerTables(execSql);
7
10
  await sqlDocumentsPersistence.ensureSchema(execSql);
11
+ const contentDownloads = await listPendingContentDownloads(execSql);
12
+ const attachmentDownloads = await listPendingAttachmentDownloads(execSql);
13
+ return [...contentDownloads, ...attachmentDownloads];
14
+ }
15
+ async function listPendingContentDownloads(execSql) {
8
16
  const rows = await execSql(`
9
17
  SELECT stored.local_id, stored.document_id, stored.app_kind,
10
18
  CASE WHEN ${emptyContentFrontierSql("stored")} THEN NULL
@@ -39,4 +47,58 @@ export async function listPendingDownloads(execSql) {
39
47
  return [item];
40
48
  });
41
49
  }
50
+ // `attachment_names` keys each slot recorded by the content as
51
+ // `<contentSha256>:<slotId>`; the hex digest never contains a colon, while a
52
+ // collection slot id (`photos:<uuid>`) can. Any local row for the slot, held
53
+ // or awaiting a remote detach, means this is no longer a first download, and a
54
+ // pending upload is this device's own file.
55
+ async function listPendingAttachmentDownloads(execSql) {
56
+ const rows = await execSql(`
57
+ SELECT stored.local_id, stored.document_id, d.title,
58
+ stored.sync_failure_message AS last_error,
59
+ substr(recorded.key, instr(recorded.key, ':') + 1) AS slot_id,
60
+ json_extract(recorded.value, '$.name') AS file_name
61
+ FROM documents stored
62
+ JOIN document_projection d ON d.local_id = stored.local_id
63
+ JOIN document_projection_text projected
64
+ ON projected.local_id = stored.local_id
65
+ JOIN json_each(projected.attachment_names) recorded
66
+ WHERE stored.app_kind = 'documents'
67
+ AND stored.document_id IS NOT NULL
68
+ AND NOT ${emptyContentFrontierSql("stored")}
69
+ AND projected.attachment_names IS NOT NULL
70
+ AND NOT EXISTS (
71
+ SELECT 1 FROM document_attachment_blob_projection held
72
+ WHERE held.local_id = stored.local_id
73
+ AND held.slot_id = substr(recorded.key, instr(recorded.key, ':') + 1)
74
+ )
75
+ AND NOT EXISTS (
76
+ SELECT 1 FROM document_pending_attachments upload
77
+ WHERE upload.local_id = stored.local_id
78
+ AND upload.slot_id = substr(recorded.key, instr(recorded.key, ':') + 1)
79
+ )
80
+ ORDER BY stored.updated_at, stored.local_id, slot_id
81
+ `);
82
+ return rows.flatMap((row) => {
83
+ const { local_id: localId, document_id: documentId, title, last_error: lastError, slot_id: slotId, file_name: fileName, } = row;
84
+ if (typeof localId !== "string" ||
85
+ typeof documentId !== "string" ||
86
+ typeof title !== "string" ||
87
+ typeof slotId !== "string" ||
88
+ slotId.length === 0 ||
89
+ typeof fileName !== "string")
90
+ return [];
91
+ const item = {
92
+ localId,
93
+ documentId,
94
+ objectKind: "attachment",
95
+ title,
96
+ reason: "initial",
97
+ lastError: typeof lastError === "string" ? lastError : null,
98
+ slotId,
99
+ fileName,
100
+ };
101
+ return [item];
102
+ });
103
+ }
42
104
  //# sourceMappingURL=pendingDownloads.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"pendingDownloads.js","sourceRoot":"","sources":["pendingDownloads.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,mEAAmE,CAAC;AAC1G,OAAO,EAAE,uBAAuB,EAAE,MAAM,0DAA0D,CAAC;AAEnG,OAAO,EAAE,uBAAuB,EAAE,MAAM,gBAAgB,CAAC;AAYzD,4EAA4E;AAC5E,MAAM,CAAC,KAAK,UAAU,oBAAoB,CACxC,OAAgB;IAEhB,MAAM,qBAAqB,CAAC,OAAO,CAAC,CAAC;IACrC,MAAM,uBAAuB,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;IACpD,MAAM,IAAI,GAAG,MAAM,OAAO,CAAC;;kBAEX,uBAAuB,CAAC,QAAQ,CAAC;;;kBAGjC,uBAAuB,CAAC,QAAQ,CAAC;;;;;;;;;aAStC,uBAAuB,CAAC,QAAQ,CAAC;;;;GAI3C,CAAC,CAAC;IACH,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE;QAC1B,MAAM,EACJ,QAAQ,EAAE,OAAO,EACjB,WAAW,EAAE,UAAU,EACvB,QAAQ,EAAE,OAAO,EACjB,KAAK,EACL,MAAM,EACN,UAAU,EAAE,SAAS,GACtB,GAAG,GAAG,CAAC;QACR,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,UAAU,KAAK,QAAQ;YAC/D,OAAO,EAAE,CAAC;QACZ,MAAM,IAAI,GAA6B;YACrC,OAAO;YACP,UAAU;YACV,UAAU,EAAE,OAAO,KAAK,WAAW,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,WAAW;YAC9D,KAAK,EAAE,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI;YAC/C,MAAM,EAAE,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,cAAc;YACzD,SAAS,EAAE,OAAO,SAAS,KAAK,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI;SAC5D,CAAC;QACF,OAAO,CAAC,IAAI,CAAC,CAAC;IAChB,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { ensureContainerTables } from \"../../../data/persistence/container-contents/containerPersistence\";\nimport { sqlDocumentsPersistence } from \"../../../data/persistence/documents/documentsPersistence\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { emptyContentFrontierSql } from \"./hydrationSql\";\n\nexport interface PendingDownloadQueueItem {\n localId: string;\n documentId: string;\n objectKind: \"document\" | \"container\";\n /** Null until content supplies a reliable title and type. */\n title: string | null;\n reason: \"initial\" | \"continuation\";\n lastError: string | null;\n}\n\n/** Durable, already-discovered content pulls, including folder metadata. */\nexport async function listPendingDownloads(\n execSql: ExecSql,\n): Promise<ReadonlyArray<PendingDownloadQueueItem>> {\n await ensureContainerTables(execSql);\n await sqlDocumentsPersistence.ensureSchema(execSql);\n const rows = await execSql(`\n SELECT stored.local_id, stored.document_id, stored.app_kind,\n CASE WHEN ${emptyContentFrontierSql(\"stored\")} THEN NULL\n WHEN stored.app_kind = 'documents' THEN d.title\n ELSE folder.display_name END AS title,\n CASE WHEN ${emptyContentFrontierSql(\"stored\")} THEN 'initial'\n ELSE 'continuation' END AS reason,\n stored.sync_failure_message AS last_error\n FROM documents stored\n LEFT JOIN document_projection d ON stored.app_kind = 'documents'\n AND d.local_id = stored.local_id\n LEFT JOIN containers folder ON stored.app_kind = 'container-metadata'\n AND folder.id = stored.local_id\n WHERE stored.document_id IS NOT NULL\n AND (${emptyContentFrontierSql(\"stored\")} OR stored.pull_continuation IS NOT NULL)\n AND ((stored.app_kind = 'documents' AND d.local_id IS NOT NULL)\n OR (stored.app_kind = 'container-metadata' AND folder.id IS NOT NULL))\n ORDER BY stored.updated_at, stored.app_kind, stored.local_id\n `);\n return rows.flatMap((row) => {\n const {\n local_id: localId,\n document_id: documentId,\n app_kind: appKind,\n title,\n reason,\n last_error: lastError,\n } = row;\n if (typeof localId !== \"string\" || typeof documentId !== \"string\")\n return [];\n const item: PendingDownloadQueueItem = {\n localId,\n documentId,\n objectKind: appKind === \"documents\" ? \"document\" : \"container\",\n title: typeof title === \"string\" ? title : null,\n reason: reason === \"initial\" ? \"initial\" : \"continuation\",\n lastError: typeof lastError === \"string\" ? lastError : null,\n };\n return [item];\n });\n}\n"]}
1
+ {"version":3,"file":"pendingDownloads.js","sourceRoot":"","sources":["pendingDownloads.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,mEAAmE,CAAC;AAC1G,OAAO,EA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CAAC,CAAC;AACL,CAAC","sourcesContent":["import { ensureContainerTables } from \"../../../data/persistence/container-contents/containerPersistence\";\nimport { sqlDocumentsPersistence } from \"../../../data/persistence/documents/documentsPersistence\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { emptyContentFrontierSql } from \"./hydrationSql\";\n\ninterface PendingContentDownload {\n localId: string;\n documentId: string;\n objectKind: \"document\" | \"container\";\n /** Null until content supplies a reliable title and type. */\n title: string | null;\n reason: \"initial\" | \"continuation\";\n lastError: string | null;\n}\n\n/**\n * The first download of a file a synced document records for a slot. The row\n * carries the identity hydration fetches with: the slot and the stored\n * record's document id.\n */\ninterface PendingAttachmentDownload {\n localId: string;\n documentId: string;\n objectKind: \"attachment\";\n /** The owning document's projected title. */\n title: string;\n reason: \"initial\";\n lastError: string | null;\n slotId: string;\n fileName: string;\n}\n\nexport type PendingDownloadQueueItem =\n | PendingContentDownload\n | PendingAttachmentDownload;\n\n/**\n * Durable, already-discovered content pulls, including folder metadata, then\n * the first downloads of files recorded by synced documents.\n */\nexport async function listPendingDownloads(\n execSql: ExecSql,\n): Promise<ReadonlyArray<PendingDownloadQueueItem>> {\n await ensureContainerTables(execSql);\n await sqlDocumentsPersistence.ensureSchema(execSql);\n const contentDownloads = await listPendingContentDownloads(execSql);\n const attachmentDownloads = await listPendingAttachmentDownloads(execSql);\n return [...contentDownloads, ...attachmentDownloads];\n}\n\nasync function listPendingContentDownloads(\n execSql: ExecSql,\n): Promise<ReadonlyArray<PendingContentDownload>> {\n const rows = await execSql(`\n SELECT stored.local_id, stored.document_id, stored.app_kind,\n CASE WHEN ${emptyContentFrontierSql(\"stored\")} THEN NULL\n WHEN stored.app_kind = 'documents' THEN d.title\n ELSE folder.display_name END AS title,\n CASE WHEN ${emptyContentFrontierSql(\"stored\")} THEN 'initial'\n ELSE 'continuation' END AS reason,\n stored.sync_failure_message AS last_error\n FROM documents stored\n LEFT JOIN document_projection d ON stored.app_kind = 'documents'\n AND d.local_id = stored.local_id\n LEFT JOIN containers folder ON stored.app_kind = 'container-metadata'\n AND folder.id = stored.local_id\n WHERE stored.document_id IS NOT NULL\n AND (${emptyContentFrontierSql(\"stored\")} OR stored.pull_continuation IS NOT NULL)\n AND ((stored.app_kind = 'documents' AND d.local_id IS NOT NULL)\n OR (stored.app_kind = 'container-metadata' AND folder.id IS NOT NULL))\n ORDER BY stored.updated_at, stored.app_kind, stored.local_id\n `);\n return rows.flatMap((row) => {\n const {\n local_id: localId,\n document_id: documentId,\n app_kind: appKind,\n title,\n reason,\n last_error: lastError,\n } = row;\n if (typeof localId !== \"string\" || typeof documentId !== \"string\")\n return [];\n const item: PendingContentDownload = {\n localId,\n documentId,\n objectKind: appKind === \"documents\" ? \"document\" : \"container\",\n title: typeof title === \"string\" ? title : null,\n reason: reason === \"initial\" ? \"initial\" : \"continuation\",\n lastError: typeof lastError === \"string\" ? lastError : null,\n };\n return [item];\n });\n}\n\n// `attachment_names` keys each slot recorded by the content as\n// `<contentSha256>:<slotId>`; the hex digest never contains a colon, while a\n// collection slot id (`photos:<uuid>`) can. Any local row for the slot, held\n// or awaiting a remote detach, means this is no longer a first download, and a\n// pending upload is this device's own file.\nasync function listPendingAttachmentDownloads(\n execSql: ExecSql,\n): Promise<ReadonlyArray<PendingAttachmentDownload>> {\n const rows = await execSql(`\n SELECT stored.local_id, stored.document_id, d.title,\n stored.sync_failure_message AS last_error,\n substr(recorded.key, instr(recorded.key, ':') + 1) AS slot_id,\n json_extract(recorded.value, '$.name') AS file_name\n FROM documents stored\n JOIN document_projection d ON d.local_id = stored.local_id\n JOIN document_projection_text projected\n ON projected.local_id = stored.local_id\n JOIN json_each(projected.attachment_names) recorded\n WHERE stored.app_kind = 'documents'\n AND stored.document_id IS NOT NULL\n AND NOT ${emptyContentFrontierSql(\"stored\")}\n AND projected.attachment_names IS NOT NULL\n AND NOT EXISTS (\n SELECT 1 FROM document_attachment_blob_projection held\n WHERE held.local_id = stored.local_id\n AND held.slot_id = substr(recorded.key, instr(recorded.key, ':') + 1)\n )\n AND NOT EXISTS (\n SELECT 1 FROM document_pending_attachments upload\n WHERE upload.local_id = stored.local_id\n AND upload.slot_id = substr(recorded.key, instr(recorded.key, ':') + 1)\n )\n ORDER BY stored.updated_at, stored.local_id, slot_id\n `);\n return rows.flatMap((row) => {\n const {\n local_id: localId,\n document_id: documentId,\n title,\n last_error: lastError,\n slot_id: slotId,\n file_name: fileName,\n } = row;\n if (\n typeof localId !== \"string\" ||\n typeof documentId !== \"string\" ||\n typeof title !== \"string\" ||\n typeof slotId !== \"string\" ||\n slotId.length === 0 ||\n typeof fileName !== \"string\"\n )\n return [];\n const item: PendingAttachmentDownload = {\n localId,\n documentId,\n objectKind: \"attachment\",\n title,\n reason: \"initial\",\n lastError: typeof lastError === \"string\" ? lastError : null,\n slotId,\n fileName,\n };\n return [item];\n });\n}\n"]}