@tearleads/client-sdk 0.1.256 → 0.1.257

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/client/documents/index.d.ts +5 -2
  2. package/client/documents/index.js +6 -1
  3. package/client/documents/index.js.map +1 -1
  4. package/client/index.d.ts +1 -1
  5. package/client/index.js.map +1 -1
  6. package/data/blobs/attachments/types.d.ts +4 -2
  7. package/data/blobs/attachments/types.js.map +1 -1
  8. package/data/documents/documentContent.d.ts +2 -0
  9. package/data/documents/documentContent.js +7 -0
  10. package/data/documents/documentContent.js.map +1 -1
  11. package/data/documents/shared/manifestBundleReaders.js +1 -1
  12. package/data/documents/shared/manifestBundleReaders.js.map +1 -1
  13. package/data/documents/shared/projection/documentCreateSigner.d.ts +19 -0
  14. package/data/documents/shared/projection/documentCreateSigner.js +49 -0
  15. package/data/documents/shared/projection/documentCreateSigner.js.map +1 -0
  16. package/data/documents/shared/projection/index.d.ts +1 -0
  17. package/data/documents/shared/projection/index.js +1 -0
  18. package/data/documents/shared/projection/index.js.map +1 -1
  19. package/data/documents/shared/readers.js +1 -1
  20. package/data/documents/shared/readers.js.map +1 -1
  21. package/data/documents/shared/types.d.ts +1 -0
  22. package/data/documents/shared/types.js.map +1 -1
  23. package/data/persistence/documents/documentsPersistence.d.ts +1 -1
  24. package/data/persistence/documents/documentsPersistence.js +4 -1
  25. package/data/persistence/documents/documentsPersistence.js.map +1 -1
  26. package/index.d.ts +3 -3
  27. package/index.js +2 -2
  28. package/index.js.map +1 -1
  29. package/internal/api-client/ApiClient.d.ts +2 -2
  30. package/internal/api-client/apiRequestRuntime.js +12 -8
  31. package/internal/api-client/apiRequestRuntime.js.map +1 -1
  32. package/internal/api-client/binaryResponseOperationTransport.js +2 -2
  33. package/internal/api-client/binaryResponseOperationTransport.js.map +1 -1
  34. package/internal/api-client/client/blobs.d.ts +2 -2
  35. package/internal/api-client/client/blobs.js +21 -9
  36. package/internal/api-client/client/blobs.js.map +1 -1
  37. package/internal/api-client/client/writerProjections.js +2 -1
  38. package/internal/api-client/client/writerProjections.js.map +1 -1
  39. package/internal/api-client/operationResponse.js +3 -3
  40. package/internal/api-client/operationResponse.js.map +1 -1
  41. package/internal/api-client/routes/blobs/multipartUpload.js +10 -3
  42. package/internal/api-client/routes/blobs/multipartUpload.js.map +1 -1
  43. package/internal/api-client/sessionRefresh.js +6 -1
  44. package/internal/api-client/sessionRefresh.js.map +1 -1
  45. package/internal/api-client/sessionResponse.js +5 -2
  46. package/internal/api-client/sessionResponse.js.map +1 -1
  47. package/internal/api-client/types.d.ts +2 -0
  48. package/internal/api-client/types.js.map +1 -1
  49. package/package.json +1 -1
  50. package/stores/documents/documentStore/initialization/createSeededDocument.d.ts +16 -0
  51. package/stores/documents/documentStore/initialization/createSeededDocument.js +119 -0
  52. package/stores/documents/documentStore/initialization/createSeededDocument.js.map +1 -0
  53. package/stores/documents/documentStore/initialization/initialContent.js.map +1 -1
  54. package/stores/documents/documentStore/rows/rowAttribution.js.map +1 -1
  55. package/stores/documents/documentStore/state.js +3 -1
  56. package/stores/documents/documentStore/state.js.map +1 -1
  57. package/stores/documents/documentStore/sync/syncShared.js +3 -2
  58. package/stores/documents/documentStore/sync/syncShared.js.map +1 -1
  59. package/stores/documents/index.d.ts +1 -0
  60. package/stores/documents/index.js +1 -0
  61. package/stores/documents/index.js.map +1 -1
  62. package/stores/documents/types.d.ts +1 -0
  63. package/stores/documents/types.js.map +1 -1
  64. package/workflows/blobs/upload/index.d.ts +1 -1
  65. package/workflows/blobs/upload/index.js +36 -18
  66. package/workflows/blobs/upload/index.js.map +1 -1
  67. package/workflows/blobs/upload/multipartStageResolution.js +12 -2
  68. package/workflows/blobs/upload/multipartStageResolution.js.map +1 -1
  69. package/workflows/blobs/upload/multipartUpload.js +10 -2
  70. package/workflows/blobs/upload/multipartUpload.js.map +1 -1
  71. package/workflows/container-contents/documentDiscovery/documentDiscoveryTypes.d.ts +160 -0
  72. package/workflows/container-contents/documentQueries/index.d.ts +1 -1
  73. package/workflows/container-contents/documentQueries/index.js +2 -2
  74. package/workflows/container-contents/documentQueries/index.js.map +1 -1
  75. package/workflows/container-contents/index.d.ts +1 -0
  76. package/workflows/container-contents/index.js +1 -0
  77. package/workflows/container-contents/index.js.map +1 -1
  78. package/workflows/container-contents/tombstones/documentTombstoneEvidence.d.ts +42 -0
  79. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js +41 -17
  80. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js.map +1 -1
  81. package/workflows/documents/create/createAdoption.js +2 -50
  82. package/workflows/documents/create/createAdoption.js.map +1 -1
  83. package/workflows/documents/create/createResponse.js +12 -1
  84. package/workflows/documents/create/createResponse.js.map +1 -1
  85. package/workflows/documents/create/createSubmission.js +14 -0
  86. package/workflows/documents/create/createSubmission.js.map +1 -0
  87. package/workflows/documents/create/index.d.ts +3 -14
  88. package/workflows/documents/create/index.js +76 -67
  89. package/workflows/documents/create/index.js.map +1 -1
  90. package/workflows/documents/create/remoteDocumentCreateRequest.d.ts +16 -15
  91. package/workflows/documents/create/remoteDocumentCreateRequest.js.map +1 -1
  92. package/workflows/documents/purge/absentDocumentPurge.d.ts +3 -0
  93. package/workflows/documents/purge/absentDocumentPurge.js +23 -0
  94. package/workflows/documents/purge/absentDocumentPurge.js.map +1 -0
  95. package/workflows/documents/purge/index.d.ts +1 -0
  96. package/workflows/documents/purge/index.js +1 -0
  97. package/workflows/documents/purge/index.js.map +1 -1
  98. package/workflows/documents/remote/remoteDocumentService.d.ts +2 -2
  99. package/workflows/documents/remote/remoteDocumentService.js.map +1 -1
@@ -1,6 +1,7 @@
1
1
  import type { StoredDocumentKind } from "../../data/documents/documentKinds.js";
2
+ import type { DiscoveredDocumentInput } from "../../data/documents/documentSummary.js";
2
3
  import type { DocumentSummaryList, DocumentSummarySort, DocumentSummarySortDirection, DocumentSummarySortKey, ListDocumentSummariesInput } from "../../data/persistence/documents/types.js";
3
- import { DEFAULT_DOCUMENT_ID as DEFAULT_LOCAL_DOCUMENT_ID, type DocumentStore, type DocumentStoreOpenOptions, type DocumentsRuntime, type PersistedDocumentListener } from "../../stores/documents/index.js";
4
+ import { DEFAULT_DOCUMENT_ID as DEFAULT_LOCAL_DOCUMENT_ID, type DocumentStore, type DocumentStoreOpenOptions, type DocumentsRuntime, type PersistedDocumentListener, type SeededDocumentInput } from "../../stores/documents/index.js";
4
5
  import { type DocumentHistory } from "../../workflows/documents/index.js";
5
6
  import type { InternalRuntime } from "../runtime/workflowRuntime.js";
6
7
  export type { DocumentAttachmentStatus, DocumentAttachmentUpload, DocumentContextValue, DocumentStore, DocumentsRuntime, PersistedDocumentListener, } from "../../stores/documents/index.js";
@@ -11,7 +12,7 @@ export type DocumentSort = DocumentSummarySort;
11
12
  export interface ListDocumentsInput extends ListDocumentSummariesInput {
12
13
  }
13
14
  export type DocumentList = DocumentSummaryList;
14
- export { DEFAULT_LOCAL_DOCUMENT_ID as DEFAULT_DOCUMENT_ID };
15
+ export type { SeededDocumentInput } from "../../stores/documents/index.js";
15
16
  export interface OpenDocumentInput {
16
17
  readonly containerId?: string | null | undefined;
17
18
  readonly documentId?: string | null | undefined;
@@ -22,6 +23,7 @@ export interface OpenDocumentInput {
22
23
  readonly initialText?: string | undefined;
23
24
  readonly localId?: string | undefined;
24
25
  }
26
+ export { DEFAULT_LOCAL_DOCUMENT_ID as DEFAULT_DOCUMENT_ID };
25
27
  export interface OpenDocumentOptions {
26
28
  readonly remoteSyncMode?: "on-demand" | "startup" | undefined;
27
29
  readonly workflowRuntime?: DocumentsRuntime | undefined;
@@ -30,6 +32,7 @@ export interface DocumentSubscriptionOptions {
30
32
  readonly containerId?: string | null | undefined;
31
33
  }
32
34
  export interface Documents {
35
+ createSeeded(input: SeededDocumentInput): Promise<DiscoveredDocumentInput | "purged">;
33
36
  delete(localId: string): Promise<boolean>;
34
37
  findLocalIdByDocumentId(documentId: string): Promise<string | null>;
35
38
  list(input?: ListDocumentsInput | undefined): Promise<DocumentList | null>;
@@ -1,5 +1,5 @@
1
1
  import { DEFAULT_DOCUMENT_KIND } from "../../data/documents/documentConstants.js";
2
- import { 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, 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 };
@@ -12,6 +12,11 @@ class DocumentsService {
12
12
  constructor(dependencies) {
13
13
  this.dependencies = dependencies;
14
14
  }
15
+ createSeeded(input) {
16
+ const { runtime } = this.dependencies;
17
+ const generation = runtime.scopeGeneration;
18
+ return createSeededDocument(this.workflowRuntime(input.containerId), input, () => runtime.scopeGeneration === generation);
19
+ }
15
20
  async delete(localId) {
16
21
  const runtime = this.workflowRuntime();
17
22
  if (runtime.infra.dbStatus !== "ready") {
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,wCAAwC,CAAC;AAU/E,OAAO,EACL,mBAAmB,IAAI,yBAAyB,EAIhD,iBAAiB,EAEjB,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;AAgCnC,OAAO,EAAE,y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AC;CACF","sourcesContent":["import { DEFAULT_DOCUMENT_KIND } from \"../../data/documents/documentConstants\";\nimport type { StoredDocumentKind } from \"../../data/documents/documentKinds\";\nimport type {\n DocumentSummaryList,\n DocumentSummarySort,\n DocumentSummarySortDirection,\n DocumentSummarySortKey,\n ListDocumentSummariesInput,\n} from \"../../data/persistence/documents/types\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport {\n DEFAULT_DOCUMENT_ID as DEFAULT_LOCAL_DOCUMENT_ID,\n type DocumentStore,\n type DocumentStoreOpenOptions,\n type DocumentsRuntime,\n openDocumentStore,\n type PersistedDocumentListener,\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 { DEFAULT_LOCAL_DOCUMENT_ID as DEFAULT_DOCUMENT_ID };\n\nexport interface OpenDocumentInput {\n readonly containerId?: string | null | undefined;\n readonly documentId?: string | null | undefined;\n readonly initialDocumentKind?: StoredDocumentKind | undefined;\n /** 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}\n\nexport interface OpenDocumentOptions {\n readonly remoteSyncMode?: \"on-demand\" | \"startup\" | undefined;\n readonly workflowRuntime?: DocumentsRuntime | undefined;\n}\n\nexport interface DocumentSubscriptionOptions {\n readonly containerId?: string | null | undefined;\n}\n\nexport interface Documents {\n delete(localId: string): Promise<boolean>;\n findLocalIdByDocumentId(documentId: string): Promise<string | null>;\n list(input?: ListDocumentsInput | undefined): Promise<DocumentList | null>;\n open(\n input?: OpenDocumentInput | undefined,\n options?: OpenDocumentOptions | undefined,\n ): DocumentStore;\n /**\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 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,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,o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AAI,CAAC,eAAe,EAAE,CAAC;QACvC,IAAI,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"]}
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, } 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, 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;AA+B7E,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} 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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AM,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"]}
@@ -12,6 +12,7 @@ export declare const BLOB_CONTENT_RECORD_NONCE_DOMAIN = "tearleads.blob.content-
12
12
  export declare const BLOB_CONTENT_RECORD_HKDF_SALT: Uint8Array<ArrayBuffer>;
13
13
  export declare const TEXT_ENCODER: TextEncoder;
14
14
  export interface BlobAttachmentRequestOptions {
15
+ readonly stillCurrent?: (() => boolean) | undefined;
15
16
  readonly expectedPaymentRequiredOrganizationId?: string | undefined;
16
17
  }
17
18
  export interface BlobAttachmentApi {
@@ -28,8 +29,8 @@ export interface BlobAttachmentApi {
28
29
  readonly status: number | null;
29
30
  } | null;
30
31
  getDocumentWriterProjection(documentId: string): Promise<DocumentWriterProjectionResponse | null>;
31
- getMultipartBlobStage(stageId: string): Promise<MultipartBlobStageStatusResponse | null>;
32
- initiateMultipartBlobStage(input: InitiateMultipartBlobStageRequest): Promise<InitiateMultipartBlobStageResponse | null>;
32
+ getMultipartBlobStage(stageId: string, options?: RequestResultOptions): Promise<MultipartBlobStageStatusResponse | null>;
33
+ initiateMultipartBlobStage(input: InitiateMultipartBlobStageRequest, options?: RequestResultOptions): Promise<InitiateMultipartBlobStageResponse | null>;
33
34
  uploadMultipartBlobPartBytes(stageId: string, partNumber: number, input: UploadMultipartBlobPartBytesRequest, options?: RequestResultOptions): Promise<UploadMultipartBlobPartResponse | null>;
34
35
  }
35
36
  export interface BlobAttachmentDetachApi {
@@ -130,6 +131,7 @@ export interface UploadDocumentAttachmentRequest {
130
131
  resolveProjectionUserKey: ProjectionUserKeyResolver;
131
132
  signedAt?: string | undefined;
132
133
  slotId: string;
134
+ stillCurrent?: (() => boolean) | undefined;
133
135
  warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;
134
136
  writerProjection?: DocumentWriterProjectionResponse | undefined;
135
137
  }
@@ -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 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 ): Promise<MultipartBlobStageStatusResponse | null>;\n initiateMultipartBlobStage(\n input: InitiateMultipartBlobStageRequest,\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 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 ): 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"]}
@@ -7,6 +7,8 @@ export interface DocumentAttachment {
7
7
  mimeType: string | null;
8
8
  }
9
9
  type StructuredDocumentShape = Pick<FullStructuredDocumentShape, "getMap">;
10
+ export declare function readSeedTag(doc: StructuredDocumentShape): string | undefined;
11
+ export declare function writeSeedTag(doc: StructuredDocumentShape, tag: string): void;
10
12
  export declare function ensureDocumentAttachmentStructure(doc: StructuredDocumentShape): void;
11
13
  export declare function getDocumentAttachments(doc: StructuredDocumentShape): DocumentAttachment[];
12
14
  export declare function addDocumentAttachments(doc: StructuredDocumentShape, attachments: ReadonlyArray<DocumentAttachment>): void;
@@ -2,6 +2,13 @@ import { compareCanonicalStrings } from "../../internal/crypto/index.js";
2
2
  import { LoroMap } from "../../internal/loro/index.js";
3
3
  const DOCUMENT_CONTENT_MAP_KEY = "content";
4
4
  const ATTACHMENT_KEY_PREFIX = "attachment:";
5
+ export function readSeedTag(doc) {
6
+ const value = doc.getMap(DOCUMENT_CONTENT_MAP_KEY).get("seedTag");
7
+ return typeof value === "string" ? value : undefined;
8
+ }
9
+ export function writeSeedTag(doc, tag) {
10
+ doc.getMap(DOCUMENT_CONTENT_MAP_KEY).set("seedTag", tag);
11
+ }
5
12
  function isStructuredAttachmentMap(value) {
6
13
  return (typeof value === "object" &&
7
14
  value !== null &&
@@ -1 +1 @@
1
- {"version":3,"file":"documentContent.js","sourceRoot":"","sources":["documentContent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAkB1C,MAAM,wBAAwB,GAAG,SAAS,CAAC;AAC3C,MAAM,qBAAqB,GAAG,aAAa,CAAC;AAE5C,SAAS,yBAAyB,CAChC,KAAc;IAEd,OAAO,CACL,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK,KAAK,IAAI;QACd,SAAS,IAAI,KAAK;QAClB,OAAO,KAAK,CAAC,OAAO,KAAK,UAAU;QACnC,KAAK,IAAI,KAAK;QACd,OAAO,KAAK,CAAC,GAAG,KAAK,UAAU;QAC/B,KAAK,IAAI,KAAK;QACd,OAAO,KAAK,CAAC,GAAG,KAAK,UAAU;QAC/B,QAAQ,IAAI,KAAK;QACjB,OAAO,KAAK,CAAC,MAAM,KAAK,UAAU,CACnC,CAAC;AACJ,CAAC;AAED,SAAS,yBAAyB,CAChC,MAAc,EACd,KAAc;IAEd,IAAI,CAAC,yBAAyB,CAAC,KAAK,CAAC,EAAE,CAAC;QACtC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,aAAa,GAAG,KAAK,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC;IACjD,MAAM,IAAI,GAAG,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IAC/B,MAAM,UAAU,GAAG,KAAK,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC;IAC3C,MAAM,QAAQ,GAAG,KAAK,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IACvC,MAAM,KAAK,GAAG,KAAK,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IAEjC,IACE,OAAO,aAAa,KAAK,QAAQ;QACjC,CAAC,gBAAgB,CAAC,IAAI,CAAC,aAAa,CAAC;QAC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E,KAAK,EAAE,EAAE;YAC/B,MAAM,cAAc,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC;YACpC,OAAO,CACL,cAAc,KAAK,SAAS;gBAC5B,UAAU,CAAC,MAAM,KAAK,cAAc,CAAC,MAAM;gBAC3C,UAAU,CAAC,aAAa,KAAK,cAAc,CAAC,aAAa;gBACzD,UAAU,CAAC,IAAI,KAAK,cAAc,CAAC,IAAI;gBACvC,UAAU,CAAC,UAAU,KAAK,cAAc,CAAC,UAAU;gBACnD,UAAU,CAAC,QAAQ,KAAK,cAAc,CAAC,QAAQ,CAChD,CAAC;QACJ,CAAC,CAAC,CACH,CAAC;AACJ,CAAC","sourcesContent":["import { compareCanonicalStrings } from \"@tearleads/crypto\";\nimport { LoroMap } from \"@tearleads/loro\";\nimport type {\n StructuredDocumentShape as FullStructuredDocumentShape,\n StructuredDocumentMap,\n} from \"./documentKinds\";\n\nexport interface DocumentAttachment {\n contentSha256: string;\n slotId: string;\n name: string;\n byteLength: number;\n mimeType: string | null;\n}\n\n// Attachment helpers only read/write maps, so callers may pass any shape that\n// provides `getMap` (a full structured document included).\ntype StructuredDocumentShape = Pick<FullStructuredDocumentShape, \"getMap\">;\n\nconst DOCUMENT_CONTENT_MAP_KEY = \"content\";\nconst ATTACHMENT_KEY_PREFIX = \"attachment:\";\n\nfunction isStructuredAttachmentMap(\n value: unknown,\n): value is StructuredDocumentMap {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"entries\" in value &&\n typeof value.entries === \"function\" &&\n \"get\" in value &&\n typeof value.get === \"function\" &&\n \"set\" in value &&\n typeof value.set === \"function\" &&\n \"delete\" in value &&\n typeof value.delete === \"function\"\n );\n}\n\nfunction parseStructuredAttachment(\n slotId: string,\n value: unknown,\n): (DocumentAttachment & { order: number | null }) | null {\n if (!isStructuredAttachmentMap(value)) {\n return null;\n }\n\n const contentSha256 = value.get(\"contentSha256\");\n const name = value.get(\"name\");\n const byteLength = value.get(\"byteLength\");\n const mimeType = value.get(\"mimeType\");\n const order = value.get(\"order\");\n\n if (\n typeof contentSha256 !== \"string\" ||\n !/^[0-9a-f]{64}$/.test(contentSha256) ||\n typeof name !== \"string\" ||\n name.length === 0 ||\n typeof byteLength !== \"number\" ||\n !Number.isInteger(byteLength) ||\n byteLength < 0 ||\n !(\n mimeType === undefined ||\n mimeType === null ||\n typeof mimeType === \"string\"\n )\n ) {\n return null;\n }\n\n return {\n contentSha256,\n byteLength,\n mimeType: mimeType ?? null,\n name,\n order: typeof order === \"number\" && Number.isFinite(order) ? order : null,\n slotId,\n };\n}\n\nexport function ensureDocumentAttachmentStructure(\n doc: StructuredDocumentShape,\n): void {\n doc.getMap(DOCUMENT_CONTENT_MAP_KEY);\n}\n\nfunction getAttachmentMapKey(slotId: string): string {\n return `${ATTACHMENT_KEY_PREFIX}${slotId}`;\n}\n\nfunction listStructuredDocumentAttachments(\n doc: StructuredDocumentShape,\n): Array<DocumentAttachment & { order: number | null }> {\n const documentMap = doc.getMap(DOCUMENT_CONTENT_MAP_KEY);\n return documentMap\n .entries()\n .flatMap(([key, value]) => {\n if (!key.startsWith(ATTACHMENT_KEY_PREFIX)) {\n return [];\n }\n\n const attachment = parseStructuredAttachment(\n key.slice(ATTACHMENT_KEY_PREFIX.length),\n value,\n );\n return attachment ? [attachment] : [];\n })\n .sort((left, right) => {\n if (left.order !== right.order) {\n if (left.order === null) {\n return 1;\n }\n\n if (right.order === null) {\n return -1;\n }\n\n return left.order - right.order;\n }\n\n return compareCanonicalStrings(left.slotId, right.slotId);\n });\n}\n\nfunction getStructuredDocumentAttachments(\n doc: StructuredDocumentShape,\n): DocumentAttachment[] {\n return listStructuredDocumentAttachments(doc).map(\n ({ order: _order, ...attachment }) => attachment,\n );\n}\n\nexport function getDocumentAttachments(\n doc: StructuredDocumentShape,\n): DocumentAttachment[] {\n return getStructuredDocumentAttachments(doc);\n}\n\nexport function addDocumentAttachments(\n doc: StructuredDocumentShape,\n attachments: ReadonlyArray<DocumentAttachment>,\n): void {\n if (attachments.length === 0) {\n return;\n }\n\n const documentMap = doc.getMap(DOCUMENT_CONTENT_MAP_KEY);\n const existingAttachments = listStructuredDocumentAttachments(doc);\n let nextOrder =\n existingAttachments.reduce((highestOrder, attachment, index) => {\n return Math.max(highestOrder, attachment.order ?? index);\n }, -1) + 1;\n\n for (const attachment of attachments) {\n const attachmentMap = documentMap.getOrCreateContainer(\n getAttachmentMapKey(attachment.slotId),\n new LoroMap(),\n );\n attachmentMap.set(\"contentSha256\", attachment.contentSha256);\n attachmentMap.set(\"name\", attachment.name);\n attachmentMap.set(\"byteLength\", attachment.byteLength);\n if (attachment.mimeType === null) {\n attachmentMap.delete(\"mimeType\");\n } else {\n attachmentMap.set(\"mimeType\", attachment.mimeType);\n }\n if (attachmentMap.get(\"order\") === undefined) {\n attachmentMap.set(\"order\", nextOrder);\n nextOrder += 1;\n }\n }\n}\n\nexport function removeDocumentAttachment(\n doc: StructuredDocumentShape,\n slotId: string,\n): void {\n doc.getMap(DOCUMENT_CONTENT_MAP_KEY).delete(getAttachmentMapKey(slotId));\n}\n\nexport function sameDocumentAttachments(\n left: ReadonlyArray<DocumentAttachment>,\n right: ReadonlyArray<DocumentAttachment>,\n): boolean {\n return (\n left.length === right.length &&\n left.every((attachment, index) => {\n const nextAttachment = right[index];\n return (\n nextAttachment !== undefined &&\n attachment.slotId === nextAttachment.slotId &&\n attachment.contentSha256 === nextAttachment.contentSha256 &&\n attachment.name === nextAttachment.name &&\n attachment.byteLength === nextAttachment.byteLength &&\n attachment.mimeType === nextAttachment.mimeType\n );\n })\n );\n}\n"]}
1
+ {"version":3,"file":"documentContent.js","sourceRoot":"","sources":["documentContent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAkB1C,MAAM,wBAAwB,GAAG,SAAS,CAAC;AAC3C,MAAM,qBAAqB,GAAG,aAAa,CAAC;AA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ExC,OAAO,CACL,IAAI,CAAC,MAAM,KAAK,KAAK,CAAC,MAAM;QAC5B,IAAI,CAAC,KAAK,CAAC,CAAC,UAAU,EAAE,KAAK,EAAE,EAAE;YAC/B,MAAM,cAAc,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC;YACpC,OAAO,CACL,cAAc,KAAK,SAAS;gBAC5B,UAAU,CAAC,MAAM,KAAK,cAAc,CAAC,MAAM;gBAC3C,UAAU,CAAC,aAAa,KAAK,cAAc,CAAC,aAAa;gBACzD,UAAU,CAAC,IAAI,KAAK,cAAc,CAAC,IAAI;gBACvC,UAAU,CAAC,UAAU,KAAK,cAAc,CAAC,UAAU;gBACnD,UAAU,CAAC,QAAQ,KAAK,cAAc,CAAC,QAAQ,CAChD,CAAC;QACJ,CAAC,CAAC,CACH,CAAC;AACJ,CAAC","sourcesContent":["import { compareCanonicalStrings } from \"@tearleads/crypto\";\nimport { LoroMap } from \"@tearleads/loro\";\nimport type {\n StructuredDocumentShape as FullStructuredDocumentShape,\n StructuredDocumentMap,\n} from \"./documentKinds\";\n\nexport interface DocumentAttachment {\n contentSha256: string;\n slotId: string;\n name: string;\n byteLength: number;\n mimeType: string | null;\n}\n\n// Attachment helpers only read/write maps, so callers may pass any shape that\n// provides `getMap` (a full structured document included).\ntype StructuredDocumentShape = Pick<FullStructuredDocumentShape, \"getMap\">;\n\nconst DOCUMENT_CONTENT_MAP_KEY = \"content\";\nconst ATTACHMENT_KEY_PREFIX = \"attachment:\";\n\nexport function readSeedTag(doc: StructuredDocumentShape): string | undefined {\n const value = doc.getMap(DOCUMENT_CONTENT_MAP_KEY).get(\"seedTag\");\n return typeof value === \"string\" ? value : undefined;\n}\n\nexport function writeSeedTag(doc: StructuredDocumentShape, tag: string): void {\n doc.getMap(DOCUMENT_CONTENT_MAP_KEY).set(\"seedTag\", tag);\n}\n\nfunction isStructuredAttachmentMap(\n value: unknown,\n): value is StructuredDocumentMap {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"entries\" in value &&\n typeof value.entries === \"function\" &&\n \"get\" in value &&\n typeof value.get === \"function\" &&\n \"set\" in value &&\n typeof value.set === \"function\" &&\n \"delete\" in value &&\n typeof value.delete === \"function\"\n );\n}\n\nfunction parseStructuredAttachment(\n slotId: string,\n value: unknown,\n): (DocumentAttachment & { order: number | null }) | null {\n if (!isStructuredAttachmentMap(value)) {\n return null;\n }\n\n const contentSha256 = value.get(\"contentSha256\");\n const name = value.get(\"name\");\n const byteLength = value.get(\"byteLength\");\n const mimeType = value.get(\"mimeType\");\n const order = value.get(\"order\");\n\n if (\n typeof contentSha256 !== \"string\" ||\n !/^[0-9a-f]{64}$/.test(contentSha256) ||\n typeof name !== \"string\" ||\n name.length === 0 ||\n typeof byteLength !== \"number\" ||\n !Number.isInteger(byteLength) ||\n byteLength < 0 ||\n !(\n mimeType === undefined ||\n mimeType === null ||\n typeof mimeType === \"string\"\n )\n ) {\n return null;\n }\n\n return {\n contentSha256,\n byteLength,\n mimeType: mimeType ?? null,\n name,\n order: typeof order === \"number\" && Number.isFinite(order) ? order : null,\n slotId,\n };\n}\n\nexport function ensureDocumentAttachmentStructure(\n doc: StructuredDocumentShape,\n): void {\n doc.getMap(DOCUMENT_CONTENT_MAP_KEY);\n}\n\nfunction getAttachmentMapKey(slotId: string): string {\n return `${ATTACHMENT_KEY_PREFIX}${slotId}`;\n}\n\nfunction listStructuredDocumentAttachments(\n doc: StructuredDocumentShape,\n): Array<DocumentAttachment & { order: number | null }> {\n const documentMap = doc.getMap(DOCUMENT_CONTENT_MAP_KEY);\n return documentMap\n .entries()\n .flatMap(([key, value]) => {\n if (!key.startsWith(ATTACHMENT_KEY_PREFIX)) {\n return [];\n }\n\n const attachment = parseStructuredAttachment(\n key.slice(ATTACHMENT_KEY_PREFIX.length),\n value,\n );\n return attachment ? [attachment] : [];\n })\n .sort((left, right) => {\n if (left.order !== right.order) {\n if (left.order === null) {\n return 1;\n }\n\n if (right.order === null) {\n return -1;\n }\n\n return left.order - right.order;\n }\n\n return compareCanonicalStrings(left.slotId, right.slotId);\n });\n}\n\nfunction getStructuredDocumentAttachments(\n doc: StructuredDocumentShape,\n): DocumentAttachment[] {\n return listStructuredDocumentAttachments(doc).map(\n ({ order: _order, ...attachment }) => attachment,\n );\n}\n\nexport function getDocumentAttachments(\n doc: StructuredDocumentShape,\n): DocumentAttachment[] {\n return getStructuredDocumentAttachments(doc);\n}\n\nexport function addDocumentAttachments(\n doc: StructuredDocumentShape,\n attachments: ReadonlyArray<DocumentAttachment>,\n): void {\n if (attachments.length === 0) {\n return;\n }\n\n const documentMap = doc.getMap(DOCUMENT_CONTENT_MAP_KEY);\n const existingAttachments = listStructuredDocumentAttachments(doc);\n let nextOrder =\n existingAttachments.reduce((highestOrder, attachment, index) => {\n return Math.max(highestOrder, attachment.order ?? index);\n }, -1) + 1;\n\n for (const attachment of attachments) {\n const attachmentMap = documentMap.getOrCreateContainer(\n getAttachmentMapKey(attachment.slotId),\n new LoroMap(),\n );\n attachmentMap.set(\"contentSha256\", attachment.contentSha256);\n attachmentMap.set(\"name\", attachment.name);\n attachmentMap.set(\"byteLength\", attachment.byteLength);\n if (attachment.mimeType === null) {\n attachmentMap.delete(\"mimeType\");\n } else {\n attachmentMap.set(\"mimeType\", attachment.mimeType);\n }\n if (attachmentMap.get(\"order\") === undefined) {\n attachmentMap.set(\"order\", nextOrder);\n nextOrder += 1;\n }\n }\n}\n\nexport function removeDocumentAttachment(\n doc: StructuredDocumentShape,\n slotId: string,\n): void {\n doc.getMap(DOCUMENT_CONTENT_MAP_KEY).delete(getAttachmentMapKey(slotId));\n}\n\nexport function sameDocumentAttachments(\n left: ReadonlyArray<DocumentAttachment>,\n right: ReadonlyArray<DocumentAttachment>,\n): boolean {\n return (\n left.length === right.length &&\n left.every((attachment, index) => {\n const nextAttachment = right[index];\n return (\n nextAttachment !== undefined &&\n attachment.slotId === nextAttachment.slotId &&\n attachment.contentSha256 === nextAttachment.contentSha256 &&\n attachment.name === nextAttachment.name &&\n attachment.byteLength === nextAttachment.byteLength &&\n attachment.mimeType === nextAttachment.mimeType\n );\n })\n );\n}\n"]}
@@ -3,7 +3,7 @@ import { isPlainObject as isPlainRecord } from "../../../internal/validators/isP
3
3
  import { canonicalKeyingJsonString, readCanonicalRecord, } from "../../keying/canonicalJson.js";
4
4
  import { readAccessEvent, readAccessManifest, } from "../../keyingProjectionVerification/readers.js";
5
5
  import { readRecordInteger, readRecordNullableString, readRecordPositiveInteger, readRecordString, readRecordValue, readStringArray, } from "../../shared/recordReaders.js";
6
- function readDocumentLinkSetManifestState(value, label) {
6
+ export function readDocumentLinkSetManifestState(value, label) {
7
7
  const record = readCanonicalRecord(value, label);
8
8
  if (readRecordInteger(record, "version", label) !== 1) {
9
9
  throw new Error(`${label}.version must be 1`);
@@ -1 +1 @@
1
- {"version":3,"file":"manifestBundleReaders.js","sourceRoot":"","sources":["manifestBundleReaders.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,sBAAsB,EACtB,yBAAyB,EAEzB,6BAA6B,GAC9B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,IAAI,aAAa,EAAE,MAAM,qCAAqC,CAAC;AAErF,OAAO,EACL,yBAAyB,EACzB,mBAAmB,GACpB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,eAAe,EACf,kBAAkB,GACnB,MAAM,4CAA4C,CAAC;AACpD,OAAO,EACL,iBAAiB,EACjB,wBAAwB,EACxB,yBAAyB,EACzB,gBAAgB,EAChB,eAAe,EACf,eAAe,GAChB,MAAM,4BAA4B,CAAC;AAEpC,SAAS,gCAAgC,CACvC,KAAc,EACd,KAAa;IAEb,MAAM,MAAM,GAAG,mBAAmB,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;IACjD,IAAI,iBAAiB,CAAC,MAAM,EAAE,SAAS,EAAE,KAAK,CAAC,KAAK,CAAC,EAAE,CAAC;QACtD,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,oBAAoB,CAAC,CAAC;IACh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AAC;AACJ,CAAC","sourcesContent":["import {\n computeAccessEventHash,\n computeAccessManifestHash,\n type DocumentLinkSetManifestState,\n deriveDocumentLinkSetManifest,\n} from \"@tearleads/crypto\";\nimport { isPlainObject as isPlainRecord } from \"@tearleads/validators/isPlainObject\";\nimport type { AccessManifestBundleWireResponse } from \"@tearleads/validators/response\";\nimport {\n canonicalKeyingJsonString,\n readCanonicalRecord,\n} from \"../../keying/canonicalJson\";\nimport {\n readAccessEvent,\n readAccessManifest,\n} from \"../../keyingProjectionVerification/readers\";\nimport {\n readRecordInteger,\n readRecordNullableString,\n readRecordPositiveInteger,\n readRecordString,\n readRecordValue,\n readStringArray,\n} from \"../../shared/recordReaders\";\n\nfunction readDocumentLinkSetManifestState(\n value: unknown,\n label: string,\n): DocumentLinkSetManifestState {\n const record = readCanonicalRecord(value, label);\n if (readRecordInteger(record, \"version\", label) !== 1) {\n throw new Error(`${label}.version must be 1`);\n }\n\n return {\n version: 1,\n documentId: readRecordString(record, \"documentId\", label),\n organizationId: readRecordString(record, \"organizationId\", label),\n epoch: readRecordPositiveInteger(record, \"epoch\", label),\n previousManifestHash: readRecordNullableString(\n record,\n \"previousManifestHash\",\n label,\n ),\n eventHash: readRecordString(record, \"eventHash\", label),\n linkedContainerIds: readStringArray(\n readRecordValue(record, \"linkedContainerIds\"),\n `${label}.linkedContainerIds`,\n ),\n };\n}\n\nexport function serializeCanonical(value: unknown, label: string): string {\n if (\n value === undefined ||\n typeof value === \"function\" ||\n typeof value === \"symbol\"\n ) {\n throw new Error(`Document create response ${label} is invalid`);\n }\n\n return canonicalKeyingJsonString(value, `Document create response ${label}`);\n}\n\nexport async function assertDocumentManifestBundleConsistent(input: {\n bundle: AccessManifestBundleWireResponse;\n label: string;\n}): Promise<{ documentId: string; organizationId: string }> {\n const manifestHash = await computeAccessManifestHash(\n readAccessManifest(input.bundle.manifest, `${input.label} manifest`),\n );\n if (manifestHash !== input.bundle.manifestHash) {\n throw new Error(`${input.label} manifest hash mismatch`);\n }\n\n const eventBundle = input.bundle.event;\n if (!isPlainRecord(eventBundle)) {\n throw new Error(`${input.label} event bundle is invalid`);\n }\n const eventHash = readRecordString(eventBundle, \"eventHash\", input.label);\n const event = Reflect.get(eventBundle, \"event\");\n const accessEvent = readAccessEvent(event, `${input.label} signed event`);\n const computedEventHash = await computeAccessEventHash(accessEvent);\n if (computedEventHash !== eventHash) {\n throw new Error(`${input.label} event hash mismatch`);\n }\n\n const state = readDocumentLinkSetManifestState(\n input.bundle.state,\n `${input.label} state`,\n );\n if (state.eventHash !== eventHash) {\n throw new Error(`${input.label} state event hash mismatch`);\n }\n const derivedManifest = await deriveDocumentLinkSetManifest(state);\n if (\n serializeCanonical(input.bundle.manifest, \"manifest\") !==\n serializeCanonical(derivedManifest, \"manifest\")\n ) {\n throw new Error(`${input.label} manifest state mismatch`);\n }\n\n return {\n documentId: state.documentId,\n organizationId: state.organizationId,\n };\n}\n"]}
1
+ {"version":3,"file":"manifestBundleReaders.js","sourceRoot":"","sources":["manifestBundleReaders.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,sBAAsB,EACtB,yBAAyB,EAEzB,6BAA6B,GAC9B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,IAAI,aAAa,EAAE,MAAM,qCAAqC,CAAC;AAErF,OAAO,EACL,yBAAyB,EACzB,mBAAmB,GACpB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,eAAe,EACf,kBAAkB,GACnB,MAAM,4CAA4C,CAAC;AACpD,OAAO,EACL,iBAAiB,EACjB,wBAAwB,EACxB,yBAAyB,EACzB,gBAAgB,EAChB,eAAe,EACf,eAAe,GAChB,MAAM,4BAA4B,CAAC;AAEpC,MAAM,UAAU,gCAAgC,CAC9C,KAAc,EACd,KAAa;IAEb,MAAM,MAAM,GAAG,mBAAmB,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;IACjD,IAAI,iBAAiB,CAAC,MAAM,EAAE,SAAS,EAAE,KAAK,CAAC,K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AED,OAAO;QACL,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,cAAc,EAAE,KAAK,CAAC,cAAc;KACrC,CAAC;AACJ,CAAC","sourcesContent":["import {\n computeAccessEventHash,\n computeAccessManifestHash,\n type DocumentLinkSetManifestState,\n deriveDocumentLinkSetManifest,\n} from \"@tearleads/crypto\";\nimport { isPlainObject as isPlainRecord } from \"@tearleads/validators/isPlainObject\";\nimport type { AccessManifestBundleWireResponse } from \"@tearleads/validators/response\";\nimport {\n canonicalKeyingJsonString,\n readCanonicalRecord,\n} from \"../../keying/canonicalJson\";\nimport {\n readAccessEvent,\n readAccessManifest,\n} from \"../../keyingProjectionVerification/readers\";\nimport {\n readRecordInteger,\n readRecordNullableString,\n readRecordPositiveInteger,\n readRecordString,\n readRecordValue,\n readStringArray,\n} from \"../../shared/recordReaders\";\n\nexport function readDocumentLinkSetManifestState(\n value: unknown,\n label: string,\n): DocumentLinkSetManifestState {\n const record = readCanonicalRecord(value, label);\n if (readRecordInteger(record, \"version\", label) !== 1) {\n throw new Error(`${label}.version must be 1`);\n }\n\n return {\n version: 1,\n documentId: readRecordString(record, \"documentId\", label),\n organizationId: readRecordString(record, \"organizationId\", label),\n epoch: readRecordPositiveInteger(record, \"epoch\", label),\n previousManifestHash: readRecordNullableString(\n record,\n \"previousManifestHash\",\n label,\n ),\n eventHash: readRecordString(record, \"eventHash\", label),\n linkedContainerIds: readStringArray(\n readRecordValue(record, \"linkedContainerIds\"),\n `${label}.linkedContainerIds`,\n ),\n };\n}\n\nexport function serializeCanonical(value: unknown, label: string): string {\n if (\n value === undefined ||\n typeof value === \"function\" ||\n typeof value === \"symbol\"\n ) {\n throw new Error(`Document create response ${label} is invalid`);\n }\n\n return canonicalKeyingJsonString(value, `Document create response ${label}`);\n}\n\nexport async function assertDocumentManifestBundleConsistent(input: {\n bundle: AccessManifestBundleWireResponse;\n label: string;\n}): Promise<{ documentId: string; organizationId: string }> {\n const manifestHash = await computeAccessManifestHash(\n readAccessManifest(input.bundle.manifest, `${input.label} manifest`),\n );\n if (manifestHash !== input.bundle.manifestHash) {\n throw new Error(`${input.label} manifest hash mismatch`);\n }\n\n const eventBundle = input.bundle.event;\n if (!isPlainRecord(eventBundle)) {\n throw new Error(`${input.label} event bundle is invalid`);\n }\n const eventHash = readRecordString(eventBundle, \"eventHash\", input.label);\n const event = Reflect.get(eventBundle, \"event\");\n const accessEvent = readAccessEvent(event, `${input.label} signed event`);\n const computedEventHash = await computeAccessEventHash(accessEvent);\n if (computedEventHash !== eventHash) {\n throw new Error(`${input.label} event hash mismatch`);\n }\n\n const state = readDocumentLinkSetManifestState(\n input.bundle.state,\n `${input.label} state`,\n );\n if (state.eventHash !== eventHash) {\n throw new Error(`${input.label} state event hash mismatch`);\n }\n const derivedManifest = await deriveDocumentLinkSetManifest(state);\n if (\n serializeCanonical(input.bundle.manifest, \"manifest\") !==\n serializeCanonical(derivedManifest, \"manifest\")\n ) {\n throw new Error(`${input.label} manifest state mismatch`);\n }\n\n return {\n documentId: state.documentId,\n organizationId: state.organizationId,\n };\n}\n"]}
@@ -0,0 +1,19 @@
1
+ import type { DocumentWriterProjectionResponse } from "../../../../internal/validators/response/index.js";
2
+ /**
3
+ * A retry after a lost create response can only recover the local user's own
4
+ * create: the server serves whatever document holds the stable id we minted,
5
+ * and an honest server only ever committed ours under it. A create event signed
6
+ * by anyone else is a foreign document colliding on that id (a member with
7
+ * write access on the same container, or a dishonest server), which must not be
8
+ * adopted as if it were the pending local write.
9
+ *
10
+ * The create event is located by walking the served head's predecessor chain,
11
+ * not by scanning the history for any parentless manifest: the history is
12
+ * server-supplied, so a dishonest server could splice in a genesis this user
13
+ * signed for a different document. Every manifest on the chain must also name
14
+ * the requested document.
15
+ */
16
+ export declare function assertDocumentCreateSigner(input: {
17
+ documentId: string;
18
+ expectedSignerUserId: string;
19
+ }, writerProjection: DocumentWriterProjectionResponse): void;
@@ -0,0 +1,49 @@
1
+ import { KeyingVerificationError } from "../../../../internal/crypto/index.js";
2
+ import { readAccessEvent, readAccessManifest, } from "../../../keyingProjectionVerification/readers.js";
3
+ /**
4
+ * A retry after a lost create response can only recover the local user's own
5
+ * create: the server serves whatever document holds the stable id we minted,
6
+ * and an honest server only ever committed ours under it. A create event signed
7
+ * by anyone else is a foreign document colliding on that id (a member with
8
+ * write access on the same container, or a dishonest server), which must not be
9
+ * adopted as if it were the pending local write.
10
+ *
11
+ * The create event is located by walking the served head's predecessor chain,
12
+ * not by scanning the history for any parentless manifest: the history is
13
+ * server-supplied, so a dishonest server could splice in a genesis this user
14
+ * signed for a different document. Every manifest on the chain must also name
15
+ * the requested document.
16
+ */
17
+ export function assertDocumentCreateSigner(input, writerProjection) {
18
+ const label = "Document create conflict";
19
+ const historyByHash = new Map(writerProjection.documentManifestHistory.map((bundle) => [
20
+ bundle.manifestHash,
21
+ bundle,
22
+ ]));
23
+ const visited = new Set();
24
+ let bundle = writerProjection.documentManifest;
25
+ for (;;) {
26
+ const manifest = readAccessManifest(bundle.manifest, `${label} manifest`);
27
+ if (manifest.objectKind !== "document" ||
28
+ manifest.objectId !== input.documentId) {
29
+ throw new KeyingVerificationError("object_mismatch", `${label} manifest chain names another document`);
30
+ }
31
+ if (manifest.previousManifestHash === null) {
32
+ const createEvent = readAccessEvent(bundle.event.event, `${label} create event`);
33
+ if (createEvent.signerUserId !== input.expectedSignerUserId) {
34
+ throw new KeyingVerificationError("signer_mismatch", `${label} create event was signed by another user`);
35
+ }
36
+ return;
37
+ }
38
+ if (visited.has(bundle.manifestHash)) {
39
+ throw new KeyingVerificationError("invalid_shape", `${label} manifest history is cyclic`);
40
+ }
41
+ visited.add(bundle.manifestHash);
42
+ const previous = historyByHash.get(manifest.previousManifestHash);
43
+ if (!previous) {
44
+ throw new KeyingVerificationError("invalid_shape", `${label} does not expose its create event`);
45
+ }
46
+ bundle = previous;
47
+ }
48
+ }
49
+ //# sourceMappingURL=documentCreateSigner.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"documentCreateSigner.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,GAAG,CAAC,MAAM,CAAC,YAAY,CAAC,EAAE,CAAC;YACrC,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,GAAG,KAAK,6BAA6B,CACtC,CAAC;QACJ,CAAC;QACD,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC;QACjC,MAAM,QAAQ,GAAG,aAAa,CAAC,GAAG,CAAC,QAAQ,CAAC,oBAAoB,CAAC,CAAC;QAClE,IAAI,CAAC,QAAQ,EAAE,CAAC;YACd,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,GAAG,KAAK,mCAAmC,CAC5C,CAAC;QACJ,CAAC;QACD,MAAM,GAAG,QAAQ,CAAC;IACpB,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n readAccessEvent,\n readAccessManifest,\n} from \"../../../keyingProjectionVerification/readers\";\n\n/**\n * A retry after a lost create response can only recover the local user's own\n * create: the server serves whatever document holds the stable id we minted,\n * and an honest server only ever committed ours under it. A create event signed\n * by anyone else is a foreign document colliding on that id (a member with\n * write access on the same container, or a dishonest server), which must not be\n * adopted as if it were the pending local write.\n *\n * The create event is located by walking the served head's predecessor chain,\n * not by scanning the history for any parentless manifest: the history is\n * server-supplied, so a dishonest server could splice in a genesis this user\n * signed for a different document. Every manifest on the chain must also name\n * the requested document.\n */\nexport function assertDocumentCreateSigner(\n input: { documentId: string; expectedSignerUserId: string },\n writerProjection: DocumentWriterProjectionResponse,\n): void {\n const label = \"Document create conflict\";\n const historyByHash = new Map(\n writerProjection.documentManifestHistory.map((bundle) => [\n bundle.manifestHash,\n bundle,\n ]),\n );\n const visited = new Set<string>();\n let bundle = writerProjection.documentManifest;\n for (;;) {\n const manifest = readAccessManifest(bundle.manifest, `${label} manifest`);\n if (\n manifest.objectKind !== \"document\" ||\n manifest.objectId !== input.documentId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n `${label} manifest chain names another document`,\n );\n }\n if (manifest.previousManifestHash === null) {\n const createEvent = readAccessEvent(\n bundle.event.event,\n `${label} create event`,\n );\n if (createEvent.signerUserId !== input.expectedSignerUserId) {\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n `${label} create event was signed by another user`,\n );\n }\n return;\n }\n if (visited.has(bundle.manifestHash)) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n `${label} manifest history is cyclic`,\n );\n }\n visited.add(bundle.manifestHash);\n const previous = historyByHash.get(manifest.previousManifestHash);\n if (!previous) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n `${label} does not expose its create event`,\n );\n }\n bundle = previous;\n }\n}\n"]}
@@ -4,6 +4,7 @@ import { type DocumentWriterProjectionAuthorization, type PrincipalPolicyCache }
4
4
  import type { ExecSql } from "../../../sqlite/sqlSchema.js";
5
5
  export { unwrapContainerKekPath } from "../containerKek/containerKekPath.js";
6
6
  export { ContainerKekHistoryUnavailableError } from "../containerKek/containerKekPathHistory.js";
7
+ export { assertDocumentCreateSigner } from "./documentCreateSigner.js";
7
8
  export { shouldRetryWithFreshProjection } from "./freshProjectionRetry.js";
8
9
  export { buildRotatedDocumentContentKeyBundle, collectContainerKeksForDocumentSync, DocumentContentKeyUnavailableError, DocumentHistoryUnavailableError, unwrapContentKeyTargetForKind, unwrapDocumentContentKeyFromBundle, unwrapDocumentContentKeyFromWriterProjection, unwrapDocumentContentKeyTarget, wrapDocumentContentKeyForCreate, } from "./projectionContentKeys.js";
9
10
  export { authorizingContainerPathRefs, authorizingContainerPathRefsForLinkSet, containerPathRefs, currentDocumentTargets, deriveDocumentCreateTargets, deriveDocumentTargetFromProjection, mergeTargetEnvelopes, readLinkedContainerIdsFromDocumentManifest, verifiedDocumentWrapTargets, } from "./projectionTargets.js";
@@ -7,6 +7,7 @@ import { assertDocumentManifestBundleConsistent, normalizeDocumentKekTargetRespo
7
7
  import { currentDocumentTargets, deriveDocumentTargetFromProjection, readLinkedContainerIdsFromDocumentManifest, } from "./projectionTargets.js";
8
8
  export { unwrapContainerKekPath } from "../containerKek/containerKekPath.js";
9
9
  export { ContainerKekHistoryUnavailableError } from "../containerKek/containerKekPathHistory.js";
10
+ export { assertDocumentCreateSigner } from "./documentCreateSigner.js";
10
11
  export { shouldRetryWithFreshProjection } from "./freshProjectionRetry.js";
11
12
  export { buildRotatedDocumentContentKeyBundle, collectContainerKeksForDocumentSync, DocumentContentKeyUnavailableError, DocumentHistoryUnavailableError, unwrapContentKeyTargetForKind, unwrapDocumentContentKeyFromBundle, unwrapDocumentContentKeyFromWriterProjection, unwrapDocumentContentKeyTarget, wrapDocumentContentKeyForCreate, } from "./projectionContentKeys.js";
12
13
  export { authorizingContainerPathRefs, authorizingContainerPathRefsForLinkSet, containerPathRefs, currentDocumentTargets, deriveDocumentCreateTargets, deriveDocumentTargetFromProjection, mergeTargetEnvelopes, readLinkedContainerIdsFromDocumentManifest, verifiedDocumentWrapTargets, } from "./projectionTargets.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,mCAAmC,EAAE,MAAM,mBAAmB,CAAC;AAExE,OAAO,EAGL,2CAA2C,GAC5C,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,mCAAmC,EAAE,MAAM,6CAA6C,CAAC;AAClG,OAAO,EAAE,+BAA+B,EAAE,MAAM,sEAAsE,CAAC;AACvH,OAAO,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAE5D,OAAO,EACL,sCAAsC,EACtC,kCAAkC,EAClC,mBAAmB,EACnB,uBAAuB,EACvB,SAAS,EACT,mBAAmB,GACpB,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,sBAAsB,EACtB,kCAAkC,EAClC,0CAA0C,GAC3C,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EAAE,sBAAsB,EAAE,MAAM,kCAAkC,CAAC;AAC1E,OAAO,EAAE,mC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;QACD,MAAM,IAAI,KAAK,CAAC,mDAAmD,CAAC,CAAC;IACvE,CAAC;IACD,MAAM,0CAA0C,CAC9C,gBAAgB,EAChB,qBAAqB,CACtB,CAAC;IAEF,MAAM,OAAO,GAAG,qBAAqB;QACnC,CAAC,CAAC,kCAAkC,CAAC,gBAAgB,CAAC,kBAAkB,CAAC;QACzE,CAAC,CAAC,sBAAsB,CAAC,gBAAgB,CAAC,CAAC;IAC7C,MAAM,mBAAmB,GACvB,MAAM,mCAAmC,CAAC,OAAO,CAAC,CAAC;IACrD,IACE,mBAAmB;QACnB,gBAAgB,CAAC,kBAAkB,CAAC,qBAAqB,EACzD,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,yDAAyD,CAAC,CAAC;IAC7E,CAAC;IAED,0CAA0C,CAAC,OAAO,EAAE,gBAAgB,CAAC,CAAC;IACtE,mDAAmD,CAAC;QAClD,OAAO;QACP,gBAAgB;KACjB,CAAC,CAAC;IAEH,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,wCAAwC,CAC5D,GAAG,KAA0E;IAE7E,IAAI,CAAC;QACH,OAAO,MAAM,gDAAgD,CAAC,GAAG,KAAK,CAAC,CAAC;IAC1E,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,mCAAmC,CAAC,KAAK,CAAC,CAAC;IAC7C,CAAC;AACH,CAAC","sourcesContent":["import type {\n DocumentContentKeyTarget,\n VerifiedContainerAccessManifest,\n} from \"@tearleads/crypto\";\nimport { computeDocumentContentKeyTargetHash } from \"@tearleads/crypto\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n type DocumentWriterProjectionAuthorization,\n type PrincipalPolicyCache,\n verifyDocumentWriterProjectionAuthorization,\n} from \"../../../keyingProjectionVerification\";\nimport { throwKeyingVerificationShapeFailure } from \"../../../keyingProjectionVerification/error\";\nimport { openPrincipalPolicyBundleReader } from \"../../../persistence/principalPolicy/principalPolicyBundleRepository\";\nimport { errorMessage } from \"../../../shared/errorMessage\";\nimport type { ExecSql } from \"../../../sqlite/sqlSchema\";\nimport {\n assertDocumentManifestBundleConsistent,\n normalizeDocumentKekTargetResponse,\n sortDocumentTargets,\n targetEnvelopeReference,\n targetKey,\n uniqueSortedStrings,\n} from \"../readers\";\nimport {\n currentDocumentTargets,\n deriveDocumentTargetFromProjection,\n readLinkedContainerIdsFromDocumentManifest,\n} from \"./projectionTargets\";\n\nexport { unwrapContainerKekPath } from \"../containerKek/containerKekPath\";\nexport { ContainerKekHistoryUnavailableError } from \"../containerKek/containerKekPathHistory\";\nexport { shouldRetryWithFreshProjection } from \"./freshProjectionRetry\";\nexport {\n buildRotatedDocumentContentKeyBundle,\n collectContainerKeksForDocumentSync,\n DocumentContentKeyUnavailableError,\n DocumentHistoryUnavailableError,\n unwrapContentKeyTargetForKind,\n unwrapDocumentContentKeyFromBundle,\n unwrapDocumentContentKeyFromWriterProjection,\n unwrapDocumentContentKeyTarget,\n wrapDocumentContentKeyForCreate,\n} from \"./projectionContentKeys\";\nexport {\n authorizingContainerPathRefs,\n authorizingContainerPathRefsForLinkSet,\n containerPathRefs,\n currentDocumentTargets,\n deriveDocumentCreateTargets,\n deriveDocumentTargetFromProjection,\n mergeTargetEnvelopes,\n readLinkedContainerIdsFromDocumentManifest,\n verifiedDocumentWrapTargets,\n} from \"./projectionTargets\";\n\nimport type { ProjectionVerificationOptions } from \"./projectionVerificationOptions\";\nimport { resolveProjectionVerifier } from \"./projectionVerificationOptions\";\n\nfunction assertSortedStringsEqual(\n left: readonly string[],\n right: readonly string[],\n message: string,\n): void {\n if (\n left.length !== right.length ||\n left.some((value, index) => value !== right[index])\n ) {\n throw new Error(message);\n }\n}\n\nfunction assertAuthorizingContainerPathsMatchDocumentTargets(input: {\n targets: readonly DocumentContentKeyTarget[];\n writerProjection: DocumentWriterProjectionResponse;\n}): void {\n if (input.writerProjection.authorizingContainerPaths.length === 0) {\n throw new Error(\"Document writer projection authorization paths missing\");\n }\n\n const targetKeys = new Set(input.targets.map(targetKey));\n for (const [\n index,\n projection,\n ] of input.writerProjection.authorizingContainerPaths.entries()) {\n let projectionTarget: DocumentContentKeyTarget;\n try {\n projectionTarget = deriveDocumentTargetFromProjection(projection);\n } catch (error) {\n throw new Error(\n `Document writer projection authorization path[${index}] is invalid: ${errorMessage(error)}`,\n );\n }\n\n if (targetKeys.has(targetKey(projectionTarget))) {\n continue;\n }\n\n // Bind server-supplied KEK paths to committed document targets before\n // using any unwrapped path KEK for document content-key material.\n throw new Error(\n `Document writer projection authorization path[${index}] is not a document target`,\n );\n }\n}\n\nfunction assertDocumentTargetsCoverLinkedContainers(\n targets: readonly DocumentContentKeyTarget[],\n writerProjection: DocumentWriterProjectionResponse,\n): void {\n // One target per linked container: a second epoch for the same container\n // would let a re-wrap land on a KEK a revoked member still holds.\n if (\n new Set(targets.map((target) => target.containerId)).size !== targets.length\n ) {\n throw new Error(\n \"Document writer projection targets name a linked container more than once\",\n );\n }\n assertSortedStringsEqual(\n uniqueSortedStrings(targets.map((target) => target.containerId)),\n readLinkedContainerIdsFromDocumentManifest(writerProjection),\n \"Document writer projection targets do not match linked containers\",\n );\n assertSortedStringsEqual(\n uniqueSortedStrings(\n writerProjection.documentKekTargets.linkedContainerManifestHashes,\n ),\n uniqueSortedStrings(targets.map((target) => target.containerManifestHash)),\n \"Document writer projection target manifest summary mismatch\",\n );\n assertSortedStringsEqual(\n uniqueSortedStrings(\n writerProjection.documentKekTargets.linkedContainerKeyEpochIds,\n ),\n uniqueSortedStrings(targets.map((target) => target.containerKeyEpochId)),\n \"Document writer projection target KEK summary mismatch\",\n );\n}\n\nasync function assertProjectionContentKeyBundleConsistent(\n writerProjection: DocumentWriterProjectionResponse,\n staleContentKeyBundle: boolean,\n): Promise<void> {\n const { manifestHash } = writerProjection.documentManifest;\n // A stale bundle may lag the link-set head, but it must still descend from\n // this document's manifest chain.\n if (\n writerProjection.contentKeyBundle.linkSetManifestHash !== manifestHash &&\n (!staleContentKeyBundle ||\n !writerProjection.documentManifestHistory.some(\n (bundle) =>\n bundle.manifestHash ===\n writerProjection.contentKeyBundle.linkSetManifestHash,\n ))\n ) {\n throw new Error(\"Document writer projection link manifest mismatch\");\n }\n\n if (!staleContentKeyBundle) {\n if (\n writerProjection.documentKekTargets.documentKeyTargetHash !==\n writerProjection.contentKeyBundle.targetHash\n ) {\n throw new Error(\"Document writer projection target hash mismatch\");\n }\n return;\n }\n\n // The stale bundle cannot match the current targets; pin it to its own\n // canonical hash instead so a tampered envelope set still fails closed.\n const staleBundleTargetHash = await computeDocumentContentKeyTargetHash(\n sortDocumentTargets(\n writerProjection.contentKeyBundle.targets.map(targetEnvelopeReference),\n ),\n );\n if (staleBundleTargetHash !== writerProjection.contentKeyBundle.targetHash) {\n throw new Error(\n \"Document writer projection stale bundle target hash is not canonical\",\n );\n }\n}\n\nasync function assertDocumentWriterProjectionConsistentInternal(\n writerProjection: DocumentWriterProjectionResponse,\n input: ProjectionVerificationOptions & {\n /**\n * Accept a projection whose content-key bundle is marked stale (wrapped\n * to superseded KEK targets after e.g. a revoke rotation). Document sync\n * opts in to heal the bundle. Attachment reads opt in because their DEK\n * is independent and opens through verified retained container KEKs.\n */\n allowStaleContentKeyBundle?: boolean | undefined;\n execSql?: ExecSql | undefined;\n persistVerificationCheckpoints?: boolean | undefined;\n onVerifiedAuthorization?:\n | ((authorization: DocumentWriterProjectionAuthorization) => void)\n | undefined;\n principalPolicyCache?: PrincipalPolicyCache | undefined;\n stillCurrent?: (() => boolean) | undefined;\n verifiedByHash?: Map<string, VerifiedContainerAccessManifest> | undefined;\n },\n): Promise<DocumentContentKeyTarget[]> {\n const resolveProjectionUserKey = resolveProjectionVerifier(\n input,\n \"Document writer projection\",\n );\n if (\n input.trustedLocalProjection !== true &&\n resolveProjectionUserKey !== null\n ) {\n const authorization = await verifyDocumentWriterProjectionAuthorization({\n execSql: input.execSql,\n openPrincipalPolicyBundleReader,\n persistVerificationCheckpoints: input.persistVerificationCheckpoints,\n principalPolicyCache: input.principalPolicyCache,\n projection: writerProjection,\n resolveUserKey: resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n verifiedByHash: input.verifiedByHash,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n input.onVerifiedAuthorization?.(authorization);\n }\n\n const staleContentKeyBundle = writerProjection.contentKeyBundleStale === true;\n if (staleContentKeyBundle && input.allowStaleContentKeyBundle !== true) {\n throw new Error(\"Document writer projection content-key bundle is stale\");\n }\n\n const manifestIdentity = await assertDocumentManifestBundleConsistent({\n bundle: writerProjection.documentManifest,\n label: \"Document writer projection manifest\",\n });\n const { documentId } = manifestIdentity;\n if (\n writerProjection.documentId !== documentId ||\n writerProjection.documentKekTargets.documentId !== documentId ||\n writerProjection.contentKeyBundle.documentId !== documentId\n ) {\n throw new Error(\"Document writer projection document id mismatch\");\n }\n if (\n writerProjection.documentKekTargets.linkSetManifestHash !==\n writerProjection.documentManifest.manifestHash\n ) {\n throw new Error(\"Document writer projection link manifest mismatch\");\n }\n await assertProjectionContentKeyBundleConsistent(\n writerProjection,\n staleContentKeyBundle,\n );\n\n const targets = staleContentKeyBundle\n ? normalizeDocumentKekTargetResponse(writerProjection.documentKekTargets)\n : currentDocumentTargets(writerProjection);\n const canonicalTargetHash =\n await computeDocumentContentKeyTargetHash(targets);\n if (\n canonicalTargetHash !==\n writerProjection.documentKekTargets.documentKeyTargetHash\n ) {\n throw new Error(\"Document writer projection target hash is not canonical\");\n }\n\n assertDocumentTargetsCoverLinkedContainers(targets, writerProjection);\n assertAuthorizingContainerPathsMatchDocumentTargets({\n targets,\n writerProjection,\n });\n\n return targets;\n}\n\nexport async function assertDocumentWriterProjectionConsistent(\n ...input: Parameters<typeof assertDocumentWriterProjectionConsistentInternal>\n): ReturnType<typeof assertDocumentWriterProjectionConsistentInternal> {\n try {\n return await assertDocumentWriterProjectionConsistentInternal(...input);\n } catch (error) {\n throwKeyingVerificationShapeFailure(error);\n }\n}\n"]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CAAC,CAAC;IAEH,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,wCAAwC,CAC5D,GAAG,KAA0E;IAE7E,IAAI,CAAC;QACH,OAAO,MAAM,gDAAgD,CAAC,GAAG,KAAK,CAAC,CAAC;IAC1E,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,mCAAmC,CAAC,KAAK,CAAC,CAAC;IAC7C,CAAC;AACH,CAAC","sourcesContent":["import type {\n DocumentContentKeyTarget,\n VerifiedContainerAccessManifest,\n} from \"@tearleads/crypto\";\nimport { computeDocumentContentKeyTargetHash } from \"@tearleads/crypto\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n type DocumentWriterProjectionAuthorization,\n type PrincipalPolicyCache,\n verifyDocumentWriterProjectionAuthorization,\n} from \"../../../keyingProjectionVerification\";\nimport { throwKeyingVerificationShapeFailure } from \"../../../keyingProjectionVerification/error\";\nimport { openPrincipalPolicyBundleReader } from \"../../../persistence/principalPolicy/principalPolicyBundleRepository\";\nimport { errorMessage } from \"../../../shared/errorMessage\";\nimport type { ExecSql } from \"../../../sqlite/sqlSchema\";\nimport {\n assertDocumentManifestBundleConsistent,\n normalizeDocumentKekTargetResponse,\n sortDocumentTargets,\n targetEnvelopeReference,\n targetKey,\n uniqueSortedStrings,\n} from \"../readers\";\nimport {\n currentDocumentTargets,\n deriveDocumentTargetFromProjection,\n readLinkedContainerIdsFromDocumentManifest,\n} from \"./projectionTargets\";\n\nexport { unwrapContainerKekPath } from \"../containerKek/containerKekPath\";\nexport { ContainerKekHistoryUnavailableError } from \"../containerKek/containerKekPathHistory\";\nexport { assertDocumentCreateSigner } from \"./documentCreateSigner\";\nexport { shouldRetryWithFreshProjection } from \"./freshProjectionRetry\";\nexport {\n buildRotatedDocumentContentKeyBundle,\n collectContainerKeksForDocumentSync,\n DocumentContentKeyUnavailableError,\n DocumentHistoryUnavailableError,\n unwrapContentKeyTargetForKind,\n unwrapDocumentContentKeyFromBundle,\n unwrapDocumentContentKeyFromWriterProjection,\n unwrapDocumentContentKeyTarget,\n wrapDocumentContentKeyForCreate,\n} from \"./projectionContentKeys\";\nexport {\n authorizingContainerPathRefs,\n authorizingContainerPathRefsForLinkSet,\n containerPathRefs,\n currentDocumentTargets,\n deriveDocumentCreateTargets,\n deriveDocumentTargetFromProjection,\n mergeTargetEnvelopes,\n readLinkedContainerIdsFromDocumentManifest,\n verifiedDocumentWrapTargets,\n} from \"./projectionTargets\";\n\nimport type { ProjectionVerificationOptions } from \"./projectionVerificationOptions\";\nimport { resolveProjectionVerifier } from \"./projectionVerificationOptions\";\n\nfunction assertSortedStringsEqual(\n left: readonly string[],\n right: readonly string[],\n message: string,\n): void {\n if (\n left.length !== right.length ||\n left.some((value, index) => value !== right[index])\n ) {\n throw new Error(message);\n }\n}\n\nfunction assertAuthorizingContainerPathsMatchDocumentTargets(input: {\n targets: readonly DocumentContentKeyTarget[];\n writerProjection: DocumentWriterProjectionResponse;\n}): void {\n if (input.writerProjection.authorizingContainerPaths.length === 0) {\n throw new Error(\"Document writer projection authorization paths missing\");\n }\n\n const targetKeys = new Set(input.targets.map(targetKey));\n for (const [\n index,\n projection,\n ] of input.writerProjection.authorizingContainerPaths.entries()) {\n let projectionTarget: DocumentContentKeyTarget;\n try {\n projectionTarget = deriveDocumentTargetFromProjection(projection);\n } catch (error) {\n throw new Error(\n `Document writer projection authorization path[${index}] is invalid: ${errorMessage(error)}`,\n );\n }\n\n if (targetKeys.has(targetKey(projectionTarget))) {\n continue;\n }\n\n // Bind server-supplied KEK paths to committed document targets before\n // using any unwrapped path KEK for document content-key material.\n throw new Error(\n `Document writer projection authorization path[${index}] is not a document target`,\n );\n }\n}\n\nfunction assertDocumentTargetsCoverLinkedContainers(\n targets: readonly DocumentContentKeyTarget[],\n writerProjection: DocumentWriterProjectionResponse,\n): void {\n // One target per linked container: a second epoch for the same container\n // would let a re-wrap land on a KEK a revoked member still holds.\n if (\n new Set(targets.map((target) => target.containerId)).size !== targets.length\n ) {\n throw new Error(\n \"Document writer projection targets name a linked container more than once\",\n );\n }\n assertSortedStringsEqual(\n uniqueSortedStrings(targets.map((target) => target.containerId)),\n readLinkedContainerIdsFromDocumentManifest(writerProjection),\n \"Document writer projection targets do not match linked containers\",\n );\n assertSortedStringsEqual(\n uniqueSortedStrings(\n writerProjection.documentKekTargets.linkedContainerManifestHashes,\n ),\n uniqueSortedStrings(targets.map((target) => target.containerManifestHash)),\n \"Document writer projection target manifest summary mismatch\",\n );\n assertSortedStringsEqual(\n uniqueSortedStrings(\n writerProjection.documentKekTargets.linkedContainerKeyEpochIds,\n ),\n uniqueSortedStrings(targets.map((target) => target.containerKeyEpochId)),\n \"Document writer projection target KEK summary mismatch\",\n );\n}\n\nasync function assertProjectionContentKeyBundleConsistent(\n writerProjection: DocumentWriterProjectionResponse,\n staleContentKeyBundle: boolean,\n): Promise<void> {\n const { manifestHash } = writerProjection.documentManifest;\n // A stale bundle may lag the link-set head, but it must still descend from\n // this document's manifest chain.\n if (\n writerProjection.contentKeyBundle.linkSetManifestHash !== manifestHash &&\n (!staleContentKeyBundle ||\n !writerProjection.documentManifestHistory.some(\n (bundle) =>\n bundle.manifestHash ===\n writerProjection.contentKeyBundle.linkSetManifestHash,\n ))\n ) {\n throw new Error(\"Document writer projection link manifest mismatch\");\n }\n\n if (!staleContentKeyBundle) {\n if (\n writerProjection.documentKekTargets.documentKeyTargetHash !==\n writerProjection.contentKeyBundle.targetHash\n ) {\n throw new Error(\"Document writer projection target hash mismatch\");\n }\n return;\n }\n\n // The stale bundle cannot match the current targets; pin it to its own\n // canonical hash instead so a tampered envelope set still fails closed.\n const staleBundleTargetHash = await computeDocumentContentKeyTargetHash(\n sortDocumentTargets(\n writerProjection.contentKeyBundle.targets.map(targetEnvelopeReference),\n ),\n );\n if (staleBundleTargetHash !== writerProjection.contentKeyBundle.targetHash) {\n throw new Error(\n \"Document writer projection stale bundle target hash is not canonical\",\n );\n }\n}\n\nasync function assertDocumentWriterProjectionConsistentInternal(\n writerProjection: DocumentWriterProjectionResponse,\n input: ProjectionVerificationOptions & {\n /**\n * Accept a projection whose content-key bundle is marked stale (wrapped\n * to superseded KEK targets after e.g. a revoke rotation). Document sync\n * opts in to heal the bundle. Attachment reads opt in because their DEK\n * is independent and opens through verified retained container KEKs.\n */\n allowStaleContentKeyBundle?: boolean | undefined;\n execSql?: ExecSql | undefined;\n persistVerificationCheckpoints?: boolean | undefined;\n onVerifiedAuthorization?:\n | ((authorization: DocumentWriterProjectionAuthorization) => void)\n | undefined;\n principalPolicyCache?: PrincipalPolicyCache | undefined;\n stillCurrent?: (() => boolean) | undefined;\n verifiedByHash?: Map<string, VerifiedContainerAccessManifest> | undefined;\n },\n): Promise<DocumentContentKeyTarget[]> {\n const resolveProjectionUserKey = resolveProjectionVerifier(\n input,\n \"Document writer projection\",\n );\n if (\n input.trustedLocalProjection !== true &&\n resolveProjectionUserKey !== null\n ) {\n const authorization = await verifyDocumentWriterProjectionAuthorization({\n execSql: input.execSql,\n openPrincipalPolicyBundleReader,\n persistVerificationCheckpoints: input.persistVerificationCheckpoints,\n principalPolicyCache: input.principalPolicyCache,\n projection: writerProjection,\n resolveUserKey: resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n verifiedByHash: input.verifiedByHash,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n input.onVerifiedAuthorization?.(authorization);\n }\n\n const staleContentKeyBundle = writerProjection.contentKeyBundleStale === true;\n if (staleContentKeyBundle && input.allowStaleContentKeyBundle !== true) {\n throw new Error(\"Document writer projection content-key bundle is stale\");\n }\n\n const manifestIdentity = await assertDocumentManifestBundleConsistent({\n bundle: writerProjection.documentManifest,\n label: \"Document writer projection manifest\",\n });\n const { documentId } = manifestIdentity;\n if (\n writerProjection.documentId !== documentId ||\n writerProjection.documentKekTargets.documentId !== documentId ||\n writerProjection.contentKeyBundle.documentId !== documentId\n ) {\n throw new Error(\"Document writer projection document id mismatch\");\n }\n if (\n writerProjection.documentKekTargets.linkSetManifestHash !==\n writerProjection.documentManifest.manifestHash\n ) {\n throw new Error(\"Document writer projection link manifest mismatch\");\n }\n await assertProjectionContentKeyBundleConsistent(\n writerProjection,\n staleContentKeyBundle,\n );\n\n const targets = staleContentKeyBundle\n ? normalizeDocumentKekTargetResponse(writerProjection.documentKekTargets)\n : currentDocumentTargets(writerProjection);\n const canonicalTargetHash =\n await computeDocumentContentKeyTargetHash(targets);\n if (\n canonicalTargetHash !==\n writerProjection.documentKekTargets.documentKeyTargetHash\n ) {\n throw new Error(\"Document writer projection target hash is not canonical\");\n }\n\n assertDocumentTargetsCoverLinkedContainers(targets, writerProjection);\n assertAuthorizingContainerPathsMatchDocumentTargets({\n targets,\n writerProjection,\n });\n\n return targets;\n}\n\nexport async function assertDocumentWriterProjectionConsistent(\n ...input: Parameters<typeof assertDocumentWriterProjectionConsistentInternal>\n): ReturnType<typeof assertDocumentWriterProjectionConsistentInternal> {\n try {\n return await assertDocumentWriterProjectionConsistentInternal(...input);\n } catch (error) {\n throwKeyingVerificationShapeFailure(error);\n }\n}\n"]}
@@ -3,7 +3,7 @@ import { CONTENT_RECORD_ENCRYPTION_SUITE, compareCanonicalStrings, } from "../..
3
3
  import { isPlainObject as isPlainRecord } from "../../../internal/validators/isPlainObject.js";
4
4
  import { readCanonicalRecord } from "../../keying/canonicalJson.js";
5
5
  import { readRecordInteger, readRecordPositiveInteger, readRecordString, readRecordValue, readStringArray, } from "../../shared/recordReaders.js";
6
- export { assertDocumentManifestBundleConsistent, serializeCanonical, } from "./manifestBundleReaders.js";
6
+ export { assertDocumentManifestBundleConsistent, readDocumentLinkSetManifestState, serializeCanonical, } from "./manifestBundleReaders.js";
7
7
  function isContentObjectKind(value) {
8
8
  return value === "blob" || value === "document";
9
9
  }