@tearleads/client-sdk 0.1.82 → 0.1.85

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 (182) hide show
  1. package/data/documents/documentSync.js.map +1 -1
  2. package/data/documents/shared/crypto.js.map +1 -1
  3. package/data/documents/shared/types.d.ts +1 -1
  4. package/data/documents/shared/types.js.map +1 -1
  5. package/data/persistence/container-contents/containerContentsPersistence.js +2 -2
  6. package/data/persistence/container-contents/containerContentsPersistence.js.map +1 -1
  7. package/data/persistence/container-contents/containerContentsPersistenceTypes.d.ts +1 -1
  8. package/data/persistence/container-contents/containerContentsPersistenceTypes.js.map +1 -1
  9. package/data/persistence/container-contents/containerDeletionPersistence.js +1 -1
  10. package/data/persistence/container-contents/containerDeletionPersistence.js.map +1 -1
  11. package/data/persistence/container-contents/containerDocumentReassignment.js +7 -9
  12. package/data/persistence/container-contents/containerDocumentReassignment.js.map +1 -1
  13. package/data/persistence/container-contents/containerMetadataMutationPersistence.js +3 -3
  14. package/data/persistence/container-contents/containerMetadataMutationPersistence.js.map +1 -1
  15. package/data/persistence/container-contents/containerMetadataPullContinuationPersistence.js +1 -1
  16. package/data/persistence/container-contents/containerMetadataPullContinuationPersistence.js.map +1 -1
  17. package/data/persistence/container-contents/containerMetadataRows.js +4 -20
  18. package/data/persistence/container-contents/containerMetadataRows.js.map +1 -1
  19. package/data/persistence/container-contents/containerPendingUpdatePersistence.js +2 -2
  20. package/data/persistence/container-contents/containerPendingUpdatePersistence.js.map +1 -1
  21. package/data/persistence/container-contents/containerRebindPersistence.js +4 -17
  22. package/data/persistence/container-contents/containerRebindPersistence.js.map +1 -1
  23. package/data/persistence/container-contents/containerReconcilePersistence.js +1 -1
  24. package/data/persistence/container-contents/containerReconcilePersistence.js.map +1 -1
  25. package/data/persistence/container-contents/containerRemovalWork.js +1 -1
  26. package/data/persistence/container-contents/containerRemovalWork.js.map +1 -1
  27. package/data/persistence/container-contents/containerStructuralRepair.js +5 -11
  28. package/data/persistence/container-contents/containerStructuralRepair.js.map +1 -1
  29. package/data/persistence/container-contents/documentContainerProjectionPersistence.js +34 -9
  30. package/data/persistence/container-contents/documentContainerProjectionPersistence.js.map +1 -1
  31. package/data/persistence/container-contents/dormantContainerMetadata.js +4 -14
  32. package/data/persistence/container-contents/dormantContainerMetadata.js.map +1 -1
  33. package/data/persistence/documents/documentDiscoveryEvidencePersistence.js +5 -9
  34. package/data/persistence/documents/documentDiscoveryEvidencePersistence.js.map +1 -1
  35. package/data/persistence/documents/documentDiscoveryReset.d.ts +6 -0
  36. package/data/persistence/documents/documentProjectionContainers.js +28 -0
  37. package/data/persistence/documents/documentProjectionContainers.js.map +1 -0
  38. package/data/persistence/documents/documentsPersistence.js +5 -9
  39. package/data/persistence/documents/documentsPersistence.js.map +1 -1
  40. package/data/persistence/documents/internal/containerDocumentTombstones.js +4 -11
  41. package/data/persistence/documents/internal/containerDocumentTombstones.js.map +1 -1
  42. package/data/persistence/documents/internal/createDocumentWithHistoryCheckpoint.js +1 -1
  43. package/data/persistence/documents/internal/createDocumentWithHistoryCheckpoint.js.map +1 -1
  44. package/data/persistence/documents/internal/discardDocument.js +2 -2
  45. package/data/persistence/documents/internal/discardDocument.js.map +1 -1
  46. package/data/persistence/documents/internal/documentDeletionPersistence.js +8 -22
  47. package/data/persistence/documents/internal/documentDeletionPersistence.js.map +1 -1
  48. package/data/persistence/documents/internal/documentMutationPersistence.js +3 -3
  49. package/data/persistence/documents/internal/documentMutationPersistence.js.map +1 -1
  50. package/data/persistence/documents/internal/documentPullContinuationPersistence.js +1 -1
  51. package/data/persistence/documents/internal/documentPullContinuationPersistence.js.map +1 -1
  52. package/data/persistence/documents/internal/documentRecordIdentity.js.map +1 -1
  53. package/data/persistence/documents/internal/documentRows.js.map +1 -1
  54. package/data/persistence/documents/internal/ensureDocumentsSchema.js +1 -1
  55. package/data/persistence/documents/internal/ensureDocumentsSchema.js.map +1 -1
  56. package/data/persistence/documents/internal/orphanSideRows.js +1 -1
  57. package/data/persistence/documents/internal/orphanSideRows.js.map +1 -1
  58. package/data/persistence/documents/internal/rowQueryPersistence.js +1 -1
  59. package/data/persistence/documents/internal/rowQueryPersistence.js.map +1 -1
  60. package/data/persistence/documents/internal/syncQueuePersistence.js +2 -2
  61. package/data/persistence/documents/internal/syncQueuePersistence.js.map +1 -1
  62. package/data/{sqlite/documentPersistence → persistence/documents/records}/documentHistoryPersistence.d.ts +1 -1
  63. package/data/{sqlite/documentPersistence → persistence/documents/records}/documentHistoryPersistence.js +5 -5
  64. package/data/persistence/documents/records/documentHistoryPersistence.js.map +1 -0
  65. package/data/{sqlite/documentPersistence → persistence/documents/records}/documentPendingUpdatePersistence.d.ts +2 -2
  66. package/data/{sqlite/documentPersistence → persistence/documents/records}/documentPendingUpdatePersistence.js +2 -2
  67. package/data/persistence/documents/records/documentPendingUpdatePersistence.js.map +1 -0
  68. package/data/{sqlite/documentPersistence → persistence/documents/records}/documentPersistenceTypes.d.ts +2 -2
  69. package/data/persistence/documents/records/documentPersistenceTypes.js.map +1 -0
  70. package/data/{sqlite/documentPersistence → persistence/documents/records}/documentRecordPersistence.d.ts +1 -1
  71. package/data/{sqlite/documentPersistence → persistence/documents/records}/documentRecordPersistence.js +4 -4
  72. package/data/persistence/documents/records/documentRecordPersistence.js.map +1 -0
  73. package/data/persistence/documents/records/documentRowsInTransaction.js +68 -0
  74. package/data/persistence/documents/records/documentRowsInTransaction.js.map +1 -0
  75. package/data/{sqlite/documentPersistence → persistence/documents/records}/documentSyncFailurePersistence.d.ts +2 -2
  76. package/data/{sqlite/documentPersistence → persistence/documents/records}/documentSyncFailurePersistence.js +3 -3
  77. package/data/persistence/documents/records/documentSyncFailurePersistence.js.map +1 -0
  78. package/data/{sqlite/documentPersistence → persistence/documents/records}/index.d.ts +2 -2
  79. package/data/{sqlite/documentPersistence → persistence/documents/records}/index.js +4 -4
  80. package/data/persistence/documents/records/index.js.map +1 -0
  81. package/data/persistence/documents/types.d.ts +2 -2
  82. package/data/persistence/documents/types.js.map +1 -1
  83. package/data/persistence/keyingCheckpoints/documentPurgeCheckpointPersistence.d.ts +2 -0
  84. package/data/persistence/keyingCheckpoints/documentPurgeCheckpointPersistence.js +9 -0
  85. package/data/persistence/keyingCheckpoints/documentPurgeCheckpointPersistence.js.map +1 -1
  86. package/data/persistence/keyingCheckpoints/keyingCheckpointPersistence.js +9 -0
  87. package/data/persistence/keyingCheckpoints/keyingCheckpointPersistence.js.map +1 -1
  88. package/data/persistence/principalPolicy/principalPolicyPersistence.js +3 -9
  89. package/data/persistence/principalPolicy/principalPolicyPersistence.js.map +1 -1
  90. package/{workflows/sync/remoteResetPrincipalScope.d.ts → data/persistence/principalPolicy/principalPolicyRemoteReset.d.ts} +1 -1
  91. package/{workflows/sync/remoteResetPrincipalScope.js → data/persistence/principalPolicy/principalPolicyRemoteReset.js} +16 -13
  92. package/data/persistence/principalPolicy/principalPolicyRemoteReset.js.map +1 -0
  93. package/data/persistence/verifiedManifestBundlePersistence.d.ts +2 -0
  94. package/data/persistence/verifiedManifestBundlePersistence.js +7 -0
  95. package/data/persistence/verifiedManifestBundlePersistence.js.map +1 -1
  96. package/data/sqlite/{documentPersistence/documentOrphanBlobReclaims.js → schema/documentOrphanBlobReclaimSchema.js} +1 -1
  97. package/data/sqlite/schema/documentOrphanBlobReclaimSchema.js.map +1 -0
  98. package/data/sqlite/schema/index.js +1 -1
  99. package/data/sqlite/schema/index.js.map +1 -1
  100. package/data/sqlite/sqliteBindBudget.js +12 -0
  101. package/data/sqlite/sqliteBindBudget.js.map +1 -1
  102. package/package.json +1 -1
  103. package/workflows/container-contents/container-state/create/createIntentSeed.js.map +1 -1
  104. package/workflows/container-contents/container-state/create/createWithMetadataPlan.js.map +1 -1
  105. package/workflows/container-contents/container-state/types.js.map +1 -1
  106. package/workflows/container-contents/metadata/index.js.map +1 -1
  107. package/workflows/container-contents/metadata/metadataEvents.d.ts +1 -1
  108. package/workflows/container-contents/metadata/metadataEvents.js.map +1 -1
  109. package/workflows/container-contents/metadata/metadataIncomingUpdateIsolation.js +1 -1
  110. package/workflows/container-contents/metadata/metadataIncomingUpdateIsolation.js.map +1 -1
  111. package/workflows/container-contents/metadata/metadataRemoteSync.d.ts +1 -1
  112. package/workflows/container-contents/metadata/metadataRemoteSync.js.map +1 -1
  113. package/workflows/container-contents/pendingWrites/index.js +1 -1
  114. package/workflows/container-contents/pendingWrites/index.js.map +1 -1
  115. package/workflows/container-contents/recovery/accessRestoration.js +1 -1
  116. package/workflows/container-contents/recovery/accessRestoration.js.map +1 -1
  117. package/workflows/container-contents/remoteReset/containerRemoteReset.d.ts +185 -0
  118. package/workflows/container-contents/remoteReset/containerRemoteReset.js +174 -0
  119. package/workflows/container-contents/remoteReset/containerRemoteReset.js.map +1 -0
  120. package/workflows/container-contents/remoteReset/remoteResetCursorScope.d.ts +14 -0
  121. package/workflows/{sync → container-contents/remoteReset}/remoteResetCursorScope.js +2 -2
  122. package/workflows/container-contents/remoteReset/remoteResetCursorScope.js.map +1 -0
  123. package/workflows/documents/create/documentCreationPersistence.js.map +1 -1
  124. package/workflows/documents/create/index.d.ts +1 -1
  125. package/workflows/documents/create/index.js.map +1 -1
  126. package/workflows/documents/documentMutationCommit.d.ts +1 -1
  127. package/workflows/documents/documentMutationCommit.js.map +1 -1
  128. package/workflows/documents/index.d.ts +2 -2
  129. package/workflows/documents/index.js +2 -2
  130. package/workflows/documents/index.js.map +1 -1
  131. package/workflows/documents/remoteReset/documentRemoteReset.d.ts +56 -0
  132. package/workflows/documents/remoteReset/documentRemoteReset.js +135 -0
  133. package/workflows/documents/remoteReset/documentRemoteReset.js.map +1 -0
  134. package/workflows/{sync → documents/remoteReset}/remoteResetAttachments.js +3 -3
  135. package/workflows/documents/remoteReset/remoteResetAttachments.js.map +1 -0
  136. package/workflows/{sync → documents/remoteReset}/remoteResetPlans.d.ts +1 -1
  137. package/workflows/{sync → documents/remoteReset}/remoteResetPlans.js +7 -7
  138. package/workflows/documents/remoteReset/remoteResetPlans.js.map +1 -0
  139. package/workflows/documents/sync/index.js.map +1 -1
  140. package/workflows/documents/sync/initialSync.d.ts +1 -1
  141. package/workflows/documents/sync/initialSync.js.map +1 -1
  142. package/workflows/documents/sync/readOnlySync.d.ts +1 -1
  143. package/workflows/documents/sync/readOnlySync.js.map +1 -1
  144. package/workflows/documents/sync/syncAttemptPlanning.js.map +1 -1
  145. package/workflows/documents/sync/syncAttemptState.d.ts +1 -1
  146. package/workflows/documents/sync/syncAttemptState.js.map +1 -1
  147. package/workflows/documents/sync/syncResponseResult.js.map +1 -1
  148. package/workflows/documents/sync/syncSubmittedResult.js.map +1 -1
  149. package/workflows/documents/syncFailures/index.js.map +1 -1
  150. package/workflows/documents/syncPlan/syncContentKeys.d.ts +1 -1
  151. package/workflows/documents/syncPlan/syncContentKeys.js.map +1 -1
  152. package/workflows/documents/syncPlan/syncPlanMaterial.js.map +1 -1
  153. package/workflows/documents/syncPlan/syncPlanRequestBounds.js.map +1 -1
  154. package/workflows/documents/syncRekeys/syncContainerRekeys.js.map +1 -1
  155. package/workflows/documents/syncRekeys/syncRecoveryRekey.d.ts +1 -1
  156. package/workflows/documents/syncRekeys/syncRecoveryRekey.js +1 -1
  157. package/workflows/documents/syncRekeys/syncRecoveryRekey.js.map +1 -1
  158. package/workflows/organizations/readModel/listLocalOrganizations.js +1 -1
  159. package/workflows/organizations/readModel/listLocalOrganizations.js.map +1 -1
  160. package/workflows/organizations/readModel/organizationRemoteReset.js +25 -0
  161. package/workflows/organizations/readModel/organizationRemoteReset.js.map +1 -0
  162. package/workflows/registration/persistRegistrationBootstrap.d.ts +1 -1
  163. package/workflows/registration/persistRegistrationBootstrap.js.map +1 -1
  164. package/workflows/sync/remoteReset.js +60 -229
  165. package/workflows/sync/remoteReset.js.map +1 -1
  166. package/workflows/sync/remoteResetScope.d.ts +7 -10
  167. package/workflows/sync/remoteResetScope.js +26 -108
  168. package/workflows/sync/remoteResetScope.js.map +1 -1
  169. package/data/sqlite/documentPersistence/documentHistoryPersistence.js.map +0 -1
  170. package/data/sqlite/documentPersistence/documentOrphanBlobReclaims.js.map +0 -1
  171. package/data/sqlite/documentPersistence/documentPendingUpdatePersistence.js.map +0 -1
  172. package/data/sqlite/documentPersistence/documentPersistenceTypes.js.map +0 -1
  173. package/data/sqlite/documentPersistence/documentRecordPersistence.js.map +0 -1
  174. package/data/sqlite/documentPersistence/documentSyncFailurePersistence.js.map +0 -1
  175. package/data/sqlite/documentPersistence/index.js.map +0 -1
  176. package/workflows/sync/remoteResetAttachments.js.map +0 -1
  177. package/workflows/sync/remoteResetBatches.js +0 -13
  178. package/workflows/sync/remoteResetBatches.js.map +0 -1
  179. package/workflows/sync/remoteResetCursorScope.js.map +0 -1
  180. package/workflows/sync/remoteResetPlans.js.map +0 -1
  181. package/workflows/sync/remoteResetPrincipalScope.js.map +0 -1
  182. /package/data/{sqlite/documentPersistence → persistence/documents/records}/documentPersistenceTypes.js +0 -0
@@ -27,4 +27,16 @@ export function sqliteRowsPerStatement(variablesPerRow, fixedVariables = 0) {
27
27
  export function sqliteInsertBatchSize(table) {
28
28
  return sqliteRowsPerStatement(Object.keys(getTableColumns(table)).length);
29
29
  }
30
+ // Keep bulk inserts, IN predicates, and expanded pair predicates comfortably
31
+ // below SQLite's common 999-bind and expression-depth limits. Some queued rows
32
+ // consume more than ten binds each, so one conservative size covers every
33
+ // reset statement.
34
+ export const REMOTE_RESET_SQL_BATCH_SIZE = 50;
35
+ export function remoteResetBatches(values) {
36
+ const batches = [];
37
+ for (let offset = 0; offset < values.length; offset += REMOTE_RESET_SQL_BATCH_SIZE) {
38
+ batches.push(values.slice(offset, offset + REMOTE_RESET_SQL_BATCH_SIZE));
39
+ }
40
+ return batches;
41
+ }
30
42
  //# sourceMappingURL=sqliteBindBudget.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"sqliteBindBudget.js","sourceRoot":"","sources":["sqliteBindBudget.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAG9C;;;;GAIG;AACH,MAAM,CAAC,MAAM,4BAA4B,GAAG,GAAG,CAAC;AAEhD;;;GAGG;AACH,MAAM,UAAU,sBAAsB,CACpC,eAAuB,EACvB,cAAc,GAAG,CAAC;IAElB,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CACrB,CAAC,4BAA4B,GAAG,cAAc,CAAC,GAAG,eAAe,CAClE,CAAC;IACF,IACE,CAAC,MAAM,CAAC,SAAS,CAAC,eAAe,CAAC;QAClC,eAAe,GAAG,CAAC;QACnB,CAAC,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC;QACjC,cAAc,GAAG,CAAC;QAClB,IAAI,GAAG,CAAC,EACR,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,iDAAiD,CAAC,CAAC;IACrE,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,qBAAqB,CAAC,KAAkB;IACtD,OAAO,sBAAsB,CAAC,MAAM,CAAC,IAAI,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;AAC5E,CAAC","sourcesContent":["import { getTableColumns } from \"drizzle-orm\";\nimport type { SQLiteTable } from \"drizzle-orm/sqlite-core\";\n\n/**\n * SQLite's historical default `SQLITE_MAX_VARIABLE_NUMBER`. Some hosts raise\n * it, but the SDK runs on several SQLite builds, so every statement it batches\n * stays within this budget.\n */\nexport const SQLITE_BOUND_VARIABLE_BUDGET = 999;\n\n/**\n * Rows (or list entries) one statement may carry when each binds\n * `variablesPerRow` values on top of `fixedVariables` shared ones.\n */\nexport function sqliteRowsPerStatement(\n variablesPerRow: number,\n fixedVariables = 0,\n): number {\n const rows = Math.floor(\n (SQLITE_BOUND_VARIABLE_BUDGET - fixedVariables) / variablesPerRow,\n );\n if (\n !Number.isInteger(variablesPerRow) ||\n variablesPerRow < 1 ||\n !Number.isInteger(fixedVariables) ||\n fixedVariables < 0 ||\n rows < 1\n ) {\n throw new Error(\"SQLite statement cannot fit its bound variables\");\n }\n return rows;\n}\n\n/**\n * Rows per multi-row INSERT into `table`. Every column may bind one value,\n * including explicit nulls, so the column count is the per-row ceiling.\n */\nexport function sqliteInsertBatchSize(table: SQLiteTable): number {\n return sqliteRowsPerStatement(Object.keys(getTableColumns(table)).length);\n}\n"]}
1
+ {"version":3,"file":"sqliteBindBudget.js","sourceRoot":"","sources":["sqliteBindBudget.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAG9C;;;;GAIG;AACH,MAAM,CAAC,MAAM,4BAA4B,GAAG,GAAG,CAAC;AAEhD;;;GAGG;AACH,MAAM,UAAU,sBAAsB,CACpC,eAAuB,EACvB,cAAc,GAAG,CAAC;IAElB,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CACrB,CAAC,4BAA4B,GAAG,cAAc,CAAC,GAAG,eAAe,CAClE,CAAC;IACF,IACE,CAAC,MAAM,CAAC,SAAS,CAAC,eAAe,CAAC;QAClC,eAAe,GAAG,CAAC;QACnB,CAAC,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC;QACjC,cAAc,GAAG,CAAC;QAClB,IAAI,GAAG,CAAC,EACR,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,iDAAiD,CAAC,CAAC;IACrE,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,qBAAqB,CAAC,KAAkB;IACtD,OAAO,sBAAsB,CAAC,MAAM,CAAC,IAAI,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;AAC5E,CAAC;AAED,6EAA6E;AAC7E,+EAA+E;AAC/E,0EAA0E;AAC1E,mBAAmB;AACnB,MAAM,CAAC,MAAM,2BAA2B,GAAG,EAAE,CAAC;AAE9C,MAAM,UAAU,kBAAkB,CAChC,MAAoB;IAEpB,MAAM,OAAO,GAAU,EAAE,CAAC;IAC1B,KACE,IAAI,MAAM,GAAG,CAAC,EACd,MAAM,GAAG,MAAM,CAAC,MAAM,EACtB,MAAM,IAAI,2BAA2B,EACrC,CAAC;QACD,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,EAAE,MAAM,GAAG,2BAA2B,CAAC,CAAC,CAAC;IAC3E,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import { getTableColumns } from \"drizzle-orm\";\nimport type { SQLiteTable } from \"drizzle-orm/sqlite-core\";\n\n/**\n * SQLite's historical default `SQLITE_MAX_VARIABLE_NUMBER`. Some hosts raise\n * it, but the SDK runs on several SQLite builds, so every statement it batches\n * stays within this budget.\n */\nexport const SQLITE_BOUND_VARIABLE_BUDGET = 999;\n\n/**\n * Rows (or list entries) one statement may carry when each binds\n * `variablesPerRow` values on top of `fixedVariables` shared ones.\n */\nexport function sqliteRowsPerStatement(\n variablesPerRow: number,\n fixedVariables = 0,\n): number {\n const rows = Math.floor(\n (SQLITE_BOUND_VARIABLE_BUDGET - fixedVariables) / variablesPerRow,\n );\n if (\n !Number.isInteger(variablesPerRow) ||\n variablesPerRow < 1 ||\n !Number.isInteger(fixedVariables) ||\n fixedVariables < 0 ||\n rows < 1\n ) {\n throw new Error(\"SQLite statement cannot fit its bound variables\");\n }\n return rows;\n}\n\n/**\n * Rows per multi-row INSERT into `table`. Every column may bind one value,\n * including explicit nulls, so the column count is the per-row ceiling.\n */\nexport function sqliteInsertBatchSize(table: SQLiteTable): number {\n return sqliteRowsPerStatement(Object.keys(getTableColumns(table)).length);\n}\n\n// Keep bulk inserts, IN predicates, and expanded pair predicates comfortably\n// below SQLite's common 999-bind and expression-depth limits. Some queued rows\n// consume more than ten binds each, so one conservative size covers every\n// reset statement.\nexport const REMOTE_RESET_SQL_BATCH_SIZE = 50;\n\nexport function remoteResetBatches<T>(\n values: readonly T[],\n): readonly (readonly T[])[] {\n const batches: T[][] = [];\n for (\n let offset = 0;\n offset < values.length;\n offset += REMOTE_RESET_SQL_BATCH_SIZE\n ) {\n batches.push(values.slice(offset, offset + REMOTE_RESET_SQL_BATCH_SIZE));\n }\n return batches;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tearleads/client-sdk",
3
- "version": "0.1.82",
3
+ "version": "0.1.85",
4
4
  "description": "React-free Tearleads client runtime: local SQLite persistence, keys, sync, encrypted blobs, and domain workflows.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -1 +1 @@
1
- {"version":3,"file":"createIntentSeed.js","sourceRoot":"","sources":["createIntentSeed.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAEtD,OAAO,EAAE,2BAA2B,EAAE,MAAM,qCAAqC,CAAC;AAClF,OAAO,EACL,2CAA2C,EAC3C,iDAAiD,GAClD,MAAM,0CAA0C,CAAC;AAIlD,OAAO,EAAE,kCAAkC,EAAE,MAAM,0BAA0B,CAAC;AAE9E;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAC1C,KAAqC,EACrC,cAA8B;IAE9B,IAAI,CAAC;QACH,OAAO,2BAA2B,CAAC;YACjC,eAAe,EAAE,mBAAmB,CAAC,cAAc,CAAC,GAAG,CAAC;YACxD,cAAc,EAAE,MAAM,KAAK,CAAC,WAAW,CAAC,kBAAkB,CACxD,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,EAC3B,cAAc,CAAC,SAAS,CAAC,EAAE,CAC5B;SACF,CAAC,CAAC;IACL,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,0BAA0B,CAC9C,wBAAiD,EACjD,IAAgC,EAChC,MAAsD;IAEtD,MAAM,UAAU,GAAa,EAAE,CAAC;IAChC,IAAI,IAAI,EAAE,CAAC;QACT,iDAAiD,CAC/C,wBAAwB,EACxB,UAAU,EACV,CAAC,IAAI,CAAC,EAAE,CAAC,CACV,CAAC;IACJ,CAAC;IACD,IAAI,QAAQ,GAAa,EAAE,CAAC;IAC5B,IAAI,CAAC;QACH,MAAM,OAAO,GAAG,MAAM,MAAM,EAAE,CAAC;QAC/B,IAAI,OAAO,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,CAAC,YAAY,EAAE,CAAC;YACnE,QAAQ,GAAG,CAAC,OAAO,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAC;QAC7C,CAAC;QACD,OAAO,OAAO,CAAC;IACjB,CAAC;YAAS,CAAC;QACT,2CAA2C,CACzC,wBAAwB,EACxB,UAAU,EACV,QAAQ,CACT,CAAC;IACJ,CAAC;AACH,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,6BAA6B,CACjD,kBAA2C,EAC3C,WAAmB,EACnB,MAAwB;IAExB,MAAM,UAAU,GAAG,kCAAkC,CAAC,WAAW,CAAC,CAAC;IACnE,kBAAkB,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC;IACpC,IAAI,CAAC;QACH,OAAO,MAAM,MAAM,EAAE,CAAC;IACxB,CAAC;YAAS,CAAC;QACT,kBAAkB,EAAE,MAAM,CAAC,UAAU,CAAC,CAAC;IACzC,CAAC;AACH,CAAC","sourcesContent":["import { encodeVersionVector } from \"@tearleads/loro\";\nimport type { PendingUpdateRecord } from \"../../../../data/sqlite/documentPersistence\";\nimport { documentCreateSeedCandidate } from \"../../../documents/sync/initialSync\";\nimport {\n discardUnacceptedContainerMetadataUpdateIds,\n preRegisterMaterializedContainerMetadataUpdateIds,\n} from \"../../metadata/metadataSyncRegistrations\";\nimport type { ContainerState } from \"../../remoteHydration\";\nimport type { createRemoteContainer } from \"../remote\";\nimport type { ContainerCreateIntentSyncState } from \"../types\";\nimport { plannedContainerMetadataDocumentId } from \"./createWithMetadataPlan\";\n\n/**\n * The queued first metadata update, when it holds the whole document, commits\n * with the create instead of a following metadata sync. A seed only saves that\n * sync, so a queue that cannot be read means no seed rather than a failed pass.\n */\nexport async function loadMetadataSeedUpdate(\n state: ContainerCreateIntentSyncState,\n containerState: ContainerState,\n) {\n try {\n return documentCreateSeedCandidate({\n documentVersion: encodeVersionVector(containerState.doc),\n pendingUpdates: await state.persistence.listPendingUpdates(\n state.runtime.infra.execSql,\n containerState.container.id,\n ),\n });\n } catch {\n return null;\n }\n}\n\n/**\n * Runs a seeded create with the seed's id registered as self-authored first,\n * as a metadata sync registers the ids it sends, so the create's own update\n * echo cannot arm the metadata sync the seed replaces. An id the create did\n * not commit is discarded.\n */\nexport async function withRegisteredMetadataSeed(\n locallyAcceptedUpdateIds: Set<string> | undefined,\n seed: PendingUpdateRecord | null,\n create: () => ReturnType<typeof createRemoteContainer>,\n): ReturnType<typeof createRemoteContainer> {\n const registered: string[] = [];\n if (seed) {\n preRegisterMaterializedContainerMetadataUpdateIds(\n locallyAcceptedUpdateIds,\n registered,\n [seed.id],\n );\n }\n let accepted: string[] = [];\n try {\n const created = await create();\n if (created && typeof created !== \"symbol\" && created.metadataSeed) {\n accepted = [created.metadataSeed.updateId];\n }\n return created;\n } finally {\n discardUnacceptedContainerMetadataUpdateIds(\n locallyAcceptedUpdateIds,\n registered,\n accepted,\n );\n }\n}\n\n/**\n * Runs a folder's create with its planned metadata document id registered, so\n * a peer's metadata hint that arrives before the response installs the id\n * still queues the folder's first read (see\n * `listContainerMetadataDocumentUpdateIds`).\n */\nexport async function withPlannedMetadataDocumentId<T>(\n plannedDocumentIds: Set<string> | undefined,\n containerId: string,\n create: () => Promise<T>,\n): Promise<T> {\n const documentId = plannedContainerMetadataDocumentId(containerId);\n plannedDocumentIds?.add(documentId);\n try {\n return await create();\n } finally {\n plannedDocumentIds?.delete(documentId);\n }\n}\n"]}
1
+ {"version":3,"file":"createIntentSeed.js","sourceRoot":"","sources":["createIntentSeed.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE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UAAU,EACV,QAAQ,CACT,CAAC;IACJ,CAAC;AACH,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,6BAA6B,CACjD,kBAA2C,EAC3C,WAAmB,EACnB,MAAwB;IAExB,MAAM,UAAU,GAAG,kCAAkC,CAAC,WAAW,CAAC,CAAC;IACnE,kBAAkB,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC;IACpC,IAAI,CAAC;QACH,OAAO,MAAM,MAAM,EAAE,CAAC;IACxB,CAAC;YAAS,CAAC;QACT,kBAAkB,EAAE,MAAM,CAAC,UAAU,CAAC,CAAC;IACzC,CAAC;AACH,CAAC","sourcesContent":["import { encodeVersionVector } from \"@tearleads/loro\";\nimport type { PendingUpdateRecord } from \"../../../../data/persistence/documents/records\";\nimport { documentCreateSeedCandidate } from \"../../../documents/sync/initialSync\";\nimport {\n discardUnacceptedContainerMetadataUpdateIds,\n preRegisterMaterializedContainerMetadataUpdateIds,\n} from \"../../metadata/metadataSyncRegistrations\";\nimport type { ContainerState } from \"../../remoteHydration\";\nimport type { createRemoteContainer } from \"../remote\";\nimport type { ContainerCreateIntentSyncState } from \"../types\";\nimport { plannedContainerMetadataDocumentId } from \"./createWithMetadataPlan\";\n\n/**\n * The queued first metadata update, when it holds the whole document, commits\n * with the create instead of a following metadata sync. A seed only saves that\n * sync, so a queue that cannot be read means no seed rather than a failed pass.\n */\nexport async function loadMetadataSeedUpdate(\n state: ContainerCreateIntentSyncState,\n containerState: ContainerState,\n) {\n try {\n return documentCreateSeedCandidate({\n documentVersion: encodeVersionVector(containerState.doc),\n pendingUpdates: await state.persistence.listPendingUpdates(\n state.runtime.infra.execSql,\n containerState.container.id,\n ),\n });\n } catch {\n return null;\n }\n}\n\n/**\n * Runs a seeded create with the seed's id registered as self-authored first,\n * as a metadata sync registers the ids it sends, so the create's own update\n * echo cannot arm the metadata sync the seed replaces. An id the create did\n * not commit is discarded.\n */\nexport async function withRegisteredMetadataSeed(\n locallyAcceptedUpdateIds: Set<string> | undefined,\n seed: PendingUpdateRecord | null,\n create: () => ReturnType<typeof createRemoteContainer>,\n): ReturnType<typeof createRemoteContainer> {\n const registered: string[] = [];\n if (seed) {\n preRegisterMaterializedContainerMetadataUpdateIds(\n locallyAcceptedUpdateIds,\n registered,\n [seed.id],\n );\n }\n let accepted: string[] = [];\n try {\n const created = await create();\n if (created && typeof created !== \"symbol\" && created.metadataSeed) {\n accepted = [created.metadataSeed.updateId];\n }\n return created;\n } finally {\n discardUnacceptedContainerMetadataUpdateIds(\n locallyAcceptedUpdateIds,\n registered,\n accepted,\n );\n }\n}\n\n/**\n * Runs a folder's create with its planned metadata document id registered, so\n * a peer's metadata hint that arrives before the response installs the id\n * still queues the folder's first read (see\n * `listContainerMetadataDocumentUpdateIds`).\n */\nexport async function withPlannedMetadataDocumentId<T>(\n plannedDocumentIds: Set<string> | undefined,\n containerId: string,\n create: () => Promise<T>,\n): Promise<T> {\n const documentId = plannedContainerMetadataDocumentId(containerId);\n plannedDocumentIds?.add(documentId);\n try {\n return await create();\n } finally {\n plannedDocumentIds?.delete(documentId);\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"createWithMetadataPlan.js","sourceRoot":"","sources":["createWithMetadataPlan.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,oCAAoC,EAAE,MAAM,qEAAqE,CAAC;AAE3H,OAAO,EACL,oCAAoC,EACpC,4CAA4C,GAC7C,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,mCAAmC,GAEpC,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,kCAAkC,EAAE,MAAM,yCAAyC,CAAC;AAsB7F,mFAAmF;AACnF,MAAM,UAAU,kCAAkC,CAChD,WAAmB;IAEnB,OAAO,WAAW,CAAC;AACrB,CAAC;AAED,KAAK,UAAU,UAAU,CAAC,KAAqC;IAC7D,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC;IAC5C,8EAA8E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C,CAAC;IACH,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,oBAAoB,EAAE,CAAC;AAClE,CAAC;AAED,iFAAiF;AACjF,MAAM,CAAC,KAAK,UAAU,+BAA+B,CACnD,KAAqC;IAErC,IAAI,CAAC;QACH,OAAO,MAAM,UAAU,CAAC,KAAK,CAAC,CAAC;IACjC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,CAAC,CAAC,KAAK,YAAY,oCAAoC,CAAC;YAAE,MAAM,KAAK,CAAC;IAC5E,CAAC;IACD,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;QAAE,OAAO,IAAI,CAAC;IAClD,MAAM,EAAE,SAAS,EAAE,GAAG,KAAK,CAAC,OAAO,CAAC;IACpC,MAAM,QAAQ,GAAG,KAAK,CAAC,gBAAgB,CAAC,WAAW,CAAC;IACpD,SAAS,CAAC,8BAA8B,CAAC,QAAQ,CAAC,CAAC;IACnD,MAAM,gBAAgB,GACpB,MAAM,SAAS,CAAC,4BAA4B,CAAC,QAAQ,CAAC,CAAC;IACzD,IAAI,CAAC,gBAAgB,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;QAAE,OAAO,IAAI,CAAC;IACvE,IACE,gBAAgB,CAAC,WAAW,KAAK,QAAQ;QACzC,gBAAgB,CAAC,cAAc,KAAK,KAAK,CAAC,gBAAgB,CAAC,cAAc,EACzE,CAAC;QACD,MAAM,IAAI,KAAK,CACb,0EAA0E,CAC3E,CAAC;IACJ,CAAC;IACD,OAAO,UAAU,CAAC,EAAE,GAAG,KAAK,EAAE,gBAAgB,EAAE,CAAC,CAAC;AACpD,CAAC","sourcesContent":["import type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport type { ProjectionUserKeyResolver } from \"../../../../data/keyingProjectionVerification\";\nimport { ProjectionDependencyUnavailableError } from \"../../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport type { PendingUpdateRecord } from \"../../../../data/sqlite/documentPersistence\";\nimport {\n buildMaterializedContainerCreatePlan,\n childContainerWriterProjectionFromCreatePlan,\n} from \"../../../containers\";\nimport {\n buildMaterializedDocumentCreatePlan,\n type resolveDocumentCreateAuthor,\n} from \"../../../documents\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../../../principals/runtimePolicyWarmer\";\nimport type { ContainerWorkflowRuntime } from \"../types\";\n\nexport interface ContainerWithMetadataPlanInput {\n readonly author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>;\n readonly containerEventId: string;\n readonly containerId: string;\n readonly containerKey: Uint8Array;\n readonly containerSignedAt: string;\n readonly metadataContentKey: Uint8Array;\n readonly metadataEventId: string;\n /** The queued update holding the metadata document's whole content. */\n readonly metadataSeedUpdate?: PendingUpdateRecord | undefined;\n readonly metadataSignedAt: string;\n readonly parentProjection: ContainerWriterProjectionResponse;\n readonly parentSecretKey: Uint8Array;\n readonly resolveProjectionUserKey: ProjectionUserKeyResolver;\n readonly runtime: ContainerWorkflowRuntime;\n readonly systemSlot?: ContainerSystemSlot | null | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\n/** A folder's metadata document takes the folder's id, known before the create. */\nexport function plannedContainerMetadataDocumentId(\n containerId: string,\n): string {\n return containerId;\n}\n\nasync function buildPlans(input: ContainerWithMetadataPlanInput) {\n const execSql = input.runtime.infra.execSql;\n // Rebuild parent- and policy-dependent hashes, signatures, and wraps on every\n // attempt while retaining the logical mutation identities and key material.\n const containerPlan = await buildMaterializedContainerCreatePlan({\n author: input.author,\n containerId: input.containerId,\n containerKey: input.containerKey,\n execSql,\n eventId: input.containerEventId,\n metadataDocumentId: plannedContainerMetadataDocumentId(input.containerId),\n systemSlot: input.systemSlot,\n parentProjection: input.parentProjection,\n parentSecretKey: input.parentSecretKey,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n signedAt: input.containerSignedAt,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n input.runtime,\n ),\n });\n const childProjection = childContainerWriterProjectionFromCreatePlan({\n materializedPlan: containerPlan,\n parentProjection: input.parentProjection,\n });\n const metadataDocumentPlan = await buildMaterializedDocumentCreatePlan({\n author: input.author,\n containerProjection: childProjection,\n contentKey: input.metadataContentKey,\n documentId: containerPlan.plan.metadataDocumentId,\n eventId: input.metadataEventId,\n execSql,\n knownContainerKeks: new Map([\n [containerPlan.plan.containerKeyEpochId, containerPlan.containerKey],\n ]),\n signedAt: input.metadataSignedAt,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.parentSecretKey,\n trustedLocalProjection: true,\n });\n return { containerPlan, childProjection, metadataDocumentPlan };\n}\n\n/** Refresh stale history evidence once, strictly before submitting the write. */\nexport async function buildContainerWithMetadataPlans(\n input: ContainerWithMetadataPlanInput,\n) {\n try {\n return await buildPlans(input);\n } catch (error) {\n if (!(error instanceof ProjectionDependencyUnavailableError)) throw error;\n }\n if (input.stillCurrent?.() === false) return null;\n const { apiClient } = input.runtime;\n const parentId = input.parentProjection.containerId;\n apiClient.evictContainerWriterProjection(parentId);\n const parentProjection =\n await apiClient.getContainerWriterProjection(parentId);\n if (!parentProjection || input.stillCurrent?.() === false) return null;\n if (\n parentProjection.containerId !== parentId ||\n parentProjection.organizationId !== input.parentProjection.organizationId\n ) {\n throw new Error(\n \"Refreshed parent projection belongs to another container or organization\",\n );\n }\n return buildPlans({ ...input, parentProjection });\n}\n"]}
1
+ {"version":3,"file":"createWithMetadataPlan.js","sourceRoot":"","sources":["createWithMetadataPlan.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,oCAAoC,EAAE,MAAM,qEAAqE,CAAC;AAE3H,OAAO,EACL,oCAAoC,EACpC,4CAA4C,GAC7C,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,mCAAmC,GAEpC,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,kCAAkC,EAAE,MAAM,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gBAAgB,EAAE,CAAC,CAAC;AACpD,CAAC","sourcesContent":["import type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport type { ProjectionUserKeyResolver } from \"../../../../data/keyingProjectionVerification\";\nimport { ProjectionDependencyUnavailableError } from \"../../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport type { PendingUpdateRecord } from \"../../../../data/persistence/documents/records\";\nimport {\n buildMaterializedContainerCreatePlan,\n childContainerWriterProjectionFromCreatePlan,\n} from \"../../../containers\";\nimport {\n buildMaterializedDocumentCreatePlan,\n type resolveDocumentCreateAuthor,\n} from \"../../../documents\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../../../principals/runtimePolicyWarmer\";\nimport type { ContainerWorkflowRuntime } from \"../types\";\n\nexport interface ContainerWithMetadataPlanInput {\n readonly author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>;\n readonly containerEventId: string;\n readonly containerId: string;\n readonly containerKey: Uint8Array;\n readonly containerSignedAt: string;\n readonly metadataContentKey: Uint8Array;\n readonly metadataEventId: string;\n /** The queued update holding the metadata document's whole content. */\n readonly metadataSeedUpdate?: PendingUpdateRecord | undefined;\n readonly metadataSignedAt: string;\n readonly parentProjection: ContainerWriterProjectionResponse;\n readonly parentSecretKey: Uint8Array;\n readonly resolveProjectionUserKey: ProjectionUserKeyResolver;\n readonly runtime: ContainerWorkflowRuntime;\n readonly systemSlot?: ContainerSystemSlot | null | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\n/** A folder's metadata document takes the folder's id, known before the create. */\nexport function plannedContainerMetadataDocumentId(\n containerId: string,\n): string {\n return containerId;\n}\n\nasync function buildPlans(input: ContainerWithMetadataPlanInput) {\n const execSql = input.runtime.infra.execSql;\n // Rebuild parent- and policy-dependent hashes, signatures, and wraps on every\n // attempt while retaining the logical mutation identities and key material.\n const containerPlan = await buildMaterializedContainerCreatePlan({\n author: input.author,\n containerId: input.containerId,\n containerKey: input.containerKey,\n execSql,\n eventId: input.containerEventId,\n metadataDocumentId: plannedContainerMetadataDocumentId(input.containerId),\n systemSlot: input.systemSlot,\n parentProjection: input.parentProjection,\n parentSecretKey: input.parentSecretKey,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n signedAt: input.containerSignedAt,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n input.runtime,\n ),\n });\n const childProjection = childContainerWriterProjectionFromCreatePlan({\n materializedPlan: containerPlan,\n parentProjection: input.parentProjection,\n });\n const metadataDocumentPlan = await buildMaterializedDocumentCreatePlan({\n author: input.author,\n containerProjection: childProjection,\n contentKey: input.metadataContentKey,\n documentId: containerPlan.plan.metadataDocumentId,\n eventId: input.metadataEventId,\n execSql,\n knownContainerKeks: new Map([\n [containerPlan.plan.containerKeyEpochId, containerPlan.containerKey],\n ]),\n signedAt: input.metadataSignedAt,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.parentSecretKey,\n trustedLocalProjection: true,\n });\n return { containerPlan, childProjection, metadataDocumentPlan };\n}\n\n/** Refresh stale history evidence once, strictly before submitting the write. */\nexport async function buildContainerWithMetadataPlans(\n input: ContainerWithMetadataPlanInput,\n) {\n try {\n return await buildPlans(input);\n } catch (error) {\n if (!(error instanceof ProjectionDependencyUnavailableError)) throw error;\n }\n if (input.stillCurrent?.() === false) return null;\n const { apiClient } = input.runtime;\n const parentId = input.parentProjection.containerId;\n apiClient.evictContainerWriterProjection(parentId);\n const parentProjection =\n await apiClient.getContainerWriterProjection(parentId);\n if (!parentProjection || input.stillCurrent?.() === false) return null;\n if (\n parentProjection.containerId !== parentId ||\n parentProjection.organizationId !== input.parentProjection.organizationId\n ) {\n throw new Error(\n \"Refreshed parent projection belongs to another container or organization\",\n );\n }\n return buildPlans({ ...input, parentProjection });\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type {\n ContainerDeleteResponse,\n ContainerWriterProjectionResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport type { ProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport type { DocumentRecord } from \"../../../data/sqlite/documentPersistence\";\nimport type {\n createRemoteContainer,\n moveRemoteContainer,\n shareRemoteContainer,\n} from \"../../containers\";\nimport type { createRemoteDocument } from \"../../documents\";\nimport type { shareRemoteContainerWithGroup } from \"../../organizations/groupShare\";\nimport type { CurrentPrincipalPolicyReader } from \"../../principals/currentPrincipalPolicyReader\";\nimport type { PrincipalPolicyHistoryReader } from \"../../principals/principalPolicyHistoryReader\";\nimport type {\n ContainerContentsPersistence,\n ContainerCreateIntentRecord,\n ContainerMoveIntentRecord,\n} from \"../containerPersistence\";\nimport type { createInitializedContainerMetadataDocument } from \"../metadata/containerMetadataDocument\";\nimport type {\n ContainerState,\n RemoteContainer as HydratedRemoteContainer,\n RemoteContainerHydrationHost,\n} from \"../remoteHydration\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\n\nexport type ContainerWorkflowApi = Parameters<\n typeof createRemoteContainer\n>[0][\"apiClient\"] &\n Parameters<typeof shareRemoteContainer>[0][\"apiClient\"] &\n Parameters<typeof shareRemoteContainerWithGroup>[0][\"apiClient\"] &\n Parameters<typeof moveRemoteContainer>[0][\"apiClient\"] &\n Parameters<typeof createRemoteDocument>[0][\"apiClient\"] &\n Partial<PrincipalPolicyHistoryReader> &\n CurrentPrincipalPolicyReader & {\n deleteContainerResult(\n containerId: string,\n options?: {\n expectedPaymentRequiredOrganizationId?: string;\n reportErrors?: boolean;\n requiredAncestorId?: string | undefined;\n },\n ): Promise<\n | { data: ContainerDeleteResponse; ok: true }\n | {\n ok: false;\n report: () => void;\n status: number | null;\n }\n >;\n primeContainerWriterProjection(\n containerId: string,\n projection: ContainerWriterProjectionResponse,\n ): void;\n };\n\nexport interface ContainerWorkflowRuntime\n extends Pick<\n ContainerContentsWorkflowRuntime,\n | \"auth\"\n | \"crypto\"\n | \"infra\"\n | \"resolveTrustedUserIdentity\"\n | \"state\"\n | \"util\"\n > {\n readonly apiClient: ContainerWorkflowApi;\n}\n\nexport interface CreatedRemoteContainerState {\n accessManifestHash: string;\n /**\n * The metadata seed the create committed, settled by the caller instead of\n * a first metadata sync. Absent when the create carried no seed or fell back\n * to a plain create.\n */\n metadataSeed?:\n | { readonly commitLsn: string | null; readonly updateId: string }\n | undefined;\n /** The slot this client signed into the create; never the server's echo. */\n systemSlot: ContainerSystemSlot | null;\n containerId: string;\n createdAt: string;\n metadataDocumentId: string;\n organizationId: string;\n /** A created container is a child; the acknowledgement echoed this parent. */\n parentId: string;\n persistedMetadataState: Pick<\n DocumentRecord,\n | \"documentId\"\n | \"contentKeyBundle\"\n | \"documentKekTargets\"\n | \"documentManifestBundle\"\n >;\n updatedAt: string;\n}\n\nexport interface SharedRemoteContainerState {\n accessEpoch: number;\n accessManifestHash: string;\n createdAt: string;\n metadataDocumentId: string;\n referencedPrincipalHeads: ReferencedPrincipalStateResponse[];\n updatedAt: string;\n writerProjection: ContainerWriterProjectionResponse | null;\n}\n\nexport interface SharedContainerState {\n container: ContainerState[\"container\"];\n record: ContainerState[\"record\"];\n}\n\nexport type SharedContainerStateResult =\n | { status: \"missing\" }\n | { status: \"confirmed\" }\n | (SharedContainerState & {\n status: \"identity-superseded\" | \"persisted\";\n });\n\nexport type RemoteContainer = HydratedRemoteContainer;\n\nexport type ContainerMetadataDocumentState = Awaited<\n ReturnType<typeof createInitializedContainerMetadataDocument>\n>[\"doc\"];\n\nexport interface CreatedChildContainerState {\n containerState: ContainerState;\n initialUpdate: Uint8Array;\n shouldRequestSync: boolean;\n}\n\nexport interface ContainerIntentSyncState {\n containersById: ReadonlyMap<string, ContainerState>;\n /**\n * Metadata update ids this device sent, so their own update echoes are\n * classified as self-authored (shared with the metadata sync).\n */\n locallyAcceptedMetadataUpdateIds?: Set<string> | undefined;\n /** Metadata document ids of folder creates in flight (shared with hints). */\n plannedMetadataDocumentIds?: Set<string> | undefined;\n persistence: ContainerContentsPersistence;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n /**\n * Verifies that a listed container is this device's pending create before it\n * is adopted and returns where it sits; `assertContainerCreateAdoptable`\n * unless a test replaces it.\n */\n verifyCreateAdoption?: (input: {\n readonly containerId: string;\n readonly expectedOrganizationId: string;\n }) => Promise<AdoptedContainerPlacement>;\n}\n\n/** Where a verified listed create committed, and where its container is now. */\nexport interface AdoptedContainerPlacement {\n /** The parent its signed epoch-1 `container.create` named. */\n readonly createdParentId: string;\n /** The verified head's parent; another writer may have moved it since. */\n readonly currentParentId: string;\n}\n\nexport type ContainerCreateIntentSyncState = ContainerIntentSyncState;\n\nexport type ContainerCreateIntentSyncHost = Pick<\n RemoteContainerHydrationHost,\n \"persistContainerState\"\n>;\n\nexport interface ContainerCreateIntentSyncInput {\n host: ContainerCreateIntentSyncHost;\n /** A parent whose own create has not settled takes no child create. */\n isCreatePending: (containerId: string) => boolean;\n isCurrent: () => boolean;\n isRemoteSyncBlocked: (organizationId: string) => boolean;\n intent: ContainerCreateIntentRecord;\n requestRemoteReconciliation: (parentContainerId: string | null) => void;\n state: ContainerCreateIntentSyncState;\n}\n\nexport type ContainerMoveIntentSyncState = ContainerIntentSyncState;\n\nexport type ContainerMoveIntentSyncHost = Pick<\n RemoteContainerHydrationHost,\n \"persistContainerState\" | \"updateSnapshot\"\n>;\n\n/** Later passes for moves the server accepted but no pass settled. */\nexport interface AcceptedMoveRetry {\n /** The server holds the move: schedule a replay to settle it. */\n arm: (intentId: string) => void;\n /** A replay failed; continue an accepted move's retries, if it has some. */\n resume: (intentId: string) => void;\n}\n\nexport interface ContainerMoveIntentSyncInput {\n host: ContainerMoveIntentSyncHost;\n isCurrent: () => boolean;\n /** A folder whose create has not settled takes no structural writes. */\n isCreatePending: (containerId: string) => boolean;\n isRemoteSyncBlocked: (organizationId: string) => boolean;\n intent: ContainerMoveIntentRecord;\n requestRemoteReconciliation: (parentContainerId: string | null) => void;\n acceptedMoveRetry: AcceptedMoveRetry;\n state: ContainerMoveIntentSyncState;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type {\n ContainerDeleteResponse,\n ContainerWriterProjectionResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport type { ProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport type { DocumentRecord } from \"../../../data/persistence/documents/records\";\nimport type {\n createRemoteContainer,\n moveRemoteContainer,\n shareRemoteContainer,\n} from \"../../containers\";\nimport type { createRemoteDocument } from \"../../documents\";\nimport type { shareRemoteContainerWithGroup } from \"../../organizations/groupShare\";\nimport type { CurrentPrincipalPolicyReader } from \"../../principals/currentPrincipalPolicyReader\";\nimport type { PrincipalPolicyHistoryReader } from \"../../principals/principalPolicyHistoryReader\";\nimport type {\n ContainerContentsPersistence,\n ContainerCreateIntentRecord,\n ContainerMoveIntentRecord,\n} from \"../containerPersistence\";\nimport type { createInitializedContainerMetadataDocument } from \"../metadata/containerMetadataDocument\";\nimport type {\n ContainerState,\n RemoteContainer as HydratedRemoteContainer,\n RemoteContainerHydrationHost,\n} from \"../remoteHydration\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\n\nexport type ContainerWorkflowApi = Parameters<\n typeof createRemoteContainer\n>[0][\"apiClient\"] &\n Parameters<typeof shareRemoteContainer>[0][\"apiClient\"] &\n Parameters<typeof shareRemoteContainerWithGroup>[0][\"apiClient\"] &\n Parameters<typeof moveRemoteContainer>[0][\"apiClient\"] &\n Parameters<typeof createRemoteDocument>[0][\"apiClient\"] &\n Partial<PrincipalPolicyHistoryReader> &\n CurrentPrincipalPolicyReader & {\n deleteContainerResult(\n containerId: string,\n options?: {\n expectedPaymentRequiredOrganizationId?: string;\n reportErrors?: boolean;\n requiredAncestorId?: string | undefined;\n },\n ): Promise<\n | { data: ContainerDeleteResponse; ok: true }\n | {\n ok: false;\n report: () => void;\n status: number | null;\n }\n >;\n primeContainerWriterProjection(\n containerId: string,\n projection: ContainerWriterProjectionResponse,\n ): void;\n };\n\nexport interface ContainerWorkflowRuntime\n extends Pick<\n ContainerContentsWorkflowRuntime,\n | \"auth\"\n | \"crypto\"\n | \"infra\"\n | \"resolveTrustedUserIdentity\"\n | \"state\"\n | \"util\"\n > {\n readonly apiClient: ContainerWorkflowApi;\n}\n\nexport interface CreatedRemoteContainerState {\n accessManifestHash: string;\n /**\n * The metadata seed the create committed, settled by the caller instead of\n * a first metadata sync. Absent when the create carried no seed or fell back\n * to a plain create.\n */\n metadataSeed?:\n | { readonly commitLsn: string | null; readonly updateId: string }\n | undefined;\n /** The slot this client signed into the create; never the server's echo. */\n systemSlot: ContainerSystemSlot | null;\n containerId: string;\n createdAt: string;\n metadataDocumentId: string;\n organizationId: string;\n /** A created container is a child; the acknowledgement echoed this parent. */\n parentId: string;\n persistedMetadataState: Pick<\n DocumentRecord,\n | \"documentId\"\n | \"contentKeyBundle\"\n | \"documentKekTargets\"\n | \"documentManifestBundle\"\n >;\n updatedAt: string;\n}\n\nexport interface SharedRemoteContainerState {\n accessEpoch: number;\n accessManifestHash: string;\n createdAt: string;\n metadataDocumentId: string;\n referencedPrincipalHeads: ReferencedPrincipalStateResponse[];\n updatedAt: string;\n writerProjection: ContainerWriterProjectionResponse | null;\n}\n\nexport interface SharedContainerState {\n container: ContainerState[\"container\"];\n record: ContainerState[\"record\"];\n}\n\nexport type SharedContainerStateResult =\n | { status: \"missing\" }\n | { status: \"confirmed\" }\n | (SharedContainerState & {\n status: \"identity-superseded\" | \"persisted\";\n });\n\nexport type RemoteContainer = HydratedRemoteContainer;\n\nexport type ContainerMetadataDocumentState = Awaited<\n ReturnType<typeof createInitializedContainerMetadataDocument>\n>[\"doc\"];\n\nexport interface CreatedChildContainerState {\n containerState: ContainerState;\n initialUpdate: Uint8Array;\n shouldRequestSync: boolean;\n}\n\nexport interface ContainerIntentSyncState {\n containersById: ReadonlyMap<string, ContainerState>;\n /**\n * Metadata update ids this device sent, so their own update echoes are\n * classified as self-authored (shared with the metadata sync).\n */\n locallyAcceptedMetadataUpdateIds?: Set<string> | undefined;\n /** Metadata document ids of folder creates in flight (shared with hints). */\n plannedMetadataDocumentIds?: Set<string> | undefined;\n persistence: ContainerContentsPersistence;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n /**\n * Verifies that a listed container is this device's pending create before it\n * is adopted and returns where it sits; `assertContainerCreateAdoptable`\n * unless a test replaces it.\n */\n verifyCreateAdoption?: (input: {\n readonly containerId: string;\n readonly expectedOrganizationId: string;\n }) => Promise<AdoptedContainerPlacement>;\n}\n\n/** Where a verified listed create committed, and where its container is now. */\nexport interface AdoptedContainerPlacement {\n /** The parent its signed epoch-1 `container.create` named. */\n readonly createdParentId: string;\n /** The verified head's parent; another writer may have moved it since. */\n readonly currentParentId: string;\n}\n\nexport type ContainerCreateIntentSyncState = ContainerIntentSyncState;\n\nexport type ContainerCreateIntentSyncHost = Pick<\n RemoteContainerHydrationHost,\n \"persistContainerState\"\n>;\n\nexport interface ContainerCreateIntentSyncInput {\n host: ContainerCreateIntentSyncHost;\n /** A parent whose own create has not settled takes no child create. */\n isCreatePending: (containerId: string) => boolean;\n isCurrent: () => boolean;\n isRemoteSyncBlocked: (organizationId: string) => boolean;\n intent: ContainerCreateIntentRecord;\n requestRemoteReconciliation: (parentContainerId: string | null) => void;\n state: ContainerCreateIntentSyncState;\n}\n\nexport type ContainerMoveIntentSyncState = ContainerIntentSyncState;\n\nexport type ContainerMoveIntentSyncHost = Pick<\n RemoteContainerHydrationHost,\n \"persistContainerState\" | \"updateSnapshot\"\n>;\n\n/** Later passes for moves the server accepted but no pass settled. */\nexport interface AcceptedMoveRetry {\n /** The server holds the move: schedule a replay to settle it. */\n arm: (intentId: string) => void;\n /** A replay failed; continue an accepted move's retries, if it has some. */\n resume: (intentId: string) => void;\n}\n\nexport interface ContainerMoveIntentSyncInput {\n host: ContainerMoveIntentSyncHost;\n isCurrent: () => boolean;\n /** A folder whose create has not settled takes no structural writes. */\n isCreatePending: (containerId: string) => boolean;\n isRemoteSyncBlocked: (organizationId: string) => boolean;\n intent: ContainerMoveIntentRecord;\n requestRemoteReconciliation: (parentContainerId: string | null) => void;\n acceptedMoveRetry: AcceptedMoveRetry;\n state: ContainerMoveIntentSyncState;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mBAAmB,EACnB,yBAAyB,GAC1B,MAAM,iBAAiB,CAAC;AAKzB,OAAO,EAAE,gCAAgC,EAAE,MAAM,6CAA6C,CAAC;AAC/F,OAAO,EACL,oBAAoB,EACpB,uCAAuC,GACxC,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,qCAAqC,EAAE,MAAM,mCAAmC,CAAC;AAC1F,OAAO,EACL,+BAA+B,EAC/B,oCAAoC,EACpC,8BAA8B,EAC9B,wCAAwC,GACzC,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAGL,2BAA2B,GAC5B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,oCAAoC,EACpC,qCAAqC,GACtC,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,sCAAsC,EAAE,MAAM,wBAAwB,CAAC;AAEhF,OAAO,EACL,uCAAuC,EACvC,sCAAsC,GACvC,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,8BAA8B,EAC9B,wCAAwC,EACxC,uCAAuC,EACvC,wCAAwC,GACzC,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,2CAA2C,EAAE,MAAM,wCAAwC,CAAC;AACrG,OAAO,EACL,8CAA8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C;AACJ,CAAC","sourcesContent":["import {\n encodeVersionVector,\n exportFullHistorySnapshot,\n} from \"@tearleads/loro\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport type { ProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport type { ContainerContentsPersistence } from \"../../../data/persistence/container-contents/containerContentsPersistence\";\nimport type { PendingUpdateRecord } from \"../../../data/sqlite/documentPersistence\";\nimport { settleOutgoingPassAndDecideReArm } from \"../../../data/sync/outgoingUpdateSettlement\";\nimport {\n readPullContinuation,\n shouldClearDocumentSyncFailureAfterPass,\n} from \"../../documents\";\nimport { applyIncomingContainerMetadataUpdates } from \"./metadataIncomingUpdateIsolation\";\nimport {\n currentMetadataPullContinuation,\n hasCurrentContainerMetadataReadState,\n installContainerMetadataRecord,\n persistContainerMetadataStateFromRuntime,\n} from \"./metadataPersistence\";\nimport {\n type ContainerMetadataSyncAttempt,\n type ContainerMetadataSyncRuntime,\n syncRemoteContainerMetadata,\n} from \"./metadataRemoteSync\";\nimport {\n createDetachedContainerMetadataState,\n installDetachedContainerMetadataState,\n} from \"./metadataStateIsolation\";\nimport { shouldRequestContainerMetadataFollowup } from \"./metadataSyncFollowup\";\n\nexport {\n hasContainerMetadataDocumentUpdateEvent,\n listContainerMetadataDocumentUpdateIds,\n} from \"./metadataEvents\";\nexport {\n installContainerMetadataRecord,\n persistContainerMetadataStateFromRuntime,\n renameContainerMetadataStateFromRuntime,\n setContainerIconMetadataStateFromRuntime,\n} from \"./metadataPersistence\";\n\nimport { invalidateContainerMetadataPullContinuation } from \"./metadataPullContinuationInvalidation\";\nimport {\n cleanupContainerMetadataRegistrationsOnFailure,\n discardUnacceptedContainerMetadataUpdateIds,\n preRegisterMaterializedContainerMetadataUpdateIds,\n} from \"./metadataSyncRegistrations\";\nimport type {\n ContainerMetadataState,\n MissingContainerMetadataState,\n SyncedContainerMetadataState,\n} from \"./metadataTypes\";\n\nexport {\n cleanupContainerMetadataRegistrationsOnFailure,\n preRegisterMaterializedContainerMetadataUpdateIds,\n} from \"./metadataSyncRegistrations\";\nexport type { ContainerMetadataPatch } from \"./metadataTypes\";\n\nexport function settleContainerMetadataOutgoingPass(\n metadataState: ContainerMetadataState,\n attempt: ContainerMetadataSyncAttempt,\n): boolean {\n const shouldReArmOutgoing = settleOutgoingPassAndDecideReArm(metadataState, {\n exhaustedPendingUpdateCount: attempt.synced.exhaustedPendingUpdateCount,\n outgoingUpdateCount: attempt.outgoingUpdateCount,\n rekeyedUpdateCount: attempt.synced.rekeyedPendingUpdateIds.length,\n settledUpdateCount: attempt.synced.settledPendingUpdateIds.length,\n acceptedRecoveryBaseline: attempt.synced.acceptedRecoveryBaseline,\n });\n return (\n attempt.synced.hasDeferredPendingUpdates ||\n shouldReArmOutgoing ||\n attempt.synced.hasIncompletePull\n );\n}\n\nfunction documentWriterProjectionMatchesMetadataSyncResponse(\n writerProjection: DocumentWriterProjectionResponse,\n synced: ContainerMetadataSyncAttempt[\"synced\"],\n): boolean {\n return (\n writerProjection.contentKeyBundle.contentKeyEpoch ===\n synced.response.contentKeyBundle.contentKeyEpoch &&\n writerProjection.contentKeyBundle.linkSetManifestHash ===\n synced.response.contentKeyBundle.linkSetManifestHash &&\n writerProjection.contentKeyBundle.targetHash ===\n synced.response.contentKeyBundle.targetHash &&\n writerProjection.documentKekTargets.linkSetManifestHash ===\n synced.response.documentKekTargets.linkSetManifestHash &&\n writerProjection.documentKekTargets.documentKeyTargetHash ===\n synced.response.documentKekTargets.documentKeyTargetHash\n );\n}\n\nfunction resolveSyncedContainerMetadataWriterProjection(\n metadataState: ContainerMetadataState,\n synced: ContainerMetadataSyncAttempt[\"synced\"],\n): DocumentWriterProjectionResponse | null {\n const writerProjection =\n synced.writerProjection ??\n (metadataState.metadataWriterProjection?.documentId ===\n synced.plan.documentId\n ? metadataState.metadataWriterProjection\n : null);\n return writerProjection &&\n documentWriterProjectionMatchesMetadataSyncResponse(\n writerProjection,\n synced,\n )\n ? writerProjection\n : null;\n}\n\n/**\n * Heals a stale metadata content-key bundle by rotating to a fresh content\n * key anchored by this full-history snapshot.\n */\nfunction metadataRotationSnapshotProvider(\n metadataState: ContainerMetadataState,\n): () => Promise<Uint8Array | null> {\n return async () => exportFullHistorySnapshot(metadataState.doc);\n}\n\ninterface SyncContainerMetadataStateInput {\n forceReadSync?: boolean | undefined;\n isCurrent: () => boolean;\n /**\n * Register sent ids before the network await so early self echoes cannot arm\n * a redundant read-sync. Shared with {@link listContainerMetadataDocumentUpdateIds}.\n */\n locallyAcceptedUpdateIds?: Set<string> | undefined;\n metadataState: ContainerMetadataState;\n onDurableStateNeedsReload?: (() => void) | undefined;\n persistence: ContainerContentsPersistence;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerMetadataSyncRuntime;\n targetSecretKey: Uint8Array;\n}\n\nasync function requestContainerMetadataSync(input: {\n documentId: string;\n metadataState: ContainerMetadataState;\n pendingUpdates: readonly PendingUpdateRecord[];\n sentUpdateIds: string[];\n syncInput: SyncContainerMetadataStateInput;\n}): Promise<ContainerMetadataSyncAttempt | null> {\n const { metadataState, sentUpdateIds, syncInput } = input;\n const { isCurrent, persistence, runtime } = syncInput;\n return cleanupContainerMetadataRegistrationsOnFailure(\n syncInput.locallyAcceptedUpdateIds,\n sentUpdateIds,\n () =>\n syncRemoteContainerMetadata({\n buildRotationSnapshot: metadataRotationSnapshotProvider(metadataState),\n containerId: metadataState.container.id,\n currentDocument: metadataState.doc,\n documentId: input.documentId,\n isCurrent,\n lastCommitLsn: metadataState.record.lastCommitLsn,\n localVersionVector: encodeVersionVector(metadataState.doc),\n onOutgoingUpdatesMaterialized: (updateIds) => {\n if (isCurrent()) {\n preRegisterMaterializedContainerMetadataUpdateIds(\n syncInput.locallyAcceptedUpdateIds,\n sentUpdateIds,\n updateIds,\n );\n }\n },\n onPullContinuationInvalidated: (continuation) =>\n invalidateContainerMetadataPullContinuation({\n continuation,\n isCurrent,\n metadataState,\n persistence,\n runtime,\n }),\n pendingUpdates: input.pendingUpdates,\n persistedState: metadataState.record,\n pullContinuation:\n currentMetadataPullContinuation(metadataState) ?? undefined,\n rekeyPendingUpdate: persistence.rekeyPendingUpdate,\n resolveProjectionUserKey: syncInput.resolveProjectionUserKey,\n runtime,\n targetSecretKey: syncInput.targetSecretKey,\n writerProjection:\n metadataState.metadataWriterProjection?.documentId ===\n input.documentId\n ? metadataState.metadataWriterProjection\n : undefined,\n }),\n );\n}\n\nexport async function syncContainerMetadataState(\n input: SyncContainerMetadataStateInput,\n): Promise<\n SyncedContainerMetadataState | MissingContainerMetadataState | null\n> {\n const { persistence, runtime } = input;\n const liveMetadataState = input.metadataState;\n const { isCurrent } = input;\n if (!isCurrent()) {\n return null;\n }\n const { documentId } = liveMetadataState.record;\n if (!documentId) {\n return null;\n }\n const execSql = runtime.infra.execSql;\n\n const pendingUpdates = await persistence.listPendingUpdates(\n execSql,\n liveMetadataState.container.id,\n );\n if (!isCurrent()) {\n return null;\n }\n if (\n pendingUpdates.length === 0 &&\n currentMetadataPullContinuation(liveMetadataState) === null &&\n !liveMetadataState.record.pullContinuationRecoveryRequired &&\n !input.forceReadSync &&\n hasCurrentContainerMetadataReadState(liveMetadataState.record)\n ) {\n return null;\n }\n const metadataState =\n await createDetachedContainerMetadataState(liveMetadataState);\n if (!isCurrent()) {\n return null;\n }\n\n const sentUpdateIds: string[] = [];\n\n const syncAttempt = await requestContainerMetadataSync({\n documentId,\n metadataState,\n pendingUpdates,\n sentUpdateIds,\n syncInput: input,\n });\n if (!syncAttempt) {\n return null;\n }\n if (!isCurrent()) {\n discardUnacceptedContainerMetadataUpdateIds(\n input.locallyAcceptedUpdateIds,\n sentUpdateIds,\n [],\n );\n return null;\n }\n const finalized = await finalizeContainerMetadataSync({\n documentId,\n isCurrent,\n locallyAcceptedUpdateIds: input.locallyAcceptedUpdateIds,\n metadataState,\n onDurableStateNeedsReload: input.onDurableStateNeedsReload,\n persistence,\n runtime,\n sentUpdateIds,\n syncAttempt,\n });\n if (!isCurrent() || !finalized) {\n return null;\n }\n if (!(\"missing\" in finalized)) {\n installDetachedContainerMetadataState(liveMetadataState, metadataState, {\n preserveConcurrentMetadataEdit: true,\n });\n }\n return finalized;\n}\n\nasync function finalizeContainerMetadataSync(input: {\n documentId: string;\n isCurrent: () => boolean;\n locallyAcceptedUpdateIds: Set<string> | undefined;\n metadataState: ContainerMetadataState;\n onDurableStateNeedsReload?: (() => void) | undefined;\n persistence: ContainerContentsPersistence;\n runtime: ContainerMetadataSyncRuntime;\n sentUpdateIds: readonly string[];\n syncAttempt: ContainerMetadataSyncAttempt;\n}): Promise<\n SyncedContainerMetadataState | MissingContainerMetadataState | null\n> {\n const { metadataState, syncAttempt } = input;\n const { outgoingUpdateCount, synced } = syncAttempt;\n if (!input.isCurrent()) {\n discardUnacceptedContainerMetadataUpdateIds(\n input.locallyAcceptedUpdateIds,\n input.sentUpdateIds,\n [],\n );\n return null;\n }\n // An id sent but not accepted will never be echoed. Accepted ids stay\n // registered until their realtime echo consumes them.\n discardUnacceptedContainerMetadataUpdateIds(\n input.locallyAcceptedUpdateIds,\n input.sentUpdateIds,\n synced.response.acceptedOutgoingUpdateIds,\n );\n metadataState.metadataWriterProjection =\n resolveSyncedContainerMetadataWriterProjection(metadataState, synced);\n if (synced.decryptedUpdates.length > 0) {\n applyIncomingContainerMetadataUpdates(metadataState.doc, synced);\n }\n const persisted = await persistContainerMetadataStateFromRuntime({\n acceptedPendingUpdateIds: synced.settledPendingUpdateIds,\n clearSyncFailure: shouldClearDocumentSyncFailureAfterPass(\n synced,\n outgoingUpdateCount,\n ),\n expectedSyncState: {\n pullContinuation: syncAttempt.consumedPullContinuation ?? null,\n record: syncAttempt.requestRecord,\n },\n metadataState,\n onDurableStateNeedsReload: input.onDurableStateNeedsReload,\n patch: {\n ...synced.persistedState,\n documentId: input.documentId,\n lastCommitLsn:\n synced.response.commitLsn ?? metadataState.record.lastCommitLsn ?? null,\n metadataDocumentId: input.documentId,\n pullContinuation: readPullContinuation(synced.response),\n },\n persistence: input.persistence,\n runtime: input.runtime,\n stillCurrent: input.isCurrent,\n });\n if (!input.isCurrent()) {\n discardUnacceptedContainerMetadataUpdateIds(\n input.locallyAcceptedUpdateIds,\n input.sentUpdateIds,\n [],\n );\n return null;\n }\n if (!persisted) {\n discardUnacceptedContainerMetadataUpdateIds(\n input.locallyAcceptedUpdateIds,\n input.sentUpdateIds,\n [],\n );\n metadataState.metadataWriterProjection = null;\n return { missing: true };\n }\n metadataState.container = persisted.container;\n installContainerMetadataRecord(metadataState, persisted.record);\n if (persisted.pullContinuationSuperseded) {\n // The response's accepted IDs were not durably settled. Treat every\n // pre-registration as unapplied so an early echo cannot hide work that the\n // forced follow-up still needs to reconcile.\n discardUnacceptedContainerMetadataUpdateIds(\n input.locallyAcceptedUpdateIds,\n input.sentUpdateIds,\n [],\n );\n metadataState.metadataWriterProjection = null;\n }\n\n return {\n ...persisted,\n shouldRequestFollowupSync: shouldRequestContainerMetadataFollowup({\n persisted,\n settleOutgoingPass: () =>\n settleContainerMetadataOutgoingPass(metadataState, syncAttempt),\n }),\n };\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mBAAmB,EACnB,yBAAyB,GAC1B,MAAM,iBAAiB,CAAC;AAKzB,OAAO,EAAE,gCAAgC,EAAE,MAAM,6CAA6C,CAAC;AAC/F,OAAO,EACL,oBAAoB,EACpB,uCAAuC,GACxC,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,qCAAqC,EAAE,MAAM,mCAAmC,CAAC;AAC1F,OAAO,EACL,+BAA+B,EAC/B,oCAAoC,EACpC,8BAA8B,EAC9B,wCAAwC,GACzC,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAGL,2BAA2B,GAC5B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,oCAAoC,EACpC,qCAAqC,GACtC,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAA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AwB,EAC9B,KAAK,CAAC,aAAa,EACnB,EAAE,CACH,CAAC;QACF,aAAa,CAAC,wBAAwB,GAAG,IAAI,CAAC;IAChD,CAAC;IAED,OAAO;QACL,GAAG,SAAS;QACZ,yBAAyB,EAAE,sCAAsC,CAAC;YAChE,SAAS;YACT,kBAAkB,EAAE,GAAG,EAAE,CACvB,mCAAmC,CAAC,aAAa,EAAE,WAAW,CAAC;SAClE,CAAC;KACH,CAAC;AACJ,CAAC","sourcesContent":["import {\n encodeVersionVector,\n exportFullHistorySnapshot,\n} from \"@tearleads/loro\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport type { ProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport type { ContainerContentsPersistence } from \"../../../data/persistence/container-contents/containerContentsPersistence\";\nimport type { PendingUpdateRecord } from \"../../../data/persistence/documents/records\";\nimport { settleOutgoingPassAndDecideReArm } from \"../../../data/sync/outgoingUpdateSettlement\";\nimport {\n readPullContinuation,\n shouldClearDocumentSyncFailureAfterPass,\n} from \"../../documents\";\nimport { applyIncomingContainerMetadataUpdates } from \"./metadataIncomingUpdateIsolation\";\nimport {\n currentMetadataPullContinuation,\n hasCurrentContainerMetadataReadState,\n installContainerMetadataRecord,\n persistContainerMetadataStateFromRuntime,\n} from \"./metadataPersistence\";\nimport {\n type ContainerMetadataSyncAttempt,\n type ContainerMetadataSyncRuntime,\n syncRemoteContainerMetadata,\n} from \"./metadataRemoteSync\";\nimport {\n createDetachedContainerMetadataState,\n installDetachedContainerMetadataState,\n} from \"./metadataStateIsolation\";\nimport { shouldRequestContainerMetadataFollowup } from \"./metadataSyncFollowup\";\n\nexport {\n hasContainerMetadataDocumentUpdateEvent,\n listContainerMetadataDocumentUpdateIds,\n} from \"./metadataEvents\";\nexport {\n installContainerMetadataRecord,\n persistContainerMetadataStateFromRuntime,\n renameContainerMetadataStateFromRuntime,\n setContainerIconMetadataStateFromRuntime,\n} from \"./metadataPersistence\";\n\nimport { invalidateContainerMetadataPullContinuation } from \"./metadataPullContinuationInvalidation\";\nimport {\n cleanupContainerMetadataRegistrationsOnFailure,\n discardUnacceptedContainerMetadataUpdateIds,\n preRegisterMaterializedContainerMetadataUpdateIds,\n} from \"./metadataSyncRegistrations\";\nimport type {\n ContainerMetadataState,\n MissingContainerMetadataState,\n SyncedContainerMetadataState,\n} from \"./metadataTypes\";\n\nexport {\n cleanupContainerMetadataRegistrationsOnFailure,\n preRegisterMaterializedContainerMetadataUpdateIds,\n} from \"./metadataSyncRegistrations\";\nexport type { ContainerMetadataPatch } from \"./metadataTypes\";\n\nexport function settleContainerMetadataOutgoingPass(\n metadataState: ContainerMetadataState,\n attempt: ContainerMetadataSyncAttempt,\n): boolean {\n const shouldReArmOutgoing = settleOutgoingPassAndDecideReArm(metadataState, {\n exhaustedPendingUpdateCount: attempt.synced.exhaustedPendingUpdateCount,\n outgoingUpdateCount: attempt.outgoingUpdateCount,\n rekeyedUpdateCount: attempt.synced.rekeyedPendingUpdateIds.length,\n settledUpdateCount: attempt.synced.settledPendingUpdateIds.length,\n acceptedRecoveryBaseline: attempt.synced.acceptedRecoveryBaseline,\n });\n return (\n attempt.synced.hasDeferredPendingUpdates ||\n shouldReArmOutgoing ||\n attempt.synced.hasIncompletePull\n );\n}\n\nfunction documentWriterProjectionMatchesMetadataSyncResponse(\n writerProjection: DocumentWriterProjectionResponse,\n synced: ContainerMetadataSyncAttempt[\"synced\"],\n): boolean {\n return (\n writerProjection.contentKeyBundle.contentKeyEpoch ===\n synced.response.contentKeyBundle.contentKeyEpoch &&\n writerProjection.contentKeyBundle.linkSetManifestHash ===\n synced.response.contentKeyBundle.linkSetManifestHash &&\n writerProjection.contentKeyBundle.targetHash ===\n synced.response.contentKeyBundle.targetHash &&\n writerProjection.documentKekTargets.linkSetManifestHash ===\n synced.response.documentKekTargets.linkSetManifestHash &&\n writerProjection.documentKekTargets.documentKeyTargetHash ===\n synced.response.documentKekTargets.documentKeyTargetHash\n );\n}\n\nfunction resolveSyncedContainerMetadataWriterProjection(\n metadataState: ContainerMetadataState,\n synced: ContainerMetadataSyncAttempt[\"synced\"],\n): DocumentWriterProjectionResponse | null {\n const writerProjection =\n synced.writerProjection ??\n (metadataState.metadataWriterProjection?.documentId ===\n synced.plan.documentId\n ? metadataState.metadataWriterProjection\n : null);\n return writerProjection &&\n documentWriterProjectionMatchesMetadataSyncResponse(\n writerProjection,\n synced,\n )\n ? writerProjection\n : null;\n}\n\n/**\n * Heals a stale metadata content-key bundle by rotating to a fresh content\n * key anchored by this full-history snapshot.\n */\nfunction metadataRotationSnapshotProvider(\n metadataState: ContainerMetadataState,\n): () => Promise<Uint8Array | null> {\n return async () => exportFullHistorySnapshot(metadataState.doc);\n}\n\ninterface SyncContainerMetadataStateInput {\n forceReadSync?: boolean | undefined;\n isCurrent: () => boolean;\n /**\n * Register sent ids before the network await so early self echoes cannot arm\n * a redundant read-sync. Shared with {@link listContainerMetadataDocumentUpdateIds}.\n */\n locallyAcceptedUpdateIds?: Set<string> | undefined;\n metadataState: ContainerMetadataState;\n onDurableStateNeedsReload?: (() => void) | undefined;\n persistence: ContainerContentsPersistence;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerMetadataSyncRuntime;\n targetSecretKey: Uint8Array;\n}\n\nasync function requestContainerMetadataSync(input: {\n documentId: string;\n metadataState: ContainerMetadataState;\n pendingUpdates: readonly PendingUpdateRecord[];\n sentUpdateIds: string[];\n syncInput: SyncContainerMetadataStateInput;\n}): Promise<ContainerMetadataSyncAttempt | null> {\n const { metadataState, sentUpdateIds, syncInput } = input;\n const { isCurrent, persistence, runtime } = syncInput;\n return cleanupContainerMetadataRegistrationsOnFailure(\n syncInput.locallyAcceptedUpdateIds,\n sentUpdateIds,\n () =>\n syncRemoteContainerMetadata({\n buildRotationSnapshot: metadataRotationSnapshotProvider(metadataState),\n containerId: metadataState.container.id,\n currentDocument: metadataState.doc,\n documentId: input.documentId,\n isCurrent,\n lastCommitLsn: metadataState.record.lastCommitLsn,\n localVersionVector: encodeVersionVector(metadataState.doc),\n onOutgoingUpdatesMaterialized: (updateIds) => {\n if (isCurrent()) {\n preRegisterMaterializedContainerMetadataUpdateIds(\n syncInput.locallyAcceptedUpdateIds,\n sentUpdateIds,\n updateIds,\n );\n }\n },\n onPullContinuationInvalidated: (continuation) =>\n invalidateContainerMetadataPullContinuation({\n continuation,\n isCurrent,\n metadataState,\n persistence,\n runtime,\n }),\n pendingUpdates: input.pendingUpdates,\n persistedState: metadataState.record,\n pullContinuation:\n currentMetadataPullContinuation(metadataState) ?? undefined,\n rekeyPendingUpdate: persistence.rekeyPendingUpdate,\n resolveProjectionUserKey: syncInput.resolveProjectionUserKey,\n runtime,\n targetSecretKey: syncInput.targetSecretKey,\n writerProjection:\n metadataState.metadataWriterProjection?.documentId ===\n input.documentId\n ? metadataState.metadataWriterProjection\n : undefined,\n }),\n );\n}\n\nexport async function syncContainerMetadataState(\n input: SyncContainerMetadataStateInput,\n): Promise<\n SyncedContainerMetadataState | MissingContainerMetadataState | null\n> {\n const { persistence, runtime } = input;\n const liveMetadataState = input.metadataState;\n const { isCurrent } = input;\n if (!isCurrent()) {\n return null;\n }\n const { documentId } = liveMetadataState.record;\n if (!documentId) {\n return null;\n }\n const execSql = runtime.infra.execSql;\n\n const pendingUpdates = await persistence.listPendingUpdates(\n execSql,\n liveMetadataState.container.id,\n );\n if (!isCurrent()) {\n return null;\n }\n if (\n pendingUpdates.length === 0 &&\n currentMetadataPullContinuation(liveMetadataState) === null &&\n !liveMetadataState.record.pullContinuationRecoveryRequired &&\n !input.forceReadSync &&\n hasCurrentContainerMetadataReadState(liveMetadataState.record)\n ) {\n return null;\n }\n const metadataState =\n await createDetachedContainerMetadataState(liveMetadataState);\n if (!isCurrent()) {\n return null;\n }\n\n const sentUpdateIds: string[] = [];\n\n const syncAttempt = await requestContainerMetadataSync({\n documentId,\n metadataState,\n pendingUpdates,\n sentUpdateIds,\n syncInput: input,\n });\n if (!syncAttempt) {\n return null;\n }\n if (!isCurrent()) {\n discardUnacceptedContainerMetadataUpdateIds(\n input.locallyAcceptedUpdateIds,\n sentUpdateIds,\n [],\n );\n return null;\n }\n const finalized = await finalizeContainerMetadataSync({\n documentId,\n isCurrent,\n locallyAcceptedUpdateIds: input.locallyAcceptedUpdateIds,\n metadataState,\n onDurableStateNeedsReload: input.onDurableStateNeedsReload,\n persistence,\n runtime,\n sentUpdateIds,\n syncAttempt,\n });\n if (!isCurrent() || !finalized) {\n return null;\n }\n if (!(\"missing\" in finalized)) {\n installDetachedContainerMetadataState(liveMetadataState, metadataState, {\n preserveConcurrentMetadataEdit: true,\n });\n }\n return finalized;\n}\n\nasync function finalizeContainerMetadataSync(input: {\n documentId: string;\n isCurrent: () => boolean;\n locallyAcceptedUpdateIds: Set<string> | undefined;\n metadataState: ContainerMetadataState;\n onDurableStateNeedsReload?: (() => void) | undefined;\n persistence: ContainerContentsPersistence;\n runtime: ContainerMetadataSyncRuntime;\n sentUpdateIds: readonly string[];\n syncAttempt: ContainerMetadataSyncAttempt;\n}): Promise<\n SyncedContainerMetadataState | MissingContainerMetadataState | null\n> {\n const { metadataState, syncAttempt } = input;\n const { outgoingUpdateCount, synced } = syncAttempt;\n if (!input.isCurrent()) {\n discardUnacceptedContainerMetadataUpdateIds(\n input.locallyAcceptedUpdateIds,\n input.sentUpdateIds,\n [],\n );\n return null;\n }\n // An id sent but not accepted will never be echoed. Accepted ids stay\n // registered until their realtime echo consumes them.\n discardUnacceptedContainerMetadataUpdateIds(\n input.locallyAcceptedUpdateIds,\n input.sentUpdateIds,\n synced.response.acceptedOutgoingUpdateIds,\n );\n metadataState.metadataWriterProjection =\n resolveSyncedContainerMetadataWriterProjection(metadataState, synced);\n if (synced.decryptedUpdates.length > 0) {\n applyIncomingContainerMetadataUpdates(metadataState.doc, synced);\n }\n const persisted = await persistContainerMetadataStateFromRuntime({\n acceptedPendingUpdateIds: synced.settledPendingUpdateIds,\n clearSyncFailure: shouldClearDocumentSyncFailureAfterPass(\n synced,\n outgoingUpdateCount,\n ),\n expectedSyncState: {\n pullContinuation: syncAttempt.consumedPullContinuation ?? null,\n record: syncAttempt.requestRecord,\n },\n metadataState,\n onDurableStateNeedsReload: input.onDurableStateNeedsReload,\n patch: {\n ...synced.persistedState,\n documentId: input.documentId,\n lastCommitLsn:\n synced.response.commitLsn ?? metadataState.record.lastCommitLsn ?? null,\n metadataDocumentId: input.documentId,\n pullContinuation: readPullContinuation(synced.response),\n },\n persistence: input.persistence,\n runtime: input.runtime,\n stillCurrent: input.isCurrent,\n });\n if (!input.isCurrent()) {\n discardUnacceptedContainerMetadataUpdateIds(\n input.locallyAcceptedUpdateIds,\n input.sentUpdateIds,\n [],\n );\n return null;\n }\n if (!persisted) {\n discardUnacceptedContainerMetadataUpdateIds(\n input.locallyAcceptedUpdateIds,\n input.sentUpdateIds,\n [],\n );\n metadataState.metadataWriterProjection = null;\n return { missing: true };\n }\n metadataState.container = persisted.container;\n installContainerMetadataRecord(metadataState, persisted.record);\n if (persisted.pullContinuationSuperseded) {\n // The response's accepted IDs were not durably settled. Treat every\n // pre-registration as unapplied so an early echo cannot hide work that the\n // forced follow-up still needs to reconcile.\n discardUnacceptedContainerMetadataUpdateIds(\n input.locallyAcceptedUpdateIds,\n input.sentUpdateIds,\n [],\n );\n metadataState.metadataWriterProjection = null;\n }\n\n return {\n ...persisted,\n shouldRequestFollowupSync: shouldRequestContainerMetadataFollowup({\n persisted,\n settleOutgoingPass: () =>\n settleContainerMetadataOutgoingPass(metadataState, syncAttempt),\n }),\n };\n}\n"]}
@@ -1,4 +1,4 @@
1
- import type { DocumentRecord } from "../../../data/sqlite/documentPersistence/index.js";
1
+ import type { DocumentRecord } from "../../../data/persistence/documents/records/index.js";
2
2
  export declare function hasContainerMetadataDocumentUpdateEvent(events: ReadonlyArray<unknown>, metadataStates: Iterable<{
3
3
  record: Pick<DocumentRecord, "documentId">;
4
4
  }>, locallyAcceptedUpdateIds?: Set<string>): boolean;
@@ -1 +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,QAAQ,EAAE,CAAC;YACxD,mBAAmB,CAAC,GAAG,CAAC,aAAa,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QAC3D,CAAC;IACH,CAAC;IACD,IAAI,mBAAmB,CAAC,IAAI,KAAK,CAAC;QAAE,OAAO,EAAE,CAAC;IAE9C,MAAM,gBAAgB,GAAG,IAAI,GAAG,EAAU,CAAC;IAC3C,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;QAC3B,IACE,CAAC,4BAA4B,CAAC,KAAK,CAAC;YACpC,CAAC,mBAAmB,CAAC,GAAG,CAAC,KAAK,CAAC,UAAU,CAAC,EAC1C,CAAC;YACD,SAAS;QACX,CAAC;QACD,IAAI,CAAC,4BAA4B,CAAC,KAAK,EAAE,wBAAwB,CAAC,EAAE,CAAC;YACnE,SAAS;QACX,CAAC;QACD,gBAAgB,CAAC,GAAG,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IACzC,CAAC;IAED,OAAO,KAAK,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC;AACtC,CAAC","sourcesContent":["import { isDocumentUpdateCreatedEvent } from \"../../../data/documents/documentSync\";\nimport type { DocumentRecord } from \"../../../data/sqlite/documentPersistence\";\n\nexport function hasContainerMetadataDocumentUpdateEvent(\n events: ReadonlyArray<unknown>,\n metadataStates: Iterable<{ record: Pick<DocumentRecord, \"documentId\"> }>,\n locallyAcceptedUpdateIds?: Set<string>,\n): boolean {\n // A boolean predicate must not consume self-echo ids before the real list\n // pass classifies the same events.\n return (\n listContainerMetadataDocumentUpdateIds(\n events,\n metadataStates,\n locallyAcceptedUpdateIds ? new Set(locallyAcceptedUpdateIds) : undefined,\n ).length > 0\n );\n}\n\n/** Consume local ids and report whether an event still contains a peer id. */\nfunction metadataEventHasRemoteUpdate(\n event: { updateIds?: readonly string[] | undefined },\n locallyAcceptedUpdateIds: Set<string> | undefined,\n): boolean {\n if (\n !locallyAcceptedUpdateIds ||\n !event.updateIds ||\n event.updateIds.length === 0\n ) {\n return true;\n }\n\n let remoteUpdateFound = false;\n for (const updateId of event.updateIds) {\n if (locallyAcceptedUpdateIds.has(updateId)) {\n locallyAcceptedUpdateIds.delete(updateId);\n } else {\n remoteUpdateFound = true;\n }\n }\n return remoteUpdateFound;\n}\n\n/**\n * `plannedDocumentIds` names the metadata documents of folders whose create is\n * in flight. A peer can edit one after the create commits but before the\n * response installs its id, and a committed seed stands in for the folder's\n * first metadata sync, so that hint must still queue a read.\n */\nexport function listContainerMetadataDocumentUpdateIds(\n events: ReadonlyArray<unknown>,\n metadataStates: Iterable<{ record: Pick<DocumentRecord, \"documentId\"> }>,\n locallyAcceptedUpdateIds?: Set<string>,\n plannedDocumentIds?: Iterable<string>,\n): string[] {\n const metadataDocumentIds = new Set<string>(plannedDocumentIds);\n for (const metadataState of metadataStates) {\n if (typeof metadataState.record.documentId === \"string\") {\n metadataDocumentIds.add(metadataState.record.documentId);\n }\n }\n if (metadataDocumentIds.size === 0) return [];\n\n const eventDocumentIds = new Set<string>();\n for (const event of events) {\n if (\n !isDocumentUpdateCreatedEvent(event) ||\n !metadataDocumentIds.has(event.documentId)\n ) {\n continue;\n }\n if (!metadataEventHasRemoteUpdate(event, locallyAcceptedUpdateIds)) {\n continue;\n }\n eventDocumentIds.add(event.documentId);\n }\n\n return Array.from(eventDocumentIds);\n}\n"]}
1
+ {"version":3,"file":"metadataEvents.js","sourceRoot":"","sources":["metadataEvents.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,4BAA4B,EAAE,MAAM,sCAAsC,CAAC;AAGpF,MAAM,UAAU,uCAAuC,CACrD,MAA8B,EAC9B,cAAwE,EACxE,wBAAsC;IAEtC,0EAA0E;IAC1E,mCAAmC;IACnC,OAAO,CACL,sCAAsC,CACpC,MAAM,EACN,cAAc,EACd,wBAAwB,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,wBAAwB,CAAC,CAAC,CAAC,CAAC,SAAS,CACzE,CAAC,MAAM,GAAG,CAAC,CACb,CA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CAAC;YACD,SAAS;QACX,CAAC;QACD,IAAI,CAAC,4BAA4B,CAAC,KAAK,EAAE,wBAAwB,CAAC,EAAE,CAAC;YACnE,SAAS;QACX,CAAC;QACD,gBAAgB,CAAC,GAAG,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IACzC,CAAC;IAED,OAAO,KAAK,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC;AACtC,CAAC","sourcesContent":["import { isDocumentUpdateCreatedEvent } from \"../../../data/documents/documentSync\";\nimport type { DocumentRecord } from \"../../../data/persistence/documents/records\";\n\nexport function hasContainerMetadataDocumentUpdateEvent(\n events: ReadonlyArray<unknown>,\n metadataStates: Iterable<{ record: Pick<DocumentRecord, \"documentId\"> }>,\n locallyAcceptedUpdateIds?: Set<string>,\n): boolean {\n // A boolean predicate must not consume self-echo ids before the real list\n // pass classifies the same events.\n return (\n listContainerMetadataDocumentUpdateIds(\n events,\n metadataStates,\n locallyAcceptedUpdateIds ? new Set(locallyAcceptedUpdateIds) : undefined,\n ).length > 0\n );\n}\n\n/** Consume local ids and report whether an event still contains a peer id. */\nfunction metadataEventHasRemoteUpdate(\n event: { updateIds?: readonly string[] | undefined },\n locallyAcceptedUpdateIds: Set<string> | undefined,\n): boolean {\n if (\n !locallyAcceptedUpdateIds ||\n !event.updateIds ||\n event.updateIds.length === 0\n ) {\n return true;\n }\n\n let remoteUpdateFound = false;\n for (const updateId of event.updateIds) {\n if (locallyAcceptedUpdateIds.has(updateId)) {\n locallyAcceptedUpdateIds.delete(updateId);\n } else {\n remoteUpdateFound = true;\n }\n }\n return remoteUpdateFound;\n}\n\n/**\n * `plannedDocumentIds` names the metadata documents of folders whose create is\n * in flight. A peer can edit one after the create commits but before the\n * response installs its id, and a committed seed stands in for the folder's\n * first metadata sync, so that hint must still queue a read.\n */\nexport function listContainerMetadataDocumentUpdateIds(\n events: ReadonlyArray<unknown>,\n metadataStates: Iterable<{ record: Pick<DocumentRecord, \"documentId\"> }>,\n locallyAcceptedUpdateIds?: Set<string>,\n plannedDocumentIds?: Iterable<string>,\n): string[] {\n const metadataDocumentIds = new Set<string>(plannedDocumentIds);\n for (const metadataState of metadataStates) {\n if (typeof metadataState.record.documentId === \"string\") {\n metadataDocumentIds.add(metadataState.record.documentId);\n }\n }\n if (metadataDocumentIds.size === 0) return [];\n\n const eventDocumentIds = new Set<string>();\n for (const event of events) {\n if (\n !isDocumentUpdateCreatedEvent(event) ||\n !metadataDocumentIds.has(event.documentId)\n ) {\n continue;\n }\n if (!metadataEventHasRemoteUpdate(event, locallyAcceptedUpdateIds)) {\n continue;\n }\n eventDocumentIds.add(event.documentId);\n }\n\n return Array.from(eventDocumentIds);\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { importDecryptedDocumentSyncUpdates, validateDocumentSyncUpdateImports, } from "../../../data/documents/shared/sync/documentSyncUpdateIsolation.js";
2
- import { recordDocumentSyncFailure } from "../../../data/sqlite/documentPersistence/index.js";
2
+ import { recordDocumentSyncFailure } from "../../../data/persistence/documents/records/index.js";
3
3
  import { getClientSQLitePersistenceRuntime } from "../../../data/sqlite/sqlitePersistenceRuntime.js";
4
4
  import { runSerializedSqlMutation, } from "../../../data/sqlite/sqlSchema.js";
5
5
  import { reportDocumentSyncQuarantine } from "../../documents/sync/reportDocumentSyncQuarantine.js";
@@ -1 +1 @@
1
- {"version":3,"file":"metadataIncomingUpdateIsolation.js","sourceRoot":"","sources":["metadataIncomingUpdateIsolation.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,kCAAkC,EAClC,iCAAiC,GAClC,MAAM,iEAAiE,CAAC;AAEzE,OAAO,EAAE,yBAAyB,EAAE,MAAM,0CAA0C,CAAC;AACrF,OAAO,EAAE,iCAAiC,EAAE,MAAM,+CAA+C,CAAC;AAClG,OAAO,EAEL,wBAAwB,GACzB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,4BAA4B,EAAE,MAAM,mDAAmD,CAAC;AAIjG,MAAM,CAAC,KAAK,UAAU,gCA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,CAAC,OAAO;SACzC,CAAC;KACL,CAAC;AACJ,CAAC","sourcesContent":["import {\n type DocumentSyncUpdateIsolationError,\n importDecryptedDocumentSyncUpdates,\n validateDocumentSyncUpdateImports,\n} from \"../../../data/documents/shared/sync/documentSyncUpdateIsolation\";\nimport type { SyncRemoteDocumentResult } from \"../../../data/documents/shared/types\";\nimport { recordDocumentSyncFailure } from \"../../../data/sqlite/documentPersistence\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../data/sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n runSerializedSqlMutation,\n} from \"../../../data/sqlite/sqlSchema\";\nimport { reportDocumentSyncQuarantine } from \"../../documents/sync/reportDocumentSyncQuarantine\";\nimport type { WorkflowRuntimeUtilInput } from \"../../shared/runtimeInput\";\nimport type { ContainerMetadataState } from \"./metadataTypes\";\n\nexport async function recordCurrentMetadataSyncFailure(input: {\n execSql: ExecSql;\n failure: {\n readonly attemptedAt: string;\n readonly message: string;\n readonly status: number | null;\n };\n isCurrent?: (() => boolean) | undefined;\n metadataScope: { appKind: string; localId: string };\n}): Promise<void> {\n await runSerializedSqlMutation(input.execSql, async (lockedExecSql) => {\n await getClientSQLitePersistenceRuntime(lockedExecSql).guardedTransaction(\n async () => {\n if (input.isCurrent?.() === false) return;\n await recordDocumentSyncFailure(\n lockedExecSql,\n input.metadataScope,\n input.failure,\n );\n },\n () => input.isCurrent?.() !== false,\n );\n });\n}\n\nexport function applyIncomingContainerMetadataUpdates(\n currentDocument: ContainerMetadataState[\"doc\"],\n result: Pick<SyncRemoteDocumentResult, \"decryptedUpdates\">,\n): void {\n importDecryptedDocumentSyncUpdates(currentDocument, result.decryptedUpdates);\n}\n\nexport function metadataIncomingUpdateIsolation(input: {\n currentDocument: ContainerMetadataState[\"doc\"];\n execSql: ExecSql;\n isCurrent?: (() => boolean) | undefined;\n logError?: WorkflowRuntimeUtilInput[\"logError\"] | undefined;\n metadataScope: { appKind: string; localId: string };\n}) {\n return {\n onIncomingUpdateIsolationFailure: async (\n failure: DocumentSyncUpdateIsolationError,\n ) => {\n await recordCurrentMetadataSyncFailure({\n ...input,\n failure: {\n attemptedAt: new Date().toISOString(),\n message: failure.message,\n status: null,\n },\n });\n if (input.isCurrent?.() === false) return;\n reportDocumentSyncQuarantine(\n input.currentDocument,\n input.logError,\n failure,\n );\n },\n validateIncomingUpdates: (\n result: Pick<SyncRemoteDocumentResult, \"decryptedUpdates\" | \"response\">,\n ) =>\n validateDocumentSyncUpdateImports({\n currentDocument: input.currentDocument,\n decryptedUpdates: result.decryptedUpdates,\n responseUpdates: result.response.updates,\n }),\n };\n}\n"]}
1
+ {"version":3,"file":"metadataIncomingUpdateIsolation.js","sourceRoot":"","sources":["metadataIncomingUpdateIsolation.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,kCAAkC,EAClC,iCAAiC,GAClC,MAAM,iEAAiE,CAAC;AAEzE,OAAO,EAAE,yBAAyB,EAAE,MAAM,6CAA6C,CAAC;AACxF,OAAO,EAAE,iCAAiC,EAAE,MAAM,+CAA+C,CAAC;AAClG,OAAO,EAEL,wBAAwB,GACzB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,4BAA4B,EAAE,MAAM,mDAAmD,CAAC;AAIjG,MAAM,CAAC,KAAK,UAAU,gCAAgC,CAAC,KAStD;IACC,MAAM,wBAAwB,CAAC,KAAK,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE;QACpE,MAAM,iCAAiC,CAAC,aAAa,CAAC,CAAC,kBAAkB,CACvE,KAAK,IAAI,EAAE;YACT,IAAI,KAAK,CAAC,SAAS,EAAE,EAAE,KAAK,KAAK;gBAAE,OAAO;YAC1C,MAAM,yBAAyB,CAC7B,aAAa,EACb,KAAK,CAAC,aAAa,EACnB,KAAK,CAAC,OAAO,CACd,CAAC;QACJ,CAAC,EACD,GAAG,EAAE,CAAC,KAAK,CAAC,SAAS,EAAE,EAAE,KAAK,KAAK,CACpC,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,qCAAqC,CACnD,eAA8C,EAC9C,MAA0D;IAE1D,kCAAkC,CAAC,eAAe,EAAE,MAAM,CAAC,gBAAgB,CAAC,CAAC;AAC/E,CAAC;AAED,MAAM,UAAU,+BAA+B,CAAC,KAM/C;IACC,OAAO;QACL,gCAAgC,EAAE,KAAK,EACrC,OAAyC,EACzC,EAAE;YACF,MAAM,gCAAgC,CAAC;gBACrC,GAAG,KAAK;gBACR,OAAO,EAAE;oBACP,WAAW,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;oBACrC,OAAO,EAAE,OAAO,CAAC,OAAO;oBACxB,MAAM,EAAE,IAAI;iBACb;aACF,CAAC,CAAC;YACH,IAAI,KAAK,CAAC,SAAS,EAAE,EAAE,KAAK,KAAK;gBAAE,OAAO;YAC1C,4BAA4B,CAC1B,KAAK,CAAC,eAAe,EACrB,KAAK,CAAC,QAAQ,EACd,OAAO,CACR,CAAC;QACJ,CAAC;QACD,uBAAuB,EAAE,CACvB,MAAuE,EACvE,EAAE,CACF,iCAAiC,CAAC;YAChC,eAAe,EAAE,KAAK,CAAC,eAAe;YACtC,gBAAgB,EAAE,MAAM,CAAC,gBAAgB;YACzC,eAAe,EAAE,MAAM,CAAC,QAAQ,CAAC,OAAO;SACzC,CAAC;KACL,CAAC;AACJ,CAAC","sourcesContent":["import {\n type DocumentSyncUpdateIsolationError,\n importDecryptedDocumentSyncUpdates,\n validateDocumentSyncUpdateImports,\n} from \"../../../data/documents/shared/sync/documentSyncUpdateIsolation\";\nimport type { SyncRemoteDocumentResult } from \"../../../data/documents/shared/types\";\nimport { recordDocumentSyncFailure } from \"../../../data/persistence/documents/records\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../data/sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n runSerializedSqlMutation,\n} from \"../../../data/sqlite/sqlSchema\";\nimport { reportDocumentSyncQuarantine } from \"../../documents/sync/reportDocumentSyncQuarantine\";\nimport type { WorkflowRuntimeUtilInput } from \"../../shared/runtimeInput\";\nimport type { ContainerMetadataState } from \"./metadataTypes\";\n\nexport async function recordCurrentMetadataSyncFailure(input: {\n execSql: ExecSql;\n failure: {\n readonly attemptedAt: string;\n readonly message: string;\n readonly status: number | null;\n };\n isCurrent?: (() => boolean) | undefined;\n metadataScope: { appKind: string; localId: string };\n}): Promise<void> {\n await runSerializedSqlMutation(input.execSql, async (lockedExecSql) => {\n await getClientSQLitePersistenceRuntime(lockedExecSql).guardedTransaction(\n async () => {\n if (input.isCurrent?.() === false) return;\n await recordDocumentSyncFailure(\n lockedExecSql,\n input.metadataScope,\n input.failure,\n );\n },\n () => input.isCurrent?.() !== false,\n );\n });\n}\n\nexport function applyIncomingContainerMetadataUpdates(\n currentDocument: ContainerMetadataState[\"doc\"],\n result: Pick<SyncRemoteDocumentResult, \"decryptedUpdates\">,\n): void {\n importDecryptedDocumentSyncUpdates(currentDocument, result.decryptedUpdates);\n}\n\nexport function metadataIncomingUpdateIsolation(input: {\n currentDocument: ContainerMetadataState[\"doc\"];\n execSql: ExecSql;\n isCurrent?: (() => boolean) | undefined;\n logError?: WorkflowRuntimeUtilInput[\"logError\"] | undefined;\n metadataScope: { appKind: string; localId: string };\n}) {\n return {\n onIncomingUpdateIsolationFailure: async (\n failure: DocumentSyncUpdateIsolationError,\n ) => {\n await recordCurrentMetadataSyncFailure({\n ...input,\n failure: {\n attemptedAt: new Date().toISOString(),\n message: failure.message,\n status: null,\n },\n });\n if (input.isCurrent?.() === false) return;\n reportDocumentSyncQuarantine(\n input.currentDocument,\n input.logError,\n failure,\n );\n },\n validateIncomingUpdates: (\n result: Pick<SyncRemoteDocumentResult, \"decryptedUpdates\" | \"response\">,\n ) =>\n validateDocumentSyncUpdateImports({\n currentDocument: input.currentDocument,\n decryptedUpdates: result.decryptedUpdates,\n responseUpdates: result.response.updates,\n }),\n };\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import type { DocumentWriterProjectionResponse } from "../../../internal/validators/response/index.js";
2
2
  import type { ProjectionUserKeyResolver } from "../../../data/keyingProjectionVerification/index.js";
3
- import type { PendingUpdateRecord } from "../../../data/sqlite/documentPersistence/index.js";
3
+ import type { PendingUpdateRecord } from "../../../data/persistence/documents/records/index.js";
4
4
  import { type RekeyPendingUpdate, syncRemoteDocument } from "../../documents/index.js";
5
5
  import type { ContainerContentsWorkflowRuntime } from "../runtime.js";
6
6
  import type { ContainerMetadataState } from "./metadataTypes.js";
@@ -1 +1 @@
1
- {"version":3,"file":"metadataRemoteSync.js","sourceRoot":"","sources":["metadataRemoteSync.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,2BAA2B,EAAE,MAAM,2EAA2E,CAAC;AAExH,OAAO,EACL,qCAAqC,EACrC,iCAAiC,EAEjC,2BAA2B,EAC3B,kBAAkB,GACnB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,kCAAkC,EAAE,MAAM,sCAAsC,CAAC;AAE1F,OAAO,EACL,+BAA+B,EAC/B,gCAAgC,GACjC,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,iCAAiC,EAAE,MAAM,sBAAsB,CAAC;AA2DzE,SAAS,kCAAkC,CAAC,KAK3C;IACC,OAAO;QACL,wBAAwB,EACtB,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,UAAU,KAAK,SAAS;YAChD,CAAC,CAAC,IAAI;YACN,CAAC,CAAC,CAAC,KAAK,CAAC,yBAAyB,IAAI,IAAI,CAAC;QAC/C,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;QAC9C,aAAa,EAAE,KAAK,CAAC,aAAa;QAClC,MAAM,EAAE,KAAK,CAAC,MAAM;KACrB,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAC/C,KAAuC;IAEvC,MAAM,EAAE,UAAU,EAAE,SAAS,EAAE,OAAO,EAAE,GAAG,KAAK,CAAC;IACjD,IAAI,CAAC,UAAU;QA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MAAM,EAAE,OAAO,CAAC,MAAM;iBACvB;gBACD,SAAS;gBACT,aAAa;aACd,CAAC,CAAC;QACL,CAAC;QACD,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,gBAAgB,EAAE,KAAK,CAAC,gBAAgB,IAAI,SAAS;QACrD,kBAAkB,EAAE,CAAC,YAAY,EAAE,QAAQ,EAAE,EAAE,CAC7C,SAAS,EAAE;YACT,CAAC,CAAC,KAAK,CAAC,kBAAkB,CAAC,YAAY,EAAE,QAAQ,CAAC;YAClD,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC;QAC3B,wBAAwB,EAAE,KAAK,CAAC,wBAAwB;QACxD,sBAAsB,EAAE,qCAAqC,CAAC;YAC5D,SAAS,EAAE,oBAAoB;YAC/B,OAAO;YACP,cAAc,EAAE,qBAAqB;SACtC,CAAC;QACF,YAAY,EAAE,SAAS;QACvB,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,+BAA+B,EAC7B,kCAAkC,CAAC,OAAO,CAAC;QAC7C,gBAAgB,EAAE,KAAK,CAAC,gBAAgB;KACzC,CAAC,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE,CAC1B,iCAAiC,CAAC;QAChC,WAAW,EAAE,KAAK,CAAC,WAAW;QAC9B,KAAK;QACL,OAAO;KACR,CAAC,CACH,CAAC;IACF,IAAI,CAAC,MAAM;QAAE,OAAO,IAAI,CAAC;IACzB,OAAO,kCAAkC,CAAC;QACxC,mBAAmB,EAAE,KAAK,CAAC,cAAc,CAAC,MAAM;QAChD,yBAAyB,EAAE,KAAK,CAAC,gBAAgB;QACjD,aAAa,EAAE,KAAK,CAAC,cAAc;QACnC,MAAM;KACP,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport type { ProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport { CONTAINER_METADATA_APP_KIND } from \"../../../data/persistence/container-contents/containerContentsPersistence\";\nimport type { PendingUpdateRecord } from \"../../../data/sqlite/documentPersistence\";\nimport {\n createDocumentWriterPublicKeyResolver,\n describeDocumentSyncSubmitFailure,\n type RekeyPendingUpdate,\n resolveDocumentCreateAuthor,\n syncRemoteDocument,\n} from \"../../documents\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../../principals/runtimePolicyWarmer\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\nimport {\n metadataIncomingUpdateIsolation,\n recordCurrentMetadataSyncFailure,\n} from \"./metadataIncomingUpdateIsolation\";\nimport { deferRecoverableMetadataSyncError } from \"./metadataSyncErrors\";\nimport type { ContainerMetadataState } from \"./metadataTypes\";\n\ntype ContainerMetadataSyncApi = Parameters<\n typeof syncRemoteDocument\n>[0][\"apiClient\"] &\n Pick<\n ContainerContentsWorkflowRuntime[\"apiClient\"],\n \"getPrincipalPolicyPages\" | \"getProjectionPolicyHistoryPages\"\n >;\n\nexport interface ContainerMetadataSyncRuntime\n extends Pick<\n ContainerContentsWorkflowRuntime,\n | \"auth\"\n | \"crypto\"\n | \"infra\"\n | \"resolveTrustedUserIdentity\"\n | \"state\"\n | \"util\"\n > {\n apiClient: ContainerMetadataSyncApi;\n}\n\ntype ContainerMetadataSyncResult = NonNullable<\n Awaited<ReturnType<typeof syncRemoteDocument>>\n>;\n\nexport interface ContainerMetadataSyncAttempt {\n consumedPullContinuation: ContainerMetadataState[\"pullContinuation\"];\n outgoingUpdateCount: number;\n requestRecord: ContainerMetadataState[\"record\"];\n synced: ContainerMetadataSyncResult;\n}\n\ninterface SyncRemoteContainerMetadataInput {\n buildRotationSnapshot?: (() => Promise<Uint8Array | null>) | undefined;\n containerId: string;\n currentDocument: ContainerMetadataState[\"doc\"];\n documentId: string | null;\n isCurrent: () => boolean;\n lastCommitLsn?: string | null | undefined;\n localVersionVector: string | null;\n onOutgoingUpdatesMaterialized?:\n | ((updateIds: readonly string[]) => void)\n | undefined;\n onPullContinuationInvalidated?: Parameters<\n typeof syncRemoteDocument\n >[0][\"onPullContinuationInvalidated\"];\n pendingUpdates: readonly PendingUpdateRecord[];\n persistedState: ContainerMetadataState[\"record\"];\n pullContinuation?: ContainerMetadataState[\"pullContinuation\"];\n rekeyPendingUpdate: RekeyPendingUpdate;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerMetadataSyncRuntime;\n targetSecretKey: Uint8Array;\n writerProjection?: DocumentWriterProjectionResponse | undefined;\n}\n\nfunction createContainerMetadataSyncAttempt(input: {\n outgoingUpdateCount: number;\n requestedPullContinuation: ContainerMetadataState[\"pullContinuation\"];\n requestRecord: ContainerMetadataState[\"record\"];\n synced: ContainerMetadataSyncResult;\n}): ContainerMetadataSyncAttempt {\n return {\n consumedPullContinuation:\n input.synced.plan.request.pullCursor === undefined\n ? null\n : (input.requestedPullContinuation ?? null),\n outgoingUpdateCount: input.outgoingUpdateCount,\n requestRecord: input.requestRecord,\n synced: input.synced,\n };\n}\n\nexport async function syncRemoteContainerMetadata(\n input: SyncRemoteContainerMetadataInput,\n): Promise<ContainerMetadataSyncAttempt | null> {\n const { documentId, isCurrent, runtime } = input;\n if (!documentId) return null;\n const author = resolveDocumentCreateAuthor(runtime);\n if (!author) {\n runtime.util.log(\n \"Container contents: skipped metadata sync because the writer context is unavailable.\",\n );\n return null;\n }\n const execSql = runtime.infra.execSql;\n const metadataScope = {\n appKind: CONTAINER_METADATA_APP_KIND,\n localId: input.containerId,\n };\n const synced = await syncRemoteDocument({\n apiClient: runtime.apiClient,\n author,\n buildRotationSnapshot: input.buildRotationSnapshot,\n documentId,\n execSql,\n isRemoteSyncBlocked: runtime.util.isRemoteSyncBlocked,\n localVersionVector: input.localVersionVector,\n minLsn: input.lastCommitLsn ?? undefined,\n ...metadataIncomingUpdateIsolation({\n currentDocument: input.currentDocument,\n execSql,\n isCurrent,\n logError: runtime.util.logError,\n metadataScope,\n }),\n onOutgoingUpdatesMaterialized: input.onOutgoingUpdatesMaterialized,\n onPullContinuationInvalidated: input.onPullContinuationInvalidated,\n onSyncTrace: (line) => runtime.util.log(`Container contents: ${line}`),\n onTerminalSubmitFailure: async (failure) => {\n await recordCurrentMetadataSyncFailure({\n execSql,\n failure: {\n attemptedAt: new Date().toISOString(),\n message: describeDocumentSyncSubmitFailure(failure),\n status: failure.status,\n },\n isCurrent,\n metadataScope,\n });\n },\n pendingUpdates: input.pendingUpdates,\n persistedState: input.persistedState,\n pullContinuation: input.pullContinuation ?? undefined,\n rekeyPendingUpdate: (rekeyExecSql, updateId) =>\n isCurrent()\n ? input.rekeyPendingUpdate(rekeyExecSql, updateId)\n : Promise.resolve(null),\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n resolveWriterPublicKey: createDocumentWriterPublicKeyResolver({\n logPrefix: \"Container contents\",\n runtime,\n writerKeyLabel: \"metadata writer key\",\n }),\n stillCurrent: isCurrent,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies:\n createRuntimePrincipalPolicyWarmer(runtime),\n writerProjection: input.writerProjection,\n }).catch((error: unknown) =>\n deferRecoverableMetadataSyncError({\n containerId: input.containerId,\n error,\n runtime,\n }),\n );\n if (!synced) return null;\n return createContainerMetadataSyncAttempt({\n outgoingUpdateCount: input.pendingUpdates.length,\n requestedPullContinuation: input.pullContinuation,\n requestRecord: input.persistedState,\n synced,\n });\n}\n"]}
1
+ {"version":3,"file":"metadataRemoteSync.js","sourceRoot":"","sources":["metadataRemoteSync.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,2BAA2B,EAAE,MAAM,2EAA2E,CAAC;AAExH,OAAO,EACL,qCAAqC,EACrC,iCAAiC,EAEjC,2BAA2B,EAC3B,kBAAkB,GACnB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,kCAAkC,EAAE,MAAM,sCAAsC,CAAC;AAE1F,OAAO,EACL,+BAA+B,EAC/B,gCAAgC,GACjC,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE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gB,EAAE,KAAK,CAAC,gBAAgB;KACzC,CAAC,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE,CAC1B,iCAAiC,CAAC;QAChC,WAAW,EAAE,KAAK,CAAC,WAAW;QAC9B,KAAK;QACL,OAAO;KACR,CAAC,CACH,CAAC;IACF,IAAI,CAAC,MAAM;QAAE,OAAO,IAAI,CAAC;IACzB,OAAO,kCAAkC,CAAC;QACxC,mBAAmB,EAAE,KAAK,CAAC,cAAc,CAAC,MAAM;QAChD,yBAAyB,EAAE,KAAK,CAAC,gBAAgB;QACjD,aAAa,EAAE,KAAK,CAAC,cAAc;QACnC,MAAM;KACP,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport type { ProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport { CONTAINER_METADATA_APP_KIND } from \"../../../data/persistence/container-contents/containerContentsPersistence\";\nimport type { PendingUpdateRecord } from \"../../../data/persistence/documents/records\";\nimport {\n createDocumentWriterPublicKeyResolver,\n describeDocumentSyncSubmitFailure,\n type RekeyPendingUpdate,\n resolveDocumentCreateAuthor,\n syncRemoteDocument,\n} from \"../../documents\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../../principals/runtimePolicyWarmer\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\nimport {\n metadataIncomingUpdateIsolation,\n recordCurrentMetadataSyncFailure,\n} from \"./metadataIncomingUpdateIsolation\";\nimport { deferRecoverableMetadataSyncError } from \"./metadataSyncErrors\";\nimport type { ContainerMetadataState } from \"./metadataTypes\";\n\ntype ContainerMetadataSyncApi = Parameters<\n typeof syncRemoteDocument\n>[0][\"apiClient\"] &\n Pick<\n ContainerContentsWorkflowRuntime[\"apiClient\"],\n \"getPrincipalPolicyPages\" | \"getProjectionPolicyHistoryPages\"\n >;\n\nexport interface ContainerMetadataSyncRuntime\n extends Pick<\n ContainerContentsWorkflowRuntime,\n | \"auth\"\n | \"crypto\"\n | \"infra\"\n | \"resolveTrustedUserIdentity\"\n | \"state\"\n | \"util\"\n > {\n apiClient: ContainerMetadataSyncApi;\n}\n\ntype ContainerMetadataSyncResult = NonNullable<\n Awaited<ReturnType<typeof syncRemoteDocument>>\n>;\n\nexport interface ContainerMetadataSyncAttempt {\n consumedPullContinuation: ContainerMetadataState[\"pullContinuation\"];\n outgoingUpdateCount: number;\n requestRecord: ContainerMetadataState[\"record\"];\n synced: ContainerMetadataSyncResult;\n}\n\ninterface SyncRemoteContainerMetadataInput {\n buildRotationSnapshot?: (() => Promise<Uint8Array | null>) | undefined;\n containerId: string;\n currentDocument: ContainerMetadataState[\"doc\"];\n documentId: string | null;\n isCurrent: () => boolean;\n lastCommitLsn?: string | null | undefined;\n localVersionVector: string | null;\n onOutgoingUpdatesMaterialized?:\n | ((updateIds: readonly string[]) => void)\n | undefined;\n onPullContinuationInvalidated?: Parameters<\n typeof syncRemoteDocument\n >[0][\"onPullContinuationInvalidated\"];\n pendingUpdates: readonly PendingUpdateRecord[];\n persistedState: ContainerMetadataState[\"record\"];\n pullContinuation?: ContainerMetadataState[\"pullContinuation\"];\n rekeyPendingUpdate: RekeyPendingUpdate;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerMetadataSyncRuntime;\n targetSecretKey: Uint8Array;\n writerProjection?: DocumentWriterProjectionResponse | undefined;\n}\n\nfunction createContainerMetadataSyncAttempt(input: {\n outgoingUpdateCount: number;\n requestedPullContinuation: ContainerMetadataState[\"pullContinuation\"];\n requestRecord: ContainerMetadataState[\"record\"];\n synced: ContainerMetadataSyncResult;\n}): ContainerMetadataSyncAttempt {\n return {\n consumedPullContinuation:\n input.synced.plan.request.pullCursor === undefined\n ? null\n : (input.requestedPullContinuation ?? null),\n outgoingUpdateCount: input.outgoingUpdateCount,\n requestRecord: input.requestRecord,\n synced: input.synced,\n };\n}\n\nexport async function syncRemoteContainerMetadata(\n input: SyncRemoteContainerMetadataInput,\n): Promise<ContainerMetadataSyncAttempt | null> {\n const { documentId, isCurrent, runtime } = input;\n if (!documentId) return null;\n const author = resolveDocumentCreateAuthor(runtime);\n if (!author) {\n runtime.util.log(\n \"Container contents: skipped metadata sync because the writer context is unavailable.\",\n );\n return null;\n }\n const execSql = runtime.infra.execSql;\n const metadataScope = {\n appKind: CONTAINER_METADATA_APP_KIND,\n localId: input.containerId,\n };\n const synced = await syncRemoteDocument({\n apiClient: runtime.apiClient,\n author,\n buildRotationSnapshot: input.buildRotationSnapshot,\n documentId,\n execSql,\n isRemoteSyncBlocked: runtime.util.isRemoteSyncBlocked,\n localVersionVector: input.localVersionVector,\n minLsn: input.lastCommitLsn ?? undefined,\n ...metadataIncomingUpdateIsolation({\n currentDocument: input.currentDocument,\n execSql,\n isCurrent,\n logError: runtime.util.logError,\n metadataScope,\n }),\n onOutgoingUpdatesMaterialized: input.onOutgoingUpdatesMaterialized,\n onPullContinuationInvalidated: input.onPullContinuationInvalidated,\n onSyncTrace: (line) => runtime.util.log(`Container contents: ${line}`),\n onTerminalSubmitFailure: async (failure) => {\n await recordCurrentMetadataSyncFailure({\n execSql,\n failure: {\n attemptedAt: new Date().toISOString(),\n message: describeDocumentSyncSubmitFailure(failure),\n status: failure.status,\n },\n isCurrent,\n metadataScope,\n });\n },\n pendingUpdates: input.pendingUpdates,\n persistedState: input.persistedState,\n pullContinuation: input.pullContinuation ?? undefined,\n rekeyPendingUpdate: (rekeyExecSql, updateId) =>\n isCurrent()\n ? input.rekeyPendingUpdate(rekeyExecSql, updateId)\n : Promise.resolve(null),\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n resolveWriterPublicKey: createDocumentWriterPublicKeyResolver({\n logPrefix: \"Container contents\",\n runtime,\n writerKeyLabel: \"metadata writer key\",\n }),\n stillCurrent: isCurrent,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies:\n createRuntimePrincipalPolicyWarmer(runtime),\n writerProjection: input.writerProjection,\n }).catch((error: unknown) =>\n deferRecoverableMetadataSyncError({\n containerId: input.containerId,\n error,\n runtime,\n }),\n );\n if (!synced) return null;\n return createContainerMetadataSyncAttempt({\n outgoingUpdateCount: input.pendingUpdates.length,\n requestedPullContinuation: input.pullContinuation,\n requestRecord: input.persistedState,\n synced,\n });\n}\n"]}
@@ -2,7 +2,7 @@ import { DOCUMENTS_APP_KIND } from "../../../data/documents/documentConstants.js
2
2
  import { CONTAINER_METADATA_APP_KIND } from "../../../data/persistence/container-contents/containerContentsPersistence.js";
3
3
  import { sqlDocumentMoveIntentPersistence } from "../../../data/persistence/container-contents/documentMoveIntentPersistence.js";
4
4
  import { sqlDocumentsPersistence } from "../../../data/persistence/documents/documentsPersistence.js";
5
- import { clearDocumentSyncFailure, resetDocumentPendingUpdateRekeyBudget, } from "../../../data/sqlite/documentPersistence/index.js";
5
+ import { clearDocumentSyncFailure, resetDocumentPendingUpdateRekeyBudget, } from "../../../data/persistence/documents/records/index.js";
6
6
  import { documentPlacementIntentTables, documentTables, LOCAL_INTENT_LANES, } from "../../../data/sqlite/schema/index.js";
7
7
  import { ensureSqlTables } from "../../../data/sqlite/sqlSchema.js";
8
8
  import { defaultContainerContentsPersistence } from "../containerPersistence.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,2CAA2C,CAAC;AAC/E,OAAO,EAAE,2BAA2B,EAAE,MAAM,2EAA2E,CAAC;AACxH,OAAO,EAAE,gCAAgC,EAAE,MAAM,4EAA4E,CAAC;AAC9H,OAAO,EAAE,uBAAuB,EAAE,MAAM,0DAA0D,CAAC;AACnG,OAAO,EACL,wBAAwB,EACxB,qCAAqC,GACtC,MAAM,0CAA0C,CAAC;AAClD,OAAO,EACL,6BAA6B,EAC7B,cAAc,EACd,kBAAkB,GACnB,MAAM,6BAA6B,CAAC;AAErC,OAAO,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AACjE,OAAO,EAA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,EAAE,KAAK,CAAC,CAAC;IAC5D,IAAI,OAAO,KAAK,kBAAkB,EAAE,CAAC;QACnC,yEAAyE;QACzE,sEAAsE;QACtE,uBAAuB;QACvB,MAAM,gCAAgC,CAAC,sBAAsB,CAAC,OAAO,EAAE;YACrE,OAAO,EAAE,KAAK,CAAC,OAAO;SACvB,CAAC,CAAC;IACL,CAAC;IACD,yEAAyE;IACzE,0EAA0E;IAC1E,sEAAsE;IACtE,wEAAwE;IACxE,yEAAyE;IACzE,IAAI,MAAM,kBAAkB,CAAC,OAAO,EAAE,KAAK,CAAC,EAAE,CAAC;QAC7C,MAAM,wBAAwB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IACjD,CAAC;AACH,CAAC;AAED;;;;;;GAMG;AACH,KAAK,UAAU,kBAAkB,CAC/B,OAAgB,EAChB,KAA2C;IAE3C,MAAM,eAAe,CAAC,OAAO,EAAE;QAC7B,GAAG,cAAc;QACjB,GAAG,6BAA6B;KACjC,CAAC,CAAC;IACH,MAAM,IAAI,GAAG,MAAM,OAAO,CACxB;;;;;;;;;;;;gCAY4B,kBAAkB,CAAC,iBAAiB;;;;;;;;;aASvD,EACT;QACE,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;KACd,CACF,CAAC;IACF,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACpB,OAAO,IAAI,CAAC;IACd,CAAC;IACD,sEAAsE;IACtE,kEAAkE;IAClE,iCAAiC;IACjC,OAAO,wBAAwB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;AAClD,CAAC","sourcesContent":["import { DOCUMENTS_APP_KIND } from \"../../../data/documents/documentConstants\";\nimport { CONTAINER_METADATA_APP_KIND } from \"../../../data/persistence/container-contents/containerContentsPersistence\";\nimport { sqlDocumentMoveIntentPersistence } from \"../../../data/persistence/container-contents/documentMoveIntentPersistence\";\nimport { sqlDocumentsPersistence } from \"../../../data/persistence/documents/documentsPersistence\";\nimport {\n clearDocumentSyncFailure,\n resetDocumentPendingUpdateRekeyBudget,\n} from \"../../../data/sqlite/documentPersistence\";\nimport {\n documentPlacementIntentTables,\n documentTables,\n LOCAL_INTENT_LANES,\n} from \"../../../data/sqlite/schema\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { ensureSqlTables } from \"../../../data/sqlite/sqlSchema\";\nimport { defaultContainerContentsPersistence } from \"../containerPersistence\";\nimport { groupPendingWriteCandidates } from \"./aggregation\";\nimport {\n hasDeferredTailScopeWork,\n listDeferredPendingWriteCandidates,\n} from \"./deferredTails\";\nimport type { PendingWriteQueueItem } from \"./pendingWritesTypes\";\nimport { listPersistedPendingWriteCandidates } from \"./sources\";\n\nexport type {\n PendingWriteQueueItem,\n PendingWriteQueueItemStatus,\n PendingWriteQueueObjectKind,\n PendingWriteQueueOperation,\n PendingWriteQueueOperationKind,\n PendingWriteQueueOperationStatus,\n} from \"./pendingWritesTypes\";\n\n/**\n * List identity-wide local state that still requires a remote write. The\n * returned diagnostic contains only navigation/display metadata and aggregate\n * counts; serialized updates, local storage keys, and upload crypto stay below\n * the workflow boundary.\n */\nexport async function listPendingWrites(\n execSql: ExecSql,\n): Promise<ReadonlyArray<PendingWriteQueueItem>> {\n await defaultContainerContentsPersistence.ensureSchema(execSql);\n await sqlDocumentsPersistence.ensureSchema(execSql);\n await sqlDocumentMoveIntentPersistence.ensureSchema(execSql);\n\n const [persisted, deferred] = await Promise.all([\n listPersistedPendingWriteCandidates(execSql),\n listDeferredPendingWriteCandidates(execSql),\n ]);\n return groupPendingWriteCandidates([...persisted, ...deferred]);\n}\n\n/**\n * Explicit manual retry for one write-queue item: reset the durable re-key\n * budget for the item's ACTUAL pending-update scope (container metadata and\n * unknown document namespaces re-key through the same recovery path as\n * ordinary documents) and clear the recorded terminal failure — the next\n * pass re-records both if they still hold. The cap protects against a\n * server driving a network-speed re-key loop; a deliberate user retry is\n * the rate-limited signal that conditions have changed (e.g. an outage that\n * burned the budget has healed). The caller re-arms the sync lanes.\n */\nexport async function resetPendingWriteRetryState(\n execSql: ExecSql,\n input: {\n localId: string;\n /** The item's `namespace` — the unrecognized documents.app_kind, if any. */\n namespace: string | null;\n objectKind: PendingWriteQueueItem[\"objectKind\"];\n },\n): Promise<void> {\n const appKind =\n input.objectKind === \"container\"\n ? CONTAINER_METADATA_APP_KIND\n : (input.namespace ??\n (input.objectKind === \"document\" ? DOCUMENTS_APP_KIND : null));\n if (appKind === null) {\n // An unknown object kind with no namespace: there is no scope to reset,\n // and guessing one could clear an unrelated scope sharing the localId.\n return;\n }\n const scope = { appKind, localId: input.localId };\n await resetDocumentPendingUpdateRekeyBudget(execSql, scope);\n if (appKind === DOCUMENTS_APP_KIND) {\n // A deliberate retry is the rate-limited signal that conditions changed:\n // a parked permission-denied move (row 7) replays once, like row 11's\n // re-key budget reset.\n await sqlDocumentMoveIntentPersistence.resetDeniedMoveIntents(execSql, {\n localId: input.localId,\n });\n }\n // Clearing the failure row is part of the re-key budget reset (edge-case\n // row 11) and only makes sense alongside queued work. A failure-only item\n // (a refused revalidation, row 13) has no queued work: its row is the\n // priming ticket that re-drives the store, so it must survive the retry\n // and clear on the next clean pass instead of vanishing with no request.\n if (await hasQueuedScopeWork(execSql, scope)) {\n await clearDocumentSyncFailure(execSql, scope);\n }\n}\n\n/**\n * Whether ANY durable outbound work exists for the scope — CRDT updates,\n * staged attachment uploads, move intents, a never-created local document, or\n * a deferred write whose only durable content is the history tail ahead of\n * its covered frontier. Mirrors the queue's own document candidate sources,\n * so \"failure-only\" here agrees with the item the panel rendered.\n */\nasync function hasQueuedScopeWork(\n execSql: ExecSql,\n scope: { appKind: string; localId: string },\n): Promise<boolean> {\n await ensureSqlTables(execSql, [\n ...documentTables,\n ...documentPlacementIntentTables,\n ]);\n const rows = await execSql(\n `SELECT 1 AS present\n WHERE EXISTS (\n SELECT 1 FROM document_history_updates pending\n WHERE pending.app_kind = ? AND pending.local_id = ?\n AND pending.update_id IS NOT NULL\n )\n OR EXISTS (\n SELECT 1 FROM document_pending_attachments attachment\n WHERE attachment.local_id = ?\n )\n OR EXISTS (\n SELECT 1 FROM local_intents intent\n WHERE intent.lane = '${LOCAL_INTENT_LANES.documentPlacement}'\n AND intent.local_id = ?\n AND intent.intent_type IN ('document.move', 'document.link')\n )\n OR EXISTS (\n SELECT 1 FROM documents stored\n WHERE stored.app_kind = ? AND stored.local_id = ?\n AND stored.document_id IS NULL\n )\n LIMIT 1`,\n [\n scope.appKind,\n scope.localId,\n scope.localId,\n scope.localId,\n scope.appKind,\n scope.localId,\n ],\n );\n if (rows.length > 0) {\n return true;\n }\n // The queue's deferred-update source has no queued rows to probe: the\n // write lives in the durable history tail, detectable only by the\n // version-vector coverage check.\n return hasDeferredTailScopeWork(execSql, scope);\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,2CAA2C,CAAC;AAC/E,OAAO,EAAE,2BAA2B,EAAE,MAAM,2EAA2E,CAAC;AACxH,OAAO,EAAE,gCAAgC,EAAE,MAAM,4EAA4E,CAAC;AAC9H,OAAO,EAAE,uBAAuB,EAAE,MAAM,0DAA0D,CAAC;AACnG,OAAO,EACL,wBAAwB,EACxB,qCAAqC,GACtC,MAAM,6CAA6C,CAAC;AACrD,OAAO,EACL,6BAA6B,EAC7B,cAAc,EACd,kBAAkB,GACnB,MAAM,6BAA6B,CAAC;AAErC,OAAO,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AACjE,OAAO,EAAE,mCAAmC,EAAE,MAAM,yBAAyB,CAAC;AAC9E,OAAO,EAAE,2BAA2B,EAAE,MAAM,eAAe,CAAC;AAC5D,OAAO,EACL,wBAAwB,EACxB,kCAAkC,GACnC,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAAE,mCA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EAAE,KAAK,CAAC,OAAO;SACvB,CAAC,CAAC;IACL,CAAC;IACD,yEAAyE;IACzE,0EAA0E;IAC1E,sEAAsE;IACtE,wEAAwE;IACxE,yEAAyE;IACzE,IAAI,MAAM,kBAAkB,CAAC,OAAO,EAAE,KAAK,CAAC,EAAE,CAAC;QAC7C,MAAM,wBAAwB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IACjD,CAAC;AACH,CAAC;AAED;;;;;;GAMG;AACH,KAAK,UAAU,kBAAkB,CAC/B,OAAgB,EAChB,KAA2C;IAE3C,MAAM,eAAe,CAAC,OAAO,EAAE;QAC7B,GAAG,cAAc;QACjB,GAAG,6BAA6B;KACjC,CAAC,CAAC;IACH,MAAM,IAAI,GAAG,MAAM,OAAO,CACxB;;;;;;;;;;;;gCAY4B,kBAAkB,CAAC,iBAAiB;;;;;;;;;aASvD,EACT;QACE,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;KACd,CACF,CAAC;IACF,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACpB,OAAO,IAAI,CAAC;IACd,CAAC;IACD,sEAAsE;IACtE,kEAAkE;IAClE,iCAAiC;IACjC,OAAO,wBAAwB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;AAClD,CAAC","sourcesContent":["import { DOCUMENTS_APP_KIND } from \"../../../data/documents/documentConstants\";\nimport { CONTAINER_METADATA_APP_KIND } from \"../../../data/persistence/container-contents/containerContentsPersistence\";\nimport { sqlDocumentMoveIntentPersistence } from \"../../../data/persistence/container-contents/documentMoveIntentPersistence\";\nimport { sqlDocumentsPersistence } from \"../../../data/persistence/documents/documentsPersistence\";\nimport {\n clearDocumentSyncFailure,\n resetDocumentPendingUpdateRekeyBudget,\n} from \"../../../data/persistence/documents/records\";\nimport {\n documentPlacementIntentTables,\n documentTables,\n LOCAL_INTENT_LANES,\n} from \"../../../data/sqlite/schema\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { ensureSqlTables } from \"../../../data/sqlite/sqlSchema\";\nimport { defaultContainerContentsPersistence } from \"../containerPersistence\";\nimport { groupPendingWriteCandidates } from \"./aggregation\";\nimport {\n hasDeferredTailScopeWork,\n listDeferredPendingWriteCandidates,\n} from \"./deferredTails\";\nimport type { PendingWriteQueueItem } from \"./pendingWritesTypes\";\nimport { listPersistedPendingWriteCandidates } from \"./sources\";\n\nexport type {\n PendingWriteQueueItem,\n PendingWriteQueueItemStatus,\n PendingWriteQueueObjectKind,\n PendingWriteQueueOperation,\n PendingWriteQueueOperationKind,\n PendingWriteQueueOperationStatus,\n} from \"./pendingWritesTypes\";\n\n/**\n * List identity-wide local state that still requires a remote write. The\n * returned diagnostic contains only navigation/display metadata and aggregate\n * counts; serialized updates, local storage keys, and upload crypto stay below\n * the workflow boundary.\n */\nexport async function listPendingWrites(\n execSql: ExecSql,\n): Promise<ReadonlyArray<PendingWriteQueueItem>> {\n await defaultContainerContentsPersistence.ensureSchema(execSql);\n await sqlDocumentsPersistence.ensureSchema(execSql);\n await sqlDocumentMoveIntentPersistence.ensureSchema(execSql);\n\n const [persisted, deferred] = await Promise.all([\n listPersistedPendingWriteCandidates(execSql),\n listDeferredPendingWriteCandidates(execSql),\n ]);\n return groupPendingWriteCandidates([...persisted, ...deferred]);\n}\n\n/**\n * Explicit manual retry for one write-queue item: reset the durable re-key\n * budget for the item's ACTUAL pending-update scope (container metadata and\n * unknown document namespaces re-key through the same recovery path as\n * ordinary documents) and clear the recorded terminal failure — the next\n * pass re-records both if they still hold. The cap protects against a\n * server driving a network-speed re-key loop; a deliberate user retry is\n * the rate-limited signal that conditions have changed (e.g. an outage that\n * burned the budget has healed). The caller re-arms the sync lanes.\n */\nexport async function resetPendingWriteRetryState(\n execSql: ExecSql,\n input: {\n localId: string;\n /** The item's `namespace` — the unrecognized documents.app_kind, if any. */\n namespace: string | null;\n objectKind: PendingWriteQueueItem[\"objectKind\"];\n },\n): Promise<void> {\n const appKind =\n input.objectKind === \"container\"\n ? CONTAINER_METADATA_APP_KIND\n : (input.namespace ??\n (input.objectKind === \"document\" ? DOCUMENTS_APP_KIND : null));\n if (appKind === null) {\n // An unknown object kind with no namespace: there is no scope to reset,\n // and guessing one could clear an unrelated scope sharing the localId.\n return;\n }\n const scope = { appKind, localId: input.localId };\n await resetDocumentPendingUpdateRekeyBudget(execSql, scope);\n if (appKind === DOCUMENTS_APP_KIND) {\n // A deliberate retry is the rate-limited signal that conditions changed:\n // a parked permission-denied move (row 7) replays once, like row 11's\n // re-key budget reset.\n await sqlDocumentMoveIntentPersistence.resetDeniedMoveIntents(execSql, {\n localId: input.localId,\n });\n }\n // Clearing the failure row is part of the re-key budget reset (edge-case\n // row 11) and only makes sense alongside queued work. A failure-only item\n // (a refused revalidation, row 13) has no queued work: its row is the\n // priming ticket that re-drives the store, so it must survive the retry\n // and clear on the next clean pass instead of vanishing with no request.\n if (await hasQueuedScopeWork(execSql, scope)) {\n await clearDocumentSyncFailure(execSql, scope);\n }\n}\n\n/**\n * Whether ANY durable outbound work exists for the scope — CRDT updates,\n * staged attachment uploads, move intents, a never-created local document, or\n * a deferred write whose only durable content is the history tail ahead of\n * its covered frontier. Mirrors the queue's own document candidate sources,\n * so \"failure-only\" here agrees with the item the panel rendered.\n */\nasync function hasQueuedScopeWork(\n execSql: ExecSql,\n scope: { appKind: string; localId: string },\n): Promise<boolean> {\n await ensureSqlTables(execSql, [\n ...documentTables,\n ...documentPlacementIntentTables,\n ]);\n const rows = await execSql(\n `SELECT 1 AS present\n WHERE EXISTS (\n SELECT 1 FROM document_history_updates pending\n WHERE pending.app_kind = ? AND pending.local_id = ?\n AND pending.update_id IS NOT NULL\n )\n OR EXISTS (\n SELECT 1 FROM document_pending_attachments attachment\n WHERE attachment.local_id = ?\n )\n OR EXISTS (\n SELECT 1 FROM local_intents intent\n WHERE intent.lane = '${LOCAL_INTENT_LANES.documentPlacement}'\n AND intent.local_id = ?\n AND intent.intent_type IN ('document.move', 'document.link')\n )\n OR EXISTS (\n SELECT 1 FROM documents stored\n WHERE stored.app_kind = ? AND stored.local_id = ?\n AND stored.document_id IS NULL\n )\n LIMIT 1`,\n [\n scope.appKind,\n scope.localId,\n scope.localId,\n scope.localId,\n scope.appKind,\n scope.localId,\n ],\n );\n if (rows.length > 0) {\n return true;\n }\n // The queue's deferred-update source has no queued rows to probe: the\n // write lives in the durable history tail, detectable only by the\n // version-vector coverage check.\n return hasDeferredTailScopeWork(execSql, scope);\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { sqlDocumentMoveIntentPersistence } from "../../../data/persistence/container-contents/documentMoveIntentPersistence.js";
2
2
  import { requestDormantMetadataRestorationSweeps } from "../../../data/persistence/container-contents/dormantMetadataSweep.js";
3
- import { hasRecordedTerminalSyncFailures } from "../../../data/sqlite/documentPersistence/index.js";
3
+ import { hasRecordedTerminalSyncFailures } from "../../../data/persistence/documents/records/index.js";
4
4
  import { requestAllDomainSyncLanes, requestDomainSyncLane, } from "../../../data/sync/syncCoordinator.js";
5
5
  import { CONTAINER_CONTENTS_SYNC_LANE_KEY } from "../syncLane.js";
6
6
  /** Recover parked work before optional presentation hydration can fail. */
@@ -1 +1 @@
1
- {"version":3,"file":"accessRestoration.js","sourceRoot":"","sources":["accessRestoration.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gCAAgC,EAAE,MAAM,4EAA4E,CAAC;AAC9H,OAAO,EAAE,uCAAuC,EAAE,MAAM,mEAAmE,CAAC;AAE5H,OAAO,EAAE,+BAA+B,EAAE,MAAM,0CAA0C,CAAC;AAE3F,OAAO,EACL,yBAAyB,EACzB,qBAAqB,GACtB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,gCAAgC,EAAE,MAAM,aAAa,CAAC;AAE/D,2EAA2E;AAC3E,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAAC,KAM/C;IACC,MAAM,EAAE,WAAW,EAAE,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,EAAE,GAAG,KAAK,CAAC;IAC7E,IAAI,CAAC,YAAY,EAAE;QAAE,OAAO;IAC5B,iEAAiE;IACjE,mEAAmE;IACnE,iEAAiE;IACjE,sEAAsE;IACtE,oEAAoE;IACpE,gCAAgC;IAChC,IACE,CAAC,CAAC,MAAM,+BAA+B,CAAC,OAAO,CAAC,CAAC;QAC/C,CAAC,MAAM,gCAAgC,CAAC,oBAAoB,CAAC,OAAO,EAAE;YACpE,cAAc;SACf,CAAC,CAAC,CAAC;QACN,YAAY,EAAE,EACd,CAAC;QACD,kEAAkE;QAClE,4DAA4D;QAC5D,MAAM,gCAAgC,CAAC,sBAAsB,CAAC,OAAO,EAAE;YACrE,cAAc;SACf,CAAC,CAAC;QACH,IAAI,YAAY,EAAE;YAAE,yBAAyB,CAAC,WAAW,CAAC,CAAC;IAC7D,CAAC;IACD,sEAAsE;IACtE,+DAA+D;IAC/D,6DAA6D;IAC7D,IAAI,YAAY,EAAE,EAAE,CAAC;QACnB,MAAM,0BAA0B,GAC9B,MAAM,uCAAuC,CAAC,OAAO,EAAE;YACrD,eAAe,EAAE,MAAM;SACxB,CAAC,CAAC;QACL,IAAI,0BAA0B,GAAG,CAAC,IAAI,YAAY,EAAE,EAAE,CAAC;YACrD,qBAAqB,CAAC,WAAW,EAAE,gCAAgC,CAAC,CAAC;QACvE,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import { sqlDocumentMoveIntentPersistence } from \"../../../data/persistence/container-contents/documentMoveIntentPersistence\";\nimport { requestDormantMetadataRestorationSweeps } from \"../../../data/persistence/container-contents/dormantMetadataSweep\";\nimport type { DomainScope } from \"../../../data/shared/domainScope\";\nimport { hasRecordedTerminalSyncFailures } from \"../../../data/sqlite/documentPersistence\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n requestAllDomainSyncLanes,\n requestDomainSyncLane,\n} from \"../../../data/sync/syncCoordinator\";\nimport { CONTAINER_CONTENTS_SYNC_LANE_KEY } from \"../syncLane\";\n\n/** Recover parked work before optional presentation hydration can fail. */\nexport async function recoverOrganizationAccess(input: {\n readonly domainScope: DomainScope;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly stillCurrent: () => boolean;\n readonly userId: string;\n}): Promise<void> {\n const { domainScope, execSql, organizationId, stillCurrent, userId } = input;\n if (!stillCurrent()) return;\n // The evidence gate: re-arm only when some queued write actually\n // recorded a terminal failure. A transient denial during bootstrap\n // (e.g. a read-model 403 before grants propagate) also flips the\n // denied flag, and re-arming then would race the startup sync passes.\n // A failed pass (`undefined`) proves nothing about restored access,\n // so it must not re-arm either.\n if (\n ((await hasRecordedTerminalSyncFailures(execSql)) ||\n (await sqlDocumentMoveIntentPersistence.hasDeniedMoveIntents(execSql, {\n organizationId,\n }))) &&\n stillCurrent()\n ) {\n // Parked permission-denied moves (row 7) only replay once flipped\n // back to pending; restore them before re-arming the lanes.\n await sqlDocumentMoveIntentPersistence.resetDeniedMoveIntents(execSql, {\n organizationId,\n });\n if (stillCurrent()) requestAllDomainSyncLanes(domainScope);\n }\n // Keep dormant cleanup independent from the write-lane evidence gate,\n // but run it afterward so a SQLite failure cannot suppress the\n // pre-existing denied-write and move-intent recovery signal.\n if (stillCurrent()) {\n const requestedDormantSweepCount =\n await requestDormantMetadataRestorationSweeps(execSql, {\n requesterUserId: userId,\n });\n if (requestedDormantSweepCount > 0 && stillCurrent()) {\n requestDomainSyncLane(domainScope, CONTAINER_CONTENTS_SYNC_LANE_KEY);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"accessRestoration.js","sourceRoot":"","sources":["accessRestoration.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gCAAgC,EAAE,MAAM,4EAA4E,CAAC;AAC9H,OAAO,EAAE,uCAAuC,EAAE,MAAM,mEAAmE,CAAC;AAC5H,OAAO,EAAE,+BAA+B,EAAE,MAAM,6CAA6C,CAAC;AAG9F,OAAO,EACL,yBAAyB,EACzB,qBAAqB,GACtB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,gCAAgC,EAAE,MAAM,aAAa,CAAC;AAE/D,2EAA2E;AAC3E,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAAC,KAM/C;IACC,MAAM,EAAE,WAAW,EAAE,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,EAAE,GAAG,KAAK,CAAC;IAC7E,IAAI,CAAC,YAAY,EAAE;QAAE,OAAO;IAC5B,iEAAiE;IACjE,mEAAmE;IACnE,iEAAiE;IACjE,sEAAsE;IACtE,oEAAoE;IACpE,gCAAgC;IAChC,IACE,CAAC,CAAC,MAAM,+BAA+B,CAAC,OAAO,CAAC,CAAC;QAC/C,CAAC,MAAM,gCAAgC,CAAC,oBAAoB,CAAC,OAAO,EAAE;YACpE,cAAc;SACf,CAAC,CAAC,CAAC;QACN,YAAY,EAAE,EACd,CAAC;QACD,kEAAkE;QAClE,4DAA4D;QAC5D,MAAM,gCAAgC,CAAC,sBAAsB,CAAC,OAAO,EAAE;YACrE,cAAc;SACf,CAAC,CAAC;QACH,IAAI,YAAY,EAAE;YAAE,yBAAyB,CAAC,WAAW,CAAC,CAAC;IAC7D,CAAC;IACD,sEAAsE;IACtE,+DAA+D;IAC/D,6DAA6D;IAC7D,IAAI,YAAY,EAAE,EAAE,CAAC;QACnB,MAAM,0BAA0B,GAC9B,MAAM,uCAAuC,CAAC,OAAO,EAAE;YACrD,eAAe,EAAE,MAAM;SACxB,CAAC,CAAC;QACL,IAAI,0BAA0B,GAAG,CAAC,IAAI,YAAY,EAAE,EAAE,CAAC;YACrD,qBAAqB,CAAC,WAAW,EAAE,gCAAgC,CAAC,CAAC;QACvE,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import { sqlDocumentMoveIntentPersistence } from \"../../../data/persistence/container-contents/documentMoveIntentPersistence\";\nimport { requestDormantMetadataRestorationSweeps } from \"../../../data/persistence/container-contents/dormantMetadataSweep\";\nimport { hasRecordedTerminalSyncFailures } from \"../../../data/persistence/documents/records\";\nimport type { DomainScope } from \"../../../data/shared/domainScope\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n requestAllDomainSyncLanes,\n requestDomainSyncLane,\n} from \"../../../data/sync/syncCoordinator\";\nimport { CONTAINER_CONTENTS_SYNC_LANE_KEY } from \"../syncLane\";\n\n/** Recover parked work before optional presentation hydration can fail. */\nexport async function recoverOrganizationAccess(input: {\n readonly domainScope: DomainScope;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly stillCurrent: () => boolean;\n readonly userId: string;\n}): Promise<void> {\n const { domainScope, execSql, organizationId, stillCurrent, userId } = input;\n if (!stillCurrent()) return;\n // The evidence gate: re-arm only when some queued write actually\n // recorded a terminal failure. A transient denial during bootstrap\n // (e.g. a read-model 403 before grants propagate) also flips the\n // denied flag, and re-arming then would race the startup sync passes.\n // A failed pass (`undefined`) proves nothing about restored access,\n // so it must not re-arm either.\n if (\n ((await hasRecordedTerminalSyncFailures(execSql)) ||\n (await sqlDocumentMoveIntentPersistence.hasDeniedMoveIntents(execSql, {\n organizationId,\n }))) &&\n stillCurrent()\n ) {\n // Parked permission-denied moves (row 7) only replay once flipped\n // back to pending; restore them before re-arming the lanes.\n await sqlDocumentMoveIntentPersistence.resetDeniedMoveIntents(execSql, {\n organizationId,\n });\n if (stillCurrent()) requestAllDomainSyncLanes(domainScope);\n }\n // Keep dormant cleanup independent from the write-lane evidence gate,\n // but run it afterward so a SQLite failure cannot suppress the\n // pre-existing denied-write and move-intent recovery signal.\n if (stillCurrent()) {\n const requestedDormantSweepCount =\n await requestDormantMetadataRestorationSweeps(execSql, {\n requesterUserId: userId,\n });\n if (requestedDormantSweepCount > 0 && stillCurrent()) {\n requestDomainSyncLane(domainScope, CONTAINER_CONTENTS_SYNC_LANE_KEY);\n }\n }\n}\n"]}