@tearleads/client-sdk 0.1.196 → 0.1.198
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.
- package/data/persistence/principalCurrentAcknowledgementPersistence.d.ts +13 -5
- package/data/persistence/principalCurrentAcknowledgementPersistence.js +30 -44
- package/data/persistence/principalCurrentAcknowledgementPersistence.js.map +1 -1
- package/data/persistence/principalHistory/principalHistoryEvidencePersistence.d.ts +3 -13
- package/data/persistence/principalHistory/principalHistoryEvidencePersistence.js +2 -18
- package/data/persistence/principalHistory/principalHistoryEvidencePersistence.js.map +1 -1
- package/data/persistence/principalHistory/principalHistoryPrefixPersistence.d.ts +119 -15
- package/data/persistence/principalHistory/principalHistoryPrefixPersistence.js +69 -99
- package/data/persistence/principalHistory/principalHistoryPrefixPersistence.js.map +1 -1
- package/data/persistence/principalHistory/principalHistoryRepository.js +134 -0
- package/data/persistence/principalHistory/principalHistoryRepository.js.map +1 -0
- package/data/persistence/principalHistory/principalHistoryStagePersistence.d.ts +119 -8
- package/data/persistence/principalHistory/principalHistoryStagePersistence.js +49 -80
- package/data/persistence/principalHistory/principalHistoryStagePersistence.js.map +1 -1
- package/data/persistence/principalHistory/principalHistoryStageRetention.js +2 -2
- package/data/persistence/principalHistory/principalHistoryStageRetention.js.map +1 -1
- package/internal/loro/changeTimestamps.d.ts +26 -0
- package/internal/loro/changeTimestamps.js +29 -0
- package/internal/loro/changeTimestamps.js.map +1 -0
- package/internal/loro/document.js +2 -0
- package/internal/loro/document.js.map +1 -1
- package/internal/loro/index.d.ts +1 -0
- package/internal/loro/index.js +1 -0
- package/internal/loro/index.js.map +1 -1
- package/package.json +1 -1
- package/workflows/principals/acknowledgements/acknowledgedPrincipalCurrents.js +3 -3
- package/workflows/principals/acknowledgements/acknowledgedPrincipalCurrents.js.map +1 -1
- package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.d.ts +1 -1
- package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.js +2 -2
- package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.js.map +1 -1
- package/workflows/principals/acknowledgements/reconcileAcknowledgedPrincipalCurrent.js +2 -2
- package/workflows/principals/acknowledgements/reconcileAcknowledgedPrincipalCurrent.js.map +1 -1
- package/workflows/principals/historyRecovery/loadRecoveredPrincipalHistoryPage.js +7 -6
- package/workflows/principals/historyRecovery/loadRecoveredPrincipalHistoryPage.js.map +1 -1
- package/workflows/principals/historyRecovery/principalHistoryRecoveryPrefix.js +4 -6
- package/workflows/principals/historyRecovery/principalHistoryRecoveryPrefix.js.map +1 -1
- package/workflows/principals/historyRecovery/principalHistoryRecoveryReferences.js +2 -3
- package/workflows/principals/historyRecovery/principalHistoryRecoveryReferences.js.map +1 -1
- package/workflows/principals/historyRecovery/principalHistoryRecoveryStage.js +3 -3
- package/workflows/principals/historyRecovery/principalHistoryRecoveryStage.js.map +1 -1
- package/workflows/principals/historyRecovery/recoverPrincipalPolicyHistory.js +4 -5
- package/workflows/principals/historyRecovery/recoverPrincipalPolicyHistory.js.map +1 -1
- package/workflows/principals/publicHistory/publicPrincipalHistoryPage.js +2 -3
- package/workflows/principals/publicHistory/publicPrincipalHistoryPage.js.map +1 -1
- package/workflows/principals/publicHistory/publicPrincipalHistoryProgress.js +9 -14
- package/workflows/principals/publicHistory/publicPrincipalHistoryProgress.js.map +1 -1
- package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js +2 -3
- package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js.map +1 -1
- package/workflows/principals/publicHistory/selectPublicPrincipalHistory.js +3 -5
- package/workflows/principals/publicHistory/selectPublicPrincipalHistory.js.map +1 -1
- package/workflows/principals/recoveryOperation/principalRecoveryDirectory.js +2 -3
- package/workflows/principals/recoveryOperation/principalRecoveryDirectory.js.map +1 -1
|
@@ -1,15 +1,11 @@
|
|
|
1
1
|
import { and, eq } from "drizzle-orm";
|
|
2
|
-
import {
|
|
3
|
-
import { principalHistoryEvidenceTables } from "../../sqlite/schema/principalHistoryEvidenceSchema.js";
|
|
4
|
-
import { principalHistoryStages, principalHistoryStageTables, } from "../../sqlite/schema/principalHistoryStageSchema.js";
|
|
5
|
-
import { getClientSQLitePersistenceRuntime } from "../../sqlite/sqlitePersistenceRuntime.js";
|
|
6
|
-
import { ensureSqlTables } from "../../sqlite/sqlSchema.js";
|
|
2
|
+
import { principalHistoryStages } from "../../sqlite/schema/principalHistoryStageSchema.js";
|
|
7
3
|
import { writePrincipalHistoryEvidencePage, } from "./principalHistoryEvidencePersistence.js";
|
|
8
4
|
import { reclaimIncompletePrincipalHistoryStages } from "./principalHistoryIncompleteRetention.js";
|
|
9
5
|
import { reclaimPrincipalHistoryNodes } from "./principalHistoryNodeRetention.js";
|
|
10
6
|
import { foldablePrincipalHistoryRootEdges, principalHistoryRootRetention, principalHistoryStageRootOwnerColumns, releasePrincipalHistoryRoot, writePrincipalHistoryRootEdges, } from "./principalHistoryRootOwnership.js";
|
|
11
7
|
import { reclaimUnpublishedPrincipalHistoryStages } from "./principalHistoryUnpublishedRetention.js";
|
|
12
|
-
const principalHistoryStageColumns = {
|
|
8
|
+
export const principalHistoryStageColumns = {
|
|
13
9
|
id: principalHistoryStages.id,
|
|
14
10
|
organizationId: principalHistoryStages.organizationId,
|
|
15
11
|
currentJson: principalHistoryStages.currentJson,
|
|
@@ -28,82 +24,55 @@ class PrincipalHistoryStageChangedError extends Error {
|
|
|
28
24
|
export function isPrincipalHistoryStageChangedError(error) {
|
|
29
25
|
return error instanceof PrincipalHistoryStageChangedError;
|
|
30
26
|
}
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
const {
|
|
34
|
-
const [
|
|
35
|
-
.select(
|
|
27
|
+
/** Publish accepted entries and index nodes atomically with authenticated progress. */
|
|
28
|
+
export async function savePrincipalHistoryStageInTransaction(tx, input, touchedAt) {
|
|
29
|
+
const { stage, evidence } = input;
|
|
30
|
+
const [previous] = await tx
|
|
31
|
+
.select({
|
|
32
|
+
progress: principalHistoryStages.progress,
|
|
33
|
+
...principalHistoryStageRootOwnerColumns,
|
|
34
|
+
})
|
|
36
35
|
.from(principalHistoryStages)
|
|
37
|
-
.where(eq(principalHistoryStages.id, id))
|
|
36
|
+
.where(eq(principalHistoryStages.id, stage.id))
|
|
38
37
|
.limit(1);
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
const
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
const
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
})
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
// The node write replays the root's edges after the page's own, as
|
|
62
|
-
// separate statements after it would.
|
|
63
|
-
const root = {
|
|
64
|
-
scopeId: evidence.scopeId,
|
|
65
|
-
organizationId: stage.organizationId,
|
|
66
|
-
rootHash: evidence.indexRootHash,
|
|
67
|
-
};
|
|
68
|
-
const retention = principalHistoryRootRetention(previous, root);
|
|
69
|
-
const rootEdges = foldablePrincipalHistoryRootEdges(retention, evidence);
|
|
70
|
-
await writePrincipalHistoryEvidencePage(tx, evidence, rootEdges);
|
|
71
|
-
const row = { ...stage, ...root, touchedAt: Date.now() };
|
|
72
|
-
await tx
|
|
73
|
-
.insert(principalHistoryStages)
|
|
74
|
-
.values(row)
|
|
75
|
-
.onConflictDoUpdate({ target: principalHistoryStages.id, set: row })
|
|
76
|
-
.run();
|
|
77
|
-
await writePrincipalHistoryRootEdges(tx, retention, rootEdges);
|
|
78
|
-
await reclaimIncompletePrincipalHistoryStages(tx, stage);
|
|
79
|
-
await reclaimUnpublishedPrincipalHistoryStages(tx, stage);
|
|
80
|
-
await reclaimPrincipalHistoryNodes(tx, evidence);
|
|
81
|
-
}, input.stillCurrent, { behavior: "immediate" });
|
|
82
|
-
assertProjectionVerificationCurrent(() => saved.committed);
|
|
38
|
+
if ((previous?.progress ?? null) !== input.previousProgress)
|
|
39
|
+
throw new PrincipalHistoryStageChangedError();
|
|
40
|
+
// The node write replays the root's edges after the page's own, as
|
|
41
|
+
// separate statements after it would.
|
|
42
|
+
const root = {
|
|
43
|
+
scopeId: evidence.scopeId,
|
|
44
|
+
organizationId: stage.organizationId,
|
|
45
|
+
rootHash: evidence.indexRootHash,
|
|
46
|
+
};
|
|
47
|
+
const retention = principalHistoryRootRetention(previous, root);
|
|
48
|
+
const rootEdges = foldablePrincipalHistoryRootEdges(retention, evidence);
|
|
49
|
+
await writePrincipalHistoryEvidencePage(tx, evidence, rootEdges);
|
|
50
|
+
const row = { ...stage, ...root, touchedAt };
|
|
51
|
+
await tx
|
|
52
|
+
.insert(principalHistoryStages)
|
|
53
|
+
.values(row)
|
|
54
|
+
.onConflictDoUpdate({ target: principalHistoryStages.id, set: row })
|
|
55
|
+
.run();
|
|
56
|
+
await writePrincipalHistoryRootEdges(tx, retention, rootEdges);
|
|
57
|
+
await reclaimIncompletePrincipalHistoryStages(tx, stage);
|
|
58
|
+
await reclaimUnpublishedPrincipalHistoryStages(tx, stage);
|
|
59
|
+
await reclaimPrincipalHistoryNodes(tx, evidence);
|
|
83
60
|
}
|
|
84
|
-
export async function
|
|
85
|
-
await
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
return;
|
|
101
|
-
await releasePrincipalHistoryRoot(db, current);
|
|
102
|
-
await db
|
|
103
|
-
.delete(principalHistoryStages)
|
|
104
|
-
.where(and(eq(principalHistoryStages.id, stage.id), eq(principalHistoryStages.progress, stage.progress)))
|
|
105
|
-
.run();
|
|
106
|
-
}, stillCurrent, { behavior: "immediate" });
|
|
107
|
-
assertProjectionVerificationCurrent(() => discarded.committed);
|
|
61
|
+
export async function discardPrincipalHistoryStageInTransaction(tx, stage) {
|
|
62
|
+
const [current] = await tx
|
|
63
|
+
.select({
|
|
64
|
+
progress: principalHistoryStages.progress,
|
|
65
|
+
...principalHistoryStageRootOwnerColumns,
|
|
66
|
+
})
|
|
67
|
+
.from(principalHistoryStages)
|
|
68
|
+
.where(eq(principalHistoryStages.id, stage.id))
|
|
69
|
+
.limit(1);
|
|
70
|
+
if (!current || current.progress !== stage.progress)
|
|
71
|
+
return;
|
|
72
|
+
await releasePrincipalHistoryRoot(tx, current);
|
|
73
|
+
await tx
|
|
74
|
+
.delete(principalHistoryStages)
|
|
75
|
+
.where(and(eq(principalHistoryStages.id, stage.id), eq(principalHistoryStages.progress, stage.progress)))
|
|
76
|
+
.run();
|
|
108
77
|
}
|
|
109
78
|
//# sourceMappingURL=principalHistoryStagePersistence.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalHistoryStagePersistence.js","sourceRoot":"","sources":["principalHistoryStagePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,mCAAmC,EAAE,MAAM,0CAA0C,CAAC;AAC/F,OAAO,EAAE,8BAA8B,EAAE,MAAM,oDAAoD,CAAC;AACpG,OAAO,EACL,sBAAsB,EACtB,2BAA2B,GAC5B,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAAE,iCAAiC,EAAE,MAAM,uCAAuC,CAAC;AAC1F,OAAO,EAAgB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACvE,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,uCAAuC,EAAE,MAAM,uCAAuC,CAAC;AAChG,OAAO,EAAE,4BAA4B,EAAE,MAAM,iCAAiC,CAAC;AAC/E,OAAO,EACL,iCAAiC,EACjC,6BAA6B,EAC7B,qCAAqC,EACrC,2BAA2B,EAC3B,8BAA8B,GAC/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,KAAK,CAAC,CAAC,CAAC,CAAC;QACZ,IAAI,CAAC,OAAO,IAAI,OAAO,CAAC,QAAQ,KAAK,KAAK,CAAC,QAAQ;YAAE,OAAO;QAC5D,MAAM,2BAA2B,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QAC/C,MAAM,EAAE;aACL,MAAM,CAAC,sBAAsB,CAAC;aAC9B,KAAK,CACJ,GAAG,CACD,EAAE,CAAC,sBAAsB,CAAC,EAAE,EAAE,KAAK,CAAC,EAAE,CAAC,EACvC,EAAE,CAAC,sBAAsB,CAAC,QAAQ,EAAE,KAAK,CAAC,QAAQ,CAAC,CACpD,CACF;aACA,GAAG,EAAE,CAAC;IACX,CAAC,EACD,YAAY,EACZ,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;IACF,mCAAmC,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC;AACjE,CAAC","sourcesContent":["import { and, eq } from \"drizzle-orm\";\nimport { assertProjectionVerificationCurrent } from \"../../keyingProjectionVerification/types\";\nimport { principalHistoryEvidenceTables } from \"../../sqlite/schema/principalHistoryEvidenceSchema\";\nimport {\n principalHistoryStages,\n principalHistoryStageTables,\n} from \"../../sqlite/schema/principalHistoryStageSchema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport {\n type PrincipalHistoryEvidencePage,\n writePrincipalHistoryEvidencePage,\n} from \"./principalHistoryEvidencePersistence\";\nimport { reclaimIncompletePrincipalHistoryStages } from \"./principalHistoryIncompleteRetention\";\nimport { reclaimPrincipalHistoryNodes } from \"./principalHistoryNodeRetention\";\nimport {\n foldablePrincipalHistoryRootEdges,\n principalHistoryRootRetention,\n principalHistoryStageRootOwnerColumns,\n releasePrincipalHistoryRoot,\n writePrincipalHistoryRootEdges,\n} from \"./principalHistoryRootOwnership\";\nimport { reclaimUnpublishedPrincipalHistoryStages } from \"./principalHistoryUnpublishedRetention\";\n\n/** A stage's verification work; its retention hints are written by persistence. */\nexport type PrincipalHistoryStage = Omit<\n typeof principalHistoryStages.$inferSelect,\n \"scopeId\" | \"touchedAt\" | \"rootHash\" | \"identityBundleFormat\"\n>;\n\nconst principalHistoryStageColumns = {\n id: principalHistoryStages.id,\n organizationId: principalHistoryStages.organizationId,\n currentJson: principalHistoryStages.currentJson,\n afterVersion: principalHistoryStages.afterVersion,\n complete: principalHistoryStages.complete,\n progress: principalHistoryStages.progress,\n};\n\nclass PrincipalHistoryStageChangedError extends Error {\n readonly code = \"principal_history_stage_changed\";\n constructor() {\n super(\n \"Another operation changed the saved principal history; resume from its current state\",\n );\n this.name = \"PrincipalHistoryStageChangedError\";\n }\n}\n\n/** Another writer replaced this stage's progress between load and save. */\nexport function isPrincipalHistoryStageChangedError(error: unknown): boolean {\n return error instanceof PrincipalHistoryStageChangedError;\n}\n\nexport async function loadPrincipalHistoryStage(\n execSql: ExecSql,\n id: string,\n): Promise<PrincipalHistoryStage | null> {\n await ensureSqlTables(execSql, principalHistoryStageTables);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const [row] = await db\n .select(principalHistoryStageColumns)\n .from(principalHistoryStages)\n .where(eq(principalHistoryStages.id, id))\n .limit(1);\n return row ?? null;\n}\n\n/** Publish accepted entries and index nodes atomically with authenticated progress. */\nexport async function savePrincipalHistoryStage(input: {\n readonly execSql: ExecSql;\n readonly stage: PrincipalHistoryStage;\n readonly evidence: PrincipalHistoryEvidencePage;\n readonly previousProgress: string | null;\n readonly stillCurrent: () => boolean;\n}): Promise<void> {\n const evidence = structuredClone(input.evidence);\n const stage = { ...input.stage, scopeId: evidence.scopeId };\n await ensureSqlTables(input.execSql, [\n ...principalHistoryStageTables,\n ...principalHistoryEvidenceTables,\n ]);\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const saved = await runtime.guardedTransaction(\n async (tx) => {\n const [previous] = await tx\n .select({\n progress: principalHistoryStages.progress,\n ...principalHistoryStageRootOwnerColumns,\n })\n .from(principalHistoryStages)\n .where(eq(principalHistoryStages.id, stage.id))\n .limit(1);\n if ((previous?.progress ?? null) !== input.previousProgress)\n throw new PrincipalHistoryStageChangedError();\n // The node write replays the root's edges after the page's own, as\n // separate statements after it would.\n const root = {\n scopeId: evidence.scopeId,\n organizationId: stage.organizationId,\n rootHash: evidence.indexRootHash,\n };\n const retention = principalHistoryRootRetention(previous, root);\n const rootEdges = foldablePrincipalHistoryRootEdges(retention, evidence);\n await writePrincipalHistoryEvidencePage(tx, evidence, rootEdges);\n const row = { ...stage, ...root, touchedAt: Date.now() };\n await tx\n .insert(principalHistoryStages)\n .values(row)\n .onConflictDoUpdate({ target: principalHistoryStages.id, set: row })\n .run();\n await writePrincipalHistoryRootEdges(tx, retention, rootEdges);\n await reclaimIncompletePrincipalHistoryStages(tx, stage);\n await reclaimUnpublishedPrincipalHistoryStages(tx, stage);\n await reclaimPrincipalHistoryNodes(tx, evidence);\n },\n input.stillCurrent,\n { behavior: \"immediate\" },\n );\n assertProjectionVerificationCurrent(() => saved.committed);\n}\n\nexport async function discardPrincipalHistoryStage(\n execSql: ExecSql,\n stage: PrincipalHistoryStage,\n stillCurrent: () => boolean,\n) {\n await ensureSqlTables(execSql, [\n ...principalHistoryStageTables,\n ...principalHistoryEvidenceTables,\n ]);\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const discarded = await runtime.guardedTransaction(\n async (db) => {\n const [current] = await db\n .select({\n progress: principalHistoryStages.progress,\n ...principalHistoryStageRootOwnerColumns,\n })\n .from(principalHistoryStages)\n .where(eq(principalHistoryStages.id, stage.id))\n .limit(1);\n if (!current || current.progress !== stage.progress) return;\n await releasePrincipalHistoryRoot(db, current);\n await db\n .delete(principalHistoryStages)\n .where(\n and(\n eq(principalHistoryStages.id, stage.id),\n eq(principalHistoryStages.progress, stage.progress),\n ),\n )\n .run();\n },\n stillCurrent,\n { behavior: \"immediate\" },\n );\n assertProjectionVerificationCurrent(() => discarded.committed);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"principalHistoryStagePersistence.js","sourceRoot":"","sources":["principalHistoryStagePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,sBAAsB,EAAE,MAAM,iDAAiD,CAAC;AAEzF,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,uCAAuC,EAAE,MAAM,uCAAuC,CAAC;AAChG,OAAO,EAAE,4BAA4B,EAAE,MAAM,iCAAiC,CAAC;AAC/E,OAAO,EACL,iCAAiC,EACjC,6BAA6B,EAC7B,qCAAqC,EACrC,2BAA2B,EAC3B,8BAA8B,GAC/B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,wCAAwC,EAAE,MAAM,wCAAwC,CAAC;AAQlG,MAAM,CAAC,MAAM,4BAA4B,GAAG;IAC1C,EAAE,EAAE,sBAAsB,CAAC,EAAE;IAC7B,cAAc,EAAE,sBAAsB,CAAC,cAAc;IACrD,WAAW,EAAE,sBAAsB,CAAC,WAAW;IAC/C,YAAY,EAAE,sBAAsB,CAAC,YAAY;IACjD,QAAQ,EAAE,sBAAsB,CAAC,QAAQ;IACzC,QAAQ,EAAE,sBAAsB,CAAC,QAAQ;CAC1C,CAAC;AAEF,MAAM,iCAAkC,SAAQ,KAAK;IAC1C,IAAI,GAAG,iCAAiC,CAAC;IAClD;QACE,KAAK,CACH,sFAAsF,CACvF,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,mCAAmC,CAAC;IAClD,CAAC;CACF;AAED,2EAA2E;AAC3E,MAAM,UAAU,mCAAmC,CAAC,KAAc;IAChE,OAAO,KAAK,YAAY,iCAAiC,CAAC;AAC5D,CAAC;AAED,uFAAuF;AACvF,MAAM,CAAC,KAAK,UAAU,sCAAsC,CAC1D,EAAgC,EAChC,KAIC,EACD,SAAiB;IAEjB,MAAM,EAA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EAAE,KAAK,CAAC,CAAC;IACzD,MAAM,wCAAwC,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;IAC1D,MAAM,4BAA4B,CAAC,EAAE,EAAE,QAAQ,CAAC,CAAC;AACnD,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,yCAAyC,CAC7D,EAAgC,EAChC,KAA4B;IAE5B,MAAM,CAAC,OAAO,CAAC,GAAG,MAAM,EAAE;SACvB,MAAM,CAAC;QACN,QAAQ,EAAE,sBAAsB,CAAC,QAAQ;QACzC,GAAG,qCAAqC;KACzC,CAAC;SACD,IAAI,CAAC,sBAAsB,CAAC;SAC5B,KAAK,CAAC,EAAE,CAAC,sBAAsB,CAAC,EAAE,EAAE,KAAK,CAAC,EAAE,CAAC,CAAC;SAC9C,KAAK,CAAC,CAAC,CAAC,CAAC;IACZ,IAAI,CAAC,OAAO,IAAI,OAAO,CAAC,QAAQ,KAAK,KAAK,CAAC,QAAQ;QAAE,OAAO;IAC5D,MAAM,2BAA2B,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;IAC/C,MAAM,EAAE;SACL,MAAM,CAAC,sBAAsB,CAAC;SAC9B,KAAK,CACJ,GAAG,CACD,EAAE,CAAC,sBAAsB,CAAC,EAAE,EAAE,KAAK,CAAC,EAAE,CAAC,EACvC,EAAE,CAAC,sBAAsB,CAAC,QAAQ,EAAE,KAAK,CAAC,QAAQ,CAAC,CACpD,CACF;SACA,GAAG,EAAE,CAAC;AACX,CAAC","sourcesContent":["import { and, eq } from \"drizzle-orm\";\nimport { principalHistoryStages } from \"../../sqlite/schema/principalHistoryStageSchema\";\nimport type { ClientSQLiteTransactionScope } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport {\n type PrincipalHistoryEvidencePage,\n writePrincipalHistoryEvidencePage,\n} from \"./principalHistoryEvidencePersistence\";\nimport { reclaimIncompletePrincipalHistoryStages } from \"./principalHistoryIncompleteRetention\";\nimport { reclaimPrincipalHistoryNodes } from \"./principalHistoryNodeRetention\";\nimport {\n foldablePrincipalHistoryRootEdges,\n principalHistoryRootRetention,\n principalHistoryStageRootOwnerColumns,\n releasePrincipalHistoryRoot,\n writePrincipalHistoryRootEdges,\n} from \"./principalHistoryRootOwnership\";\nimport { reclaimUnpublishedPrincipalHistoryStages } from \"./principalHistoryUnpublishedRetention\";\n\n/** A stage's verification work; its retention hints are written by persistence. */\nexport type PrincipalHistoryStage = Omit<\n typeof principalHistoryStages.$inferSelect,\n \"scopeId\" | \"touchedAt\" | \"rootHash\" | \"identityBundleFormat\"\n>;\n\nexport const principalHistoryStageColumns = {\n id: principalHistoryStages.id,\n organizationId: principalHistoryStages.organizationId,\n currentJson: principalHistoryStages.currentJson,\n afterVersion: principalHistoryStages.afterVersion,\n complete: principalHistoryStages.complete,\n progress: principalHistoryStages.progress,\n};\n\nclass PrincipalHistoryStageChangedError extends Error {\n readonly code = \"principal_history_stage_changed\";\n constructor() {\n super(\n \"Another operation changed the saved principal history; resume from its current state\",\n );\n this.name = \"PrincipalHistoryStageChangedError\";\n }\n}\n\n/** Another writer replaced this stage's progress between load and save. */\nexport function isPrincipalHistoryStageChangedError(error: unknown): boolean {\n return error instanceof PrincipalHistoryStageChangedError;\n}\n\n/** Publish accepted entries and index nodes atomically with authenticated progress. */\nexport async function savePrincipalHistoryStageInTransaction(\n tx: ClientSQLiteTransactionScope,\n input: {\n readonly stage: PrincipalHistoryStage & { readonly scopeId: string };\n readonly evidence: PrincipalHistoryEvidencePage;\n readonly previousProgress: string | null;\n },\n touchedAt: number,\n): Promise<void> {\n const { stage, evidence } = input;\n const [previous] = await tx\n .select({\n progress: principalHistoryStages.progress,\n ...principalHistoryStageRootOwnerColumns,\n })\n .from(principalHistoryStages)\n .where(eq(principalHistoryStages.id, stage.id))\n .limit(1);\n if ((previous?.progress ?? null) !== input.previousProgress)\n throw new PrincipalHistoryStageChangedError();\n // The node write replays the root's edges after the page's own, as\n // separate statements after it would.\n const root = {\n scopeId: evidence.scopeId,\n organizationId: stage.organizationId,\n rootHash: evidence.indexRootHash,\n };\n const retention = principalHistoryRootRetention(previous, root);\n const rootEdges = foldablePrincipalHistoryRootEdges(retention, evidence);\n await writePrincipalHistoryEvidencePage(tx, evidence, rootEdges);\n const row = { ...stage, ...root, touchedAt };\n await tx\n .insert(principalHistoryStages)\n .values(row)\n .onConflictDoUpdate({ target: principalHistoryStages.id, set: row })\n .run();\n await writePrincipalHistoryRootEdges(tx, retention, rootEdges);\n await reclaimIncompletePrincipalHistoryStages(tx, stage);\n await reclaimUnpublishedPrincipalHistoryStages(tx, stage);\n await reclaimPrincipalHistoryNodes(tx, evidence);\n}\n\nexport async function discardPrincipalHistoryStageInTransaction(\n tx: ClientSQLiteTransactionScope,\n stage: PrincipalHistoryStage,\n): Promise<void> {\n const [current] = await tx\n .select({\n progress: principalHistoryStages.progress,\n ...principalHistoryStageRootOwnerColumns,\n })\n .from(principalHistoryStages)\n .where(eq(principalHistoryStages.id, stage.id))\n .limit(1);\n if (!current || current.progress !== stage.progress) return;\n await releasePrincipalHistoryRoot(tx, current);\n await tx\n .delete(principalHistoryStages)\n .where(\n and(\n eq(principalHistoryStages.id, stage.id),\n eq(principalHistoryStages.progress, stage.progress),\n ),\n )\n .run();\n}\n"]}
|
|
@@ -5,10 +5,10 @@ import { principalHistoryStageRootOwnerColumns, releasePrincipalHistoryRoots, }
|
|
|
5
5
|
/** Each publication reclaims at most this many obsolete completed heads. */
|
|
6
6
|
export const PRINCIPAL_HISTORY_STAGE_RECLAIM_LIMIT = 16;
|
|
7
7
|
/** Mark a stored stage as just used by a writer for its principal history. */
|
|
8
|
-
export async function touchPrincipalHistoryStage(tx, input) {
|
|
8
|
+
export async function touchPrincipalHistoryStage(tx, input, touchedAt) {
|
|
9
9
|
await tx
|
|
10
10
|
.update(principalHistoryStages)
|
|
11
|
-
.set({ scopeId: input.scopeId, touchedAt
|
|
11
|
+
.set({ scopeId: input.scopeId, touchedAt })
|
|
12
12
|
.where(eq(principalHistoryStages.id, input.id))
|
|
13
13
|
.run();
|
|
14
14
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalHistoryStageRetention.js","sourceRoot":"","sources":["principalHistoryStageRetention.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AAC9D,OAAO,EAAE,sBAAsB,EAAE,MAAM,iDAAiD,CAAC;AAEzF,OAAO,EAAE,uCAAuC,EAAE,MAAM,yDAAyD,CAAC;AAClH,OAAO,EACL,qCAAqC,EACrC,4BAA4B,GAC7B,MAAM,iCAAiC,CAAC;AAEzC,4EAA4E;AAC5E,MAAM,CAAC,MAAM,qCAAqC,GAAG,EAAE,CAAC;AAExD,8EAA8E;AAC9E,MAAM,CAAC,KAAK,UAAU,0BAA0B,CAC9C,EAAgC,EAChC,KAAwD;
|
|
1
|
+
{"version":3,"file":"principalHistoryStageRetention.js","sourceRoot":"","sources":["principalHistoryStageRetention.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AAC9D,OAAO,EAAE,sBAAsB,EAAE,MAAM,iDAAiD,CAAC;AAEzF,OAAO,EAAE,uCAAuC,EAAE,MAAM,yDAAyD,CAAC;AAClH,OAAO,EACL,qCAAqC,EACrC,4BAA4B,GAC7B,MAAM,iCAAiC,CAAC;AAEzC,4EAA4E;AAC5E,MAAM,CAAC,MAAM,qCAAqC,GAAG,EAAE,CAAC;AAExD,8EAA8E;AAC9E,MAAM,CAAC,KAAK,UAAU,0BAA0B,CAC9C,EAAgC,EAChC,KAAwD,EACxD,SAAiB;IAEjB,MAAM,EAAE;SACL,MAAM,CAAC,sBAAsB,CAAC;SAC9B,GAAG,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,SAAS,EAAE,CAA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C,QAAQ,CAAC,CAC5C,CAAC;IACF,MAAM,uCAAuC,CAC3C,EAAE,EACF,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC;QAC3B,GAAG,KAAK;QACR,OAAO,EAAE,KAAK,CAAC,YAAY,GAAG,CAAC;KAChC,CAAC,CAAC,CACJ,CAAC;IACF,MAAM,EAAE;SACL,MAAM,CAAC,sBAAsB,CAAC;SAC9B,KAAK,CACJ,OAAO,CACL,sBAAsB,CAAC,EAAE,EACzB,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,CACtC,CACF;SACA,GAAG,EAAE,CAAC;AACX,CAAC","sourcesContent":["import { and, asc, desc, eq, inArray, lt } from \"drizzle-orm\";\nimport { principalHistoryStages } from \"../../sqlite/schema/principalHistoryStageSchema\";\nimport type { ClientSQLiteTransactionScope } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { archivePrincipalHistoryKeyEnvelopeBatch } from \"../principalKeys/principalKeyEnvelopeArchivePersistence\";\nimport {\n principalHistoryStageRootOwnerColumns,\n releasePrincipalHistoryRoots,\n} from \"./principalHistoryRootOwnership\";\n\n/** Each publication reclaims at most this many obsolete completed heads. */\nexport const PRINCIPAL_HISTORY_STAGE_RECLAIM_LIMIT = 16;\n\n/** Mark a stored stage as just used by a writer for its principal history. */\nexport async function touchPrincipalHistoryStage(\n tx: ClientSQLiteTransactionScope,\n input: { readonly id: string; readonly scopeId: string },\n touchedAt: number,\n) {\n await tx\n .update(principalHistoryStages)\n .set({ scopeId: input.scopeId, touchedAt })\n .where(eq(principalHistoryStages.id, input.id))\n .run();\n}\n\n/** The prefix and its key candidates must be published in this transaction. */\nexport async function reclaimCompletedPrincipalHistoryStages(\n tx: ClientSQLiteTransactionScope,\n prefix: {\n readonly scopeId: string;\n readonly organizationId: string;\n readonly version: number;\n },\n) {\n const obsolete = await tx\n .select({\n stage: {\n id: principalHistoryStages.id,\n organizationId: principalHistoryStages.organizationId,\n currentJson: principalHistoryStages.currentJson,\n afterVersion: principalHistoryStages.afterVersion,\n },\n owner: principalHistoryStageRootOwnerColumns,\n })\n .from(principalHistoryStages)\n .where(\n and(\n eq(principalHistoryStages.scopeId, prefix.scopeId),\n eq(principalHistoryStages.organizationId, prefix.organizationId),\n eq(principalHistoryStages.complete, true),\n lt(principalHistoryStages.afterVersion, prefix.version),\n ),\n )\n .orderBy(\n desc(principalHistoryStages.afterVersion),\n desc(principalHistoryStages.touchedAt),\n asc(principalHistoryStages.id),\n )\n // Keep the current completed head and its newest completed predecessor.\n // This also preserves the prefix-only predecessor restored after an ack.\n .offset(2)\n .limit(PRINCIPAL_HISTORY_STAGE_RECLAIM_LIMIT);\n if (obsolete.length === 0) return;\n await releasePrincipalHistoryRoots(\n tx,\n prefix,\n obsolete.map(({ owner }) => owner.rootHash),\n );\n await archivePrincipalHistoryKeyEnvelopeBatch(\n tx,\n obsolete.map(({ stage }) => ({\n ...stage,\n version: stage.afterVersion + 1,\n })),\n );\n await tx\n .delete(principalHistoryStages)\n .where(\n inArray(\n principalHistoryStages.id,\n obsolete.map(({ stage }) => stage.id),\n ),\n )\n .run();\n}\n"]}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { LoroDoc } from "loro-crdt";
|
|
2
|
+
/**
|
|
3
|
+
* The longest span, in seconds, that one change may cover after its own
|
|
4
|
+
* timestamp. Loro folds a peer's consecutive commits into one change while
|
|
5
|
+
* they fall inside this window, and a change carries exactly one timestamp,
|
|
6
|
+
* so this is the time resolution of a document's history: an operation was
|
|
7
|
+
* committed no later than this many seconds after its change's timestamp.
|
|
8
|
+
*
|
|
9
|
+
* A wider window stores fewer changes and coarser times. One second costs at
|
|
10
|
+
* most one change per second of activity, which measured as roughly a fifth
|
|
11
|
+
* more snapshot bytes for the slowest possible typist (one character every
|
|
12
|
+
* one to three seconds) and far less for ordinary bursts.
|
|
13
|
+
*/
|
|
14
|
+
export declare const DOCUMENT_CHANGE_MERGE_INTERVAL_SECONDS = 1;
|
|
15
|
+
/**
|
|
16
|
+
* Make every change this document authors carry the Unix time of its commit,
|
|
17
|
+
* rounded to the nearest second. History is the only durable record of when
|
|
18
|
+
* an edit happened: uploads coalesce local writes, and local tail rows fold
|
|
19
|
+
* into checkpoints.
|
|
20
|
+
*
|
|
21
|
+
* The setting belongs to the document instance, not to its exported bytes, so
|
|
22
|
+
* it must be applied to every document that can author. A document without it
|
|
23
|
+
* stamps the largest timestamp it has imported instead of the current time,
|
|
24
|
+
* which silently back-dates its edits. `fork()` copies the setting.
|
|
25
|
+
*/
|
|
26
|
+
export declare function recordChangeTimestamps(doc: LoroDoc): void;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The longest span, in seconds, that one change may cover after its own
|
|
3
|
+
* timestamp. Loro folds a peer's consecutive commits into one change while
|
|
4
|
+
* they fall inside this window, and a change carries exactly one timestamp,
|
|
5
|
+
* so this is the time resolution of a document's history: an operation was
|
|
6
|
+
* committed no later than this many seconds after its change's timestamp.
|
|
7
|
+
*
|
|
8
|
+
* A wider window stores fewer changes and coarser times. One second costs at
|
|
9
|
+
* most one change per second of activity, which measured as roughly a fifth
|
|
10
|
+
* more snapshot bytes for the slowest possible typist (one character every
|
|
11
|
+
* one to three seconds) and far less for ordinary bursts.
|
|
12
|
+
*/
|
|
13
|
+
export const DOCUMENT_CHANGE_MERGE_INTERVAL_SECONDS = 1;
|
|
14
|
+
/**
|
|
15
|
+
* Make every change this document authors carry the Unix time of its commit,
|
|
16
|
+
* rounded to the nearest second. History is the only durable record of when
|
|
17
|
+
* an edit happened: uploads coalesce local writes, and local tail rows fold
|
|
18
|
+
* into checkpoints.
|
|
19
|
+
*
|
|
20
|
+
* The setting belongs to the document instance, not to its exported bytes, so
|
|
21
|
+
* it must be applied to every document that can author. A document without it
|
|
22
|
+
* stamps the largest timestamp it has imported instead of the current time,
|
|
23
|
+
* which silently back-dates its edits. `fork()` copies the setting.
|
|
24
|
+
*/
|
|
25
|
+
export function recordChangeTimestamps(doc) {
|
|
26
|
+
doc.setRecordTimestamp(true);
|
|
27
|
+
doc.setChangeMergeInterval(DOCUMENT_CHANGE_MERGE_INTERVAL_SECONDS);
|
|
28
|
+
}
|
|
29
|
+
//# sourceMappingURL=changeTimestamps.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"changeTimestamps.js","sourceRoot":"","sources":["changeTimestamps.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,sCAAsC,GAAG,CAAC,CAAC;AAExD;;;;;;;;;;GAUG;AACH,MAAM,UAAU,sBAAsB,CAAC,GAAY;IACjD,GAAG,CAAC,kBAAkB,CAAC,IAAI,CAAC,CAAC;IAC7B,GAAG,CAAC,sBAAsB,CAAC,sCAAsC,CAAC,CAAC;AACrE,CAAC","sourcesContent":["import type { LoroDoc } from \"loro-crdt\";\n\n/**\n * The longest span, in seconds, that one change may cover after its own\n * timestamp. Loro folds a peer's consecutive commits into one change while\n * they fall inside this window, and a change carries exactly one timestamp,\n * so this is the time resolution of a document's history: an operation was\n * committed no later than this many seconds after its change's timestamp.\n *\n * A wider window stores fewer changes and coarser times. One second costs at\n * most one change per second of activity, which measured as roughly a fifth\n * more snapshot bytes for the slowest possible typist (one character every\n * one to three seconds) and far less for ordinary bursts.\n */\nexport const DOCUMENT_CHANGE_MERGE_INTERVAL_SECONDS = 1;\n\n/**\n * Make every change this document authors carry the Unix time of its commit,\n * rounded to the nearest second. History is the only durable record of when\n * an edit happened: uploads coalesce local writes, and local tail rows fold\n * into checkpoints.\n *\n * The setting belongs to the document instance, not to its exported bytes, so\n * it must be applied to every document that can author. A document without it\n * stamps the largest timestamp it has imported instead of the current time,\n * which silently back-dates its edits. `fork()` copies the setting.\n */\nexport function recordChangeTimestamps(doc: LoroDoc): void {\n doc.setRecordTimestamp(true);\n doc.setChangeMergeInterval(DOCUMENT_CHANGE_MERGE_INTERVAL_SECONDS);\n}\n"]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { base64ToBytes, bytesToBase64 } from "../encoding/index.js";
|
|
2
2
|
import { LoroDoc, VersionVector } from "loro-crdt";
|
|
3
|
+
import { recordChangeTimestamps } from "./changeTimestamps.js";
|
|
3
4
|
import { serializeCanonicalHistory } from "./historyCanonicalization.js";
|
|
4
5
|
import { getImportBlobMetadata } from "./importMetadata.js";
|
|
5
6
|
export { getImportBlobMetadata } from "./importMetadata.js";
|
|
@@ -47,6 +48,7 @@ export async function derivePeerId(seed) {
|
|
|
47
48
|
export async function createDocument(peerSeed) {
|
|
48
49
|
const doc = new LoroDoc();
|
|
49
50
|
doc.setPeerId(await derivePeerId(peerSeed));
|
|
51
|
+
recordChangeTimestamps(doc);
|
|
50
52
|
return doc;
|
|
51
53
|
}
|
|
52
54
|
export function exportAllUpdates(doc) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"document.js","sourceRoot":"","sources":["document.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACnE,OAAO,EAAE,OAAO,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AACnD,OAAO,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AACtE,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAEzD,OAAO,EAAE,qBAAqB,EAAuB,MAAM,kBAAkB,CAAC;AAE9E,SAAS,cAAc,CAAC,KAAa;IACnC,OAAO,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC7B,CAAC;AAED,MAAM,oBAAoB,GAAG,aAAa,CAAC;AAE3C,MAAM,OAAO,qCAAsC,SAAQ,KAAK;IACrD,UAAU,CAAyB;IAE5C,YAAY,UAAkC;QAC5C,KAAK,CACH,SAAS,UAAU,KAAK,UAAU,CAAC,CAAC,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,CAAC;IACN,CAAC;YAAS,CAAC;QACT,GAAG,CAAC,IAAI,EAAE,CAAC;IACb,CAAC;AACH,CAAC","sourcesContent":["import { base64ToBytes, bytesToBase64 } from \"@tearleads/encoding\";\nimport { LoroDoc, VersionVector } from \"loro-crdt\";\nimport { serializeCanonicalHistory } from \"./historyCanonicalization\";\nimport { getImportBlobMetadata } from \"./importMetadata\";\n\nexport { getImportBlobMetadata, type ImportBlobMode } from \"./importMetadata\";\n\nfunction isPeerIdString(value: string): value is `${number}` {\n return /^\\d+$/.test(value);\n}\n\nconst MAX_POSTGRES_INTEGER = 2_147_483_647;\n\nexport class LoroImportUnresolvedDependenciesError extends Error {\n readonly importKind: \"snapshot\" | \"updates\";\n\n constructor(importKind: \"snapshot\" | \"updates\") {\n super(\n `import${importKind === \"snapshot\" ? \"Snapshot\" : \"Updates\"} received ${\n importKind === \"snapshot\" ? \"a snapshot\" : \"updates\"\n } with unresolved pending dependencies`,\n );\n this.name = \"LoroImportUnresolvedDependenciesError\";\n this.importKind = importKind;\n }\n}\n\nexport interface VersionVectorSpan {\n peerId: `${number}`;\n startCounter: number;\n endCounter: number;\n}\n\nfunction assertSupportedVersionVectorCounter(counter: number): void {\n if (\n !Number.isInteger(counter) ||\n counter < 0 ||\n counter > MAX_POSTGRES_INTEGER\n ) {\n throw new Error(\n \"Version vector counter is outside the supported integer range.\",\n );\n }\n}\n\nfunction normalizeVersionVectorEntries(\n versionVector: VersionVector,\n): Map<`${number}`, number> {\n const entries = new Map<`${number}`, number>();\n\n for (const [peerId, counter] of versionVector.toJSON()) {\n const normalizedPeerId = String(peerId);\n if (!isPeerIdString(normalizedPeerId)) {\n throw new Error(\"Version vector contains a non-numeric peer ID.\");\n }\n assertSupportedVersionVectorCounter(counter);\n entries.set(normalizedPeerId, counter);\n }\n\n return entries;\n}\n\nexport async function derivePeerId(\n seed: string | Uint8Array,\n): Promise<`${number}`> {\n const bytes =\n typeof seed === \"string\" ? new TextEncoder().encode(seed) : seed;\n const digest = new Uint8Array(\n await crypto.subtle.digest(\"SHA-256\", bytes.slice()),\n );\n const view = new DataView(\n digest.buffer,\n digest.byteOffset,\n digest.byteLength,\n );\n const peerId = (view.getBigUint64(0, false) || 1n).toString();\n\n if (!isPeerIdString(peerId)) {\n throw new Error(\"Failed to derive a numeric peer ID.\");\n }\n\n return peerId;\n}\n\nexport async function createDocument(peerSeed: string | Uint8Array) {\n const doc = new LoroDoc();\n doc.setPeerId(await derivePeerId(peerSeed));\n return doc;\n}\n\nexport function exportAllUpdates(doc: LoroDoc): Uint8Array {\n return doc.export({ mode: \"update\" });\n}\n\n/** Deterministic, peer-uncompressed identity for an operation-log prefix. */\nexport function exportFullHistoryIdentity(\n doc: LoroDoc,\n endVersion?: string,\n): string {\n return serializeCanonicalHistory(\n doc.exportJsonUpdates(\n undefined,\n endVersion === undefined ? undefined : decodeVersionVector(endVersion),\n false,\n ),\n );\n}\n\n/**\n * Export a mergeable, full-history snapshot — the only snapshot form this\n * codebase produces. Every document is born with full durable history and\n * restored from it, so a partial (gc'd) export here is an invariant\n * violation, not a state to accommodate; fail loudly instead of publishing a\n * blob that could not safely merge concurrent frontiers.\n */\nexport function exportFullHistorySnapshot(doc: LoroDoc): Uint8Array {\n const snapshot = doc.export({ mode: \"snapshot\" });\n const metadata = getImportBlobMetadata(snapshot);\n if (\n metadata.mode !== \"snapshot\" ||\n !versionVectorsEqual(\n metadata.partialStartVersionVector,\n emptyVersionVector(),\n )\n ) {\n throw new Error(\n \"Document export lost full history; this document was restored from an incomplete source\",\n );\n }\n return snapshot;\n}\n\nexport function exportUpdatesSince(\n doc: LoroDoc,\n encodedVersionVector?: string | null,\n): Uint8Array {\n if (!encodedVersionVector) {\n return exportAllUpdates(doc);\n }\n\n return doc.export({\n mode: \"update\",\n from: VersionVector.decode(base64ToBytes(encodedVersionVector)),\n });\n}\n\nexport function encodeEncodedVersionVector(\n versionVector: VersionVector,\n): string {\n return bytesToBase64(versionVector.encode());\n}\n\nexport function encodeVersionVector(doc: LoroDoc): string {\n return encodeEncodedVersionVector(doc.oplogVersion());\n}\n\nexport function emptyVersionVector(): string {\n return encodeEncodedVersionVector(new VersionVector(undefined));\n}\n\nexport function decodeVersionVector(\n encodedVersionVector: string | null | undefined,\n): VersionVector {\n if (!encodedVersionVector) {\n return new VersionVector(undefined);\n }\n\n return VersionVector.decode(base64ToBytes(encodedVersionVector));\n}\n\nexport function getUpdateVersionVectors(update: Uint8Array): {\n partialStartVersionVector: string;\n partialEndVersionVector: string;\n} {\n const metadata = getImportBlobMetadata(update);\n\n return {\n partialStartVersionVector: metadata.partialStartVersionVector,\n partialEndVersionVector: metadata.partialEndVersionVector,\n };\n}\n\nexport function satisfiesVersionVector(\n encodedVersionVector: string | null | undefined,\n partialVersionVector: string,\n): boolean {\n const versionVector = decodeVersionVector(encodedVersionVector);\n const requiredVersionVector = decodeVersionVector(partialVersionVector);\n\n for (const [peerId, counter] of requiredVersionVector.toJSON()) {\n if ((versionVector.get(peerId) ?? 0) < counter) {\n return false;\n }\n }\n\n return true;\n}\n\nexport function mergeVersionVectors(\n encodedVersionVectors: ReadonlyArray<string>,\n): string {\n const merged = new Map<`${number}`, number>();\n\n for (const encodedVersionVector of encodedVersionVectors) {\n for (const [normalizedPeerId, counter] of normalizeVersionVectorEntries(\n decodeVersionVector(encodedVersionVector),\n )) {\n merged.set(\n normalizedPeerId,\n Math.max(merged.get(normalizedPeerId) ?? 0, counter),\n );\n }\n }\n\n return encodeEncodedVersionVector(VersionVector.parseJSON(merged));\n}\n\nexport function listVersionVectorSpans(input: {\n partialStartVersionVector: string;\n partialEndVersionVector: string;\n}): VersionVectorSpan[] {\n const startEntries = normalizeVersionVectorEntries(\n decodeVersionVector(input.partialStartVersionVector),\n );\n const endEntries = normalizeVersionVectorEntries(\n decodeVersionVector(input.partialEndVersionVector),\n );\n const spans: VersionVectorSpan[] = [];\n\n for (const [peerId, startCounter] of startEntries) {\n const endCounter = endEntries.get(peerId) ?? 0;\n if (startCounter > endCounter) {\n throw new Error(\"Version vector end must cover start.\");\n }\n }\n\n for (const [peerId, endCounter] of endEntries) {\n const startCounter = startEntries.get(peerId) ?? 0;\n if (endCounter <= startCounter) {\n continue;\n }\n\n spans.push({ peerId, startCounter, endCounter });\n }\n\n return spans.sort((left, right) => left.peerId.localeCompare(right.peerId));\n}\n\nexport function versionVectorsEqual(\n left: string | null | undefined,\n right: string | null | undefined,\n): boolean {\n const leftEntries = decodeVersionVector(left).toJSON();\n const rightEntries = decodeVersionVector(right).toJSON();\n\n if (leftEntries.size !== rightEntries.size) {\n return false;\n }\n\n for (const [peerId, leftCounter] of leftEntries) {\n if (rightEntries.get(peerId) !== leftCounter) {\n return false;\n }\n }\n\n return true;\n}\n\nexport function importUpdates(doc: LoroDoc, updates: Uint8Array[]): void {\n // Reject an obsolete member before importBatch can mutate the document.\n for (const update of updates) getImportBlobMetadata(update);\n const status = doc.importBatch(updates);\n if (status.pending != null && status.pending.size > 0) {\n // importBatch applies out-of-order batches correctly but can still report\n // the intermediate pending set it saw mid-batch. Trust the document, not\n // the report: the import only genuinely failed when the document's final\n // version does not cover some batched update's end version.\n const documentVersion = encodeVersionVector(doc);\n const covered = updates.every((update) =>\n satisfiesVersionVector(\n documentVersion,\n getImportBlobMetadata(update).partialEndVersionVector,\n ),\n );\n if (!covered) {\n throw new LoroImportUnresolvedDependenciesError(\"updates\");\n }\n }\n}\n\n/**\n * Load a snapshot blob into a document. Snapshots MUST go through a single\n * `import()`, never `importBatch()`. A non-empty `pending` means the import\n * target is incompatible or dependencies are missing, so fail loudly instead\n * of silently loading a short document.\n */\nexport function importSnapshot(doc: LoroDoc, snapshot: Uint8Array): void {\n getImportBlobMetadata(snapshot);\n const status = doc.import(snapshot);\n // Reject only a genuinely incomplete import: `pending` can be an empty\n // VersionVector (size 0) rather than null when everything resolved, so test\n // for at least one unresolved dependency instead of mere presence.\n if (status.pending != null && status.pending.size > 0) {\n throw new LoroImportUnresolvedDependenciesError(\"snapshot\");\n }\n}\n\nexport function getTextValue(doc: LoroDoc, key = \"text\"): string {\n return doc.getText(key).toString();\n}\n\nexport interface TextCharOpId {\n /** Peer of the op that inserted this character. */\n peerId: `${number}`;\n /** Counter of that op — identifies the character within the peer's stream. */\n counter: number;\n}\n\nexport interface TextCharBlameSource {\n /** One entry per Unicode code point of the prose, in document order. */\n codePoints: string[];\n /** The op id that inserted each code point — same length and order as `codePoints`. */\n opIds: TextCharOpId[];\n}\n\n/**\n * Walk a LoroText's prose once, collecting each Unicode code point alongside the\n * op id `(peerId, counter)` of the op that inserted it. The two arrays share an\n * index, so callers can both blame and re-render the prose (the per-range view)\n * from a single pass.\n *\n * One Loro op (one counter) is one code point, but an astral character spans\n * two UTF-16 units. Loro cursors address UTF-16 positions; an interior\n * low-surrogate position has no op id. Iterate code points and advance by their\n * UTF-16 length so attribution neither splits nor double-counts a character.\n */\nfunction collectTextCharBlame(doc: LoroDoc, key: string): TextCharBlameSource {\n const text = doc.getText(key);\n const codePoints: string[] = [];\n const opIds: TextCharOpId[] = [];\n let utf16Start = 0;\n for (const char of text.toString()) {\n // getCursor mints a WASM-backed Cursor each call; free it immediately after\n // reading its op id so a long document does not pile up cursors on the heap.\n const cursor = text.getCursor(utf16Start, 1);\n const opId = cursor?.pos();\n cursor?.free();\n if (opId === undefined) {\n throw new Error(\n `LoroText \"${key}\" code point starting at UTF-16 index ${utf16Start} has no op id.`,\n );\n }\n codePoints.push(char);\n opIds.push({ peerId: opId.peer, counter: opId.counter });\n utf16Start += char.length;\n }\n return { codePoints, opIds };\n}\n\n/**\n * Per-character op-id attribution for a LoroText container's prose. Returns one\n * `(peerId, counter)` per Unicode code point — the op that inserted that\n * character — in document order; the array length equals the code-point count\n * (`[...text].length`). This is the client-side primitive for character-level\n * \"blame\": each op id resolves to a writer by intersecting it against the\n * document's edit-attribution segments.\n */\nexport function listTextCharOpIds(doc: LoroDoc, key = \"text\"): TextCharOpId[] {\n return collectTextCharBlame(doc, key).opIds;\n}\n\n/**\n * {@link listTextCharOpIds} for a persisted snapshot blob, without opening an\n * editor: rebuilds a throwaway read-only `LoroDoc` from the snapshot and reads\n * each character's op id, so blame is exact. The doc is only read, never\n * edited, so no peer id is set.\n *\n * Extraction is linear: `getCursor()` is an O(log n) b-tree lookup per code\n * point (measured ~1.8µs/char — ~90ms for a 50k-char snapshot, flat per char and\n * unaffected by tombstones). `maxCharacters` (UTF-16 length) is therefore a soft\n * guard against pathologically large prose, not a quadratic cliff: over it we\n * return `null` (\"skipped, too large\", distinct from `[]` for an empty document)\n * rather than do unbounded synchronous work on the render thread.\n */\nexport function listSnapshotCharOpIds(\n snapshot: Uint8Array,\n maxCharacters: number,\n key = \"text\",\n): TextCharOpId[] | null {\n const source = listSnapshotCharBlameSource(snapshot, maxCharacters, key);\n return source === null ? null : source.opIds;\n}\n\n/**\n * {@link listSnapshotCharBlameSource} is {@link listSnapshotCharOpIds} that also\n * returns each code point's text, so a caller can render the prose tinted by\n * writer (the per-range \"blame\" view) without a second snapshot reconstruction.\n * Same linear cost and `maxCharacters` guard.\n */\nexport function listSnapshotCharBlameSource(\n snapshot: Uint8Array,\n maxCharacters: number,\n key = \"text\",\n): TextCharBlameSource | null {\n const doc = new LoroDoc();\n try {\n importSnapshot(doc, snapshot);\n if (doc.getText(key).length > maxCharacters) {\n return null;\n }\n return collectTextCharBlame(doc, key);\n } finally {\n // The throwaway doc is WASM-backed and never returned — free it immediately\n // rather than waiting for GC, since blame rebuilds one per Info-panel load.\n doc.free();\n }\n}\n\nexport interface FieldEditor {\n /** The map key (e.g. `firstName`, `cardNumber`) of a structured document field. */\n key: string;\n /** Peer of the op that last set this field, or null if none is recorded. */\n peerId: `${number}` | null;\n}\n\n/**\n * The structured-document counterpart to {@link listSnapshotCharBlameSource}:\n * for a persisted snapshot, name the peer that last wrote each key of a LoroMap\n * (the document's `fields` map). Structured documents (contacts, cards, licenses)\n * store each field as a `LoroMap` entry — a last-writer-wins register that keeps\n * the setting op's peer, which `getLastEditor` reads. That peer resolves to a\n * writer via the same attribution segments,\n * giving per-field \"blame\". Fields carry only the peer (no op counter), so\n * resolution is peer-level. A note (or any document without this map) yields an\n * empty array. Reconstructing the small map is cheap, so there is no size cap.\n */\nexport function listSnapshotFieldEditors(\n snapshot: Uint8Array,\n mapKey: string,\n): FieldEditor[] {\n const doc = new LoroDoc();\n try {\n importSnapshot(doc, snapshot);\n const map = doc.getMap(mapKey);\n return map.keys().map((key) => ({\n key,\n peerId: map.getLastEditor(key) ?? null,\n }));\n } finally {\n doc.free();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"document.js","sourceRoot":"","sources":["document.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACnE,OAAO,EAAE,OAAO,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AACnD,OAAO,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AACtE,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAEzD,OAAO,EAAE,qBAAqB,EAAuB,MAAM,kBAAkB,CAAC;AAE9E,SAAS,cAAc,CAAC,KAAa;IACnC,OAAO,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC7B,CAAC;AAED,MAAM,oBAAoB,GAAG,aAAa,CAAC;AAE3C,MAAM,OAAO,qCAAsC,SAAQ,KAAK;IACrD,UAAU,CAAyB;IAE5C,YAAY,UAAkC;QAC5C,KAAK,CACH,SAAS,UAAU,KAAK,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,SAAS,aACzD,UAAU,KAAK,UAAU,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,SAC7C,uCAAuC,CACxC,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,uCAAuC,CAAC;QACpD,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC/B,CAAC;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,OAAO,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;AAC/C,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,2BAA2B,CACzC,QAAoB,EACpB,aAAqB,EACrB,GAAG,GAAG,MAAM;IAEZ,MAAM,GAAG,GAAG,IAAI,OAAO,EAAE,CAAC;IAC1B,IAAI,CAAC;QACH,cAAc,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;QAC9B,IAAI,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,GAAG,aAAa,EAAE,CAAC;YAC5C,OAAO,IAAI,CAAC;QACd,CAAC;QACD,OAAO,oBAAoB,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;IACxC,CAAC;YAAS,CAAC;QACT,4EAA4E;QAC5E,4EAA4E;QAC5E,GAAG,CAAC,IAAI,EAAE,CAAC;IACb,CAAC;AACH,CAAC;AASD;;;;;;;;;;GAUG;AACH,MAAM,UAAU,wBAAwB,CACtC,QAAoB,EACpB,MAAc;IAEd,MAAM,GAAG,GAAG,IAAI,OAAO,EAAE,CAAC;IAC1B,IAAI,CAAC;QACH,cAAc,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;QAC9B,MAAM,GAAG,GAAG,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QAC/B,OAAO,GAAG,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;YAC9B,GAAG;YACH,MAAM,EAAE,GAAG,CAAC,aAAa,CAAC,GAAG,CAAC,IAAI,IAAI;SACvC,CAAC,CAAC,CAAC;IACN,CAAC;YAAS,CAAC;QACT,GAAG,CAAC,IAAI,EAAE,CAAC;IACb,CAAC;AACH,CAAC","sourcesContent":["import { base64ToBytes, bytesToBase64 } from \"@tearleads/encoding\";\nimport { LoroDoc, VersionVector } from \"loro-crdt\";\nimport { recordChangeTimestamps } from \"./changeTimestamps\";\nimport { serializeCanonicalHistory } from \"./historyCanonicalization\";\nimport { getImportBlobMetadata } from \"./importMetadata\";\n\nexport { getImportBlobMetadata, type ImportBlobMode } from \"./importMetadata\";\n\nfunction isPeerIdString(value: string): value is `${number}` {\n return /^\\d+$/.test(value);\n}\n\nconst MAX_POSTGRES_INTEGER = 2_147_483_647;\n\nexport class LoroImportUnresolvedDependenciesError extends Error {\n readonly importKind: \"snapshot\" | \"updates\";\n\n constructor(importKind: \"snapshot\" | \"updates\") {\n super(\n `import${importKind === \"snapshot\" ? \"Snapshot\" : \"Updates\"} received ${\n importKind === \"snapshot\" ? \"a snapshot\" : \"updates\"\n } with unresolved pending dependencies`,\n );\n this.name = \"LoroImportUnresolvedDependenciesError\";\n this.importKind = importKind;\n }\n}\n\nexport interface VersionVectorSpan {\n peerId: `${number}`;\n startCounter: number;\n endCounter: number;\n}\n\nfunction assertSupportedVersionVectorCounter(counter: number): void {\n if (\n !Number.isInteger(counter) ||\n counter < 0 ||\n counter > MAX_POSTGRES_INTEGER\n ) {\n throw new Error(\n \"Version vector counter is outside the supported integer range.\",\n );\n }\n}\n\nfunction normalizeVersionVectorEntries(\n versionVector: VersionVector,\n): Map<`${number}`, number> {\n const entries = new Map<`${number}`, number>();\n\n for (const [peerId, counter] of versionVector.toJSON()) {\n const normalizedPeerId = String(peerId);\n if (!isPeerIdString(normalizedPeerId)) {\n throw new Error(\"Version vector contains a non-numeric peer ID.\");\n }\n assertSupportedVersionVectorCounter(counter);\n entries.set(normalizedPeerId, counter);\n }\n\n return entries;\n}\n\nexport async function derivePeerId(\n seed: string | Uint8Array,\n): Promise<`${number}`> {\n const bytes =\n typeof seed === \"string\" ? new TextEncoder().encode(seed) : seed;\n const digest = new Uint8Array(\n await crypto.subtle.digest(\"SHA-256\", bytes.slice()),\n );\n const view = new DataView(\n digest.buffer,\n digest.byteOffset,\n digest.byteLength,\n );\n const peerId = (view.getBigUint64(0, false) || 1n).toString();\n\n if (!isPeerIdString(peerId)) {\n throw new Error(\"Failed to derive a numeric peer ID.\");\n }\n\n return peerId;\n}\n\nexport async function createDocument(peerSeed: string | Uint8Array) {\n const doc = new LoroDoc();\n doc.setPeerId(await derivePeerId(peerSeed));\n recordChangeTimestamps(doc);\n return doc;\n}\n\nexport function exportAllUpdates(doc: LoroDoc): Uint8Array {\n return doc.export({ mode: \"update\" });\n}\n\n/** Deterministic, peer-uncompressed identity for an operation-log prefix. */\nexport function exportFullHistoryIdentity(\n doc: LoroDoc,\n endVersion?: string,\n): string {\n return serializeCanonicalHistory(\n doc.exportJsonUpdates(\n undefined,\n endVersion === undefined ? undefined : decodeVersionVector(endVersion),\n false,\n ),\n );\n}\n\n/**\n * Export a mergeable, full-history snapshot — the only snapshot form this\n * codebase produces. Every document is born with full durable history and\n * restored from it, so a partial (gc'd) export here is an invariant\n * violation, not a state to accommodate; fail loudly instead of publishing a\n * blob that could not safely merge concurrent frontiers.\n */\nexport function exportFullHistorySnapshot(doc: LoroDoc): Uint8Array {\n const snapshot = doc.export({ mode: \"snapshot\" });\n const metadata = getImportBlobMetadata(snapshot);\n if (\n metadata.mode !== \"snapshot\" ||\n !versionVectorsEqual(\n metadata.partialStartVersionVector,\n emptyVersionVector(),\n )\n ) {\n throw new Error(\n \"Document export lost full history; this document was restored from an incomplete source\",\n );\n }\n return snapshot;\n}\n\nexport function exportUpdatesSince(\n doc: LoroDoc,\n encodedVersionVector?: string | null,\n): Uint8Array {\n if (!encodedVersionVector) {\n return exportAllUpdates(doc);\n }\n\n return doc.export({\n mode: \"update\",\n from: VersionVector.decode(base64ToBytes(encodedVersionVector)),\n });\n}\n\nexport function encodeEncodedVersionVector(\n versionVector: VersionVector,\n): string {\n return bytesToBase64(versionVector.encode());\n}\n\nexport function encodeVersionVector(doc: LoroDoc): string {\n return encodeEncodedVersionVector(doc.oplogVersion());\n}\n\nexport function emptyVersionVector(): string {\n return encodeEncodedVersionVector(new VersionVector(undefined));\n}\n\nexport function decodeVersionVector(\n encodedVersionVector: string | null | undefined,\n): VersionVector {\n if (!encodedVersionVector) {\n return new VersionVector(undefined);\n }\n\n return VersionVector.decode(base64ToBytes(encodedVersionVector));\n}\n\nexport function getUpdateVersionVectors(update: Uint8Array): {\n partialStartVersionVector: string;\n partialEndVersionVector: string;\n} {\n const metadata = getImportBlobMetadata(update);\n\n return {\n partialStartVersionVector: metadata.partialStartVersionVector,\n partialEndVersionVector: metadata.partialEndVersionVector,\n };\n}\n\nexport function satisfiesVersionVector(\n encodedVersionVector: string | null | undefined,\n partialVersionVector: string,\n): boolean {\n const versionVector = decodeVersionVector(encodedVersionVector);\n const requiredVersionVector = decodeVersionVector(partialVersionVector);\n\n for (const [peerId, counter] of requiredVersionVector.toJSON()) {\n if ((versionVector.get(peerId) ?? 0) < counter) {\n return false;\n }\n }\n\n return true;\n}\n\nexport function mergeVersionVectors(\n encodedVersionVectors: ReadonlyArray<string>,\n): string {\n const merged = new Map<`${number}`, number>();\n\n for (const encodedVersionVector of encodedVersionVectors) {\n for (const [normalizedPeerId, counter] of normalizeVersionVectorEntries(\n decodeVersionVector(encodedVersionVector),\n )) {\n merged.set(\n normalizedPeerId,\n Math.max(merged.get(normalizedPeerId) ?? 0, counter),\n );\n }\n }\n\n return encodeEncodedVersionVector(VersionVector.parseJSON(merged));\n}\n\nexport function listVersionVectorSpans(input: {\n partialStartVersionVector: string;\n partialEndVersionVector: string;\n}): VersionVectorSpan[] {\n const startEntries = normalizeVersionVectorEntries(\n decodeVersionVector(input.partialStartVersionVector),\n );\n const endEntries = normalizeVersionVectorEntries(\n decodeVersionVector(input.partialEndVersionVector),\n );\n const spans: VersionVectorSpan[] = [];\n\n for (const [peerId, startCounter] of startEntries) {\n const endCounter = endEntries.get(peerId) ?? 0;\n if (startCounter > endCounter) {\n throw new Error(\"Version vector end must cover start.\");\n }\n }\n\n for (const [peerId, endCounter] of endEntries) {\n const startCounter = startEntries.get(peerId) ?? 0;\n if (endCounter <= startCounter) {\n continue;\n }\n\n spans.push({ peerId, startCounter, endCounter });\n }\n\n return spans.sort((left, right) => left.peerId.localeCompare(right.peerId));\n}\n\nexport function versionVectorsEqual(\n left: string | null | undefined,\n right: string | null | undefined,\n): boolean {\n const leftEntries = decodeVersionVector(left).toJSON();\n const rightEntries = decodeVersionVector(right).toJSON();\n\n if (leftEntries.size !== rightEntries.size) {\n return false;\n }\n\n for (const [peerId, leftCounter] of leftEntries) {\n if (rightEntries.get(peerId) !== leftCounter) {\n return false;\n }\n }\n\n return true;\n}\n\nexport function importUpdates(doc: LoroDoc, updates: Uint8Array[]): void {\n // Reject an obsolete member before importBatch can mutate the document.\n for (const update of updates) getImportBlobMetadata(update);\n const status = doc.importBatch(updates);\n if (status.pending != null && status.pending.size > 0) {\n // importBatch applies out-of-order batches correctly but can still report\n // the intermediate pending set it saw mid-batch. Trust the document, not\n // the report: the import only genuinely failed when the document's final\n // version does not cover some batched update's end version.\n const documentVersion = encodeVersionVector(doc);\n const covered = updates.every((update) =>\n satisfiesVersionVector(\n documentVersion,\n getImportBlobMetadata(update).partialEndVersionVector,\n ),\n );\n if (!covered) {\n throw new LoroImportUnresolvedDependenciesError(\"updates\");\n }\n }\n}\n\n/**\n * Load a snapshot blob into a document. Snapshots MUST go through a single\n * `import()`, never `importBatch()`. A non-empty `pending` means the import\n * target is incompatible or dependencies are missing, so fail loudly instead\n * of silently loading a short document.\n */\nexport function importSnapshot(doc: LoroDoc, snapshot: Uint8Array): void {\n getImportBlobMetadata(snapshot);\n const status = doc.import(snapshot);\n // Reject only a genuinely incomplete import: `pending` can be an empty\n // VersionVector (size 0) rather than null when everything resolved, so test\n // for at least one unresolved dependency instead of mere presence.\n if (status.pending != null && status.pending.size > 0) {\n throw new LoroImportUnresolvedDependenciesError(\"snapshot\");\n }\n}\n\nexport function getTextValue(doc: LoroDoc, key = \"text\"): string {\n return doc.getText(key).toString();\n}\n\nexport interface TextCharOpId {\n /** Peer of the op that inserted this character. */\n peerId: `${number}`;\n /** Counter of that op — identifies the character within the peer's stream. */\n counter: number;\n}\n\nexport interface TextCharBlameSource {\n /** One entry per Unicode code point of the prose, in document order. */\n codePoints: string[];\n /** The op id that inserted each code point — same length and order as `codePoints`. */\n opIds: TextCharOpId[];\n}\n\n/**\n * Walk a LoroText's prose once, collecting each Unicode code point alongside the\n * op id `(peerId, counter)` of the op that inserted it. The two arrays share an\n * index, so callers can both blame and re-render the prose (the per-range view)\n * from a single pass.\n *\n * One Loro op (one counter) is one code point, but an astral character spans\n * two UTF-16 units. Loro cursors address UTF-16 positions; an interior\n * low-surrogate position has no op id. Iterate code points and advance by their\n * UTF-16 length so attribution neither splits nor double-counts a character.\n */\nfunction collectTextCharBlame(doc: LoroDoc, key: string): TextCharBlameSource {\n const text = doc.getText(key);\n const codePoints: string[] = [];\n const opIds: TextCharOpId[] = [];\n let utf16Start = 0;\n for (const char of text.toString()) {\n // getCursor mints a WASM-backed Cursor each call; free it immediately after\n // reading its op id so a long document does not pile up cursors on the heap.\n const cursor = text.getCursor(utf16Start, 1);\n const opId = cursor?.pos();\n cursor?.free();\n if (opId === undefined) {\n throw new Error(\n `LoroText \"${key}\" code point starting at UTF-16 index ${utf16Start} has no op id.`,\n );\n }\n codePoints.push(char);\n opIds.push({ peerId: opId.peer, counter: opId.counter });\n utf16Start += char.length;\n }\n return { codePoints, opIds };\n}\n\n/**\n * Per-character op-id attribution for a LoroText container's prose. Returns one\n * `(peerId, counter)` per Unicode code point — the op that inserted that\n * character — in document order; the array length equals the code-point count\n * (`[...text].length`). This is the client-side primitive for character-level\n * \"blame\": each op id resolves to a writer by intersecting it against the\n * document's edit-attribution segments.\n */\nexport function listTextCharOpIds(doc: LoroDoc, key = \"text\"): TextCharOpId[] {\n return collectTextCharBlame(doc, key).opIds;\n}\n\n/**\n * {@link listTextCharOpIds} for a persisted snapshot blob, without opening an\n * editor: rebuilds a throwaway read-only `LoroDoc` from the snapshot and reads\n * each character's op id, so blame is exact. The doc is only read, never\n * edited, so no peer id is set.\n *\n * Extraction is linear: `getCursor()` is an O(log n) b-tree lookup per code\n * point (measured ~1.8µs/char — ~90ms for a 50k-char snapshot, flat per char and\n * unaffected by tombstones). `maxCharacters` (UTF-16 length) is therefore a soft\n * guard against pathologically large prose, not a quadratic cliff: over it we\n * return `null` (\"skipped, too large\", distinct from `[]` for an empty document)\n * rather than do unbounded synchronous work on the render thread.\n */\nexport function listSnapshotCharOpIds(\n snapshot: Uint8Array,\n maxCharacters: number,\n key = \"text\",\n): TextCharOpId[] | null {\n const source = listSnapshotCharBlameSource(snapshot, maxCharacters, key);\n return source === null ? null : source.opIds;\n}\n\n/**\n * {@link listSnapshotCharBlameSource} is {@link listSnapshotCharOpIds} that also\n * returns each code point's text, so a caller can render the prose tinted by\n * writer (the per-range \"blame\" view) without a second snapshot reconstruction.\n * Same linear cost and `maxCharacters` guard.\n */\nexport function listSnapshotCharBlameSource(\n snapshot: Uint8Array,\n maxCharacters: number,\n key = \"text\",\n): TextCharBlameSource | null {\n const doc = new LoroDoc();\n try {\n importSnapshot(doc, snapshot);\n if (doc.getText(key).length > maxCharacters) {\n return null;\n }\n return collectTextCharBlame(doc, key);\n } finally {\n // The throwaway doc is WASM-backed and never returned — free it immediately\n // rather than waiting for GC, since blame rebuilds one per Info-panel load.\n doc.free();\n }\n}\n\nexport interface FieldEditor {\n /** The map key (e.g. `firstName`, `cardNumber`) of a structured document field. */\n key: string;\n /** Peer of the op that last set this field, or null if none is recorded. */\n peerId: `${number}` | null;\n}\n\n/**\n * The structured-document counterpart to {@link listSnapshotCharBlameSource}:\n * for a persisted snapshot, name the peer that last wrote each key of a LoroMap\n * (the document's `fields` map). Structured documents (contacts, cards, licenses)\n * store each field as a `LoroMap` entry — a last-writer-wins register that keeps\n * the setting op's peer, which `getLastEditor` reads. That peer resolves to a\n * writer via the same attribution segments,\n * giving per-field \"blame\". Fields carry only the peer (no op counter), so\n * resolution is peer-level. A note (or any document without this map) yields an\n * empty array. Reconstructing the small map is cheap, so there is no size cap.\n */\nexport function listSnapshotFieldEditors(\n snapshot: Uint8Array,\n mapKey: string,\n): FieldEditor[] {\n const doc = new LoroDoc();\n try {\n importSnapshot(doc, snapshot);\n const map = doc.getMap(mapKey);\n return map.keys().map((key) => ({\n key,\n peerId: map.getLastEditor(key) ?? null,\n }));\n } finally {\n doc.free();\n }\n}\n"]}
|
package/internal/loro/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export { LoroList, LoroMap } from "loro-crdt";
|
|
2
|
+
export { DOCUMENT_CHANGE_MERGE_INTERVAL_SECONDS } from "./changeTimestamps.js";
|
|
2
3
|
export { createDocument, decodeVersionVector, derivePeerId, emptyVersionVector, encodeEncodedVersionVector, encodeVersionVector, exportAllUpdates, exportFullHistoryIdentity, exportFullHistorySnapshot, exportUpdatesSince, type FieldEditor, getImportBlobMetadata, getTextValue, getUpdateVersionVectors, type ImportBlobMode, importSnapshot, importUpdates, LoroImportUnresolvedDependenciesError, listSnapshotCharBlameSource, listSnapshotCharOpIds, listSnapshotFieldEditors, listTextCharOpIds, listVersionVectorSpans, mergeVersionVectors, satisfiesVersionVector, type TextCharBlameSource, type TextCharOpId, type VersionVectorSpan, versionVectorsEqual, } from "./document.js";
|
|
3
4
|
export * from "./shared/index.js";
|
|
4
5
|
export { updateMatchesDocumentHistory } from "./updateIdentity.js";
|
package/internal/loro/index.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export { LoroList, LoroMap } from "loro-crdt";
|
|
2
|
+
export { DOCUMENT_CHANGE_MERGE_INTERVAL_SECONDS } from "./changeTimestamps.js";
|
|
2
3
|
export { createDocument, decodeVersionVector, derivePeerId, emptyVersionVector, encodeEncodedVersionVector, encodeVersionVector, exportAllUpdates, exportFullHistoryIdentity, exportFullHistorySnapshot, exportUpdatesSince, getImportBlobMetadata, getTextValue, getUpdateVersionVectors, importSnapshot, importUpdates, LoroImportUnresolvedDependenciesError, listSnapshotCharBlameSource, listSnapshotCharOpIds, listSnapshotFieldEditors, listTextCharOpIds, listVersionVectorSpans, mergeVersionVectors, satisfiesVersionVector, versionVectorsEqual, } from "./document.js";
|
|
3
4
|
export * from "./shared/index.js";
|
|
4
5
|
export { updateMatchesDocumentHistory } from "./updateIdentity.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EACL,cAAc,EACd,mBAAmB,EACnB,YAAY,EACZ,kBAAkB,EAClB,0BAA0B,EAC1B,mBAAmB,EACnB,gBAAgB,EAChB,yBAAyB,EACzB,yBAAyB,EACzB,kBAAkB,EAElB,qBAAqB,EACrB,YAAY,EACZ,uBAAuB,EAEvB,cAAc,EACd,aAAa,EACb,qCAAqC,EACrC,2BAA2B,EAC3B,qBAAqB,EACrB,wBAAwB,EACxB,iBAAiB,EACjB,sBAAsB,EACtB,mBAAmB,EACnB,sBAAsB,EAItB,mBAAmB,GACpB,MAAM,YAAY,CAAC;AACpB,cAAc,UAAU,CAAC;AACzB,OAAO,EAAE,4BAA4B,EAAE,MAAM,kBAAkB,CAAC;AAChE,OAAO,EACL,2BAA2B,EAC3B,qBAAqB,GACtB,MAAM,gBAAgB,CAAC","sourcesContent":["export { LoroList, LoroMap } from \"loro-crdt\";\nexport {\n createDocument,\n decodeVersionVector,\n derivePeerId,\n emptyVersionVector,\n encodeEncodedVersionVector,\n encodeVersionVector,\n exportAllUpdates,\n exportFullHistoryIdentity,\n exportFullHistorySnapshot,\n exportUpdatesSince,\n type FieldEditor,\n getImportBlobMetadata,\n getTextValue,\n getUpdateVersionVectors,\n type ImportBlobMode,\n importSnapshot,\n importUpdates,\n LoroImportUnresolvedDependenciesError,\n listSnapshotCharBlameSource,\n listSnapshotCharOpIds,\n listSnapshotFieldEditors,\n listTextCharOpIds,\n listVersionVectorSpans,\n mergeVersionVectors,\n satisfiesVersionVector,\n type TextCharBlameSource,\n type TextCharOpId,\n type VersionVectorSpan,\n versionVectorsEqual,\n} from \"./document\";\nexport * from \"./shared\";\nexport { updateMatchesDocumentHistory } from \"./updateIdentity\";\nexport {\n exportUpdatesInVersionRange,\n minimumVersionVectors,\n} from \"./versionRange\";\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EAAE,sCAAsC,EAAE,MAAM,oBAAoB,CAAC;AAC5E,OAAO,EACL,cAAc,EACd,mBAAmB,EACnB,YAAY,EACZ,kBAAkB,EAClB,0BAA0B,EAC1B,mBAAmB,EACnB,gBAAgB,EAChB,yBAAyB,EACzB,yBAAyB,EACzB,kBAAkB,EAElB,qBAAqB,EACrB,YAAY,EACZ,uBAAuB,EAEvB,cAAc,EACd,aAAa,EACb,qCAAqC,EACrC,2BAA2B,EAC3B,qBAAqB,EACrB,wBAAwB,EACxB,iBAAiB,EACjB,sBAAsB,EACtB,mBAAmB,EACnB,sBAAsB,EAItB,mBAAmB,GACpB,MAAM,YAAY,CAAC;AACpB,cAAc,UAAU,CAAC;AACzB,OAAO,EAAE,4BAA4B,EAAE,MAAM,kBAAkB,CAAC;AAChE,OAAO,EACL,2BAA2B,EAC3B,qBAAqB,GACtB,MAAM,gBAAgB,CAAC","sourcesContent":["export { LoroList, LoroMap } from \"loro-crdt\";\nexport { DOCUMENT_CHANGE_MERGE_INTERVAL_SECONDS } from \"./changeTimestamps\";\nexport {\n createDocument,\n decodeVersionVector,\n derivePeerId,\n emptyVersionVector,\n encodeEncodedVersionVector,\n encodeVersionVector,\n exportAllUpdates,\n exportFullHistoryIdentity,\n exportFullHistorySnapshot,\n exportUpdatesSince,\n type FieldEditor,\n getImportBlobMetadata,\n getTextValue,\n getUpdateVersionVectors,\n type ImportBlobMode,\n importSnapshot,\n importUpdates,\n LoroImportUnresolvedDependenciesError,\n listSnapshotCharBlameSource,\n listSnapshotCharOpIds,\n listSnapshotFieldEditors,\n listTextCharOpIds,\n listVersionVectorSpans,\n mergeVersionVectors,\n satisfiesVersionVector,\n type TextCharBlameSource,\n type TextCharOpId,\n type VersionVectorSpan,\n versionVectorsEqual,\n} from \"./document\";\nexport * from \"./shared\";\nexport { updateMatchesDocumentHistory } from \"./updateIdentity\";\nexport {\n exportUpdatesInVersionRange,\n minimumVersionVectors,\n} from \"./versionRange\";\n"]}
|
package/package.json
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
|
|
2
2
|
import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
|
|
3
|
-
import { PrincipalAcknowledgementChangedError,
|
|
3
|
+
import { PrincipalAcknowledgementChangedError, } from "../../../data/persistence/principalCurrentAcknowledgementPersistence.js";
|
|
4
4
|
import { preparePrincipalHistoryEvidencePage } from "../../../data/persistence/principalHistory/principalHistoryEvidencePersistence.js";
|
|
5
|
+
import { PrincipalHistoryRepository } from "../../../data/persistence/principalHistory/principalHistoryRepository.js";
|
|
5
6
|
import { ownPrincipalHistoryProtection } from "../../../data/principals/principalHistoryProtection.js";
|
|
6
7
|
import { assertPrincipalHistoryVerificationMode, principalHistoryVerificationContext, } from "../historyRecovery/principalHistoryRecoveryVerification.js";
|
|
7
8
|
import { collectPrincipalPolicySignerPublicKeys, publishVerifiedCurrent, } from "../policyVerification.js";
|
|
@@ -135,8 +136,7 @@ export async function recordAcknowledgedPrincipalCurrents(input) {
|
|
|
135
136
|
for (let attempt = 0;; attempt += 1) {
|
|
136
137
|
const reconciled = await reconcilePublications(entries, publications);
|
|
137
138
|
try {
|
|
138
|
-
await persistAcknowledgedPrincipalCurrents({
|
|
139
|
-
execSql,
|
|
139
|
+
await new PrincipalHistoryRepository(execSql).persistAcknowledgedPrincipalCurrents({
|
|
140
140
|
organizationId,
|
|
141
141
|
entries: reconciled,
|
|
142
142
|
retirements,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"acknowledgedPrincipalCurrents.js","sourceRoot":"","sources":["acknowledgedPrincipalCurrents.ts"],"names":[],"mappings":"AACA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAGL,oCAAoC,EACpC,oCAAoC,GACrC,MAAM,sEAAsE,CAAC;AAC9E,OAAO,EAAE,mCAAmC,EAAE,MAAM,gFAAgF,CAAC;AACrI,OAAO,EAAE,6BAA6B,EAAE,MAAM,qDAAqD,CAAC;AAGpG,OAAO,EACL,sCAAsC,EACtC,mCAAmC,GACpC,MAAM,yDAAyD,CAAC;AACjE,OAAO,EACL,sCAAsC,EACtC,sBAAsB,GACvB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAEL,uCAAuC,GACxC,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,qCAAqC,EAAE,MAAM,sCAAsC,CAAC;AAE7F,OAAO,EACL,+BAA+B,EAC/B,yBAAyB,GAC1B,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,qCAAqC,EAAE,MAAM,yCAAyC,CAAC;AAgBhG,KAAK,UAAU,kBAAkB,CAC/B,OAA6C,EAC7C,OAAkC,EAClC,OAAmC,EACnC,WAAoD,EACpD,MAAsC;IAEtC,OAAO,GAAG;QACR,GAAG,OAAO;QACV,UAAU,EAAE;YACV,GAAG,OAAO,CAAC,UAAU;YACrB,OAAO,EAAE,mCAAmC,CAAC,OAAO,CAAC;SACtD;KACF,CAAC;IACF,MAAM,YAAY,GAAG,GAAG,EAAE,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,IAAI,OAAO,CAAC,YAAY,EAAE,CAAC;IAC9E,mCAAmC,CAAC,YAAY,CAAC,CAAC;IAClD,MAAM,EACJ,OAAO,EACP,KAAK,EACL,SAAS,EACT,QAAQ,EACR,QAAQ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AO,EAAE,UAAU;oBACnB,WAAW;oBACX,YAAY,EAAE,GAAG,EAAE,CACjB,YAAY,EAAE;wBACd,OAAO,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,CAAC;iBAC3D,CAAC,CAAC;gBACH,MAAM;YACR,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,IACE,CAAC,CAAC,KAAK,YAAY,oCAAoC,CAAC;oBACxD,OAAO,IAAI,CAAC;oBAEZ,MAAM,KAAK,CAAC;YAChB,CAAC;QACH,CAAC;QACD,OAAO,YAAY,CAAC,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC;IAClD,CAAC;YAAS,CAAC;QACT,KAAK,MAAM,KAAK,IAAI,OAAO;YAAE,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACzE,CAAC;AACH,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport {\n KeyingVerificationError,\n type VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyMutationResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport {\n type AcknowledgedPrincipalCurrentPublication,\n type AcknowledgedPrincipalCurrentRetirement,\n PrincipalAcknowledgementChangedError,\n persistAcknowledgedPrincipalCurrents,\n} from \"../../../data/persistence/principalCurrentAcknowledgementPersistence\";\nimport { preparePrincipalHistoryEvidencePage } from \"../../../data/persistence/principalHistory/principalHistoryEvidencePersistence\";\nimport { ownPrincipalHistoryProtection } from \"../../../data/principals/principalHistoryProtection\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { RecoverPrincipalPolicyHistoryOptions } from \"../historyRecovery/principalHistoryRecoveryTypes\";\nimport {\n assertPrincipalHistoryVerificationMode,\n principalHistoryVerificationContext,\n} from \"../historyRecovery/principalHistoryRecoveryVerification\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n publishVerifiedCurrent,\n} from \"../policyVerification\";\nimport {\n type AcknowledgedPrincipalPredecessor,\n restoreAcknowledgedPrincipalPredecessor,\n} from \"./acknowledgedPrincipalPredecessor\";\nimport { prepareInitialGroupCurrentPublication } from \"./initialPrincipalCurrentPublication\";\nimport type { PrincipalAcknowledgementChecks } from \"./principalAcknowledgementChecks\";\nimport {\n sealPrincipalCurrentPublication,\n sealPrincipalCurrentStage,\n} from \"./principalCurrentPublicationSeal\";\nimport { reconcileAcknowledgedPrincipalCurrent } from \"./reconcileAcknowledgedPrincipalCurrent\";\n\nexport interface AcknowledgedPrincipalCurrentInput {\n /** Capture before submitting the mutation; null only for a new group. */\n readonly predecessor: AcknowledgedPrincipalPredecessor | null;\n /** Only a newly authored group at version one; never skips a predecessor. */\n readonly initialGroup?: boolean | undefined;\n /** The same scoped protection and verification mode used to recover the predecessor. */\n readonly recovery: Omit<\n RecoverPrincipalPolicyHistoryOptions,\n \"execSql\" | \"organizationId\" | \"stillCurrent\"\n >;\n readonly request: PutPrincipalPolicyRequest;\n readonly response: PrincipalPolicyMutationResponse;\n}\n\nasync function preparePublication(\n options: RecoverPrincipalPolicyHistoryOptions,\n request: PutPrincipalPolicyRequest,\n current: PrincipalPolicyPageCurrent,\n predecessor: AcknowledgedPrincipalPredecessor | null,\n checks: PrincipalAcknowledgementChecks,\n): Promise<AcknowledgedPrincipalCurrentPublication> {\n options = {\n ...options,\n protection: {\n ...options.protection,\n context: principalHistoryVerificationContext(options),\n },\n };\n const stillCurrent = () => !options.signal?.aborted && options.stillCurrent();\n assertProjectionVerificationCurrent(stillCurrent);\n const {\n scopeId,\n saved,\n artifacts,\n verifier,\n previous,\n predecessorIndexRootHash,\n } = await restoreAcknowledgedPrincipalPredecessor(options, predecessor);\n const expectedHead = await checks.authoredHead(request);\n const keys = await collectPrincipalPolicySignerPublicKeys({\n bundle: { ...current, previousStates: [] },\n resolveTrustedUserIdentity: options.resolveTrustedUserIdentity,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n if (\"error\" in keys)\n throw new KeyingVerificationError(\n keys.error === \"not-found\" ? \"missing_dependency\" : \"signer_mismatch\",\n \"Acknowledged principal signer could not be authenticated\",\n );\n const externalAuthority = await options.loadExternalAuthority?.(\n request.state.externalAuthority ? [request.state.externalAuthority] : [],\n );\n assertProjectionVerificationCurrent(stillCurrent);\n const policy = await checks.acknowledgeSuccessor({\n verifiedCurrentPolicy: previous,\n expectedHead,\n request,\n response: current.currentState,\n signerPublicKeys: keys.signerPublicKeys,\n externalAuthority,\n stillCurrent,\n });\n await publishVerifiedCurrent(options, current, stillCurrent);\n const entry = {\n state: current.currentState,\n projection: current.currentProjection,\n grants: current.currentGrants,\n };\n assertPrincipalHistoryVerificationMode(options, [entry]);\n const predecessorStage = await sealPrincipalCurrentStage(\n options,\n previous.state,\n verifier,\n artifacts,\n );\n const appended = await verifier.append({\n entries: [entry],\n signerPublicKeys: keys.signerPublicKeys,\n ...(externalAuthority ? { externalAuthority } : {}),\n });\n if (!appended.ok) throw appended.error;\n const sealed = await sealPrincipalCurrentPublication(\n options,\n scopeId,\n expectedHead,\n verifier,\n current,\n );\n assertProjectionVerificationCurrent(stillCurrent);\n return {\n policy,\n previousPrefixProgress: saved.progress,\n predecessorStage,\n predecessorIndexRootHash,\n ...sealed,\n evidence: await preparePrincipalHistoryEvidencePage({\n indexRootHash: appended.value.indexRootHash,\n scopeId,\n organizationId: options.organizationId,\n entries: [entry],\n nodes: appended.value.indexNodes,\n }),\n };\n}\n\n/** The acknowledged currents of one mutation, recorded together. */\nexport interface AcknowledgedPrincipalCurrentBatch {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly entries: readonly AcknowledgedPrincipalCurrentInput[];\n readonly retirements?:\n | readonly AcknowledgedPrincipalCurrentRetirement[]\n | undefined;\n readonly stillCurrent: () => boolean;\n}\n\nasync function reconcilePublications(\n entries: readonly {\n readonly options: RecoverPrincipalPolicyHistoryOptions;\n }[],\n publications: readonly AcknowledgedPrincipalCurrentPublication[],\n) {\n const reconciled = [];\n for (const [index, publication] of publications.entries()) {\n const entry = entries[index];\n if (!entry) throw new Error(\"Missing acknowledgement entry\");\n reconciled.push(\n await reconcileAcknowledgedPrincipalCurrent(entry.options, publication),\n );\n }\n return reconciled;\n}\n\ninterface OwnedAcknowledgementEntry {\n readonly initialGroup: boolean;\n readonly request: PutPrincipalPolicyRequest;\n readonly response: PrincipalPolicyMutationResponse;\n readonly options: RecoverPrincipalPolicyHistoryOptions;\n readonly predecessor: AcknowledgedPrincipalPredecessor | null;\n}\n\n/** Rebuild each acknowledged current from its owned request, then prepare it. */\nasync function preparePublications(\n entries: readonly OwnedAcknowledgementEntry[],\n checks: PrincipalAcknowledgementChecks,\n) {\n const currents: PrincipalPolicyPageCurrent[] = [];\n for (const entry of entries)\n currents.push(\n await checks.acknowledgedCurrent({\n request: entry.request,\n response: entry.response,\n }),\n );\n const publications: AcknowledgedPrincipalCurrentPublication[] = [];\n for (const [index, entry] of entries.entries()) {\n const current = currents[index];\n if (!current) throw new Error(\"Missing acknowledgement entry\");\n publications.push(\n await (entry.initialGroup\n ? prepareInitialGroupCurrentPublication\n : preparePublication)(\n entry.options,\n entry.request,\n current,\n entry.predecessor,\n checks,\n ),\n );\n }\n return { currents, publications };\n}\n\n/**\n * Extend authenticated local progress and retain exact acknowledged artifacts\n * atomically with pins, once `checks` accept each acknowledgement.\n */\nexport async function recordAcknowledgedPrincipalCurrents(\n input: AcknowledgedPrincipalCurrentBatch & {\n readonly checks: PrincipalAcknowledgementChecks;\n },\n): Promise<VerifiedPrincipalPolicyCurrent[]> {\n const checks = input.checks;\n const execSql = input.execSql;\n const organizationId = input.organizationId;\n const stillCurrent = input.stillCurrent;\n const retirements = structuredClone(input.retirements ?? []);\n const entries: OwnedAcknowledgementEntry[] = [];\n try {\n assertProjectionVerificationCurrent(stillCurrent);\n // Own every entry and protection key before the first await, so a caller\n // mutating a later receipt cannot change what this batch checks.\n for (const entry of input.entries)\n entries.push({\n initialGroup: entry.initialGroup === true,\n predecessor: structuredClone(entry.predecessor),\n request: structuredClone(entry.request),\n response: structuredClone(entry.response),\n options: {\n ...entry.recovery,\n expectedHead: structuredClone(entry.recovery.expectedHead),\n protection: ownPrincipalHistoryProtection(entry.recovery.protection),\n execSql,\n organizationId,\n stillCurrent,\n },\n });\n const { currents, publications } = await preparePublications(\n entries,\n checks,\n );\n checks.assertDirectoryBindings(organizationId, currents);\n for (let attempt = 0; ; attempt += 1) {\n const reconciled = await reconcilePublications(entries, publications);\n try {\n await persistAcknowledgedPrincipalCurrents({\n execSql,\n organizationId,\n entries: reconciled,\n retirements,\n stillCurrent: () =>\n stillCurrent() &&\n entries.every((entry) => !entry.options.signal?.aborted),\n });\n break;\n } catch (error) {\n if (\n !(error instanceof PrincipalAcknowledgementChangedError) ||\n attempt >= 7\n )\n throw error;\n }\n }\n return publications.map(({ policy }) => policy);\n } finally {\n for (const entry of entries) entry.options.protection.localKey.fill(0);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"acknowledgedPrincipalCurrents.js","sourceRoot":"","sources":["acknowledgedPrincipalCurrents.ts"],"names":[],"mappings":"AACA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAGL,oCAAoC,GACrC,MAAM,sEAAsE,CAAC;AAC9E,OAAO,EAAE,mCAAmC,EAAE,MAAM,gFAAgF,CAAC;AACrI,OAAO,EAAE,0BAA0B,EAAE,MAAM,uEAAuE,CAAC;AACnH,OAAO,EAAE,6BAA6B,EAAE,MAAM,qDAAqD,CAAC;AAGpG,OAAO,EACL,sCAAsC,EACtC,mCAAmC,GAC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,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC;IAClD,CAAC;YAAS,CAAC;QACT,KAAK,MAAM,KAAK,IAAI,OAAO;YAAE,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACzE,CAAC;AACH,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport {\n KeyingVerificationError,\n type VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyMutationResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport {\n type AcknowledgedPrincipalCurrentPublication,\n type AcknowledgedPrincipalCurrentRetirement,\n PrincipalAcknowledgementChangedError,\n} from \"../../../data/persistence/principalCurrentAcknowledgementPersistence\";\nimport { preparePrincipalHistoryEvidencePage } from \"../../../data/persistence/principalHistory/principalHistoryEvidencePersistence\";\nimport { PrincipalHistoryRepository } from \"../../../data/persistence/principalHistory/principalHistoryRepository\";\nimport { ownPrincipalHistoryProtection } from \"../../../data/principals/principalHistoryProtection\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { RecoverPrincipalPolicyHistoryOptions } from \"../historyRecovery/principalHistoryRecoveryTypes\";\nimport {\n assertPrincipalHistoryVerificationMode,\n principalHistoryVerificationContext,\n} from \"../historyRecovery/principalHistoryRecoveryVerification\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n publishVerifiedCurrent,\n} from \"../policyVerification\";\nimport {\n type AcknowledgedPrincipalPredecessor,\n restoreAcknowledgedPrincipalPredecessor,\n} from \"./acknowledgedPrincipalPredecessor\";\nimport { prepareInitialGroupCurrentPublication } from \"./initialPrincipalCurrentPublication\";\nimport type { PrincipalAcknowledgementChecks } from \"./principalAcknowledgementChecks\";\nimport {\n sealPrincipalCurrentPublication,\n sealPrincipalCurrentStage,\n} from \"./principalCurrentPublicationSeal\";\nimport { reconcileAcknowledgedPrincipalCurrent } from \"./reconcileAcknowledgedPrincipalCurrent\";\n\nexport interface AcknowledgedPrincipalCurrentInput {\n /** Capture before submitting the mutation; null only for a new group. */\n readonly predecessor: AcknowledgedPrincipalPredecessor | null;\n /** Only a newly authored group at version one; never skips a predecessor. */\n readonly initialGroup?: boolean | undefined;\n /** The same scoped protection and verification mode used to recover the predecessor. */\n readonly recovery: Omit<\n RecoverPrincipalPolicyHistoryOptions,\n \"execSql\" | \"organizationId\" | \"stillCurrent\"\n >;\n readonly request: PutPrincipalPolicyRequest;\n readonly response: PrincipalPolicyMutationResponse;\n}\n\nasync function preparePublication(\n options: RecoverPrincipalPolicyHistoryOptions,\n request: PutPrincipalPolicyRequest,\n current: PrincipalPolicyPageCurrent,\n predecessor: AcknowledgedPrincipalPredecessor | null,\n checks: PrincipalAcknowledgementChecks,\n): Promise<AcknowledgedPrincipalCurrentPublication> {\n options = {\n ...options,\n protection: {\n ...options.protection,\n context: principalHistoryVerificationContext(options),\n },\n };\n const stillCurrent = () => !options.signal?.aborted && options.stillCurrent();\n assertProjectionVerificationCurrent(stillCurrent);\n const {\n scopeId,\n saved,\n artifacts,\n verifier,\n previous,\n predecessorIndexRootHash,\n } = await restoreAcknowledgedPrincipalPredecessor(options, predecessor);\n const expectedHead = await checks.authoredHead(request);\n const keys = await collectPrincipalPolicySignerPublicKeys({\n bundle: { ...current, previousStates: [] },\n resolveTrustedUserIdentity: options.resolveTrustedUserIdentity,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n if (\"error\" in keys)\n throw new KeyingVerificationError(\n keys.error === \"not-found\" ? \"missing_dependency\" : \"signer_mismatch\",\n \"Acknowledged principal signer could not be authenticated\",\n );\n const externalAuthority = await options.loadExternalAuthority?.(\n request.state.externalAuthority ? [request.state.externalAuthority] : [],\n );\n assertProjectionVerificationCurrent(stillCurrent);\n const policy = await checks.acknowledgeSuccessor({\n verifiedCurrentPolicy: previous,\n expectedHead,\n request,\n response: current.currentState,\n signerPublicKeys: keys.signerPublicKeys,\n externalAuthority,\n stillCurrent,\n });\n await publishVerifiedCurrent(options, current, stillCurrent);\n const entry = {\n state: current.currentState,\n projection: current.currentProjection,\n grants: current.currentGrants,\n };\n assertPrincipalHistoryVerificationMode(options, [entry]);\n const predecessorStage = await sealPrincipalCurrentStage(\n options,\n previous.state,\n verifier,\n artifacts,\n );\n const appended = await verifier.append({\n entries: [entry],\n signerPublicKeys: keys.signerPublicKeys,\n ...(externalAuthority ? { externalAuthority } : {}),\n });\n if (!appended.ok) throw appended.error;\n const sealed = await sealPrincipalCurrentPublication(\n options,\n scopeId,\n expectedHead,\n verifier,\n current,\n );\n assertProjectionVerificationCurrent(stillCurrent);\n return {\n policy,\n previousPrefixProgress: saved.progress,\n predecessorStage,\n predecessorIndexRootHash,\n ...sealed,\n evidence: await preparePrincipalHistoryEvidencePage({\n indexRootHash: appended.value.indexRootHash,\n scopeId,\n organizationId: options.organizationId,\n entries: [entry],\n nodes: appended.value.indexNodes,\n }),\n };\n}\n\n/** The acknowledged currents of one mutation, recorded together. */\nexport interface AcknowledgedPrincipalCurrentBatch {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly entries: readonly AcknowledgedPrincipalCurrentInput[];\n readonly retirements?:\n | readonly AcknowledgedPrincipalCurrentRetirement[]\n | undefined;\n readonly stillCurrent: () => boolean;\n}\n\nasync function reconcilePublications(\n entries: readonly {\n readonly options: RecoverPrincipalPolicyHistoryOptions;\n }[],\n publications: readonly AcknowledgedPrincipalCurrentPublication[],\n) {\n const reconciled = [];\n for (const [index, publication] of publications.entries()) {\n const entry = entries[index];\n if (!entry) throw new Error(\"Missing acknowledgement entry\");\n reconciled.push(\n await reconcileAcknowledgedPrincipalCurrent(entry.options, publication),\n );\n }\n return reconciled;\n}\n\ninterface OwnedAcknowledgementEntry {\n readonly initialGroup: boolean;\n readonly request: PutPrincipalPolicyRequest;\n readonly response: PrincipalPolicyMutationResponse;\n readonly options: RecoverPrincipalPolicyHistoryOptions;\n readonly predecessor: AcknowledgedPrincipalPredecessor | null;\n}\n\n/** Rebuild each acknowledged current from its owned request, then prepare it. */\nasync function preparePublications(\n entries: readonly OwnedAcknowledgementEntry[],\n checks: PrincipalAcknowledgementChecks,\n) {\n const currents: PrincipalPolicyPageCurrent[] = [];\n for (const entry of entries)\n currents.push(\n await checks.acknowledgedCurrent({\n request: entry.request,\n response: entry.response,\n }),\n );\n const publications: AcknowledgedPrincipalCurrentPublication[] = [];\n for (const [index, entry] of entries.entries()) {\n const current = currents[index];\n if (!current) throw new Error(\"Missing acknowledgement entry\");\n publications.push(\n await (entry.initialGroup\n ? prepareInitialGroupCurrentPublication\n : preparePublication)(\n entry.options,\n entry.request,\n current,\n entry.predecessor,\n checks,\n ),\n );\n }\n return { currents, publications };\n}\n\n/**\n * Extend authenticated local progress and retain exact acknowledged artifacts\n * atomically with pins, once `checks` accept each acknowledgement.\n */\nexport async function recordAcknowledgedPrincipalCurrents(\n input: AcknowledgedPrincipalCurrentBatch & {\n readonly checks: PrincipalAcknowledgementChecks;\n },\n): Promise<VerifiedPrincipalPolicyCurrent[]> {\n const checks = input.checks;\n const execSql = input.execSql;\n const organizationId = input.organizationId;\n const stillCurrent = input.stillCurrent;\n const retirements = structuredClone(input.retirements ?? []);\n const entries: OwnedAcknowledgementEntry[] = [];\n try {\n assertProjectionVerificationCurrent(stillCurrent);\n // Own every entry and protection key before the first await, so a caller\n // mutating a later receipt cannot change what this batch checks.\n for (const entry of input.entries)\n entries.push({\n initialGroup: entry.initialGroup === true,\n predecessor: structuredClone(entry.predecessor),\n request: structuredClone(entry.request),\n response: structuredClone(entry.response),\n options: {\n ...entry.recovery,\n expectedHead: structuredClone(entry.recovery.expectedHead),\n protection: ownPrincipalHistoryProtection(entry.recovery.protection),\n execSql,\n organizationId,\n stillCurrent,\n },\n });\n const { currents, publications } = await preparePublications(\n entries,\n checks,\n );\n checks.assertDirectoryBindings(organizationId, currents);\n for (let attempt = 0; ; attempt += 1) {\n const reconciled = await reconcilePublications(entries, publications);\n try {\n await new PrincipalHistoryRepository(\n execSql,\n ).persistAcknowledgedPrincipalCurrents({\n organizationId,\n entries: reconciled,\n retirements,\n stillCurrent: () =>\n stillCurrent() &&\n entries.every((entry) => !entry.options.signal?.aborted),\n });\n break;\n } catch (error) {\n if (\n !(error instanceof PrincipalAcknowledgementChangedError) ||\n attempt >= 7\n )\n throw error;\n }\n }\n return publications.map(({ policy }) => policy);\n } finally {\n for (const entry of entries) entry.options.protection.localKey.fill(0);\n }\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { PrincipalHistoryPrefix } from "../../../data/persistence/principalHistory/principalHistoryPrefixPersistence.js";
|
|
2
2
|
import type { RecoverPrincipalPolicyHistoryOptions } from "../historyRecovery/principalHistoryRecoveryTypes.js";
|
|
3
3
|
/** Sealed predecessor evidence, owned by a mutation before its request is sent. */
|
|
4
4
|
export type AcknowledgedPrincipalPredecessor = Readonly<PrincipalHistoryPrefix>;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { KeyingVerificationError, restorePrincipalPolicyHistoryVerifier, verifyPrincipalPolicyCurrent, } from "../../../internal/crypto/index.js";
|
|
2
2
|
import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
|
|
3
|
-
import {
|
|
3
|
+
import { PrincipalHistoryRepository } from "../../../data/persistence/principalHistory/principalHistoryRepository.js";
|
|
4
4
|
import { principalHeadMatchesReference } from "../../../data/principals/organizationAuthorityDescriptor.js";
|
|
5
5
|
import { principalHistoryEvidenceScopeId, principalHistoryPrefixProtection, } from "../../../data/principals/principalHistoryPrefixProtection.js";
|
|
6
6
|
import { ownPrincipalHistoryProtection } from "../../../data/principals/principalHistoryProtection.js";
|
|
@@ -68,7 +68,7 @@ export async function captureAcknowledgedPrincipalPredecessor(input) {
|
|
|
68
68
|
head: options.expectedHead,
|
|
69
69
|
protection: options.protection,
|
|
70
70
|
});
|
|
71
|
-
const restored = await restoreAcknowledgedPrincipalPrefix(options, await
|
|
71
|
+
const restored = await restoreAcknowledgedPrincipalPrefix(options, await new PrincipalHistoryRepository(options.execSql).loadPrincipalHistoryPrefix(scopeId));
|
|
72
72
|
assertProjectionVerificationCurrent(current);
|
|
73
73
|
if (!principalHeadMatchesReference(restored.previous.state, options.expectedHead))
|
|
74
74
|
throw new Error("Principal policy changed before submission; retry the mutation");
|