@tearleads/client-sdk 0.1.207 → 0.1.208

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 (46) hide show
  1. package/client/documents/index.d.ts +8 -0
  2. package/client/documents/index.js +14 -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/documents/documentRestore.d.ts +30 -0
  7. package/data/documents/documentRestore.js +77 -0
  8. package/data/documents/documentRestore.js.map +1 -0
  9. package/data/documents/documentRowList.d.ts +6 -0
  10. package/data/documents/documentRowList.js +31 -0
  11. package/data/documents/documentRowList.js.map +1 -1
  12. package/data/documents/index.d.ts +1 -0
  13. package/data/documents/index.js.map +1 -1
  14. package/index.d.ts +3 -3
  15. package/index.js +1 -1
  16. package/index.js.map +1 -1
  17. package/internal/loro/historyTimeline.d.ts +57 -0
  18. package/internal/loro/historyTimeline.js +271 -0
  19. package/internal/loro/historyTimeline.js.map +1 -0
  20. package/internal/loro/index.d.ts +1 -0
  21. package/internal/loro/index.js +1 -0
  22. package/internal/loro/index.js.map +1 -1
  23. package/package.json +1 -1
  24. package/stores/documents/documentStore/history/restoreContent.js +127 -0
  25. package/stores/documents/documentStore/history/restoreContent.js.map +1 -0
  26. package/stores/documents/documentStore/index.js +4 -4
  27. package/stores/documents/documentStore/index.js.map +1 -1
  28. package/stores/documents/documentStore/mutations.js +1 -1
  29. package/stores/documents/documentStore/mutations.js.map +1 -1
  30. package/stores/documents/documentStore/rows/index.js +8 -0
  31. package/stores/documents/documentStore/rows/index.js.map +1 -1
  32. package/stores/documents/registry.js +1 -0
  33. package/stores/documents/registry.js.map +1 -1
  34. package/stores/documents/removedDocumentStore.js +1 -0
  35. package/stores/documents/removedDocumentStore.js.map +1 -1
  36. package/stores/documents/types.d.ts +10 -1
  37. package/stores/documents/types.js.map +1 -1
  38. package/workflows/documents/history/documentHistory.d.ts +72 -0
  39. package/workflows/documents/history/documentHistory.js +103 -0
  40. package/workflows/documents/history/documentHistory.js.map +1 -0
  41. package/workflows/documents/history/documentHistoryChange.d.ts +51 -0
  42. package/workflows/documents/history/documentHistoryChange.js +110 -0
  43. package/workflows/documents/history/documentHistoryChange.js.map +1 -0
  44. package/workflows/documents/index.d.ts +2 -0
  45. package/workflows/documents/index.js +2 -0
  46. package/workflows/documents/index.js.map +1 -1
@@ -1,8 +1,10 @@
1
1
  import type { StoredDocumentKind } from "../../data/documents/documentKinds.js";
2
2
  import type { DocumentSummaryList, DocumentSummarySort, DocumentSummarySortDirection, DocumentSummarySortKey, ListDocumentSummariesInput } from "../../data/persistence/documents/types.js";
3
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 { type DocumentHistory } from "../../workflows/documents/index.js";
4
5
  import type { InternalRuntime } from "../runtime/workflowRuntime.js";
5
6
  export type { DocumentAttachmentStatus, DocumentAttachmentUpload, DocumentContextValue, DocumentStore, DocumentsRuntime, PersistedDocumentListener, } from "../../stores/documents/index.js";
7
+ export type { DocumentHistory, DocumentHistoryChange, DocumentHistoryRowChange, DocumentHistoryStop, DocumentHistoryTextChange, DocumentHistoryVersion, DocumentHistoryVersionEntry, DocumentHistoryView, } from "../../workflows/documents/index.js";
6
8
  export type DocumentSortDirection = DocumentSummarySortDirection;
7
9
  export type DocumentSortKey = DocumentSummarySortKey;
8
10
  export type DocumentSort = DocumentSummarySort;
@@ -32,6 +34,12 @@ export interface Documents {
32
34
  findLocalIdByDocumentId(documentId: string): Promise<string | null>;
33
35
  list(input?: ListDocumentsInput | undefined): Promise<DocumentList | null>;
34
36
  open(input?: OpenDocumentInput | undefined, options?: OpenDocumentOptions | undefined): DocumentStore;
37
+ /**
38
+ * Open a read-only replay of a document's durable local history. Resolves to
39
+ * null while the database is not ready or the document has no history yet.
40
+ * The caller must `close()` the result.
41
+ */
42
+ openHistory(localId: string): Promise<DocumentHistory | null>;
35
43
  subscribe(listener: PersistedDocumentListener, options?: DocumentSubscriptionOptions | undefined): () => void;
36
44
  workflowRuntime(containerId?: string | null | undefined): DocumentsRuntime;
37
45
  }
@@ -1,7 +1,7 @@
1
1
  import { DEFAULT_DOCUMENT_KIND } from "../../data/documents/documentConstants.js";
2
2
  import { 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
- import { createDocumentsWorkflowRuntime, defaultDocumentsPersistence, deletePersistedDocument, reclaimDocumentOrphanBlobs, } from "../../workflows/documents/index.js";
4
+ import { createDocumentsWorkflowRuntime, defaultDocumentsPersistence, deletePersistedDocument, openDocumentHistory, reclaimDocumentOrphanBlobs, } from "../../workflows/documents/index.js";
5
5
  export { DEFAULT_LOCAL_DOCUMENT_ID as DEFAULT_DOCUMENT_ID };
6
6
  export function createDocuments(dependencies) {
7
7
  return new DocumentsService(dependencies);
@@ -58,6 +58,19 @@ class DocumentsService {
58
58
  remoteSyncMode: options.remoteSyncMode,
59
59
  });
60
60
  }
61
+ async openHistory(localId) {
62
+ const runtime = this.workflowRuntime();
63
+ if (runtime.infra.dbStatus !== "ready") {
64
+ return null;
65
+ }
66
+ await this.ensureSchema(runtime.infra.execSql);
67
+ return openDocumentHistory({
68
+ documentProjectors: runtime.infra.documentProjectors,
69
+ execSql: runtime.infra.execSql,
70
+ localId,
71
+ persistence: defaultDocumentsPersistence,
72
+ });
73
+ }
61
74
  subscribe(listener, options = {}) {
62
75
  return subscribeToPersistedDocuments(this.dependencies.runtime.workflowInput(options.containerId).state
63
76
  .domainScope, listener);
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,wCAAwC,CAAC;AA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AAe,CAAC,WAAW,CAAC,CAAC;QAC/D,OAAO,iBAAiB,CACtB,OAAO,CAAC,KAAK,CAAC,WAAW,EACzB,OAAO,EACP,OAAO,EACP,UAAU,EACV,WAAW,EACX,mBAAmB,EACnB;YACE,WAAW;YACX,uBAAuB;YACvB,cAAc,EAAE,OAAO,CAAC,cAAc;SACvC,CACF,CAAC;IACJ,CAAC;IAED,SAAS,CACP,QAAmC,EACnC,UAAuC,EAAE;QAEzC,OAAO,6BAA6B,CAClC,IAAI,CAAC,YAAY,CAAC,OAAO,CAAC,aAAa,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,KAAK;aAC/D,WAAW,EACd,QAAQ,CACT,CAAC;IACJ,CAAC;IAEO,YAAY,CAAC,OAAgB;QACnC,MAAM,QAAQ,GAAG,IAAI,CAAC,sBAAsB,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QAC1D,IAAI,QAAQ,EAAE,CAAC;YACb,OAAO,QAAQ,CAAC;QAClB,CAAC;QAED,MAAM,MAAM,GAAG,2BAA2B;aACvC,YAAY,CAAC,OAAO,CAAC;aACrB,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;YACxB,IAAI,CAAC,sBAAsB,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;YAC5C,MAAM,KAAK,CAAC;QACd,CAAC,CAAC,CAAC;QACL,IAAI,CAAC,sBAAsB,CAAC,GAAG,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QACjD,OAAO,MAAM,CAAC;IAChB,CAAC;CACF","sourcesContent":["import { DEFAULT_DOCUMENT_KIND } from \"../../data/documents/documentConstants\";\nimport type { StoredDocumentKind } from \"../../data/documents/documentKinds\";\nimport type {\n DocumentSummaryList,\n DocumentSummarySort,\n DocumentSummarySortDirection,\n DocumentSummarySortKey,\n ListDocumentSummariesInput,\n} from \"../../data/persistence/documents/types\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport {\n DEFAULT_DOCUMENT_ID as DEFAULT_LOCAL_DOCUMENT_ID,\n type DocumentStore,\n type DocumentStoreOpenOptions,\n type DocumentsRuntime,\n openDocumentStore,\n type PersistedDocumentListener,\n subscribeToPersistedDocuments,\n} from \"../../stores/documents\";\nimport { emitPersistedDocumentDeletion } from \"../../stores/documents/registry\";\nimport {\n createDocumentsWorkflowRuntime,\n defaultDocumentsPersistence,\n deletePersistedDocument,\n reclaimDocumentOrphanBlobs,\n} from \"../../workflows/documents\";\nimport type { InternalRuntime } from \"../runtime/workflowRuntime\";\n\nexport type {\n DocumentAttachmentStatus,\n DocumentAttachmentUpload,\n DocumentContextValue,\n DocumentStore,\n DocumentsRuntime,\n PersistedDocumentListener,\n} from \"../../stores/documents\";\n\nexport type DocumentSortDirection = DocumentSummarySortDirection;\nexport type DocumentSortKey = DocumentSummarySortKey;\n\nexport type DocumentSort = DocumentSummarySort;\n\nexport interface ListDocumentsInput extends ListDocumentSummariesInput {}\n\nexport type DocumentList = DocumentSummaryList;\n\nexport { DEFAULT_LOCAL_DOCUMENT_ID as DEFAULT_DOCUMENT_ID };\n\nexport interface OpenDocumentInput {\n readonly containerId?: string | null | undefined;\n readonly documentId?: string | null | undefined;\n readonly initialDocumentKind?: StoredDocumentKind | undefined;\n /** 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 subscribe(\n listener: PersistedDocumentListener,\n options?: DocumentSubscriptionOptions | undefined,\n ): () => void;\n workflowRuntime(containerId?: string | null | undefined): DocumentsRuntime;\n}\n\ninterface DocumentsDependencies {\n getDefaultContainerId: () => string | null;\n runtime: InternalRuntime;\n}\n\nexport function createDocuments(\n dependencies: DocumentsDependencies,\n): Documents {\n return new DocumentsService(dependencies);\n}\n\nclass DocumentsService implements Documents {\n private readonly schemaEnsuresByExecSql = new WeakMap<\n ExecSql,\n Promise<void>\n >();\n\n constructor(private readonly dependencies: DocumentsDependencies) {}\n\n async delete(localId: string): Promise<boolean> {\n const runtime = this.workflowRuntime();\n if (runtime.infra.dbStatus !== \"ready\") {\n return false;\n }\n\n const deleted = await deletePersistedDocument({\n documentProjectors: runtime.infra.documentProjectors,\n execSql: runtime.infra.execSql,\n localId,\n persistence: defaultDocumentsPersistence,\n });\n if (!deleted) return false;\n void reclaimDocumentOrphanBlobs(runtime);\n emitPersistedDocumentDeletion(runtime.state.domainScope, localId);\n return true;\n }\n\n async findLocalIdByDocumentId(documentId: string): Promise<string | null> {\n const runtime = this.dependencies.runtime.workflowInput();\n if (runtime.infra.dbStatus !== \"ready\") {\n return null;\n }\n\n await this.ensureSchema(runtime.infra.execSql);\n return defaultDocumentsPersistence.findLocalIdByDocumentId(\n runtime.infra.execSql,\n documentId,\n );\n }\n\n async list(input: ListDocumentsInput = {}): Promise<DocumentList | null> {\n const runtime = this.dependencies.runtime.workflowInput();\n if (runtime.infra.dbStatus !== \"ready\") {\n return null;\n }\n\n await this.ensureSchema(runtime.infra.execSql);\n return defaultDocumentsPersistence.listDocumentSummaries(\n runtime.infra.execSql,\n input,\n );\n }\n\n workflowRuntime(\n containerId = this.dependencies.getDefaultContainerId(),\n ): DocumentsRuntime {\n const input = this.dependencies.runtime.workflowInput(containerId);\n return createDocumentsWorkflowRuntime(input);\n }\n\n open(\n input: OpenDocumentInput = {},\n options: OpenDocumentOptions = {},\n ): DocumentStore {\n const {\n containerId,\n documentId = null,\n initialDocumentKind = DEFAULT_DOCUMENT_KIND,\n 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 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;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,8BAA8B,EAE9B,2BAA2B,EAC3B,uBAAuB,EACvB,mBAAmB,EACnB,0BAA0B,GAC3B,MAAM,2BAA2B,CAAC;AAgCnC,OAAO,EAAE,yBAAyB,IAAI,mBAAmB,EAAE,CAAC;AAgD5D,MAAM,UAAU,eAAe,CAC7B,YAAmC;IAEnC,OAAO,IAAI,gBAAgB,CAAC,YAAY,CAAC,CAAC;AAC5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,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 {\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 createDocumentsWorkflowRuntime,\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 documentProjectors: runtime.infra.documentProjectors,\n execSql: runtime.infra.execSql,\n localId,\n persistence: defaultDocumentsPersistence,\n });\n if (!deleted) return false;\n void reclaimDocumentOrphanBlobs(runtime);\n emitPersistedDocumentDeletion(runtime.state.domainScope, localId);\n return true;\n }\n\n async findLocalIdByDocumentId(documentId: string): Promise<string | null> {\n const runtime = this.dependencies.runtime.workflowInput();\n if (runtime.infra.dbStatus !== \"ready\") {\n return null;\n }\n\n await this.ensureSchema(runtime.infra.execSql);\n return defaultDocumentsPersistence.findLocalIdByDocumentId(\n runtime.infra.execSql,\n documentId,\n );\n }\n\n async list(input: ListDocumentsInput = {}): Promise<DocumentList | null> {\n const runtime = this.dependencies.runtime.workflowInput();\n if (runtime.infra.dbStatus !== \"ready\") {\n return null;\n }\n\n await this.ensureSchema(runtime.infra.execSql);\n return defaultDocumentsPersistence.listDocumentSummaries(\n runtime.infra.execSql,\n input,\n );\n }\n\n workflowRuntime(\n containerId = this.dependencies.getDefaultContainerId(),\n ): DocumentsRuntime {\n const input = this.dependencies.runtime.workflowInput(containerId);\n return createDocumentsWorkflowRuntime(input);\n }\n\n open(\n input: OpenDocumentInput = {},\n options: OpenDocumentOptions = {},\n ): DocumentStore {\n const {\n containerId,\n documentId = null,\n initialDocumentKind = DEFAULT_DOCUMENT_KIND,\n 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, 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, } 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;AAuB7E,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,QAAQ,GAKT,MAAM,oBAAoB,CAAC;AAC5B,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 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 Database,\n type DatabaseListener,\n type DatabaseOptions,\n type DatabaseSnapshot,\n type DatabaseStatus,\n} from \"./runtime/database\";\nexport {\n Events,\n type EventsListener,\n type EventsSnapshot,\n} from \"./runtime/events\";\nexport {\n createBrowserNetworkStatusSource,\n Network,\n type NetworkListener,\n type NetworkMode,\n type NetworkStatusSource,\n} from \"./runtime/network\";\nexport type {\n PrincipalHistoryKeyProvider,\n PrincipalHistoryKeyScope,\n} from \"./runtime/principalHistoryProtection\";\nexport {\n SyncBillingGate,\n type SyncBillingGateListener,\n} from \"./runtime/syncBillingGate\";\nexport type {\n SecurityIncident,\n SecurityIncidentListener,\n SecurityIncidentObjectKind,\n SecurityIncidents,\n} from \"./securityIncidents\";\nexport { PurgedOrganizationRecoveryBillingRequiredError } from \"./session/sessionRecoveryErrors\";\nexport type {\n CreateOrganizationOptions,\n Session,\n SessionContext,\n SessionCreateOrganizationResult,\n SessionListener,\n SessionRecoverOrganizationResult,\n SessionRegistrationRefusal,\n SessionRegistrationResult,\n SessionSnapshot,\n UserSession,\n} from \"./session/sessionTypes\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,GAElB,MAAM,4BAA4B,CAAC;AAKpC,OAAO,EACL,8BAA8B,GAE/B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACL,+BAA+B,EAK/B,8BAA8B,GAC/B,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,yBAAyB,EACzB,0BAA0B,EAC1B,oBAAoB,EACpB,yBAAyB,EACzB,sBAAsB,EACtB,4BAA4B,EAC5B,4BAA4B,EAE5B,yBAAyB,GAO1B,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAyB,KAAK,EAAE,MAAM,SAAS,CAAC;AAgDvD,OAAO,EAAE,sCAAsC,EAAE,MAAM,qBAAqB,CAAC;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,QAAQ,GAKT,MAAM,oBAAoB,CAAC;AAC5B,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 Database,\n type DatabaseListener,\n type DatabaseOptions,\n type DatabaseSnapshot,\n type DatabaseStatus,\n} from \"./runtime/database\";\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"]}
@@ -0,0 +1,30 @@
1
+ import { type DocumentProjectorRegistryInput, type StructuredDocumentShape } from "./documentKinds.js";
2
+ import { type DocumentRowAttribution } from "./documentRowList.js";
3
+ /**
4
+ * The content of a document that a restore writes back: its text, structured
5
+ * fields, and rows. Attachments are not part of it. Their bytes are not kept
6
+ * once detached, so a restore leaves the document's attachments as they are.
7
+ */
8
+ export interface DocumentRestoreContent {
9
+ readonly rows: ReadonlyArray<{
10
+ readonly fields: Readonly<Record<string, string>>;
11
+ readonly id: string;
12
+ }>;
13
+ readonly structuredFields: Readonly<Record<string, string>>;
14
+ readonly text: string;
15
+ }
16
+ /** A document whose text can be replaced, as a Loro document's can. */
17
+ type RestorableDocument = Omit<StructuredDocumentShape, "getText"> & {
18
+ getText: (key: string) => {
19
+ toString: () => string;
20
+ update: (text: string) => void;
21
+ };
22
+ };
23
+ /**
24
+ * Write `content` into the document as ordinary edits and report whether
25
+ * anything changed. Nothing is rewound: the document keeps its whole history
26
+ * and gains the operations that carry it back to this content, so the restore
27
+ * syncs and merges like any other edit.
28
+ */
29
+ export declare function restoreDocumentContent(doc: RestorableDocument, content: DocumentRestoreContent, attribution: DocumentRowAttribution, registry?: DocumentProjectorRegistryInput | undefined): boolean;
30
+ export {};
@@ -0,0 +1,77 @@
1
+ import { readStoredDocumentState, writeStoredDocumentFields, } from "./documentKinds.js";
2
+ import { addDocumentRow, createDocumentRowId, listDocumentRows, removeDocumentRow, replaceDocumentRowFields, } from "./documentRowList.js";
3
+ function restoreText(doc, text) {
4
+ const current = doc.getText("text");
5
+ if (current.toString() === text)
6
+ return false;
7
+ current.update(text);
8
+ return true;
9
+ }
10
+ function restoreStructuredFields(doc, target, registry) {
11
+ const current = readStoredDocumentState(doc, registry);
12
+ // A note has no structured fields to restore.
13
+ if (current.documentKind === "note")
14
+ return false;
15
+ const patch = {};
16
+ for (const key of new Set([
17
+ ...Object.keys(current.structuredFields),
18
+ ...Object.keys(target),
19
+ ])) {
20
+ if (current.structuredFields[key] !== target[key]) {
21
+ patch[key] = target[key];
22
+ }
23
+ }
24
+ if (Object.keys(patch).length === 0)
25
+ return false;
26
+ writeStoredDocumentFields(doc, current.documentKind, patch, registry);
27
+ return true;
28
+ }
29
+ /**
30
+ * Make the document's rows equal `target`. A row that still exists is patched
31
+ * cell by cell under its own id, a row that is gone from `target` is removed,
32
+ * and a row the document no longer has is added back as a new row with a new
33
+ * id, at the end.
34
+ *
35
+ * The new id is what keeps a restore safe to merge: two devices restoring the
36
+ * same version at once each add their own copy, and both copies stay distinct
37
+ * rows that can be edited or removed. Re-adding under the old id would leave
38
+ * two rows sharing it, with writes reaching only the first. Row order is not
39
+ * restored, because a row cannot be moved.
40
+ */
41
+ function restoreRows(doc, target, attribution) {
42
+ const current = listDocumentRows(doc);
43
+ const targetById = new Map(target.map((row) => [row.id, row]));
44
+ const currentIds = new Set(current.map((row) => row.id));
45
+ let changed = false;
46
+ for (const row of current) {
47
+ const wanted = targetById.get(row.id);
48
+ if (wanted === undefined) {
49
+ changed = removeDocumentRow(doc, row.id) || changed;
50
+ }
51
+ else {
52
+ changed =
53
+ replaceDocumentRowFields(doc, row.id, wanted.fields, attribution) ||
54
+ changed;
55
+ }
56
+ }
57
+ for (const row of target) {
58
+ if (!currentIds.has(row.id)) {
59
+ addDocumentRow(doc, createDocumentRowId(), row.fields, attribution);
60
+ changed = true;
61
+ }
62
+ }
63
+ return changed;
64
+ }
65
+ /**
66
+ * Write `content` into the document as ordinary edits and report whether
67
+ * anything changed. Nothing is rewound: the document keeps its whole history
68
+ * and gains the operations that carry it back to this content, so the restore
69
+ * syncs and merges like any other edit.
70
+ */
71
+ export function restoreDocumentContent(doc, content, attribution, registry) {
72
+ const textChanged = restoreText(doc, content.text);
73
+ const fieldsChanged = restoreStructuredFields(doc, content.structuredFields, registry);
74
+ const rowsChanged = restoreRows(doc, content.rows, attribution);
75
+ return textChanged || fieldsChanged || rowsChanged;
76
+ }
77
+ //# sourceMappingURL=documentRestore.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"documentRestore.js","sourceRoot":"","sources":["documentRestore.ts"],"names":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AAO,CAAC;AACjB,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,sBAAsB,CACpC,GAAuB,EACvB,OAA+B,EAC/B,WAAmC,EACnC,QAAqD;IAErD,MAAM,WAAW,GAAG,WAAW,CAAC,GAAG,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;IACnD,MAAM,aAAa,GAAG,uBAAuB,CAC3C,GAAG,EACH,OAAO,CAAC,gBAAgB,EACxB,QAAQ,CACT,CAAC;IACF,MAAM,WAAW,GAAG,WAAW,CAAC,GAAG,EAAE,OAAO,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC;IAChE,OAAO,WAAW,IAAI,aAAa,IAAI,WAAW,CAAC;AACrD,CAAC","sourcesContent":["import {\n type DocumentProjectorRegistryInput,\n readStoredDocumentState,\n type StructuredDocumentShape,\n writeStoredDocumentFields,\n} from \"./documentKinds\";\nimport {\n addDocumentRow,\n createDocumentRowId,\n type DocumentRowAttribution,\n listDocumentRows,\n removeDocumentRow,\n replaceDocumentRowFields,\n} from \"./documentRowList\";\n\n/**\n * The content of a document that a restore writes back: its text, structured\n * fields, and rows. Attachments are not part of it. Their bytes are not kept\n * once detached, so a restore leaves the document's attachments as they are.\n */\nexport interface DocumentRestoreContent {\n readonly rows: ReadonlyArray<{\n readonly fields: Readonly<Record<string, string>>;\n readonly id: string;\n }>;\n readonly structuredFields: Readonly<Record<string, string>>;\n readonly text: string;\n}\n\ntype RestoreRow = DocumentRestoreContent[\"rows\"][number];\n\n/** A document whose text can be replaced, as a Loro document's can. */\ntype RestorableDocument = Omit<StructuredDocumentShape, \"getText\"> & {\n getText: (key: string) => {\n toString: () => string;\n update: (text: string) => void;\n };\n};\n\nfunction restoreText(doc: RestorableDocument, text: string): boolean {\n const current = doc.getText(\"text\");\n if (current.toString() === text) return false;\n current.update(text);\n return true;\n}\n\nfunction restoreStructuredFields(\n doc: StructuredDocumentShape,\n target: Readonly<Record<string, string>>,\n registry: DocumentProjectorRegistryInput | undefined,\n): boolean {\n const current = readStoredDocumentState(doc, registry);\n // A note has no structured fields to restore.\n if (current.documentKind === \"note\") return false;\n const patch: Record<string, string | undefined> = {};\n for (const key of new Set([\n ...Object.keys(current.structuredFields),\n ...Object.keys(target),\n ])) {\n if (current.structuredFields[key] !== target[key]) {\n patch[key] = target[key];\n }\n }\n if (Object.keys(patch).length === 0) return false;\n writeStoredDocumentFields(doc, current.documentKind, patch, registry);\n return true;\n}\n\n/**\n * Make the document's rows equal `target`. A row that still exists is patched\n * cell by cell under its own id, a row that is gone from `target` is removed,\n * and a row the document no longer has is added back as a new row with a new\n * id, at the end.\n *\n * The new id is what keeps a restore safe to merge: two devices restoring the\n * same version at once each add their own copy, and both copies stay distinct\n * rows that can be edited or removed. Re-adding under the old id would leave\n * two rows sharing it, with writes reaching only the first. Row order is not\n * restored, because a row cannot be moved.\n */\nfunction restoreRows(\n doc: StructuredDocumentShape,\n target: ReadonlyArray<RestoreRow>,\n attribution: DocumentRowAttribution,\n): boolean {\n const current = listDocumentRows(doc);\n const targetById = new Map(target.map((row) => [row.id, row]));\n const currentIds = new Set(current.map((row) => row.id));\n let changed = false;\n for (const row of current) {\n const wanted = targetById.get(row.id);\n if (wanted === undefined) {\n changed = removeDocumentRow(doc, row.id) || changed;\n } else {\n changed =\n replaceDocumentRowFields(doc, row.id, wanted.fields, attribution) ||\n changed;\n }\n }\n for (const row of target) {\n if (!currentIds.has(row.id)) {\n addDocumentRow(doc, createDocumentRowId(), row.fields, attribution);\n changed = true;\n }\n }\n return changed;\n}\n\n/**\n * Write `content` into the document as ordinary edits and report whether\n * anything changed. Nothing is rewound: the document keeps its whole history\n * and gains the operations that carry it back to this content, so the restore\n * syncs and merges like any other edit.\n */\nexport function restoreDocumentContent(\n doc: RestorableDocument,\n content: DocumentRestoreContent,\n attribution: DocumentRowAttribution,\n registry?: DocumentProjectorRegistryInput | undefined,\n): boolean {\n const textChanged = restoreText(doc, content.text);\n const fieldsChanged = restoreStructuredFields(\n doc,\n content.structuredFields,\n registry,\n );\n const rowsChanged = restoreRows(doc, content.rows, attribution);\n return textChanged || fieldsChanged || rowsChanged;\n}\n"]}
@@ -26,6 +26,12 @@ export declare function ensureDocumentRowsStructure(doc: RowListDocumentShape):
26
26
  export declare function listDocumentRows(doc: RowListDocumentShape): DocumentRow[];
27
27
  export declare function addDocumentRow(doc: RowListDocumentShape, id: string, fields: Readonly<Record<string, string>>, attribution: DocumentRowAttribution): void;
28
28
  export declare function setDocumentRowFields(doc: RowListDocumentShape, id: string, patch: Readonly<Record<string, string>>, attribution: DocumentRowAttribution): boolean;
29
+ /**
30
+ * Make a row's cells equal `fields`: write the ones that differ and clear the
31
+ * ones that are absent. Untouched cells keep their last editor. Returns whether
32
+ * the row exists and anything changed.
33
+ */
34
+ export declare function replaceDocumentRowFields(doc: RowListDocumentShape, id: string, fields: Readonly<Record<string, string>>, attribution: DocumentRowAttribution): boolean;
29
35
  export declare function removeDocumentRow(doc: RowListDocumentShape, id: string): boolean;
30
36
  export declare function sameDocumentRows(left: ReadonlyArray<DocumentRow>, right: ReadonlyArray<DocumentRow>): boolean;
31
37
  export {};
@@ -121,6 +121,37 @@ export function setDocumentRowFields(doc, id, patch, attribution) {
121
121
  row.set(ROW_UPDATED_AT_KEY, attribution.at);
122
122
  return true;
123
123
  }
124
+ /**
125
+ * Make a row's cells equal `fields`: write the ones that differ and clear the
126
+ * ones that are absent. Untouched cells keep their last editor. Returns whether
127
+ * the row exists and anything changed.
128
+ */
129
+ export function replaceDocumentRowFields(doc, id, fields, attribution) {
130
+ const row = findRowMap(doc.getList(DOCUMENT_ROWS_LIST_KEY), id);
131
+ if (!row) {
132
+ return false;
133
+ }
134
+ let changed = false;
135
+ for (const key of row.keys()) {
136
+ // Own keys only: a cell named `constructor` or `toString` is not "in"
137
+ // the restored fields merely because every object inherits one.
138
+ if (!key.startsWith(ROW_META_PREFIX) && !Object.hasOwn(fields, key)) {
139
+ row.delete(key);
140
+ changed = true;
141
+ }
142
+ }
143
+ for (const [key, value] of Object.entries(fields)) {
144
+ if (!key.startsWith(ROW_META_PREFIX) && row.get(key) !== value) {
145
+ row.set(key, value);
146
+ changed = true;
147
+ }
148
+ }
149
+ if (changed) {
150
+ row.set(ROW_UPDATED_BY_KEY, attribution.userId);
151
+ row.set(ROW_UPDATED_AT_KEY, attribution.at);
152
+ }
153
+ return changed;
154
+ }
124
155
  export function removeDocumentRow(doc, id) {
125
156
  const list = doc.getList(DOCUMENT_ROWS_LIST_KEY);
126
157
  for (let index = 0; index < list.length; index += 1) {
@@ -1 +1 @@
1
- {"version":3,"file":"documentRowList.js","sourceRoot":"","sources":["documentRowList.ts"],"names":[],"mappings":"AAAA,OAAO,EAAiB,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAEzD,6EAA6E;AAC7E,4EAA4E;AAC5E,2EAA2E;AAC3E,uEAAuE;AACvE,8EAA8E;AAC9E,mCAAmC;AACnC,MAAM,sBAAsB,GAAG,MAAM,CAAC;AAEtC,6EAA6E;AAC7E,yDAAyD;AACzD,MAAM,eAAe,GAAG,GAAG,CAAC;AAC5B,MAAM,UAAU,GAAG,KAAK,CAAC;AACzB,MAAM,kBAAkB,GAAG,YAAY,CAAC;AACxC,MAAM,kBAAkB,GAAG,YAAY,CAAC;AACxC,MAAM,kBAAkB,GAAG,YAAY,CAAC;AACxC,MAAM,kBAAkB,GAAG,YAAY,CAAC;AA4CxC,IAAI,iBAAiB,GAAG,CAAC,CAAC;AAE1B,MAAM,UAAU,mBAAmB;IACjC,MAAM,QAAQ,GAAG,UAAU,CAAC,MAAM,EAAE,UAAU,EAAE,EAAE,CAAC;IACnD,IAAI,QAAQ,EAAE,CAAC;QACb,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,iBAAiB,IAAI,CAAC,CAAC;IACvB,OAAO,OAAO,IAAI,CAAC,GAAG,EAAE,IAAI,iBAAiB,EAAE,CAAC;AAClD,CAAC;AAED,SAAS,aAAa,CAAC,GAAY,EAAE,GAAW;IAC9C,MAAM,KAAK,GAAG,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f,CAAC;IAED,MAAM,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAC1C,MAAM,SAAS,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IAC5C,IAAI,QAAQ,CAAC,MAAM,KAAK,SAAS,CAAC,MAAM,EAAE,CAAC;QACzC,OAAO,KAAK,CAAC;IACf,CAAC;IAED,6EAA6E;IAC7E,wEAAwE;IACxE,OAAO,QAAQ,CAAC,KAAK,CACnB,CAAC,GAAG,EAAE,EAAE,CACN,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC;QACtC,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,KAAK,KAAK,CAAC,YAAY,CAAC,GAAG,CAAC,CACrD,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,gBAAgB,CAC9B,IAAgC,EAChC,KAAiC;IAEjC,OAAO,CACL,IAAI,CAAC,MAAM,KAAK,KAAK,CAAC,MAAM;QAC5B,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE;YACxB,MAAM,OAAO,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC;YAC7B,OAAO,OAAO,KAAK,SAAS,IAAI,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;QACxD,CAAC,CAAC,CACH,CAAC;AACJ,CAAC","sourcesContent":["import { type LoroList, LoroMap } from \"@tearleads/loro\";\n\n// A document's repeated rows (e.g. a .env file's variables, a blood pressure\n// tracker's readings) live in one first-class Loro list — each row a nested\n// LoroMap. Storing each row as its own container makes concurrent edits to\n// different rows (or different cells of the same row) merge instead of\n// clobbering; only two writes to the same cell of the same row race, and Loro\n// resolves those last-writer-wins.\nconst DOCUMENT_ROWS_LIST_KEY = \"rows\";\n\n// Reserved row-map keys are namespaced so they never collide with a document\n// type's own field names (none of which begin with \"@\").\nconst ROW_META_PREFIX = \"@\";\nconst ROW_ID_KEY = \"@id\";\nconst ROW_CREATED_BY_KEY = \"@createdBy\";\nconst ROW_CREATED_AT_KEY = \"@createdAt\";\nconst ROW_UPDATED_BY_KEY = \"@updatedBy\";\nconst ROW_UPDATED_AT_KEY = \"@updatedAt\";\n\nexport interface DocumentRowAttribution {\n // The signing user id of the writer, or \"\" when unauthenticated. Matches the\n // key the edit-attribution/blame layer resolves against.\n userId: string;\n // ISO-8601 timestamp of the write.\n at: string;\n}\n\nexport interface DocumentRow {\n id: string;\n fields: Record<string, string>;\n createdBy: string;\n createdAt: string;\n updatedBy: string;\n updatedAt: string;\n // The Loro peer id that last wrote this row (read from the last-editor register\n // of the always-restamped \"@updatedAt\" key). Unlike `updatedBy` — a\n // self-attested user id stored in the row — this peer can be resolved to a\n // server-verified writer via the edit-attribution segments. Null when the\n // register has no editor (e.g. a never-written row). Survives snapshot\n // reload, so it is stable across the store's persist cycle.\n updatedByPeer: string | null;\n // The Loro peer that created this row (last editor of the write-once\n // \"@createdAt\" key), resolvable to a verified writer like `updatedByPeer`.\n createdByPeer: string | null;\n // Per-cell last-editor peers, keyed identically to `fields`. Each resolves to\n // the verified writer of that specific cell's current value — the field-level\n // analog of `updatedByPeer`.\n fieldEditors: Record<string, string | null>;\n}\n\n// The minimal projection of a row the document projector needs to derive a\n// title (e.g. a reading/variable count) without depending on the store.\nexport interface DocumentRowSummary {\n id: string;\n fields: Readonly<Record<string, string>>;\n}\n\ninterface RowListDocumentShape {\n getList: (key: string) => LoroList;\n}\n\nlet localRowIdCounter = 0;\n\nexport function createDocumentRowId(): string {\n const randomId = globalThis.crypto?.randomUUID?.();\n if (randomId) {\n return randomId;\n }\n\n localRowIdCounter += 1;\n return `row-${Date.now()}-${localRowIdCounter}`;\n}\n\nfunction readRowString(row: LoroMap, key: string): string {\n const value = row.get(key);\n return typeof value === \"string\" ? value : \"\";\n}\n\n// The peer that last set a key, from Loro's per-key last-writer-wins register.\n// \"@updatedAt\" is restamped with a fresh timestamp on every row write, so its\n// last editor is the peer of the row's most recent write. (Probing \"@updatedBy\"\n// would be wrong: it stores a user id that repeats when one user edits twice,\n// which Loro records as a no-op, leaving the register on the earlier writer.)\nfunction readRowEditorPeer(row: LoroMap, key: string): string | null {\n return row.getLastEditor(key) ?? null;\n}\n\nfunction parseDocumentRow(row: LoroMap): DocumentRow | null {\n const id = readRowString(row, ROW_ID_KEY);\n if (id.length === 0) {\n return null;\n }\n\n const fields: Record<string, string> = {};\n const fieldEditors: Record<string, string | null> = {};\n for (const [key, value] of row.entries()) {\n if (key.startsWith(ROW_META_PREFIX)) {\n continue;\n }\n if (typeof value === \"string\") {\n fields[key] = value;\n // Each data cell has its own last-editor register, so field-level\n // attribution is read the same way as the row-level peer.\n fieldEditors[key] = readRowEditorPeer(row, key);\n }\n }\n\n return {\n id,\n fields,\n fieldEditors,\n createdBy: readRowString(row, ROW_CREATED_BY_KEY),\n createdAt: readRowString(row, ROW_CREATED_AT_KEY),\n createdByPeer: readRowEditorPeer(row, ROW_CREATED_AT_KEY),\n updatedBy: readRowString(row, ROW_UPDATED_BY_KEY),\n updatedAt: readRowString(row, ROW_UPDATED_AT_KEY),\n updatedByPeer: readRowEditorPeer(row, ROW_UPDATED_AT_KEY),\n };\n}\n\nexport function ensureDocumentRowsStructure(doc: RowListDocumentShape): void {\n doc.getList(DOCUMENT_ROWS_LIST_KEY);\n}\n\nfunction findRowMap(list: LoroList, id: string): LoroMap | null {\n for (let index = 0; index < list.length; index += 1) {\n const value = list.get(index);\n if (value instanceof LoroMap && readRowString(value, ROW_ID_KEY) === id) {\n return value;\n }\n }\n\n return null;\n}\n\nexport function listDocumentRows(doc: RowListDocumentShape): DocumentRow[] {\n const list = doc.getList(DOCUMENT_ROWS_LIST_KEY);\n const rows: DocumentRow[] = [];\n for (let index = 0; index < list.length; index += 1) {\n const value = list.get(index);\n if (value instanceof LoroMap) {\n const row = parseDocumentRow(value);\n if (row) {\n rows.push(row);\n }\n }\n }\n\n return rows;\n}\n\nfunction writeRowFields(\n row: LoroMap,\n fields: Readonly<Record<string, string>>,\n): void {\n for (const [key, value] of Object.entries(fields)) {\n // Never let a caller's field name overwrite reserved metadata.\n if (key.startsWith(ROW_META_PREFIX)) {\n continue;\n }\n row.set(key, value);\n }\n}\n\nexport function addDocumentRow(\n doc: RowListDocumentShape,\n id: string,\n fields: Readonly<Record<string, string>>,\n attribution: DocumentRowAttribution,\n): void {\n const list = doc.getList(DOCUMENT_ROWS_LIST_KEY);\n const row = list.pushContainer(new LoroMap());\n row.set(ROW_ID_KEY, id);\n row.set(ROW_CREATED_BY_KEY, attribution.userId);\n row.set(ROW_CREATED_AT_KEY, attribution.at);\n row.set(ROW_UPDATED_BY_KEY, attribution.userId);\n row.set(ROW_UPDATED_AT_KEY, attribution.at);\n writeRowFields(row, fields);\n}\n\nexport function setDocumentRowFields(\n doc: RowListDocumentShape,\n id: string,\n patch: Readonly<Record<string, string>>,\n attribution: DocumentRowAttribution,\n): boolean {\n const list = doc.getList(DOCUMENT_ROWS_LIST_KEY);\n const row = findRowMap(list, id);\n if (!row) {\n return false;\n }\n\n writeRowFields(row, patch);\n row.set(ROW_UPDATED_BY_KEY, attribution.userId);\n row.set(ROW_UPDATED_AT_KEY, attribution.at);\n return true;\n}\n\nexport function removeDocumentRow(\n doc: RowListDocumentShape,\n id: string,\n): boolean {\n const list = doc.getList(DOCUMENT_ROWS_LIST_KEY);\n for (let index = 0; index < list.length; index += 1) {\n const value = list.get(index);\n if (value instanceof LoroMap && readRowString(value, ROW_ID_KEY) === id) {\n list.delete(index, 1);\n return true;\n }\n }\n\n return false;\n}\n\nfunction sameRow(left: DocumentRow, right: DocumentRow): boolean {\n if (\n left.id !== right.id ||\n left.createdBy !== right.createdBy ||\n left.createdAt !== right.createdAt ||\n left.createdByPeer !== right.createdByPeer ||\n left.updatedBy !== right.updatedBy ||\n left.updatedAt !== right.updatedAt ||\n left.updatedByPeer !== right.updatedByPeer\n ) {\n return false;\n }\n\n const leftKeys = Object.keys(left.fields);\n const rightKeys = Object.keys(right.fields);\n if (leftKeys.length !== rightKeys.length) {\n return false;\n }\n\n // fieldEditors shares the exact key set as fields, so comparing per key here\n // also covers a cell whose value is unchanged but whose editor changed.\n return leftKeys.every(\n (key) =>\n left.fields[key] === right.fields[key] &&\n left.fieldEditors[key] === right.fieldEditors[key],\n );\n}\n\nexport function sameDocumentRows(\n left: ReadonlyArray<DocumentRow>,\n right: ReadonlyArray<DocumentRow>,\n): boolean {\n return (\n left.length === right.length &&\n left.every((row, index) => {\n const nextRow = right[index];\n return nextRow !== undefined && sameRow(row, nextRow);\n })\n );\n}\n"]}
1
+ {"version":3,"file":"documentRowList.js","sourceRoot":"","sources":["documentRowList.ts"],"names":[],"mappings":"AAAA,OAAO,EAAiB,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAEzD,6EAA6E;AAC7E,4EAA4E;AAC5E,2EAA2E;AAC3E,uEAAuE;AACvE,8EAA8E;AAC9E,mCAAmC;AACnC,MAAM,sBAAsB,GAAG,MAAM,CAAC;AAEtC,6EAA6E;AAC7E,yDAAyD;AACzD,MAAM,eAAe,GAAG,GAAG,CAAC;AAC5B,MAAM,UAAU,GAAG,KAAK,CAAC;AACzB,MAAM,kBAAkB,GAAG,YAAY,CAAC;AACxC,MAAM,kBAAkB,GAAG,YAAY,CAAC;AACxC,MAAM,kBAAkB,GAAG,YAAY,CAAC;AACxC,MAAM,kBAAkB,GAAG,YAAY,CAAC;AA4CxC,IAAI,iBAAiB,GAAG,CAAC,CAAC;AAE1B,MAAM,UAAU,mBAAmB;IACjC,MAAM,QAAQ,GAAG,UAAU,CAAC,MAAM,EAAE,UAAU,EAAE,EAAE,CAAC;IACnD,IAAI,QAAQ,EAAE,CAAC;QACb,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,iBAAiB,IAAI,CAAC,CAAC;IACvB,OAAO,OAAO,IAAI,CAAC,GAAG,EAAE,IAAI,iBAAiB,EAAE,CAAC;AAClD,CAAC;AAED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K,CAAC;IACf,CAAC;IAED,MAAM,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAC1C,MAAM,SAAS,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IAC5C,IAAI,QAAQ,CAAC,MAAM,KAAK,SAAS,CAAC,MAAM,EAAE,CAAC;QACzC,OAAO,KAAK,CAAC;IACf,CAAC;IAED,6EAA6E;IAC7E,wEAAwE;IACxE,OAAO,QAAQ,CAAC,KAAK,CACnB,CAAC,GAAG,EAAE,EAAE,CACN,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC;QACtC,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,KAAK,KAAK,CAAC,YAAY,CAAC,GAAG,CAAC,CACrD,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,gBAAgB,CAC9B,IAAgC,EAChC,KAAiC;IAEjC,OAAO,CACL,IAAI,CAAC,MAAM,KAAK,KAAK,CAAC,MAAM;QAC5B,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE;YACxB,MAAM,OAAO,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC;YAC7B,OAAO,OAAO,KAAK,SAAS,IAAI,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;QACxD,CAAC,CAAC,CACH,CAAC;AACJ,CAAC","sourcesContent":["import { type LoroList, LoroMap } from \"@tearleads/loro\";\n\n// A document's repeated rows (e.g. a .env file's variables, a blood pressure\n// tracker's readings) live in one first-class Loro list — each row a nested\n// LoroMap. Storing each row as its own container makes concurrent edits to\n// different rows (or different cells of the same row) merge instead of\n// clobbering; only two writes to the same cell of the same row race, and Loro\n// resolves those last-writer-wins.\nconst DOCUMENT_ROWS_LIST_KEY = \"rows\";\n\n// Reserved row-map keys are namespaced so they never collide with a document\n// type's own field names (none of which begin with \"@\").\nconst ROW_META_PREFIX = \"@\";\nconst ROW_ID_KEY = \"@id\";\nconst ROW_CREATED_BY_KEY = \"@createdBy\";\nconst ROW_CREATED_AT_KEY = \"@createdAt\";\nconst ROW_UPDATED_BY_KEY = \"@updatedBy\";\nconst ROW_UPDATED_AT_KEY = \"@updatedAt\";\n\nexport interface DocumentRowAttribution {\n // The signing user id of the writer, or \"\" when unauthenticated. Matches the\n // key the edit-attribution/blame layer resolves against.\n userId: string;\n // ISO-8601 timestamp of the write.\n at: string;\n}\n\nexport interface DocumentRow {\n id: string;\n fields: Record<string, string>;\n createdBy: string;\n createdAt: string;\n updatedBy: string;\n updatedAt: string;\n // The Loro peer id that last wrote this row (read from the last-editor register\n // of the always-restamped \"@updatedAt\" key). Unlike `updatedBy` — a\n // self-attested user id stored in the row — this peer can be resolved to a\n // server-verified writer via the edit-attribution segments. Null when the\n // register has no editor (e.g. a never-written row). Survives snapshot\n // reload, so it is stable across the store's persist cycle.\n updatedByPeer: string | null;\n // The Loro peer that created this row (last editor of the write-once\n // \"@createdAt\" key), resolvable to a verified writer like `updatedByPeer`.\n createdByPeer: string | null;\n // Per-cell last-editor peers, keyed identically to `fields`. Each resolves to\n // the verified writer of that specific cell's current value — the field-level\n // analog of `updatedByPeer`.\n fieldEditors: Record<string, string | null>;\n}\n\n// The minimal projection of a row the document projector needs to derive a\n// title (e.g. a reading/variable count) without depending on the store.\nexport interface DocumentRowSummary {\n id: string;\n fields: Readonly<Record<string, string>>;\n}\n\ninterface RowListDocumentShape {\n getList: (key: string) => LoroList;\n}\n\nlet localRowIdCounter = 0;\n\nexport function createDocumentRowId(): string {\n const randomId = globalThis.crypto?.randomUUID?.();\n if (randomId) {\n return randomId;\n }\n\n localRowIdCounter += 1;\n return `row-${Date.now()}-${localRowIdCounter}`;\n}\n\nfunction readRowString(row: LoroMap, key: string): string {\n const value = row.get(key);\n return typeof value === \"string\" ? value : \"\";\n}\n\n// The peer that last set a key, from Loro's per-key last-writer-wins register.\n// \"@updatedAt\" is restamped with a fresh timestamp on every row write, so its\n// last editor is the peer of the row's most recent write. (Probing \"@updatedBy\"\n// would be wrong: it stores a user id that repeats when one user edits twice,\n// which Loro records as a no-op, leaving the register on the earlier writer.)\nfunction readRowEditorPeer(row: LoroMap, key: string): string | null {\n return row.getLastEditor(key) ?? null;\n}\n\nfunction parseDocumentRow(row: LoroMap): DocumentRow | null {\n const id = readRowString(row, ROW_ID_KEY);\n if (id.length === 0) {\n return null;\n }\n\n const fields: Record<string, string> = {};\n const fieldEditors: Record<string, string | null> = {};\n for (const [key, value] of row.entries()) {\n if (key.startsWith(ROW_META_PREFIX)) {\n continue;\n }\n if (typeof value === \"string\") {\n fields[key] = value;\n // Each data cell has its own last-editor register, so field-level\n // attribution is read the same way as the row-level peer.\n fieldEditors[key] = readRowEditorPeer(row, key);\n }\n }\n\n return {\n id,\n fields,\n fieldEditors,\n createdBy: readRowString(row, ROW_CREATED_BY_KEY),\n createdAt: readRowString(row, ROW_CREATED_AT_KEY),\n createdByPeer: readRowEditorPeer(row, ROW_CREATED_AT_KEY),\n updatedBy: readRowString(row, ROW_UPDATED_BY_KEY),\n updatedAt: readRowString(row, ROW_UPDATED_AT_KEY),\n updatedByPeer: readRowEditorPeer(row, ROW_UPDATED_AT_KEY),\n };\n}\n\nexport function ensureDocumentRowsStructure(doc: RowListDocumentShape): void {\n doc.getList(DOCUMENT_ROWS_LIST_KEY);\n}\n\nfunction findRowMap(list: LoroList, id: string): LoroMap | null {\n for (let index = 0; index < list.length; index += 1) {\n const value = list.get(index);\n if (value instanceof LoroMap && readRowString(value, ROW_ID_KEY) === id) {\n return value;\n }\n }\n\n return null;\n}\n\nexport function listDocumentRows(doc: RowListDocumentShape): DocumentRow[] {\n const list = doc.getList(DOCUMENT_ROWS_LIST_KEY);\n const rows: DocumentRow[] = [];\n for (let index = 0; index < list.length; index += 1) {\n const value = list.get(index);\n if (value instanceof LoroMap) {\n const row = parseDocumentRow(value);\n if (row) {\n rows.push(row);\n }\n }\n }\n\n return rows;\n}\n\nfunction writeRowFields(\n row: LoroMap,\n fields: Readonly<Record<string, string>>,\n): void {\n for (const [key, value] of Object.entries(fields)) {\n // Never let a caller's field name overwrite reserved metadata.\n if (key.startsWith(ROW_META_PREFIX)) {\n continue;\n }\n row.set(key, value);\n }\n}\n\nexport function addDocumentRow(\n doc: RowListDocumentShape,\n id: string,\n fields: Readonly<Record<string, string>>,\n attribution: DocumentRowAttribution,\n): void {\n const list = doc.getList(DOCUMENT_ROWS_LIST_KEY);\n const row = list.pushContainer(new LoroMap());\n row.set(ROW_ID_KEY, id);\n row.set(ROW_CREATED_BY_KEY, attribution.userId);\n row.set(ROW_CREATED_AT_KEY, attribution.at);\n row.set(ROW_UPDATED_BY_KEY, attribution.userId);\n row.set(ROW_UPDATED_AT_KEY, attribution.at);\n writeRowFields(row, fields);\n}\n\nexport function setDocumentRowFields(\n doc: RowListDocumentShape,\n id: string,\n patch: Readonly<Record<string, string>>,\n attribution: DocumentRowAttribution,\n): boolean {\n const list = doc.getList(DOCUMENT_ROWS_LIST_KEY);\n const row = findRowMap(list, id);\n if (!row) {\n return false;\n }\n\n writeRowFields(row, patch);\n row.set(ROW_UPDATED_BY_KEY, attribution.userId);\n row.set(ROW_UPDATED_AT_KEY, attribution.at);\n return true;\n}\n\n/**\n * Make a row's cells equal `fields`: write the ones that differ and clear the\n * ones that are absent. Untouched cells keep their last editor. Returns whether\n * the row exists and anything changed.\n */\nexport function replaceDocumentRowFields(\n doc: RowListDocumentShape,\n id: string,\n fields: Readonly<Record<string, string>>,\n attribution: DocumentRowAttribution,\n): boolean {\n const row = findRowMap(doc.getList(DOCUMENT_ROWS_LIST_KEY), id);\n if (!row) {\n return false;\n }\n\n let changed = false;\n for (const key of row.keys()) {\n // Own keys only: a cell named `constructor` or `toString` is not \"in\"\n // the restored fields merely because every object inherits one.\n if (!key.startsWith(ROW_META_PREFIX) && !Object.hasOwn(fields, key)) {\n row.delete(key);\n changed = true;\n }\n }\n for (const [key, value] of Object.entries(fields)) {\n if (!key.startsWith(ROW_META_PREFIX) && row.get(key) !== value) {\n row.set(key, value);\n changed = true;\n }\n }\n if (changed) {\n row.set(ROW_UPDATED_BY_KEY, attribution.userId);\n row.set(ROW_UPDATED_AT_KEY, attribution.at);\n }\n return changed;\n}\n\nexport function removeDocumentRow(\n doc: RowListDocumentShape,\n id: string,\n): boolean {\n const list = doc.getList(DOCUMENT_ROWS_LIST_KEY);\n for (let index = 0; index < list.length; index += 1) {\n const value = list.get(index);\n if (value instanceof LoroMap && readRowString(value, ROW_ID_KEY) === id) {\n list.delete(index, 1);\n return true;\n }\n }\n\n return false;\n}\n\nfunction sameRow(left: DocumentRow, right: DocumentRow): boolean {\n if (\n left.id !== right.id ||\n left.createdBy !== right.createdBy ||\n left.createdAt !== right.createdAt ||\n left.createdByPeer !== right.createdByPeer ||\n left.updatedBy !== right.updatedBy ||\n left.updatedAt !== right.updatedAt ||\n left.updatedByPeer !== right.updatedByPeer\n ) {\n return false;\n }\n\n const leftKeys = Object.keys(left.fields);\n const rightKeys = Object.keys(right.fields);\n if (leftKeys.length !== rightKeys.length) {\n return false;\n }\n\n // fieldEditors shares the exact key set as fields, so comparing per key here\n // also covers a cell whose value is unchanged but whose editor changed.\n return leftKeys.every(\n (key) =>\n left.fields[key] === right.fields[key] &&\n left.fieldEditors[key] === right.fieldEditors[key],\n );\n}\n\nexport function sameDocumentRows(\n left: ReadonlyArray<DocumentRow>,\n right: ReadonlyArray<DocumentRow>,\n): boolean {\n return (\n left.length === right.length &&\n left.every((row, index) => {\n const nextRow = right[index];\n return nextRow !== undefined && sameRow(row, nextRow);\n })\n );\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  export * from "./documentConstants.js";
2
2
  export * from "./documentContent.js";
3
3
  export { createDocumentProjectorRegistry, type DocumentClientProjectionDefinition, type DocumentClientProjectionDeleteInput, type DocumentClientProjectionSaveInput, type DocumentFieldValidationIssue, type DocumentProjection, type DocumentProjectorDefinition, type DocumentProjectorInput, type DocumentProjectorRegistry, type DocumentProjectorRegistryInput, defaultDocumentProjectorRegistry, deriveStoredDocumentTitle, getDocumentClientProjectionTables, getStoredDocumentTypeLabel, getUntitledDocumentTitle, initializeStoredDocumentKind, projectStoredDocumentState, readStoredDocumentState, readStringDocumentField, type StoredDocumentKind, type StoredDocumentState, type StructuredDocumentMap, type StructuredDocumentShape, type StructuredDocumentText, type ValidatedDocumentFields, writeStoredDocumentFields, } from "./documentKinds.js";
4
+ export type { DocumentRestoreContent } from "./documentRestore.js";
4
5
  export type { DocumentRow, DocumentRowSummary, } from "./documentRowList.js";
5
6
  export * from "./documentSummary.js";
6
7
  export { resolveOpIdAttribution, summarizeDocumentContributors, writerByPeerId, } from "./editAttribution.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,cAAc,qBAAqB,CAAC;AACpC,cAAc,mBAAmB,CAAC;AAClC,OAAO,EACL,+BAA+B,EAU/B,gCAAgC,EAChC,yBAAyB,EACzB,iCAAiC,EACjC,0BAA0B,EAC1B,wBAAwB,EACxB,4BAA4B,EAC5B,0BAA0B,EAC1B,uBAAuB,EACvB,uBAAuB,EAOvB,yBAAyB,GAC1B,MAAM,iBAAiB,CAAC;AAKzB,cAAc,mBAAmB,CAAC;AAClC,OAAO,EACL,sBAAsB,EACtB,6BAA6B,EAC7B,cAAc,GACf,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,sBAAsB,EACtB,mBAAmB,EACnB,2BAA2B,EAC3B,8BAA8B,EAC9B,6BAA6B,EAE7B,0BAA0B,EAC1B,gBAAgB,GACjB,MAAM,WAAW,CAAC","sourcesContent":["export * from \"./documentConstants\";\nexport * from \"./documentContent\";\nexport {\n createDocumentProjectorRegistry,\n type DocumentClientProjectionDefinition,\n type DocumentClientProjectionDeleteInput,\n type DocumentClientProjectionSaveInput,\n type DocumentFieldValidationIssue,\n type DocumentProjection,\n type DocumentProjectorDefinition,\n type DocumentProjectorInput,\n type DocumentProjectorRegistry,\n type DocumentProjectorRegistryInput,\n defaultDocumentProjectorRegistry,\n deriveStoredDocumentTitle,\n getDocumentClientProjectionTables,\n getStoredDocumentTypeLabel,\n getUntitledDocumentTitle,\n initializeStoredDocumentKind,\n projectStoredDocumentState,\n readStoredDocumentState,\n readStringDocumentField,\n type StoredDocumentKind,\n type StoredDocumentState,\n type StructuredDocumentMap,\n type StructuredDocumentShape,\n type StructuredDocumentText,\n type ValidatedDocumentFields,\n writeStoredDocumentFields,\n} from \"./documentKinds\";\nexport type {\n DocumentRow,\n DocumentRowSummary,\n} from \"./documentRowList\";\nexport * from \"./documentSummary\";\nexport {\n resolveOpIdAttribution,\n summarizeDocumentContributors,\n writerByPeerId,\n} from \"./editAttribution\";\nexport {\n ENV_FILE_DOCUMENT_KIND,\n ENV_FILE_NAME_FIELD,\n ENV_FILE_VARIABLE_KEY_FIELD,\n ENV_FILE_VARIABLE_NAME_PATTERN,\n ENV_FILE_VARIABLE_VALUE_FIELD,\n type EnvFileVariable,\n isValidEnvFileVariableName,\n parseEnvFileText,\n} from \"./envFile\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,cAAc,qBAAqB,CAAC;AACpC,cAAc,mBAAmB,CAAC;AAClC,OAAO,EACL,+BAA+B,EAU/B,gCAAgC,EAChC,yBAAyB,EACzB,iCAAiC,EACjC,0BAA0B,EAC1B,wBAAwB,EACxB,4BAA4B,EAC5B,0BAA0B,EAC1B,uBAAuB,EACvB,uBAAuB,EAOvB,yBAAyB,GAC1B,MAAM,iBAAiB,CAAC;AAMzB,cAAc,mBAAmB,CAAC;AAClC,OAAO,EACL,sBAAsB,EACtB,6BAA6B,EAC7B,cAAc,GACf,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,sBAAsB,EACtB,mBAAmB,EACnB,2BAA2B,EAC3B,8BAA8B,EAC9B,6BAA6B,EAE7B,0BAA0B,EAC1B,gBAAgB,GACjB,MAAM,WAAW,CAAC","sourcesContent":["export * from \"./documentConstants\";\nexport * from \"./documentContent\";\nexport {\n createDocumentProjectorRegistry,\n type DocumentClientProjectionDefinition,\n type DocumentClientProjectionDeleteInput,\n type DocumentClientProjectionSaveInput,\n type DocumentFieldValidationIssue,\n type DocumentProjection,\n type DocumentProjectorDefinition,\n type DocumentProjectorInput,\n type DocumentProjectorRegistry,\n type DocumentProjectorRegistryInput,\n defaultDocumentProjectorRegistry,\n deriveStoredDocumentTitle,\n getDocumentClientProjectionTables,\n getStoredDocumentTypeLabel,\n getUntitledDocumentTitle,\n initializeStoredDocumentKind,\n projectStoredDocumentState,\n readStoredDocumentState,\n readStringDocumentField,\n type StoredDocumentKind,\n type StoredDocumentState,\n type StructuredDocumentMap,\n type StructuredDocumentShape,\n type StructuredDocumentText,\n type ValidatedDocumentFields,\n writeStoredDocumentFields,\n} from \"./documentKinds\";\nexport type { DocumentRestoreContent } from \"./documentRestore\";\nexport type {\n DocumentRow,\n DocumentRowSummary,\n} from \"./documentRowList\";\nexport * from \"./documentSummary\";\nexport {\n resolveOpIdAttribution,\n summarizeDocumentContributors,\n writerByPeerId,\n} from \"./editAttribution\";\nexport {\n ENV_FILE_DOCUMENT_KIND,\n ENV_FILE_NAME_FIELD,\n ENV_FILE_VARIABLE_KEY_FIELD,\n ENV_FILE_VARIABLE_NAME_PATTERN,\n ENV_FILE_VARIABLE_VALUE_FIELD,\n type EnvFileVariable,\n isValidEnvFileVariableName,\n parseEnvFileText,\n} from \"./envFile\";\n"]}
package/index.d.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  export { type ApiRequestCounts, type ApiRequestEndpointCounts, ApiRequestMetrics, type ApiRequestMetricsSnapshot, } from "./internal/api-client/index.js";
2
- export type { AbandonOrganizationPolicyMutationInput, AddOrganizationGroupUserInput, BlobInfo, BlobInfoAttachmentKind, BlobInfoDocumentReference, BlobInfoInput, BlobInfoList, BlobInfoSort, BlobInfoSortDirection, BlobInfoSortKey, BrowserLocalKeyringOptions, ContainerContents, ContainerContentsContextValue, ContainerContentsStore, ContainerContentsStoreOptions, ContainerDocumentLinkInput, ContainerDocumentLinks, ContainerDocumentObjectSyncState, ContainerDocumentObjectSyncStatus, ContainerDocumentQueries, ContainerDocumentSidebarRow, ContainerInfo, ContainerInfoInput, ContainerItemRow, ContainerItemSort, ContainerItemSortDirection, ContainerItemSortKey, ContainerNode, ContainerShareAccessLevel, CreateOrganizationOptions, DatabaseListener, DatabaseOptions, DatabaseSnapshot, DatabaseStatus, DeviceFirst, DeviceFirstContainerContents, DiscardUnreadableOrganizationPolicyMutationInput, DocumentAttachmentStatus, DocumentAttachmentUpload, DocumentAttributionRangesInput, DocumentAttributionRangesPage, DocumentContextValue, DocumentInfo, DocumentInfoInput, DocumentList, DocumentSort, DocumentSortDirection, DocumentSortKey, DocumentStore, DocumentSubscriptionOptions, Documents, DocumentsRuntime, DomainScope, FileSaver, Identity, IdentityGenerationResult, IdentityKeyPackage, IdentityListener, IdentityOptions, IdentitySnapshot, IndexedDbLocalKeyringManifestStoreOptions, IndexedDbWrappingKeyKeystoreOptions, LinkDocumentToContainerInput, ListDocumentsInput, LocalKeyPurpose, LocalKeyring, LocalKeyringManifest, LocalKeyringManifestFormat, LocalKeyringManifestStorage, LocalKeyringManifestStore, LocalKeyringOptions, LocalKeyringPinCode, LocalKeyringScope, LocalKeyringSession, LocalOrganizationSummary, LocalProjectionReconciledDelta, LocalProjectionSnapshot, LocalProjectionView, LocalSecretContext, LocalStorageLocalKeyringManifestStoreOptions, Logger, MergeDocumentSummary, MoveDocumentToContainerInput, NetworkListener, NetworkMode, NetworkStatusSource, NormalizedLocalKeyringScope, OpenContainerDocumentInput, OpenDocumentInput, OpenDocumentOptions, OrganizationBilling, OrganizationBillingHistory, OrganizationBillingHistoryEntry, OrganizationBillingManagementUrl, OrganizationBillingView, OrganizationContainerGrant, OrganizationContainerGrants, OrganizationDataUsage, OrganizationDeviceDataUsage, OrganizationDeviceDocumentUsageCategoryBreakdown, OrganizationDirectory, OrganizationDirectoryAndGroups, OrganizationDirectoryUser, OrganizationGrantRef, OrganizationGroupContainer, OrganizationGroupContainers, OrganizationGroupDetails, OrganizationGroupMember, OrganizationGroupMembers, OrganizationGroupMutationReceipt, OrganizationGroupMutationResult, OrganizationGroupPolicyHistory, OrganizationGroupSummary, OrganizationLeaveRequestResult, OrganizationMembership, OrganizationMemberships, OrganizationPolicyGrantChange, OrganizationPolicyGroupChange,
2
+ export type { AbandonOrganizationPolicyMutationInput, AddOrganizationGroupUserInput, BlobInfo, BlobInfoAttachmentKind, BlobInfoDocumentReference, BlobInfoInput, BlobInfoList, BlobInfoSort, BlobInfoSortDirection, BlobInfoSortKey, BrowserLocalKeyringOptions, ContainerContents, ContainerContentsContextValue, ContainerContentsStore, ContainerContentsStoreOptions, ContainerDocumentLinkInput, ContainerDocumentLinks, ContainerDocumentObjectSyncState, ContainerDocumentObjectSyncStatus, ContainerDocumentQueries, ContainerDocumentSidebarRow, ContainerInfo, ContainerInfoInput, ContainerItemRow, ContainerItemSort, ContainerItemSortDirection, ContainerItemSortKey, ContainerNode, ContainerShareAccessLevel, CreateOrganizationOptions, DatabaseListener, DatabaseOptions, DatabaseSnapshot, DatabaseStatus, DeviceFirst, DeviceFirstContainerContents, DiscardUnreadableOrganizationPolicyMutationInput, DocumentAttachmentStatus, DocumentAttachmentUpload, DocumentAttributionRangesInput, DocumentAttributionRangesPage, DocumentContextValue, DocumentHistory, DocumentHistoryChange, DocumentHistoryRowChange, DocumentHistoryStop, DocumentHistoryTextChange, DocumentHistoryVersion, DocumentHistoryVersionEntry, DocumentHistoryView, DocumentInfo, DocumentInfoInput, DocumentList, DocumentSort, DocumentSortDirection, DocumentSortKey, DocumentStore, DocumentSubscriptionOptions, Documents, DocumentsRuntime, DomainScope, FileSaver, Identity, IdentityGenerationResult, IdentityKeyPackage, IdentityListener, IdentityOptions, IdentitySnapshot, IndexedDbLocalKeyringManifestStoreOptions, IndexedDbWrappingKeyKeystoreOptions, LinkDocumentToContainerInput, ListDocumentsInput, LocalKeyPurpose, LocalKeyring, LocalKeyringManifest, LocalKeyringManifestFormat, LocalKeyringManifestStorage, LocalKeyringManifestStore, LocalKeyringOptions, LocalKeyringPinCode, LocalKeyringScope, LocalKeyringSession, LocalOrganizationSummary, LocalProjectionReconciledDelta, LocalProjectionSnapshot, LocalProjectionView, LocalSecretContext, LocalStorageLocalKeyringManifestStoreOptions, Logger, MergeDocumentSummary, MoveDocumentToContainerInput, NetworkListener, NetworkMode, NetworkStatusSource, NormalizedLocalKeyringScope, OpenContainerDocumentInput, OpenDocumentInput, OpenDocumentOptions, OrganizationBilling, OrganizationBillingHistory, OrganizationBillingHistoryEntry, OrganizationBillingManagementUrl, OrganizationBillingView, OrganizationContainerGrant, OrganizationContainerGrants, OrganizationDataUsage, OrganizationDeviceDataUsage, OrganizationDeviceDocumentUsageCategoryBreakdown, OrganizationDirectory, OrganizationDirectoryAndGroups, OrganizationDirectoryUser, OrganizationGrantRef, OrganizationGroupContainer, OrganizationGroupContainers, OrganizationGroupDetails, OrganizationGroupMember, OrganizationGroupMembers, OrganizationGroupMutationReceipt, OrganizationGroupMutationResult, OrganizationGroupPolicyHistory, OrganizationGroupSummary, OrganizationLeaveRequestResult, OrganizationMembership, OrganizationMemberships, OrganizationPolicyGrantChange, OrganizationPolicyGroupChange,
3
3
  /** Verified organization display page with an optional older-page cursor. */
4
4
  OrganizationPolicyHistory, OrganizationPolicyHistoryEntry, OrganizationProfile, OrganizationSyncPauseResult, Organizations, OrganizationUserDetail, PendingWriteQueueItem, PendingWriteQueueItemStatus, PendingWriteQueueObjectKind, PendingWriteQueueOperation, PendingWriteQueueOperationKind, PendingWriteQueueOperationStatus, PersistedDocumentListener, PinCodeBrowserLocalKeyringOptions, PinCodeWrappingKeyKeystoreOptions, PurgeDocumentInput, PurgeDocumentResult, ReconciliationService, RemoveOrganizationGroupUserInput, ResolvedUserIdentity, SaveFileRequest, SecurityIncident, SecurityIncidentListener, SecurityIncidentObjectKind, SecurityIncidents, Session, SessionContext, SessionCreateOrganizationResult, SessionListener, SessionRecoverOrganizationResult, SessionRegistrationRefusal, SessionRegistrationResult, SessionSnapshot, SetActiveDocumentContainerInput, SetLinkedContainerIdsForDocument, UnlinkDocumentFromContainerInput, UnwrapLocalSecretInput, UserIdentities, UserSession, WrapLocalSecretInput, WrappedLocalSecretEnvelope, WrappedLocalSecretFormat, WrappingKeyHandle, WrappingKeyKeystore, WrappingKeyMaterialStorage, } from "./client/index.js";
5
5
  export { type BlobStoreFactory, Blobs, createBrowserLocalKeyring, createBrowserLocalKeyringManifestStore, createBrowserNetworkStatusSource, createContainerDocumentObjectSyncState, createDomainScope, createIndexedDbLocalKeyringManifestStore, createIndexedDbWrappingKeyKeystore, createLocalKeyring, createLocalStorageLocalKeyringManifestStore, createMemoryLocalKeyringManifestStore, createMemoryWrappingKeyKeystore, createPinCodeBrowserLocalKeyring, createPinCodeWrappingKeyKeystore, createRevenueCatPurchases, createUnavailableDirectCheckout, createUnavailablePurchases, createWebViewLocalKeyring, Database, DEFAULT_DOCUMENT_ID, type DirectCheckoutAppearance, type DirectCheckoutCapability, type DirectCheckoutConfirmation, type DirectCheckoutSession, DirectCheckoutUnavailableError, decodeLocalKeyringSqliteKey, Events, type EventsListener, type EventsSnapshot, encodeLocalKeyringSqliteKey, enqueueReconciliationForEvents, IDENTITY_KEY_PACKAGE_FORMAT, isPinCodeWrappedLocalSecretEnvelope, LOCAL_KEYRING_MANIFEST_FORMAT, localKeyringScopeKey, Network, normalizeLocalKeyringScope, type PrincipalHistoryKeyProvider, type PrincipalHistoryKeyScope, PurchaseAbortedError, PurchaseAlreadyOwnedError, PurchaseCancelledError, PurchaseIdentityPendingError, PurchaseProviderStalledError, type PurchasesCapability, PurchasesUnavailableError, PurgedOrganizationRecoveryBillingRequiredError, parseLocalKeyringManifest, type RevenueCatBackend, type RevenueCatCustomerInfo, type RevenueCatPackage, type RevenueCatPurchasesConfig, SyncBillingGate, type SyncBillingGateListener, type SyncPurchaseResult, type SyncSubscriptionOption, serializeLocalKeyringManifest, UnverifiedUserIdentityError, WRAPPED_LOCAL_SECRET_FORMAT, } from "./client/index.js";
6
- export type { DiscoveredDocumentInput, DocumentAttachment, DocumentClientProjectionDefinition, DocumentClientProjectionDeleteInput, DocumentClientProjectionSaveInput, DocumentFieldValidationIssue, DocumentProjection, DocumentProjectorDefinition, DocumentProjectorInput, DocumentProjectorRegistry, DocumentProjectorRegistryInput, DocumentRow, DocumentRowSummary, DocumentSummary, EnvFileVariable, StoredDocumentKind, StoredDocumentState, StructuredDocumentMap, StructuredDocumentShape, StructuredDocumentText, ValidatedDocumentFields, } from "./data/documents/index.js";
6
+ export type { DiscoveredDocumentInput, DocumentAttachment, DocumentClientProjectionDefinition, DocumentClientProjectionDeleteInput, DocumentClientProjectionSaveInput, DocumentFieldValidationIssue, DocumentProjection, DocumentProjectorDefinition, DocumentProjectorInput, DocumentProjectorRegistry, DocumentProjectorRegistryInput, DocumentRestoreContent, DocumentRow, DocumentRowSummary, DocumentSummary, EnvFileVariable, StoredDocumentKind, StoredDocumentState, StructuredDocumentMap, StructuredDocumentShape, StructuredDocumentText, ValidatedDocumentFields, } from "./data/documents/index.js";
7
7
  export { addDocumentAttachments, createDocumentProjectorRegistry, createDocumentSignerDeviceId, DEFAULT_DOCUMENT_ACCESS_EPOCH, DEFAULT_DOCUMENT_KIND, defaultDocumentProjectorRegistry, deriveStoredDocumentTitle, ENV_FILE_DOCUMENT_KIND, ENV_FILE_NAME_FIELD, ENV_FILE_VARIABLE_KEY_FIELD, ENV_FILE_VARIABLE_NAME_PATTERN, ENV_FILE_VARIABLE_VALUE_FIELD, ensureDocumentAttachmentStructure, getDocumentAttachments, getDocumentClientProjectionTables, getStoredDocumentTypeLabel, getUntitledDocumentTitle, initializeStoredDocumentKind, isValidEnvFileVariableName, parseEnvFileText, projectStoredDocumentState, readStoredDocumentState, readStringDocumentField, resolveOpIdAttribution, sameDocumentAttachments, summarizeDocumentContributors, writerByPeerId, writeStoredDocumentFields, } from "./data/documents/index.js";
8
8
  export type { ContainerContentsSnapshot, ContainerContentsStoreRuntime, ContainerContentsStoreState, ContainerContentsStoreSyncAgent, ContainerContentsStoreSyncState, ContainerState, PurgeMoveSettlement, PurgeOptions, PurgeProgress, } from "./stores/container-contents/index.js";
9
9
  export { createContainerContentsStore, createContainerContentsStoreState, createContainerContentsStoreSyncAgent, getOrCreateContainerContentsStore, isSystemContainerNode, requestContainerContentsDocumentPriming, subscribeToContainerContentsStore, updateContainerContentsSnapshot, updateContainerContentsStoreRuntime, } from "./stores/container-contents/index.js";
@@ -18,7 +18,7 @@ export { ContainerSyncWatermarkRepository, createContainerContentsDocumentsRunti
18
18
  export type { AggregatedContainerKekLog, ContainerMutationAuthor, ContainerMutationCollaborators, ContainerReciteApi, ContainerWriteRefusal, KeyringRebuildResult, MaterializedContainerRekeyPlan, } from "./workflows/containers/index.js";
19
19
  export { buildMaterializedContainerRekeyPlan, buildRootContainerCreatePlan, ContainerAuthorAccessError, ContainerKekRepairInaccessibleError, ContainerKekRepairRequiredError, ContainerKeyringOverrideStaleError, ContainerMutationService, ContainerPathTooDeepError, classifyContainerWriteRefusal, containerWriterProjectionFromRekeyPlan, fetchContainerKekLog, HistoricalWrapUnavailableError, type HistoricalWrapUnavailableReason, isProjectionVerificationCancelledError, rebuildKeyringEntriesFromLog, recoverKeyringEntryFromWraps, rootContainerWriterProjectionFromCreatePlan, } from "./workflows/containers/index.js";
20
20
  export type { DocumentBirthResult, DocumentRecord, DocumentSyncContainerRekeyBuilder, DocumentSyncPullContinuation, DocumentSyncUpdateIsolationError, DocumentsPersistence, DocumentsWorkflowRuntime, DocumentsWorkflowRuntimeInput, IncomingDocumentSyncUpdateValidator, LocalAttachmentRecord, PendingAttachmentRecord, PendingUpdateInsert, PendingUpdateRecord, QueuedPendingUpdateRecord, SyncRemoteDocumentInput, } from "./workflows/documents/index.js";
21
- export { buildMaterializedDocumentCreatePlan, createDocumentProjectionUserKeyResolver, createDocumentsWorkflowRuntime, createRemoteDocument, DOCUMENT_SYNC_TRACE_FRAGMENT, DOCUMENT_SYNC_TRACE_PATTERN, DOCUMENTS_APP_KIND, DocumentRawHistoryUnavailableError, defaultDocumentsPersistence, deletePersistedDocument, deriveStableDocumentId, isDatabaseUnavailableError, isDocumentSyncUpdateIsolationError, persistedDocumentCreateStateFromResponse, readPullContinuation, syncRemoteDocument, unwrapContainerKekPath, unwrapDocumentContentKeyTarget, validateDocumentSyncUpdateImports, } from "./workflows/documents/index.js";
21
+ export { buildMaterializedDocumentCreatePlan, createDocumentProjectionUserKeyResolver, createDocumentsWorkflowRuntime, createRemoteDocument, DOCUMENT_SYNC_TRACE_FRAGMENT, DOCUMENT_SYNC_TRACE_PATTERN, DOCUMENTS_APP_KIND, DocumentRawHistoryUnavailableError, defaultDocumentsPersistence, deletePersistedDocument, deriveStableDocumentId, isDatabaseUnavailableError, isDocumentSyncUpdateIsolationError, isEmptyDocumentHistoryChange, persistedDocumentCreateStateFromResponse, readPullContinuation, syncRemoteDocument, unwrapContainerKekPath, unwrapDocumentContentKeyTarget, validateDocumentSyncUpdateImports, } from "./workflows/documents/index.js";
22
22
  export type { AcknowledgedPrincipalCurrentInput, AcknowledgedPrincipalCurrentRetirement, AuthoredPrincipalMutation, OrganizationDocumentUsageCategory, OrganizationGroupPolicyHistoryEntry, OrganizationNativePurchaseEligibility, OrganizationPrincipalMemberChange, OrganizationPrincipalMemberChangeType, OrganizationPrincipalPolicyHistory, OrganizationPrincipalPolicyHistoryEntry, PrincipalMutationJournalContext, PrincipalMutationJournalScope, PrincipalMutationResponse, ReconcileOrganizationDataUsageInput, } from "./workflows/organizations/index.js";
23
23
  export { abandonJournaledPrincipalMutation, addOrganizationGroupUser, buildInitialGroupPolicyRequest, buildInitialMemberGroupPolicyRequest, buildOrganizationGroupPolicyHistory, buildOrganizationProfileDocumentPatch, buildRosterProfileDocumentPatch, checkNativePurchaseEligibility, createInitializedRosterProfileDocument, createOrganizationGroup, DEFAULT_PERSONAL_ORGANIZATION_PROFILE_NAME, deriveOrganizationMetadataContainerSystemSlot, deriveOrganizationRosterProfileContainerSystemSlot, discardUnreadableJournaledPrincipalMutation, GroupMembershipNameMismatchError, GroupShareNameMismatchError, getOrganizationProfileDocumentLocalId, getRosterProfileDocumentLocalId, loadLocalOrganizationDataUsage, loadLocalOrganizationDirectoryAndGroups, loadOrganizationBilling, loadOrganizationBillingHistory, loadOrganizationBillingManagementUrl, ORGANIZATION_DOCUMENT_USAGE_CATEGORIES, ORGANIZATION_METADATA_CONTAINER_NAME, ORGANIZATION_PROFILE_DOCUMENT_KIND, ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME, PendingPrincipalMutationError, PrincipalMutationOutcomeUnknownError, ROSTER_PROFILE_DOCUMENT_KIND, readJournaledPrincipalMutation, readOrganizationProfileName, reconcileOrganizationDataUsage, reconcileOrganizationDirectoryAndGroups, recoverJournaledPrincipalMutation, removeOrganizationGroupUser, resolveOrganizationBillingView, retainAcknowledgedPrincipalCurrents, revokeOrganizationContainerGrant, shareRemoteContainerWithGroup, startOrganizationTrial, submitJournaledPrincipalMutation, subscribeOrganizationReadModelInvalidation, UnreadablePrincipalMutationError, updateOrganizationProfile, updateOrganizationRosterEntry, } from "./workflows/organizations/index.js";
24
24
  export type { AcknowledgedPrincipalPredecessor, CacheReferencedPrincipalPoliciesOptions, PrincipalHistoryProtectionLease, ProjectionPolicyHistoryRecoveryOptions, RecoveredPrincipalPolicyHistory, RecoveredScopedPrincipalPolicyHistory, RecoverPrincipalPolicyHistoryOptions, RecoverScopedPrincipalPolicyHistoryOptions, } from "./workflows/principals/index.js";
package/index.js CHANGED
@@ -10,7 +10,7 @@ export { Tearleads } from "./Tearleads.js";
10
10
  export { BlobAttachmentService, blobByteSourceInputLength, createBlobByteSource, createBlobStore, createEncryptedBlobStore, createLazyEncryptedBlobStore, createMemoryBlobStore, purgeOpfsBlobStore, readBlobByteSource, wrapEncryptedBlobStore, } from "./workflows/blobs/index.js";
11
11
  export { ContainerSyncWatermarkRepository, createContainerContentsDocumentsRuntime, createContainerContentsProjectionUserKeyResolver, createContainerContentsStoreWorkflowRuntime, createContainerContentsSyncLane, createContainerContentsWorkflowRuntime, createContainerParentSyncLane, createInitializedContainerMetadataDocument, defaultContainerContentsPersistence, deriveContainerSystemSlot, initializeDocumentLinksSchema, listBlobInfo, listDocumentLinkedContainerIds, loadContainerInfo, loadDocumentAttributionRanges, loadDocumentInfo, replaceDocumentLinks, syncedContainerDocumentObjectSyncState, } from "./workflows/container-contents/index.js";
12
12
  export { buildMaterializedContainerRekeyPlan, buildRootContainerCreatePlan, ContainerAuthorAccessError, ContainerKekRepairInaccessibleError, ContainerKekRepairRequiredError, ContainerKeyringOverrideStaleError, ContainerMutationService, ContainerPathTooDeepError, classifyContainerWriteRefusal, containerWriterProjectionFromRekeyPlan, fetchContainerKekLog, HistoricalWrapUnavailableError, isProjectionVerificationCancelledError, rebuildKeyringEntriesFromLog, recoverKeyringEntryFromWraps, rootContainerWriterProjectionFromCreatePlan, } from "./workflows/containers/index.js";
13
- export { buildMaterializedDocumentCreatePlan, createDocumentProjectionUserKeyResolver, createDocumentsWorkflowRuntime, createRemoteDocument, DOCUMENT_SYNC_TRACE_FRAGMENT, DOCUMENT_SYNC_TRACE_PATTERN, DOCUMENTS_APP_KIND, DocumentRawHistoryUnavailableError, defaultDocumentsPersistence, deletePersistedDocument, deriveStableDocumentId, isDatabaseUnavailableError, isDocumentSyncUpdateIsolationError, persistedDocumentCreateStateFromResponse, readPullContinuation, syncRemoteDocument, unwrapContainerKekPath, unwrapDocumentContentKeyTarget, validateDocumentSyncUpdateImports, } from "./workflows/documents/index.js";
13
+ export { buildMaterializedDocumentCreatePlan, createDocumentProjectionUserKeyResolver, createDocumentsWorkflowRuntime, createRemoteDocument, DOCUMENT_SYNC_TRACE_FRAGMENT, DOCUMENT_SYNC_TRACE_PATTERN, DOCUMENTS_APP_KIND, DocumentRawHistoryUnavailableError, defaultDocumentsPersistence, deletePersistedDocument, deriveStableDocumentId, isDatabaseUnavailableError, isDocumentSyncUpdateIsolationError, isEmptyDocumentHistoryChange, persistedDocumentCreateStateFromResponse, readPullContinuation, syncRemoteDocument, unwrapContainerKekPath, unwrapDocumentContentKeyTarget, validateDocumentSyncUpdateImports, } from "./workflows/documents/index.js";
14
14
  export { abandonJournaledPrincipalMutation, addOrganizationGroupUser, buildInitialGroupPolicyRequest, buildInitialMemberGroupPolicyRequest, buildOrganizationGroupPolicyHistory, buildOrganizationProfileDocumentPatch, buildRosterProfileDocumentPatch, checkNativePurchaseEligibility, createInitializedRosterProfileDocument, createOrganizationGroup, DEFAULT_PERSONAL_ORGANIZATION_PROFILE_NAME, deriveOrganizationMetadataContainerSystemSlot, deriveOrganizationRosterProfileContainerSystemSlot, discardUnreadableJournaledPrincipalMutation, GroupMembershipNameMismatchError, GroupShareNameMismatchError, getOrganizationProfileDocumentLocalId, getRosterProfileDocumentLocalId, loadLocalOrganizationDataUsage, loadLocalOrganizationDirectoryAndGroups, loadOrganizationBilling, loadOrganizationBillingHistory, loadOrganizationBillingManagementUrl, ORGANIZATION_DOCUMENT_USAGE_CATEGORIES, ORGANIZATION_METADATA_CONTAINER_NAME, ORGANIZATION_PROFILE_DOCUMENT_KIND, ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME, PendingPrincipalMutationError, PrincipalMutationOutcomeUnknownError, ROSTER_PROFILE_DOCUMENT_KIND, readJournaledPrincipalMutation, readOrganizationProfileName, reconcileOrganizationDataUsage, reconcileOrganizationDirectoryAndGroups, recoverJournaledPrincipalMutation, removeOrganizationGroupUser, resolveOrganizationBillingView, retainAcknowledgedPrincipalCurrents, revokeOrganizationContainerGrant, shareRemoteContainerWithGroup, startOrganizationTrial, submitJournaledPrincipalMutation, subscribeOrganizationReadModelInvalidation, UnreadablePrincipalMutationError, updateOrganizationProfile, updateOrganizationRosterEntry, } from "./workflows/organizations/index.js";
15
15
  export { cacheReferencedPrincipalPolicies, captureAcknowledgedPrincipalPredecessor, PrincipalPolicyHistoryReadError, recoverPrincipalPolicyHistory, recoverProjectionPolicyHistory, recoverScopedPrincipalPolicyHistory, } from "./workflows/principals/index.js";
16
16
  export { bootstrapRootContainer, buildInitialOrganizationPolicyRequest, createInitialRootMetadataBootstrap, persistRegistrationBootstrap, registerIdentity, } from "./workflows/registration/index.js";