@tearleads/client-sdk 0.1.246 → 0.1.248

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/Tearleads.js +4 -2
  2. package/Tearleads.js.map +1 -1
  3. package/data/persistence/principalPolicy/heldOrganizationDirectories.js +53 -0
  4. package/data/persistence/principalPolicy/heldOrganizationDirectories.js.map +1 -0
  5. package/data/persistence/verifiedManifestBundlePersistence.d.ts +8 -3
  6. package/data/persistence/verifiedManifestBundlePersistence.js +34 -15
  7. package/data/persistence/verifiedManifestBundlePersistence.js.map +1 -1
  8. package/internal/api-client/ApiClient.d.ts +2 -0
  9. package/internal/api-client/client/session.d.ts +2 -0
  10. package/internal/api-client/heldDirectoryCitations.d.ts +19 -0
  11. package/internal/api-client/heldDirectoryCitations.js +37 -0
  12. package/internal/api-client/heldDirectoryCitations.js.map +1 -0
  13. package/internal/api-client/index.d.ts +1 -1
  14. package/internal/api-client/index.js.map +1 -1
  15. package/internal/api-client/verifiedManifestCitations.d.ts +16 -6
  16. package/internal/api-client/verifiedManifestCitations.js +32 -13
  17. package/internal/api-client/verifiedManifestCitations.js.map +1 -1
  18. package/internal/api-client/writerProjectionRequests.js +5 -3
  19. package/internal/api-client/writerProjectionRequests.js.map +1 -1
  20. package/internal/validators/knownManifestsRefinements.js +1 -1
  21. package/internal/validators/knownManifestsRefinements.js.map +1 -1
  22. package/internal/validators/operation/auth.d.ts +14 -0
  23. package/internal/validators/operation/auth.js +2 -1
  24. package/internal/validators/operation/auth.js.map +1 -1
  25. package/internal/validators/operation/writerProjections.d.ts +11 -11
  26. package/internal/validators/operation/writerProjections.js +1 -1
  27. package/internal/validators/operation/writerProjections.js.map +1 -1
  28. package/internal/validators/response/areas/auth.d.ts +1 -1
  29. package/internal/validators/response/areas/auth.js +1 -1
  30. package/internal/validators/response/areas/auth.js.map +1 -1
  31. package/internal/validators/response/areas/principals.d.ts +2 -1
  32. package/internal/validators/response/areas/principals.js +1 -1
  33. package/internal/validators/response/areas/principals.js.map +1 -1
  34. package/internal/validators/response/container.d.ts +4 -4
  35. package/internal/validators/response/container.js +2 -2
  36. package/internal/validators/response/container.js.map +1 -1
  37. package/internal/validators/response/documentMutation.d.ts +4 -4
  38. package/internal/validators/response/documentMutation.js +2 -2
  39. package/internal/validators/response/documentMutation.js.map +1 -1
  40. package/internal/validators/response/documentSyncSchema.d.ts +5 -0
  41. package/internal/validators/response/documentSyncSchema.js +1 -1
  42. package/internal/validators/response/documentSyncSchema.js.map +1 -1
  43. package/internal/validators/response/policyEvidenceWire.d.ts +17 -0
  44. package/internal/validators/response/policyEvidenceWire.js +36 -0
  45. package/internal/validators/response/policyEvidenceWire.js.map +1 -0
  46. package/internal/validators/response/projectionPolicyEvidence.d.ts +175 -0
  47. package/internal/validators/response/projectionPolicyEvidence.js +13 -0
  48. package/internal/validators/response/projectionPolicyEvidence.js.map +1 -1
  49. package/internal/validators/response/registration.d.ts +17 -1
  50. package/internal/validators/response/registration.js +31 -2
  51. package/internal/validators/response/registration.js.map +1 -1
  52. package/internal/validators/response/writerProjectionWire.d.ts +11 -7
  53. package/internal/validators/response/writerProjectionWire.js +19 -10
  54. package/internal/validators/response/writerProjectionWire.js.map +1 -1
  55. package/internal/validators/util/index.d.ts +1 -1
  56. package/internal/validators/util/index.js +1 -1
  57. package/internal/validators/util/index.js.map +1 -1
  58. package/internal/validators/util/knownManifestWire.d.ts +9 -3
  59. package/internal/validators/util/knownManifestWire.js +24 -8
  60. package/internal/validators/util/knownManifestWire.js.map +1 -1
  61. package/package.json +1 -1
  62. package/workflows/registration/organizationCreation/createOrganization.js +3 -0
  63. package/workflows/registration/organizationCreation/createOrganization.js.map +1 -1
  64. package/workflows/registration/organizationProvisioningPersistence.d.ts +7 -0
  65. package/workflows/registration/organizationProvisioningPersistence.js +1 -0
  66. package/workflows/registration/organizationProvisioningPersistence.js.map +1 -1
  67. package/workflows/registration/persistRegistrationBootstrap.d.ts +7 -0
  68. package/workflows/registration/persistRegistrationBootstrap.js +6 -2
  69. package/workflows/registration/persistRegistrationBootstrap.js.map +1 -1
  70. package/workflows/registration/registerIdentity.js +1 -0
  71. package/workflows/registration/registerIdentity.js.map +1 -1
@@ -4,17 +4,23 @@ import { z } from "zod";
4
4
  * receives: an uncited manifest or KEK level always travels.
5
5
  */
6
6
  export declare const KNOWN_MANIFEST_HINT_LIMIT = 48;
7
+ /**
8
+ * Organization directory states one request may declare held, beside its
9
+ * manifest and KEK-level hints.
10
+ */
11
+ export declare const KNOWN_DIRECTORY_HINT_LIMIT = 8;
7
12
  /** The typed digests one request declares held. */
8
13
  export interface KnownManifestHints {
9
14
  readonly manifests: readonly string[];
10
15
  readonly kekLevels: readonly string[];
16
+ readonly directories: readonly string[];
11
17
  }
12
18
  /**
13
- * Null unless the header is 1–48 unique typed entries, each `m:` or `k:`
14
- * followed by a lowercase SHA-256 hex digest.
19
+ * Null unless the header is unique typed entries, at most 48 `m:` or `k:`
20
+ * and at most 8 `d:`, each followed by a lowercase SHA-256 hex digest.
15
21
  */
16
22
  export declare function parseKnownManifestHints(value: string): KnownManifestHints | null;
17
- /** The header value for `hints`; callers keep the total within the limit. */
23
+ /** The header value for `hints`; callers keep each kind within its limit. */
18
24
  export declare function formatKnownManifestHints(hints: KnownManifestHints): string;
19
25
  export declare const KnownManifestsHeadersSchema: z.ZodObject<{
20
26
  "x-known-manifests": z.ZodOptional<z.ZodString>;
@@ -7,23 +7,33 @@ import { isSha256HexString, SHA256_HEX_LENGTH } from "./protocol.js";
7
7
  * receives: an uncited manifest or KEK level always travels.
8
8
  */
9
9
  export const KNOWN_MANIFEST_HINT_LIMIT = 48;
10
- /** `m:` cites a manifest bundle by hash, `k:` a KEK level by digest. */
10
+ /**
11
+ * Organization directory states one request may declare held, beside its
12
+ * manifest and KEK-level hints.
13
+ */
14
+ export const KNOWN_DIRECTORY_HINT_LIMIT = 8;
15
+ /**
16
+ * `m:` cites a manifest bundle by hash, `k:` a KEK level by digest, `d:` an
17
+ * organization directory payload by its signed state's hash.
18
+ */
11
19
  const MANIFEST_HINT_PREFIX = "m:";
12
20
  const KEK_LEVEL_HINT_PREFIX = "k:";
13
- const KNOWN_MANIFEST_HINT_CHARACTERS = KNOWN_MANIFEST_HINT_LIMIT *
21
+ const DIRECTORY_HINT_PREFIX = "d:";
22
+ const KNOWN_MANIFEST_HINT_CHARACTERS = (KNOWN_MANIFEST_HINT_LIMIT + KNOWN_DIRECTORY_HINT_LIMIT) *
14
23
  (MANIFEST_HINT_PREFIX.length + SHA256_HEX_LENGTH + 1) -
15
24
  1;
16
25
  /**
17
- * Null unless the header is 1–48 unique typed entries, each `m:` or `k:`
18
- * followed by a lowercase SHA-256 hex digest.
26
+ * Null unless the header is unique typed entries, at most 48 `m:` or `k:`
27
+ * and at most 8 `d:`, each followed by a lowercase SHA-256 hex digest.
19
28
  */
20
29
  export function parseKnownManifestHints(value) {
21
30
  const entries = value.split(",");
22
- if (entries.length > KNOWN_MANIFEST_HINT_LIMIT ||
31
+ if (entries.length > KNOWN_MANIFEST_HINT_LIMIT + KNOWN_DIRECTORY_HINT_LIMIT ||
23
32
  new Set(entries).size !== entries.length)
24
33
  return null;
25
34
  const manifests = [];
26
35
  const kekLevels = [];
36
+ const directories = [];
27
37
  for (const entry of entries) {
28
38
  const digest = entry.slice(MANIFEST_HINT_PREFIX.length);
29
39
  if (!isSha256HexString(digest))
@@ -32,22 +42,28 @@ export function parseKnownManifestHints(value) {
32
42
  manifests.push(digest);
33
43
  else if (entry.startsWith(KEK_LEVEL_HINT_PREFIX))
34
44
  kekLevels.push(digest);
45
+ else if (entry.startsWith(DIRECTORY_HINT_PREFIX))
46
+ directories.push(digest);
35
47
  else
36
48
  return null;
37
49
  }
38
- return { manifests, kekLevels };
50
+ if (manifests.length + kekLevels.length > KNOWN_MANIFEST_HINT_LIMIT ||
51
+ directories.length > KNOWN_DIRECTORY_HINT_LIMIT)
52
+ return null;
53
+ return { manifests, kekLevels, directories };
39
54
  }
40
- /** The header value for `hints`; callers keep the total within the limit. */
55
+ /** The header value for `hints`; callers keep each kind within its limit. */
41
56
  export function formatKnownManifestHints(hints) {
42
57
  return [
43
58
  ...hints.kekLevels.map((digest) => `${KEK_LEVEL_HINT_PREFIX}${digest}`),
44
59
  ...hints.manifests.map((hash) => `${MANIFEST_HINT_PREFIX}${hash}`),
60
+ ...hints.directories.map((hash) => `${DIRECTORY_HINT_PREFIX}${hash}`),
45
61
  ].join(",");
46
62
  }
47
63
  const hintHeader = registerJsonSchemaFragment(z.string().max(KNOWN_MANIFEST_HINT_CHARACTERS), {
48
64
  type: "string",
49
65
  maxLength: KNOWN_MANIFEST_HINT_CHARACTERS,
50
- description: `Comma-separated typed digests the device holds verified: m:<manifest hash> for an access-manifest bundle, k:<level digest> for a container KEK level; at most ${KNOWN_MANIFEST_HINT_LIMIT}, unique`,
66
+ description: `Comma-separated typed digests the device holds verified: m:<manifest hash> for an access-manifest bundle, k:<level digest> for a container KEK level (at most ${KNOWN_MANIFEST_HINT_LIMIT} of these), d:<organization state hash> for that state's directory payload (at most ${KNOWN_DIRECTORY_HINT_LIMIT}); unique`,
51
67
  });
52
68
  export const KnownManifestsHeadersSchema = z.object({
53
69
  "x-known-manifests": registerJsonSchemaRuntimeRefinements(hintHeader.refine((value) => parseKnownManifestHints(value) !== null), [knownManifestsHeaderRefinement]).optional(),
@@ -1 +1 @@
1
- {"version":3,"file":"knownManifestWire.js","sourceRoot":"","sources":["knownManifestWire.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EACL,0BAA0B,EAC1B,oCAAoC,GACrC,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,8BAA8B,EAAE,MAAM,8BAA8B,CAAC;AAC9E,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAElE;;;GAGG;AACH,MAAM,CAAC,MAAM,yBAAyB,GAAG,EAAE,CAAC;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KAAK,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,GAAG,oBAAoB,GAAG,IAAI,EAAE,CAAC;KACnE,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACd,CAAC;AAED,MAAM,UAAU,GAAG,0BAA0B,CAC3C,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,8BAA8B,CAAC,EAC9C;IACE,IAAI,EAAE,QAAQ;IACd,SAAS,EAAE,8BAA8B;IACzC,WAAW,EAAE,iKAAiK,yBAAyB,UAAU;CAClN,CACF,CAAC;AAEF,MAAM,CAAC,MAAM,2BAA2B,GAAG,CAAC,CAAC,MAAM,CAAC;IAClD,mBAAmB,EAAE,oCAAoC,CACvD,UAAU,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,uBAAuB,CAAC,KAAK,CAAC,KAAK,IAAI,CAAC,EACrE,CAAC,8BAA8B,CAAC,CACjC,CAAC,QAAQ,EAAE;CACb,CAAC,CAAC","sourcesContent":["import { z } from \"zod\";\nimport {\n registerJsonSchemaFragment,\n registerJsonSchemaRuntimeRefinements,\n} from \"../jsonSchema\";\nimport { knownManifestsHeaderRefinement } from \"../knownManifestsRefinements\";\nimport { isSha256HexString, SHA256_HEX_LENGTH } from \"./protocol\";\n\n/**\n * Hints bound the omission a request can ask for, never the history a reader\n * receives: an uncited manifest or KEK level always travels.\n */\nexport const KNOWN_MANIFEST_HINT_LIMIT = 48;\n/** `m:` cites a manifest bundle by hash, `k:` a KEK level by digest. */\nconst MANIFEST_HINT_PREFIX = \"m:\";\nconst KEK_LEVEL_HINT_PREFIX = \"k:\";\nconst KNOWN_MANIFEST_HINT_CHARACTERS =\n KNOWN_MANIFEST_HINT_LIMIT *\n (MANIFEST_HINT_PREFIX.length + SHA256_HEX_LENGTH + 1) -\n 1;\n\n/** The typed digests one request declares held. */\nexport interface KnownManifestHints {\n readonly manifests: readonly string[];\n readonly kekLevels: readonly string[];\n}\n\n/**\n * Null unless the header is 1–48 unique typed entries, each `m:` or `k:`\n * followed by a lowercase SHA-256 hex digest.\n */\nexport function parseKnownManifestHints(\n value: string,\n): KnownManifestHints | null {\n const entries = value.split(\",\");\n if (\n entries.length > KNOWN_MANIFEST_HINT_LIMIT ||\n new Set(entries).size !== entries.length\n )\n return null;\n const manifests: string[] = [];\n const kekLevels: string[] = [];\n for (const entry of entries) {\n const digest = entry.slice(MANIFEST_HINT_PREFIX.length);\n if (!isSha256HexString(digest)) return null;\n if (entry.startsWith(MANIFEST_HINT_PREFIX)) manifests.push(digest);\n else if (entry.startsWith(KEK_LEVEL_HINT_PREFIX)) kekLevels.push(digest);\n else return null;\n }\n return { manifests, kekLevels };\n}\n\n/** The header value for `hints`; callers keep the total within the limit. */\nexport function formatKnownManifestHints(hints: KnownManifestHints): string {\n return [\n ...hints.kekLevels.map((digest) => `${KEK_LEVEL_HINT_PREFIX}${digest}`),\n ...hints.manifests.map((hash) => `${MANIFEST_HINT_PREFIX}${hash}`),\n ].join(\",\");\n}\n\nconst hintHeader = registerJsonSchemaFragment(\n z.string().max(KNOWN_MANIFEST_HINT_CHARACTERS),\n {\n type: \"string\",\n maxLength: KNOWN_MANIFEST_HINT_CHARACTERS,\n description: `Comma-separated typed digests the device holds verified: m:<manifest hash> for an access-manifest bundle, k:<level digest> for a container KEK level; at most ${KNOWN_MANIFEST_HINT_LIMIT}, unique`,\n },\n);\n\nexport const KnownManifestsHeadersSchema = z.object({\n \"x-known-manifests\": registerJsonSchemaRuntimeRefinements(\n hintHeader.refine((value) => parseKnownManifestHints(value) !== null),\n [knownManifestsHeaderRefinement],\n ).optional(),\n});\n"]}
1
+ {"version":3,"file":"knownManifestWire.js","sourceRoot":"","sources":["knownManifestWire.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EACL,0BAA0B,EAC1B,oCAAoC,GACrC,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,8BA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,uBAAuB,CAAC,KAAK,CAAC,KAAK,IAAI,CAAC,EACrE,CAAC,8BAA8B,CAAC,CACjC,CAAC,QAAQ,EAAE;CACb,CAAC,CAAC","sourcesContent":["import { z } from \"zod\";\nimport {\n registerJsonSchemaFragment,\n registerJsonSchemaRuntimeRefinements,\n} from \"../jsonSchema\";\nimport { knownManifestsHeaderRefinement } from \"../knownManifestsRefinements\";\nimport { isSha256HexString, SHA256_HEX_LENGTH } from \"./protocol\";\n\n/**\n * Hints bound the omission a request can ask for, never the history a reader\n * receives: an uncited manifest or KEK level always travels.\n */\nexport const KNOWN_MANIFEST_HINT_LIMIT = 48;\n/**\n * Organization directory states one request may declare held, beside its\n * manifest and KEK-level hints.\n */\nexport const KNOWN_DIRECTORY_HINT_LIMIT = 8;\n/**\n * `m:` cites a manifest bundle by hash, `k:` a KEK level by digest, `d:` an\n * organization directory payload by its signed state's hash.\n */\nconst MANIFEST_HINT_PREFIX = \"m:\";\nconst KEK_LEVEL_HINT_PREFIX = \"k:\";\nconst DIRECTORY_HINT_PREFIX = \"d:\";\nconst KNOWN_MANIFEST_HINT_CHARACTERS =\n (KNOWN_MANIFEST_HINT_LIMIT + KNOWN_DIRECTORY_HINT_LIMIT) *\n (MANIFEST_HINT_PREFIX.length + SHA256_HEX_LENGTH + 1) -\n 1;\n\n/** The typed digests one request declares held. */\nexport interface KnownManifestHints {\n readonly manifests: readonly string[];\n readonly kekLevels: readonly string[];\n readonly directories: readonly string[];\n}\n\n/**\n * Null unless the header is unique typed entries, at most 48 `m:` or `k:`\n * and at most 8 `d:`, each followed by a lowercase SHA-256 hex digest.\n */\nexport function parseKnownManifestHints(\n value: string,\n): KnownManifestHints | null {\n const entries = value.split(\",\");\n if (\n entries.length > KNOWN_MANIFEST_HINT_LIMIT + KNOWN_DIRECTORY_HINT_LIMIT ||\n new Set(entries).size !== entries.length\n )\n return null;\n const manifests: string[] = [];\n const kekLevels: string[] = [];\n const directories: string[] = [];\n for (const entry of entries) {\n const digest = entry.slice(MANIFEST_HINT_PREFIX.length);\n if (!isSha256HexString(digest)) return null;\n if (entry.startsWith(MANIFEST_HINT_PREFIX)) manifests.push(digest);\n else if (entry.startsWith(KEK_LEVEL_HINT_PREFIX)) kekLevels.push(digest);\n else if (entry.startsWith(DIRECTORY_HINT_PREFIX)) directories.push(digest);\n else return null;\n }\n if (\n manifests.length + kekLevels.length > KNOWN_MANIFEST_HINT_LIMIT ||\n directories.length > KNOWN_DIRECTORY_HINT_LIMIT\n )\n return null;\n return { manifests, kekLevels, directories };\n}\n\n/** The header value for `hints`; callers keep each kind within its limit. */\nexport function formatKnownManifestHints(hints: KnownManifestHints): string {\n return [\n ...hints.kekLevels.map((digest) => `${KEK_LEVEL_HINT_PREFIX}${digest}`),\n ...hints.manifests.map((hash) => `${MANIFEST_HINT_PREFIX}${hash}`),\n ...hints.directories.map((hash) => `${DIRECTORY_HINT_PREFIX}${hash}`),\n ].join(\",\");\n}\n\nconst hintHeader = registerJsonSchemaFragment(\n z.string().max(KNOWN_MANIFEST_HINT_CHARACTERS),\n {\n type: \"string\",\n maxLength: KNOWN_MANIFEST_HINT_CHARACTERS,\n description: `Comma-separated typed digests the device holds verified: m:<manifest hash> for an access-manifest bundle, k:<level digest> for a container KEK level (at most ${KNOWN_MANIFEST_HINT_LIMIT} of these), d:<organization state hash> for that state's directory payload (at most ${KNOWN_DIRECTORY_HINT_LIMIT}); unique`,\n },\n);\n\nexport const KnownManifestsHeadersSchema = z.object({\n \"x-known-manifests\": registerJsonSchemaRuntimeRefinements(\n hintHeader.refine((value) => parseKnownManifestHints(value) !== null),\n [knownManifestsHeaderRefinement],\n ).optional(),\n});\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tearleads/client-sdk",
3
- "version": "0.1.246",
3
+ "version": "0.1.248",
4
4
  "description": "React-free Tearleads client runtime: local SQLite persistence, keys, sync, encrypted blobs, and domain workflows.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -108,6 +108,9 @@ export async function createOrganization(input) {
108
108
  ...artifacts,
109
109
  completeProvisioningAttempt: organizationCreationCompletion(input, artifacts.organizationId),
110
110
  canStartDurableMutation: input.isIdentityCurrent,
111
+ // No position: the seeded documents are read once, as another session of
112
+ // this user may already have edited them.
113
+ commitLsn: null,
111
114
  onPersistQueued: input.onPersistQueued,
112
115
  containerId: durableRootContainerId,
113
116
  dbClient: input.dbClient,
@@ -1 +1 @@
1
- {"version":3,"file":"createOrganization.js","sourceRoot":"","sources":["createOrganization.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,wCAAwC,GACzC,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EAAE,aAAa,EAAE,MAAM,gCAAgC,CAAC;AAC/D,OAAO,EACL,sCAAsC,EAItC,oCAAoC,GACrC,MAAM,6BAA6B,CAAC;AAErC,OAAO,EAEL,8BAA8B,EAC9B,0BAA0B,EAC1B,2BAA2B,GAC5B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,0CAA0C,EAC1C,kDAAkD,GACnD,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,kCAAkC,EAAE,MAAM,uCAAuC,CAAC;AAG3F,OAAO,EAAE,kDAAkD,EAAE,CAAC;AA+C9D,SAAS,4BAA4B,CAAC,KAIrC;IACC,IACE,KAAK,CAAC,QAAQ,CAAC,cAAc,KAAK,KAAK,CAAC,OAAO,CAAC,cAAc;QAC9D,KAAK,CAAC,QAAQ,CAAC,eAAe,KAAK,KAAK,CAAC,OAAO,CAAC,eAAe,EAChE,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IACD,IACE,CAAC,KAAK,CAAC,QAAQ,CAAC,sBAAsB;QACtC,KAAK,CAAC,QAAQ,CAAC,MAAM,KAAK,KAAK,CAAC,QAAQ,CAAC,MAAM,EAC/C,CAAC;QACD,MAAM,IAAI,KAAK,CACb,+DAA+D,CAChE,CAAC;IACJ,CAAC;IACD,KAAK,CAAC,QAAQ,CAAC,GAAG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,KAAK,CAAC,sBAAsB;YACpD,QAAQ;YACR,gBAAgB,EAAE,KAAK,CAAC,cAAc,CAAC,gBAAgB;YACvD,MAAM,EAAE,KAAK,CAAC,MAAM;YACpB,OAAO,EAAE,aAAa,CAAC,KAAK,CAAC,QAAQ,CAAC;YACtC,YAAY,EAAE,KAAK,CAAC,iBAAiB;SACtC,CAAC,CAAC;QAEH,OAAO,IAAI,CAAC;IAEd,IAAI,4BAA4B,CAAC,EAAE,QAAQ,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,EAAE,CAAC;QACzE,yEAAyE;QACzE,4DAA4D;QAC5D,yEAAyE;QACzE,0EAA0E;QAC1E,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,KAAK,CAAC,GAAG,EAAE,CAAC,yBAAyB,QAAQ,CAAC,cAAc,GAAG,CAAC,CAAC;IACjE,MAAM,oCAAoC,CAAC;QACzC,GAAG,SAAS;QACZ,2BAA2B,EAAE,8BAA8B,CACzD,KAAK,EACL,SAAS,CAAC,cAAc,CACzB;QACD,uBAAuB,EAAE,KAAK,CAAC,iBAAiB;QAChD,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,WAAW,EAAE,sBAAsB;QACnC,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;QAC5C,GAAG,EAAE,KAAK,CAAC,GAAG;QACd,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,qBAAqB,EAAE,KAAK,CAAC,qBAAqB;QAClD,QAAQ;KACT,CAAC,CAAC;IAEH,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import {\n type EncapsulationKeyPair,\n type SigningKeyPair,\n signOrganizationReplacementAuthorization,\n} from \"@tearleads/crypto\";\nimport type { CreateOrganizationRequest } from \"@tearleads/validators/request\";\nimport type { CreateOrganizationResponse } from \"@tearleads/validators/response\";\nimport type { DocumentProjectorRegistryInput } from \"../../../data/documents/documentKinds\";\nimport type { ExecSqlClientLike } from \"../../../data/sqlite/sqlSchema\";\nimport { createExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n buildOrganizationProvisioningArtifacts,\n type OrganizationProvisioningArtifacts,\n type OrganizationProvisioningArtifactsInput,\n type ProvisionedSystemContainerSpec,\n persistOrganizationProvisioningState,\n} from \"../organizationProvisioning\";\nimport type { ProvisionedStatePrimer } from \"../provisionedStatePrimer\";\nimport {\n type CreateOrganizationApi,\n organizationCreationCompletion,\n organizationCreationIntent,\n requestOrganizationCreation,\n} from \"./organizationCreationIntent\";\nimport {\n makeOrganizationProvisioningAttemptDurable,\n removeNativeSubscriptionRestoreProvisioningAttempt,\n} from \"./organizationProvisioningAttempt\";\nimport { pinOrganizationReplacementResponse } from \"./organizationReplacementVerification\";\n\nexport type { CreateOrganizationApi } from \"./organizationCreationIntent\";\nexport { removeNativeSubscriptionRestoreProvisioningAttempt };\n\nexport interface CreateOrganizationInput {\n identityTrustDomain: string;\n apiClient: CreateOrganizationApi;\n dbClient: ExecSqlClientLike;\n documentProjectors?: DocumentProjectorRegistryInput | undefined;\n encapsulationKeyPair: EncapsulationKeyPair;\n /**\n * Returns false once the identity that supplied the key pairs is no longer\n * active. Checked before the remote create (so a stale request is never\n * submitted) and again before local persistence: an identity switch closes\n * or renews the captured database client, so persisting would write another\n * identity's bootstrap — or throw — after the org already exists remotely.\n * The caller discards the result.\n */\n isIdentityCurrent?: (() => boolean) | undefined;\n /** @internal Forwarded to the bootstrap persist; test-only seam. */\n onPersistQueued?: (() => void) | undefined;\n log?: ((message: string) => void) | undefined;\n logError?: ((message: string | Error, cause?: unknown) => void) | undefined;\n /** Overrides the seeded organization profile name; see registration. */\n organizationProfileName?: string | undefined;\n /** Seeds what the committed bootstrap already proves. */\n primeProvisionedState?: ProvisionedStatePrimer | undefined;\n /**\n * App-owned system containers to provision atomically with the new\n * organization (e.g. a trash bin). See registration.\n */\n provisionedSystemContainers?:\n | ReadonlyArray<ProvisionedSystemContainerSpec>\n | undefined;\n /** Purged organization whose personal-org generation this replaces. */\n replacesOrganizationId?: string | undefined;\n /** Marks and durably replays a fresh native-subscription restore target. */\n nativeSubscriptionRestore?: boolean | undefined;\n /** Overrides the seeded self roster-profile nickname; see registration. */\n rosterProfileNickname?: string | undefined;\n signingKeyPair: SigningKeyPair;\n /**\n * The already-registered user creating the organization; they become its\n * founding admin. The server independently requires this to match the\n * authenticated session.\n */\n userId: string;\n}\n\nfunction isAdoptedReplacementResponse(input: {\n creation: CreateOrganizationInput;\n request: CreateOrganizationRequest;\n response: CreateOrganizationResponse;\n}): boolean {\n if (\n input.response.organizationId === input.request.organizationId &&\n input.response.rootContainerId === input.request.rootContainerId\n ) {\n return false;\n }\n if (\n !input.creation.replacesOrganizationId ||\n input.response.userId !== input.creation.userId\n ) {\n throw new Error(\n \"Organization provisioning returned an unexpected organization\",\n );\n }\n input.creation.log?.(\n `Organization replacement adopted (${input.response.organizationId})`,\n );\n return true;\n}\n\nasync function buildOrganizationCandidate(\n input: CreateOrganizationInput,\n rootContainerId: string,\n): Promise<OrganizationProvisioningArtifacts | null> {\n const artifactsInput: OrganizationProvisioningArtifactsInput = {\n identityTrustDomain: input.identityTrustDomain,\n encapsulationKeyPair: input.encapsulationKeyPair,\n organizationProfileName: input.organizationProfileName,\n provisionedSystemContainers: input.provisionedSystemContainers,\n rootContainerId,\n rosterProfileNickname: input.rosterProfileNickname,\n signingKeyPair: input.signingKeyPair,\n userId: input.userId,\n };\n const artifacts: OrganizationProvisioningArtifacts =\n await buildOrganizationProvisioningArtifacts(artifactsInput);\n\n if (input.replacesOrganizationId) {\n artifacts.replacementAuthorization =\n await signOrganizationReplacementAuthorization(\n {\n ...artifacts,\n replacesOrganizationId: input.replacesOrganizationId,\n rootContainerId,\n userId: input.userId,\n },\n input.signingKeyPair,\n );\n }\n\n if (\n input.replacesOrganizationId &&\n input.isIdentityCurrent &&\n !input.isIdentityCurrent()\n ) {\n input.log?.(\n \"Organization creation aborted: identity changed while building artifacts\",\n );\n return null;\n }\n\n return artifacts;\n}\n\n/**\n * Provisions an additional organization for an already-registered user, reusing\n * the exact artifact-build and local-persistence path as registration\n * ({@link buildOrganizationProvisioningArtifacts} /\n * {@link persistOrganizationProvisioningState}). Unlike registration it mints a\n * fresh root container id, signs with the caller's existing identity, and needs\n * no auth challenge — the user is already authenticated.\n */\nexport async function createOrganization(\n input: CreateOrganizationInput,\n): Promise<CreateOrganizationResponse | null> {\n input.log?.(\"Creating organization...\");\n\n const rootContainerId = crypto.randomUUID();\n const candidateArtifacts = await buildOrganizationCandidate(\n input,\n rootContainerId,\n );\n\n if (!candidateArtifacts) return null;\n\n const durableAttempt = await makeOrganizationProvisioningAttemptDurable({\n artifacts: candidateArtifacts,\n creationIntent: organizationCreationIntent(input),\n canStartDurableMutation: input.isIdentityCurrent,\n dbClient: input.dbClient,\n nativeSubscriptionRestore: input.nativeSubscriptionRestore,\n replacesOrganizationId: input.replacesOrganizationId,\n rootContainerId,\n userId: input.userId,\n });\n if (!durableAttempt) {\n input.log?.(\n \"Organization creation aborted: identity changed before saving artifacts\",\n );\n return null;\n }\n const {\n artifacts,\n request,\n rootContainerId: durableRootContainerId,\n } = durableAttempt;\n\n if (input.isIdentityCurrent && !input.isIdentityCurrent()) {\n input.log?.(\n \"Organization creation aborted: identity changed before provisioning\",\n );\n return null;\n }\n\n const response = await requestOrganizationCreation(input, request);\n if (!response) return null;\n\n if (input.isIdentityCurrent && !input.isIdentityCurrent()) {\n input.log?.(\n \"Organization creation discarded: identity changed while provisioning\",\n );\n return null;\n }\n\n if (\n input.replacesOrganizationId &&\n !(await pinOrganizationReplacementResponse({\n replacesOrganizationId: input.replacesOrganizationId,\n response,\n signingPublicKey: input.signingKeyPair.signingPublicKey,\n userId: input.userId,\n execSql: createExecSql(input.dbClient),\n stillCurrent: input.isIdentityCurrent,\n }))\n )\n return null;\n\n if (isAdoptedReplacementResponse({ creation: input, request, response })) {\n // Another device authorized this winning genesis with the same identity.\n // Its encrypted bootstrap will hydrate normally; persisting\n // this device's losing candidate would instead create an unrelated local\n // root. The session reset rebinds retained local data to the winning ids.\n return response;\n }\n\n input.log?.(`Organization created (${response.organizationId})`);\n await persistOrganizationProvisioningState({\n ...artifacts,\n completeProvisioningAttempt: organizationCreationCompletion(\n input,\n artifacts.organizationId,\n ),\n canStartDurableMutation: input.isIdentityCurrent,\n onPersistQueued: input.onPersistQueued,\n containerId: durableRootContainerId,\n dbClient: input.dbClient,\n documentProjectors: input.documentProjectors,\n log: input.log,\n logError: input.logError,\n primeProvisionedState: input.primeProvisionedState,\n response,\n });\n\n return response;\n}\n"]}
1
+ {"version":3,"file":"createOrganization.js","sourceRoot":"","sources":["createOrganization.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,wCAAwC,GACzC,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EAAE,aAAa,EAAE,MAAM,gCAAgC,CAAC;AAC/D,OAAO,EACL,sCAAsC,EAItC,oCAAoC,GACrC,MAAM,6BAA6B,CAAC;AAErC,OAAO,EAEL,8BAA8B,EAC9B,0BAA0B,EAC1B,2BAA2B,GAC5B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,0CAA0C,EAC1C,kDAAkD,GACnD,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,kCAAkC,EAAE,MAAM,uCAAuC,CAAC;AAG3F,OAAO,EAAE,kDAAkD,EAAE,CAAC;AA+C9D,SAAS,4BAA4B,CAAC,KAIrC;IACC,IACE,KAAK,CAAC,QAAQ,CAAC,cAAc,KAAK,KAAK,CAAC,OAAO,CAAC,cAAc;QAC9D,KAAK,CAAC,QAAQ,CAAC,eAAe,KAAK,KAAK,CAAC,OAAO,CAAC,eAAe,EAChE,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IACD,IACE,CAAC,KAAK,CAAC,QAAQ,CAAC,sBAAsB;QACtC,KAAK,CAAC,QAAQ,CAAC,MAAM,KAAK,KAAK,CAAC,QAAQ,CAAC,MAAM,EAC/C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uthorization,\n} from \"@tearleads/crypto\";\nimport type { CreateOrganizationRequest } from \"@tearleads/validators/request\";\nimport type { CreateOrganizationResponse } from \"@tearleads/validators/response\";\nimport type { DocumentProjectorRegistryInput } from \"../../../data/documents/documentKinds\";\nimport type { ExecSqlClientLike } from \"../../../data/sqlite/sqlSchema\";\nimport { createExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n buildOrganizationProvisioningArtifacts,\n type OrganizationProvisioningArtifacts,\n type OrganizationProvisioningArtifactsInput,\n type ProvisionedSystemContainerSpec,\n persistOrganizationProvisioningState,\n} from \"../organizationProvisioning\";\nimport type { ProvisionedStatePrimer } from \"../provisionedStatePrimer\";\nimport {\n type CreateOrganizationApi,\n organizationCreationCompletion,\n organizationCreationIntent,\n requestOrganizationCreation,\n} from \"./organizationCreationIntent\";\nimport {\n makeOrganizationProvisioningAttemptDurable,\n removeNativeSubscriptionRestoreProvisioningAttempt,\n} from \"./organizationProvisioningAttempt\";\nimport { pinOrganizationReplacementResponse } from \"./organizationReplacementVerification\";\n\nexport type { CreateOrganizationApi } from \"./organizationCreationIntent\";\nexport { removeNativeSubscriptionRestoreProvisioningAttempt };\n\nexport interface CreateOrganizationInput {\n identityTrustDomain: string;\n apiClient: CreateOrganizationApi;\n dbClient: ExecSqlClientLike;\n documentProjectors?: DocumentProjectorRegistryInput | undefined;\n encapsulationKeyPair: EncapsulationKeyPair;\n /**\n * Returns false once the identity that supplied the key pairs is no longer\n * active. Checked before the remote create (so a stale request is never\n * submitted) and again before local persistence: an identity switch closes\n * or renews the captured database client, so persisting would write another\n * identity's bootstrap — or throw — after the org already exists remotely.\n * The caller discards the result.\n */\n isIdentityCurrent?: (() => boolean) | undefined;\n /** @internal Forwarded to the bootstrap persist; test-only seam. */\n onPersistQueued?: (() => void) | undefined;\n log?: ((message: string) => void) | undefined;\n logError?: ((message: string | Error, cause?: unknown) => void) | undefined;\n /** Overrides the seeded organization profile name; see registration. */\n organizationProfileName?: string | undefined;\n /** Seeds what the committed bootstrap already proves. */\n primeProvisionedState?: ProvisionedStatePrimer | undefined;\n /**\n * App-owned system containers to provision atomically with the new\n * organization (e.g. a trash bin). See registration.\n */\n provisionedSystemContainers?:\n | ReadonlyArray<ProvisionedSystemContainerSpec>\n | undefined;\n /** Purged organization whose personal-org generation this replaces. */\n replacesOrganizationId?: string | undefined;\n /** Marks and durably replays a fresh native-subscription restore target. */\n nativeSubscriptionRestore?: boolean | undefined;\n /** Overrides the seeded self roster-profile nickname; see registration. */\n rosterProfileNickname?: string | undefined;\n signingKeyPair: SigningKeyPair;\n /**\n * The already-registered user creating the organization; they become its\n * founding admin. The server independently requires this to match the\n * authenticated session.\n */\n userId: string;\n}\n\nfunction isAdoptedReplacementResponse(input: {\n creation: CreateOrganizationInput;\n request: CreateOrganizationRequest;\n response: CreateOrganizationResponse;\n}): boolean {\n if (\n input.response.organizationId === input.request.organizationId &&\n input.response.rootContainerId === input.request.rootContainerId\n ) {\n return false;\n }\n if (\n !input.creation.replacesOrganizationId ||\n input.response.userId !== input.creation.userId\n ) {\n throw new Error(\n \"Organization provisioning returned an unexpected organization\",\n );\n }\n input.creation.log?.(\n `Organization replacement adopted (${input.response.organizationId})`,\n );\n return true;\n}\n\nasync function buildOrganizationCandidate(\n input: CreateOrganizationInput,\n rootContainerId: string,\n): Promise<OrganizationProvisioningArtifacts | null> {\n const artifactsInput: OrganizationProvisioningArtifactsInput = {\n identityTrustDomain: input.identityTrustDomain,\n encapsulationKeyPair: input.encapsulationKeyPair,\n organizationProfileName: input.organizationProfileName,\n provisionedSystemContainers: input.provisionedSystemContainers,\n rootContainerId,\n rosterProfileNickname: input.rosterProfileNickname,\n signingKeyPair: input.signingKeyPair,\n userId: input.userId,\n };\n const artifacts: OrganizationProvisioningArtifacts =\n await buildOrganizationProvisioningArtifacts(artifactsInput);\n\n if (input.replacesOrganizationId) {\n artifacts.replacementAuthorization =\n await signOrganizationReplacementAuthorization(\n {\n ...artifacts,\n replacesOrganizationId: input.replacesOrganizationId,\n rootContainerId,\n userId: input.userId,\n },\n input.signingKeyPair,\n );\n }\n\n if (\n input.replacesOrganizationId &&\n input.isIdentityCurrent &&\n !input.isIdentityCurrent()\n ) {\n input.log?.(\n \"Organization creation aborted: identity changed while building artifacts\",\n );\n return null;\n }\n\n return artifacts;\n}\n\n/**\n * Provisions an additional organization for an already-registered user, reusing\n * the exact artifact-build and local-persistence path as registration\n * ({@link buildOrganizationProvisioningArtifacts} /\n * {@link persistOrganizationProvisioningState}). Unlike registration it mints a\n * fresh root container id, signs with the caller's existing identity, and needs\n * no auth challenge — the user is already authenticated.\n */\nexport async function createOrganization(\n input: CreateOrganizationInput,\n): Promise<CreateOrganizationResponse | null> {\n input.log?.(\"Creating organization...\");\n\n const rootContainerId = crypto.randomUUID();\n const candidateArtifacts = await buildOrganizationCandidate(\n input,\n rootContainerId,\n );\n\n if (!candidateArtifacts) return null;\n\n const durableAttempt = await makeOrganizationProvisioningAttemptDurable({\n artifacts: candidateArtifacts,\n creationIntent: organizationCreationIntent(input),\n canStartDurableMutation: input.isIdentityCurrent,\n dbClient: input.dbClient,\n nativeSubscriptionRestore: input.nativeSubscriptionRestore,\n replacesOrganizationId: input.replacesOrganizationId,\n rootContainerId,\n userId: input.userId,\n });\n if (!durableAttempt) {\n input.log?.(\n \"Organization creation aborted: identity changed before saving artifacts\",\n );\n return null;\n }\n const {\n artifacts,\n request,\n rootContainerId: durableRootContainerId,\n } = durableAttempt;\n\n if (input.isIdentityCurrent && !input.isIdentityCurrent()) {\n input.log?.(\n \"Organization creation aborted: identity changed before provisioning\",\n );\n return null;\n }\n\n const response = await requestOrganizationCreation(input, request);\n if (!response) return null;\n\n if (input.isIdentityCurrent && !input.isIdentityCurrent()) {\n input.log?.(\n \"Organization creation discarded: identity changed while provisioning\",\n );\n return null;\n }\n\n if (\n input.replacesOrganizationId &&\n !(await pinOrganizationReplacementResponse({\n replacesOrganizationId: input.replacesOrganizationId,\n response,\n signingPublicKey: input.signingKeyPair.signingPublicKey,\n userId: input.userId,\n execSql: createExecSql(input.dbClient),\n stillCurrent: input.isIdentityCurrent,\n }))\n )\n return null;\n\n if (isAdoptedReplacementResponse({ creation: input, request, response })) {\n // Another device authorized this winning genesis with the same identity.\n // Its encrypted bootstrap will hydrate normally; persisting\n // this device's losing candidate would instead create an unrelated local\n // root. The session reset rebinds retained local data to the winning ids.\n return response;\n }\n\n input.log?.(`Organization created (${response.organizationId})`);\n await persistOrganizationProvisioningState({\n ...artifacts,\n completeProvisioningAttempt: organizationCreationCompletion(\n input,\n artifacts.organizationId,\n ),\n canStartDurableMutation: input.isIdentityCurrent,\n // No position: the seeded documents are read once, as another session of\n // this user may already have edited them.\n commitLsn: null,\n onPersistQueued: input.onPersistQueued,\n containerId: durableRootContainerId,\n dbClient: input.dbClient,\n documentProjectors: input.documentProjectors,\n log: input.log,\n logError: input.logError,\n primeProvisionedState: input.primeProvisionedState,\n response,\n });\n\n return response;\n}\n"]}
@@ -10,6 +10,13 @@ type PersistOrganizationProvisioningStateInput = Pick<OrganizationProvisioningAr
10
10
  readonly canStartDurableMutation?: (() => boolean) | undefined;
11
11
  /** @internal Forwarded to the bootstrap persist; test-only seam. */
12
12
  readonly onPersistQueued?: (() => void) | undefined;
13
+ /**
14
+ * The commit position to record for every seeded document: registration's,
15
+ * or null for an additional organization, which reports none because
16
+ * another session of its creator can edit those documents before this
17
+ * device subscribes to them.
18
+ */
19
+ readonly commitLsn: string | null;
13
20
  readonly containerId: string;
14
21
  readonly dbClient: ExecSqlClientLike;
15
22
  readonly documentProjectors?: DocumentProjectorRegistryInput | undefined;
@@ -152,6 +152,7 @@ export async function persistOrganizationProvisioningState(input) {
152
152
  acknowledgedAccessHeads: artifacts.acknowledgedAccessHeads,
153
153
  authoredDiscoveryHeads: artifacts.authoredDiscoveryHeads,
154
154
  canStartDurableMutation: input.canStartDurableMutation,
155
+ commitLsn: input.commitLsn,
155
156
  completeProvisioningAttempt: input.completeProvisioningAttempt,
156
157
  onPersistQueued: input.onPersistQueued,
157
158
  containerId: input.containerId,
@@ -1 +1 @@
1
- {"version":3,"file":"organizationProvisioningPersistence.js","sourceRoot":"","sources":["organizationProvisioningPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAGpD,OAAO,EAAE,wCAAwC,EAAE,MAAM,uCAAuC,CAAC;AAEjG,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAE5D,OAAO,EAAE,uCAAuC,EAAE,MAAM,gCAAgC,CAAC;AACzF,OAAO,EACL,sCAAsC,EACtC,gCAAgC,GACjC,MAAM,+BAA+B,CAAC;AAGvC,OAAO,EACL,mCAAmC,EACnC,0BAA0B,GAC3B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,4CAA4C,EAC5C,mDAAmD,GACpD,MAAM,0CAA0C,CAAC;AAuClD,SAAS,kCAAkC,CACzC,QAA0C,EAC1C,QAAiB;IAEjB,OAAO,CACL,QAAQ,KAAK,SAAS;QACtB,QAAQ,CAAC,8BAA8B,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAC3D,CAAC;AACJ,CAAC;AAED,SAAS,gCAAgC,CACvC,QAA0C,EAC1C,SAA4E,EAC5E,SAOC;IAED,OAAO;QACL,WAAW,EAAE,SAAS,CAAC,SAAS,CAAC,YAAY,CAAC,KAAK;QACnD,eAAe,EAAE,SAAS,CAAC,SAAS,CAAC,YAAY,CAAC,YAAY;QAC9D,WAAW,EAAE,SAAS,CAAC,WAAW;QAClC,SAAS,EAAE,SAAS,CAAC,SAAS,CAAC,SAAS;QACxC,kBAAkB,EAAE,SAAS,CAAC,gBAAgB,CAAC,EAAE;QACjD,qBAAqB,EAAE,SAAS,CAAC,8BAA8B;QAC/D,8BAA8B,EAAE,kCAAkC,CAChE,QAAQ,EACR,SAAS,CAAC,gBAAgB,CAAC,mBAAmB,CAAC,eAAe,CAAC,CAAC,CAAC,EAAE,EAAE,CACtE;QACD,gBAAgB,EAAE,a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AAqB,EAAE,CAAC;gBAClC,UAAU,EAAE,yBAAyB,CAAC,KAAK,CAAC;gBAC5C,QAAQ,EAAE,KAAK,CAAC,QAAQ;gBACxB,SAAS,EAAE,KAAK,CAAC,uBAAuB,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC;gBACxD,cAAc,EAAE,KAAK,CAAC,QAAQ,CAAC,cAAc;gBAC7C,QAAQ,EAAE;oBACR,UAAU,EAAE,SAAS,CAAC,uBAAuB;oBAC7C,WAAW,EAAE,SAAS,CAAC,wBAAwB;oBAC/C,YAAY,EAAE,SAAS,CAAC,yBAAyB;iBAClD;gBACD,eAAe,EAAE,KAAK,CAAC,QAAQ,CAAC,eAAe;gBAC/C,MAAM,EAAE,KAAK,CAAC,QAAQ,CAAC,MAAM;aAC9B,CAAC,CAAC;IACP,CAAC;IAAC,OAAO,KAAc,EAAE,CAAC;QACxB,IAAI,KAAK,CAAC,QAAQ,EAAE,CAAC;YACnB,KAAK,CAAC,QAAQ,CAAC,qCAAqC,EAAE,KAAK,CAAC,CAAC;QAC/D,CAAC;aAAM,CAAC;YACN,OAAO,CAAC,KAAK,CAAC,sCAAsC,EAAE,KAAK,CAAC,CAAC;QAC/D,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import { bytesToBase64 } from \"@tearleads/encoding\";\nimport type { OrganizationProvisioningResponse } from \"@tearleads/validators/response\";\nimport type { DocumentProjectorRegistryInput } from \"../../data/documents/documentKinds\";\nimport { persistedDocumentCreateStateFromResponse } from \"../../data/documents/shared/responses\";\nimport type { ExecSql, ExecSqlClientLike } from \"../../data/sqlite/sqlSchema\";\nimport { createExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { OrganizationProvisioningArtifacts } from \"./organizationProvisioningArtifacts\";\nimport { persistRegistrationBootstrapFromExecSql } from \"./persistRegistrationBootstrap\";\nimport {\n buildOrganizationProfileBootstrapInput,\n buildRosterProfileBootstrapInput,\n} from \"./profileBootstrapPersistence\";\nimport type { ProvisionedContainerSeed } from \"./provisionedContainerSeeds\";\nimport type { ProvisionedStatePrimer } from \"./provisionedStatePrimer\";\nimport {\n provisioningAcknowledgedAccessHeads,\n provisioningDiscoveryHeads,\n} from \"./provisioningAcknowledgement\";\nimport {\n principalPolicyBundleFromInitialGroupRequest,\n principalPolicyBundleFromInitialOrganizationRequest,\n} from \"./registrationPrincipalPolicyPersistence\";\n\ntype PersistOrganizationProvisioningStateInput = Pick<\n OrganizationProvisioningArtifacts,\n | \"bootstrap\"\n | \"initialAdminGroup\"\n | \"initialMemberGroup\"\n | \"initialOrganizationPolicy\"\n | \"organizationMetadataBootstrap\"\n | \"rootContainer\"\n | \"rootMetadataDocument\"\n | \"rootMetadataDocumentRequest\"\n | \"rosterProfileBootstrap\"\n | \"systemContainerBootstraps\"\n> & {\n /** @internal Runs inside the guarded bootstrap transaction, never after commit. */\n readonly completeProvisioningAttempt?:\n | ((execSql: ExecSql) => Promise<void>)\n | undefined;\n /** Forwarded to the bootstrap persist's in-mutex currency check. */\n readonly canStartDurableMutation?: (() => boolean) | undefined;\n /** @internal Forwarded to the bootstrap persist; test-only seam. */\n readonly onPersistQueued?: (() => void) | undefined;\n readonly containerId: string;\n readonly dbClient: ExecSqlClientLike;\n readonly documentProjectors?: DocumentProjectorRegistryInput | undefined;\n readonly log?: ((message: string) => void) | undefined;\n readonly logError?:\n | ((message: string | Error, cause?: unknown) => void)\n | undefined;\n /** Seeds what the bootstrap proves once it commits. */\n readonly primeProvisionedState?: ProvisionedStatePrimer | undefined;\n readonly response: OrganizationProvisioningResponse;\n};\n\ntype PersistBootstrapInput = Parameters<\n typeof persistRegistrationBootstrapFromExecSql\n>[1];\n\nfunction coreMetadataInitialUpdateCommitted(\n response: OrganizationProvisioningResponse,\n updateId?: string,\n): boolean {\n return (\n updateId !== undefined &&\n response.committedCoreMetadataUpdateIds.includes(updateId)\n );\n}\n\nfunction buildCoreContainerBootstrapInput(\n response: OrganizationProvisioningResponse,\n container: OrganizationProvisioningResponse[\"organizationMetadataContainer\"],\n bootstrap: Pick<\n OrganizationProvisioningArtifacts[\"rosterProfileBootstrap\"],\n | \"containerId\"\n | \"containerMetadataDocument\"\n | \"containerMetadataInitialUpdate\"\n | \"containerRequest\"\n | \"systemSlot\"\n >,\n): NonNullable<PersistBootstrapInput[\"organizationMetadataContainer\"]> {\n return {\n accessEpoch: container.container.manifestHead.epoch,\n accessStateHash: container.container.manifestHead.manifestHash,\n containerId: bootstrap.containerId,\n createdAt: container.container.createdAt,\n metadataDocumentId: container.metadataDocument.id,\n metadataInitialUpdate: bootstrap.containerMetadataInitialUpdate,\n metadataInitialUpdateCommitted: coreMetadataInitialUpdateCommitted(\n response,\n bootstrap.containerRequest.initialMetadataSync.outgoingUpdates[0]?.id,\n ),\n metadataSnapshot: bytesToBase64(bootstrap.containerMetadataInitialUpdate),\n metadataState: persistedDocumentCreateStateFromResponse(\n bootstrap.containerMetadataDocument.plan,\n container.metadataDocument,\n ),\n systemSlot: bootstrap.systemSlot,\n updatedAt: container.container.updatedAt,\n };\n}\n\nfunction buildSystemContainersBootstrapInput(\n input: PersistOrganizationProvisioningStateInput,\n): PersistBootstrapInput[\"systemContainers\"] {\n const responses = input.response.systemContainers;\n if (responses.length === 0) {\n return;\n }\n const responseByContainerId = new Map(\n responses.map((response) => [response.container.containerId, response]),\n );\n const entries: NonNullable<PersistBootstrapInput[\"systemContainers\"]> = [];\n for (const bootstrap of input.systemContainerBootstraps) {\n const response = responseByContainerId.get(bootstrap.containerId);\n if (!response) {\n continue;\n }\n entries.push({\n accessEpoch: response.container.manifestHead.epoch,\n accessStateHash: response.container.manifestHead.manifestHash,\n containerId: bootstrap.containerId,\n createdAt: response.container.createdAt,\n icon: bootstrap.icon,\n metadataDocumentId: response.metadataDocument.id,\n metadataSnapshot: bytesToBase64(bootstrap.containerMetadataInitialUpdate),\n metadataState: persistedDocumentCreateStateFromResponse(\n bootstrap.containerMetadataDocument.plan,\n response.metadataDocument,\n ),\n name: bootstrap.name,\n systemSlot: bootstrap.systemSlot,\n updatedAt: response.container.updatedAt,\n });\n }\n return entries.length > 0 ? entries : undefined;\n}\n\n/** Every container the request created, with the head the response acknowledged. */\nfunction provisionedContainerSeeds(\n input: PersistOrganizationProvisioningStateInput,\n): ProvisionedContainerSeed[] {\n const { response } = input;\n const systemHeads = new Map(\n response.systemContainers.map(({ container }) => [\n container.containerId,\n container.manifestHead.manifestHash,\n ]),\n );\n return [\n {\n acknowledgedManifestHash: response.rootMetadataAccessStateHash,\n plan: input.rootContainer.plan,\n },\n {\n acknowledgedManifestHash:\n response.rosterProfileContainer?.container.manifestHead.manifestHash,\n plan: input.rosterProfileBootstrap.containerPlan.plan,\n },\n {\n acknowledgedManifestHash:\n response.organizationMetadataContainer.container.manifestHead\n .manifestHash,\n plan: input.organizationMetadataBootstrap.containerPlan.plan,\n },\n ...input.systemContainerBootstraps.map((bootstrap) => ({\n acknowledgedManifestHash: systemHeads.get(bootstrap.containerId),\n plan: bootstrap.containerPlan.plan,\n })),\n ];\n}\n\nasync function buildProvisioningPersistenceArtifacts(\n input: PersistOrganizationProvisioningStateInput,\n) {\n const acknowledgedAccessHeads = await provisioningAcknowledgedAccessHeads({\n expectedOrganizationId: input.rootContainer.plan.state.organizationId,\n expectedUserId: input.rootContainer.plan.event.signerUserId,\n organizationMetadata: {\n containerPlan: input.organizationMetadataBootstrap.containerPlan.plan,\n metadataDocumentPlan:\n input.organizationMetadataBootstrap.containerMetadataDocument.plan,\n },\n organizationProfileDocumentPlan:\n input.organizationMetadataBootstrap.organizationProfileDocument.plan,\n response: input.response,\n rootContainerPlan: input.rootContainer.plan,\n rootMetadataDocumentPlan: input.rootMetadataDocument.plan,\n rosterProfile: {\n containerPlan: input.rosterProfileBootstrap.containerPlan.plan,\n metadataDocumentPlan:\n input.rosterProfileBootstrap.containerMetadataDocument.plan,\n },\n rosterProfileDocumentPlan:\n input.rosterProfileBootstrap.profileDocument.plan,\n systemContainers: input.systemContainerBootstraps.map((bootstrap) => ({\n containerPlan: bootstrap.containerPlan.plan,\n metadataDocumentPlan: bootstrap.containerMetadataDocument.plan,\n })),\n });\n const [\n initialAdminGroupPolicy,\n initialMemberGroupPolicy,\n initialOrganizationPolicy,\n ] = await Promise.all([\n principalPolicyBundleFromInitialGroupRequest(input.initialAdminGroup),\n principalPolicyBundleFromInitialGroupRequest(input.initialMemberGroup),\n principalPolicyBundleFromInitialOrganizationRequest(\n input.initialOrganizationPolicy,\n ),\n ]);\n return {\n acknowledgedAccessHeads,\n // Discovery lists the seeded profile documents; their signed heads are the\n // ones this client just authored and the server acknowledged.\n authoredDiscoveryHeads: provisioningDiscoveryHeads([\n {\n plan: input.rosterProfileBootstrap.profileDocument.plan,\n response: input.response.rosterProfileDocument,\n },\n {\n plan: input.organizationMetadataBootstrap.organizationProfileDocument\n .plan,\n response: input.response.organizationProfileDocument,\n },\n ]),\n initialAdminGroupPolicy,\n initialMemberGroupPolicy,\n initialOrganizationPolicy,\n organizationMetadataContainer: buildCoreContainerBootstrapInput(\n input.response,\n input.response.organizationMetadataContainer,\n input.organizationMetadataBootstrap,\n ),\n organizationProfileDocument: buildOrganizationProfileBootstrapInput({\n containerId: input.organizationMetadataBootstrap.containerId,\n materializedDocument:\n input.organizationMetadataBootstrap.organizationProfileDocument,\n request:\n input.organizationMetadataBootstrap.organizationProfileDocumentRequest,\n response: input.response,\n snapshot: input.organizationMetadataBootstrap.organizationProfileSnapshot,\n }),\n rosterProfileContainer: input.response.rosterProfileContainer\n ? buildCoreContainerBootstrapInput(\n input.response,\n input.response.rosterProfileContainer,\n input.rosterProfileBootstrap,\n )\n : undefined,\n rosterProfileDocument: buildRosterProfileBootstrapInput({\n containerId: input.rosterProfileBootstrap.containerId,\n initialUpdate: input.rosterProfileBootstrap.profileDocumentInitialUpdate,\n materializedDocument: input.rosterProfileBootstrap.profileDocument,\n request: input.rosterProfileBootstrap.profileDocumentRequest,\n response: input.response,\n }),\n systemContainers: buildSystemContainersBootstrapInput(input),\n };\n}\n\nexport async function persistOrganizationProvisioningState(\n input: PersistOrganizationProvisioningStateInput,\n): Promise<void> {\n try {\n const artifacts = await buildProvisioningPersistenceArtifacts(input);\n const persisted = await persistRegistrationBootstrapFromExecSql(\n createExecSql(input.dbClient),\n {\n acknowledgedAccessHeads: artifacts.acknowledgedAccessHeads,\n authoredDiscoveryHeads: artifacts.authoredDiscoveryHeads,\n canStartDurableMutation: input.canStartDurableMutation,\n completeProvisioningAttempt: input.completeProvisioningAttempt,\n onPersistQueued: input.onPersistQueued,\n containerId: input.containerId,\n documentProjectors: input.documentProjectors,\n initialAdminGroupPolicy: artifacts.initialAdminGroupPolicy,\n initialMemberGroupPolicy: artifacts.initialMemberGroupPolicy,\n initialOrganizationPolicy: artifacts.initialOrganizationPolicy,\n organizationId: input.response.organizationId,\n // The provisioning response does not expose the root container's own\n // timestamps. Its metadata document is created in the same transaction,\n // so its server timestamp is the acknowledged remote anchor for the\n // locally persisted root row.\n rootContainerServerTimestamp:\n input.response.rootMetadataDocument.createdAt,\n rootMetadataAccessEpoch: input.response.rootMetadataAccessEpoch,\n rootMetadataAccessStateHash: input.response.rootMetadataAccessStateHash,\n rootMetadataDocumentId: input.response.rootMetadataDocumentId,\n rootMetadataInitialUpdate: input.bootstrap.initialUpdate,\n rootMetadataInitialUpdateCommitted: coreMetadataInitialUpdateCommitted(\n input.response,\n input.rootMetadataDocumentRequest.initialSync.outgoingUpdates[0]?.id,\n ),\n rootMetadataSnapshot: bytesToBase64(input.bootstrap.initialUpdate),\n rootMetadataState: persistedDocumentCreateStateFromResponse(\n input.rootMetadataDocument.plan,\n input.response.rootMetadataDocument,\n ),\n ...(artifacts.rosterProfileContainer\n ? { rosterProfileContainer: artifacts.rosterProfileContainer }\n : {}),\n organizationMetadataContainer: artifacts.organizationMetadataContainer,\n ...(artifacts.organizationProfileDocument\n ? {\n organizationProfileDocument:\n artifacts.organizationProfileDocument,\n }\n : {}),\n ...(artifacts.rosterProfileDocument\n ? { rosterProfileDocument: artifacts.rosterProfileDocument }\n : {}),\n ...(artifacts.systemContainers\n ? { systemContainers: artifacts.systemContainers }\n : {}),\n userId: input.response.userId,\n },\n );\n input.log?.(\n persisted\n ? \"Local organization bootstrap persisted\"\n : \"Local organization bootstrap skipped: identity replaced\",\n );\n if (persisted)\n await input.primeProvisionedState?.({\n containers: provisionedContainerSeeds(input),\n database: input.dbClient,\n isCurrent: input.canStartDurableMutation ?? (() => true),\n organizationId: input.response.organizationId,\n policies: {\n adminGroup: artifacts.initialAdminGroupPolicy,\n memberGroup: artifacts.initialMemberGroupPolicy,\n organization: artifacts.initialOrganizationPolicy,\n },\n rootContainerId: input.response.rootContainerId,\n userId: input.response.userId,\n });\n } catch (error: unknown) {\n if (input.logError) {\n input.logError(\"Failed to persist registration data\", error);\n } else {\n console.error(\"Failed to persist registration data:\", error);\n }\n throw error;\n }\n}\n"]}
1
+ {"version":3,"file":"organizationProvisioningPersistence.js","sourceRoot":"","sources":["organizationProvisioningPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAGpD,OAAO,EAAE,wCAAwC,EAAE,MAAM,uCAAuC,CAAC;AAEjG,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAE5D,OAAO,EAAE,uCAAuC,EAAE,MAAM,gCAAgC,CAAC;AACzF,OAAO,EACL,sCAAsC,EACtC,gCAAgC,GACjC,MAAM,+BAA+B,CAAC;AAGvC,OAAO,EACL,mCAAmC,EACnC,0BAA0B,GAC3B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,4CAA4C,EAC5C,mDAAmD,GACpD,MAAM,0CAA0C,CAAC;AA8ClD,SAAS,kCAAkC,CACzC,QAA0C,EAC1C,QAAiB;IAEjB,OAAO,CACL,QAAQ,KAAK,SAAS;QACtB,QAAQ,CAAC,8BAA8B,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAC3D,CAAC;AACJ,CAAC;AAED,SAAS,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OAAO,CAAC,KAAK,CAAC,sCAAsC,EAAE,KAAK,CAAC,CAAC;QAC/D,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import { bytesToBase64 } from \"@tearleads/encoding\";\nimport type { OrganizationProvisioningResponse } from \"@tearleads/validators/response\";\nimport type { DocumentProjectorRegistryInput } from \"../../data/documents/documentKinds\";\nimport { persistedDocumentCreateStateFromResponse } from \"../../data/documents/shared/responses\";\nimport type { ExecSql, ExecSqlClientLike } from \"../../data/sqlite/sqlSchema\";\nimport { createExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { OrganizationProvisioningArtifacts } from \"./organizationProvisioningArtifacts\";\nimport { persistRegistrationBootstrapFromExecSql } from \"./persistRegistrationBootstrap\";\nimport {\n buildOrganizationProfileBootstrapInput,\n buildRosterProfileBootstrapInput,\n} from \"./profileBootstrapPersistence\";\nimport type { ProvisionedContainerSeed } from \"./provisionedContainerSeeds\";\nimport type { ProvisionedStatePrimer } from \"./provisionedStatePrimer\";\nimport {\n provisioningAcknowledgedAccessHeads,\n provisioningDiscoveryHeads,\n} from \"./provisioningAcknowledgement\";\nimport {\n principalPolicyBundleFromInitialGroupRequest,\n principalPolicyBundleFromInitialOrganizationRequest,\n} from \"./registrationPrincipalPolicyPersistence\";\n\ntype PersistOrganizationProvisioningStateInput = Pick<\n OrganizationProvisioningArtifacts,\n | \"bootstrap\"\n | \"initialAdminGroup\"\n | \"initialMemberGroup\"\n | \"initialOrganizationPolicy\"\n | \"organizationMetadataBootstrap\"\n | \"rootContainer\"\n | \"rootMetadataDocument\"\n | \"rootMetadataDocumentRequest\"\n | \"rosterProfileBootstrap\"\n | \"systemContainerBootstraps\"\n> & {\n /** @internal Runs inside the guarded bootstrap transaction, never after commit. */\n readonly completeProvisioningAttempt?:\n | ((execSql: ExecSql) => Promise<void>)\n | undefined;\n /** Forwarded to the bootstrap persist's in-mutex currency check. */\n readonly canStartDurableMutation?: (() => boolean) | undefined;\n /** @internal Forwarded to the bootstrap persist; test-only seam. */\n readonly onPersistQueued?: (() => void) | undefined;\n /**\n * The commit position to record for every seeded document: registration's,\n * or null for an additional organization, which reports none because\n * another session of its creator can edit those documents before this\n * device subscribes to them.\n */\n readonly commitLsn: string | null;\n readonly containerId: string;\n readonly dbClient: ExecSqlClientLike;\n readonly documentProjectors?: DocumentProjectorRegistryInput | undefined;\n readonly log?: ((message: string) => void) | undefined;\n readonly logError?:\n | ((message: string | Error, cause?: unknown) => void)\n | undefined;\n /** Seeds what the bootstrap proves once it commits. */\n readonly primeProvisionedState?: ProvisionedStatePrimer | undefined;\n readonly response: OrganizationProvisioningResponse;\n};\n\ntype PersistBootstrapInput = Parameters<\n typeof persistRegistrationBootstrapFromExecSql\n>[1];\n\nfunction coreMetadataInitialUpdateCommitted(\n response: OrganizationProvisioningResponse,\n updateId?: string,\n): boolean {\n return (\n updateId !== undefined &&\n response.committedCoreMetadataUpdateIds.includes(updateId)\n );\n}\n\nfunction buildCoreContainerBootstrapInput(\n response: OrganizationProvisioningResponse,\n container: OrganizationProvisioningResponse[\"organizationMetadataContainer\"],\n bootstrap: Pick<\n OrganizationProvisioningArtifacts[\"rosterProfileBootstrap\"],\n | \"containerId\"\n | \"containerMetadataDocument\"\n | \"containerMetadataInitialUpdate\"\n | \"containerRequest\"\n | \"systemSlot\"\n >,\n): NonNullable<PersistBootstrapInput[\"organizationMetadataContainer\"]> {\n return {\n accessEpoch: container.container.manifestHead.epoch,\n accessStateHash: container.container.manifestHead.manifestHash,\n containerId: bootstrap.containerId,\n createdAt: container.container.createdAt,\n metadataDocumentId: container.metadataDocument.id,\n metadataInitialUpdate: bootstrap.containerMetadataInitialUpdate,\n metadataInitialUpdateCommitted: coreMetadataInitialUpdateCommitted(\n response,\n bootstrap.containerRequest.initialMetadataSync.outgoingUpdates[0]?.id,\n ),\n metadataSnapshot: bytesToBase64(bootstrap.containerMetadataInitialUpdate),\n metadataState: persistedDocumentCreateStateFromResponse(\n bootstrap.containerMetadataDocument.plan,\n container.metadataDocument,\n ),\n systemSlot: bootstrap.systemSlot,\n updatedAt: container.container.updatedAt,\n };\n}\n\nfunction buildSystemContainersBootstrapInput(\n input: PersistOrganizationProvisioningStateInput,\n): PersistBootstrapInput[\"systemContainers\"] {\n const responses = input.response.systemContainers;\n if (responses.length === 0) {\n return;\n }\n const responseByContainerId = new Map(\n responses.map((response) => [response.container.containerId, response]),\n );\n const entries: NonNullable<PersistBootstrapInput[\"systemContainers\"]> = [];\n for (const bootstrap of input.systemContainerBootstraps) {\n const response = responseByContainerId.get(bootstrap.containerId);\n if (!response) {\n continue;\n }\n entries.push({\n accessEpoch: response.container.manifestHead.epoch,\n accessStateHash: response.container.manifestHead.manifestHash,\n containerId: bootstrap.containerId,\n createdAt: response.container.createdAt,\n icon: bootstrap.icon,\n metadataDocumentId: response.metadataDocument.id,\n metadataSnapshot: bytesToBase64(bootstrap.containerMetadataInitialUpdate),\n metadataState: persistedDocumentCreateStateFromResponse(\n bootstrap.containerMetadataDocument.plan,\n response.metadataDocument,\n ),\n name: bootstrap.name,\n systemSlot: bootstrap.systemSlot,\n updatedAt: response.container.updatedAt,\n });\n }\n return entries.length > 0 ? entries : undefined;\n}\n\n/** Every container the request created, with the head the response acknowledged. */\nfunction provisionedContainerSeeds(\n input: PersistOrganizationProvisioningStateInput,\n): ProvisionedContainerSeed[] {\n const { response } = input;\n const systemHeads = new Map(\n response.systemContainers.map(({ container }) => [\n container.containerId,\n container.manifestHead.manifestHash,\n ]),\n );\n return [\n {\n acknowledgedManifestHash: response.rootMetadataAccessStateHash,\n plan: input.rootContainer.plan,\n },\n {\n acknowledgedManifestHash:\n response.rosterProfileContainer?.container.manifestHead.manifestHash,\n plan: input.rosterProfileBootstrap.containerPlan.plan,\n },\n {\n acknowledgedManifestHash:\n response.organizationMetadataContainer.container.manifestHead\n .manifestHash,\n plan: input.organizationMetadataBootstrap.containerPlan.plan,\n },\n ...input.systemContainerBootstraps.map((bootstrap) => ({\n acknowledgedManifestHash: systemHeads.get(bootstrap.containerId),\n plan: bootstrap.containerPlan.plan,\n })),\n ];\n}\n\nasync function buildProvisioningPersistenceArtifacts(\n input: PersistOrganizationProvisioningStateInput,\n) {\n const acknowledgedAccessHeads = await provisioningAcknowledgedAccessHeads({\n expectedOrganizationId: input.rootContainer.plan.state.organizationId,\n expectedUserId: input.rootContainer.plan.event.signerUserId,\n organizationMetadata: {\n containerPlan: input.organizationMetadataBootstrap.containerPlan.plan,\n metadataDocumentPlan:\n input.organizationMetadataBootstrap.containerMetadataDocument.plan,\n },\n organizationProfileDocumentPlan:\n input.organizationMetadataBootstrap.organizationProfileDocument.plan,\n response: input.response,\n rootContainerPlan: input.rootContainer.plan,\n rootMetadataDocumentPlan: input.rootMetadataDocument.plan,\n rosterProfile: {\n containerPlan: input.rosterProfileBootstrap.containerPlan.plan,\n metadataDocumentPlan:\n input.rosterProfileBootstrap.containerMetadataDocument.plan,\n },\n rosterProfileDocumentPlan:\n input.rosterProfileBootstrap.profileDocument.plan,\n systemContainers: input.systemContainerBootstraps.map((bootstrap) => ({\n containerPlan: bootstrap.containerPlan.plan,\n metadataDocumentPlan: bootstrap.containerMetadataDocument.plan,\n })),\n });\n const [\n initialAdminGroupPolicy,\n initialMemberGroupPolicy,\n initialOrganizationPolicy,\n ] = await Promise.all([\n principalPolicyBundleFromInitialGroupRequest(input.initialAdminGroup),\n principalPolicyBundleFromInitialGroupRequest(input.initialMemberGroup),\n principalPolicyBundleFromInitialOrganizationRequest(\n input.initialOrganizationPolicy,\n ),\n ]);\n return {\n acknowledgedAccessHeads,\n // Discovery lists the seeded profile documents; their signed heads are the\n // ones this client just authored and the server acknowledged.\n authoredDiscoveryHeads: provisioningDiscoveryHeads([\n {\n plan: input.rosterProfileBootstrap.profileDocument.plan,\n response: input.response.rosterProfileDocument,\n },\n {\n plan: input.organizationMetadataBootstrap.organizationProfileDocument\n .plan,\n response: input.response.organizationProfileDocument,\n },\n ]),\n initialAdminGroupPolicy,\n initialMemberGroupPolicy,\n initialOrganizationPolicy,\n organizationMetadataContainer: buildCoreContainerBootstrapInput(\n input.response,\n input.response.organizationMetadataContainer,\n input.organizationMetadataBootstrap,\n ),\n organizationProfileDocument: buildOrganizationProfileBootstrapInput({\n containerId: input.organizationMetadataBootstrap.containerId,\n materializedDocument:\n input.organizationMetadataBootstrap.organizationProfileDocument,\n request:\n input.organizationMetadataBootstrap.organizationProfileDocumentRequest,\n response: input.response,\n snapshot: input.organizationMetadataBootstrap.organizationProfileSnapshot,\n }),\n rosterProfileContainer: input.response.rosterProfileContainer\n ? buildCoreContainerBootstrapInput(\n input.response,\n input.response.rosterProfileContainer,\n input.rosterProfileBootstrap,\n )\n : undefined,\n rosterProfileDocument: buildRosterProfileBootstrapInput({\n containerId: input.rosterProfileBootstrap.containerId,\n initialUpdate: input.rosterProfileBootstrap.profileDocumentInitialUpdate,\n materializedDocument: input.rosterProfileBootstrap.profileDocument,\n request: input.rosterProfileBootstrap.profileDocumentRequest,\n response: input.response,\n }),\n systemContainers: buildSystemContainersBootstrapInput(input),\n };\n}\n\nexport async function persistOrganizationProvisioningState(\n input: PersistOrganizationProvisioningStateInput,\n): Promise<void> {\n try {\n const artifacts = await buildProvisioningPersistenceArtifacts(input);\n const persisted = await persistRegistrationBootstrapFromExecSql(\n createExecSql(input.dbClient),\n {\n acknowledgedAccessHeads: artifacts.acknowledgedAccessHeads,\n authoredDiscoveryHeads: artifacts.authoredDiscoveryHeads,\n canStartDurableMutation: input.canStartDurableMutation,\n commitLsn: input.commitLsn,\n completeProvisioningAttempt: input.completeProvisioningAttempt,\n onPersistQueued: input.onPersistQueued,\n containerId: input.containerId,\n documentProjectors: input.documentProjectors,\n initialAdminGroupPolicy: artifacts.initialAdminGroupPolicy,\n initialMemberGroupPolicy: artifacts.initialMemberGroupPolicy,\n initialOrganizationPolicy: artifacts.initialOrganizationPolicy,\n organizationId: input.response.organizationId,\n // The provisioning response does not expose the root container's own\n // timestamps. Its metadata document is created in the same transaction,\n // so its server timestamp is the acknowledged remote anchor for the\n // locally persisted root row.\n rootContainerServerTimestamp:\n input.response.rootMetadataDocument.createdAt,\n rootMetadataAccessEpoch: input.response.rootMetadataAccessEpoch,\n rootMetadataAccessStateHash: input.response.rootMetadataAccessStateHash,\n rootMetadataDocumentId: input.response.rootMetadataDocumentId,\n rootMetadataInitialUpdate: input.bootstrap.initialUpdate,\n rootMetadataInitialUpdateCommitted: coreMetadataInitialUpdateCommitted(\n input.response,\n input.rootMetadataDocumentRequest.initialSync.outgoingUpdates[0]?.id,\n ),\n rootMetadataSnapshot: bytesToBase64(input.bootstrap.initialUpdate),\n rootMetadataState: persistedDocumentCreateStateFromResponse(\n input.rootMetadataDocument.plan,\n input.response.rootMetadataDocument,\n ),\n ...(artifacts.rosterProfileContainer\n ? { rosterProfileContainer: artifacts.rosterProfileContainer }\n : {}),\n organizationMetadataContainer: artifacts.organizationMetadataContainer,\n ...(artifacts.organizationProfileDocument\n ? {\n organizationProfileDocument:\n artifacts.organizationProfileDocument,\n }\n : {}),\n ...(artifacts.rosterProfileDocument\n ? { rosterProfileDocument: artifacts.rosterProfileDocument }\n : {}),\n ...(artifacts.systemContainers\n ? { systemContainers: artifacts.systemContainers }\n : {}),\n userId: input.response.userId,\n },\n );\n input.log?.(\n persisted\n ? \"Local organization bootstrap persisted\"\n : \"Local organization bootstrap skipped: identity replaced\",\n );\n if (persisted)\n await input.primeProvisionedState?.({\n containers: provisionedContainerSeeds(input),\n database: input.dbClient,\n isCurrent: input.canStartDurableMutation ?? (() => true),\n organizationId: input.response.organizationId,\n policies: {\n adminGroup: artifacts.initialAdminGroupPolicy,\n memberGroup: artifacts.initialMemberGroupPolicy,\n organization: artifacts.initialOrganizationPolicy,\n },\n rootContainerId: input.response.rootContainerId,\n userId: input.response.userId,\n });\n } catch (error: unknown) {\n if (input.logError) {\n input.logError(\"Failed to persist registration data\", error);\n } else {\n console.error(\"Failed to persist registration data:\", error);\n }\n throw error;\n }\n}\n"]}
@@ -34,6 +34,12 @@ export interface RegistrationBootstrapInput {
34
34
  authoredDiscoveryHeads: readonly AuthoredDiscoveryHead[];
35
35
  /** Checked inside the mutation queue claim; false skips every write. */
36
36
  canStartDurableMutation?: (() => boolean) | undefined;
37
+ /**
38
+ * The provisioning's commit position, read after its transaction. Every
39
+ * seeded document keeps it as its last commit, so its first read passes it
40
+ * as `minLsn` and a clean seed needs no read at all.
41
+ */
42
+ commitLsn: string | null;
37
43
  /**
38
44
  * @internal Test-only synchronization seam. Invoked synchronously,
39
45
  * immediately before this persist joins the serialized mutation queue —
@@ -82,6 +88,7 @@ export declare function persistInitialDocumentBootstrap(execSql: ExecSql, input:
82
88
  documentState: Pick<DocumentRecord, "contentKeyBundle" | "documentKekTargets" | "documentManifestBundle">;
83
89
  initialUpdate: Uint8Array;
84
90
  initialUpdateCommitted: boolean;
91
+ lastCommitLsn: string | null;
85
92
  localId: string;
86
93
  }): Promise<void>;
87
94
  /**
@@ -23,7 +23,7 @@ async function persistProvisionedContainerBootstrap(execSql, input) {
23
23
  accessStateHash: container.accessStateHash,
24
24
  documentId: container.metadataDocumentId,
25
25
  id: container.containerId,
26
- lastCommitLsn: null,
26
+ lastCommitLsn: input.lastCommitLsn,
27
27
  metadataUpdates: container.metadataSnapshot,
28
28
  snapshotEndVersion: "",
29
29
  contentKeyBundle: metadataState.contentKeyBundle ?? null,
@@ -56,7 +56,7 @@ async function persistRootContainerBootstrap(execSql, input) {
56
56
  accessStateHash: input.rootMetadataAccessStateHash,
57
57
  documentId: input.rootMetadataDocumentId,
58
58
  id: input.containerId,
59
- lastCommitLsn: null,
59
+ lastCommitLsn: input.commitLsn,
60
60
  metadataUpdates: input.rootMetadataSnapshot,
61
61
  snapshotEndVersion: "",
62
62
  contentKeyBundle: input.rootMetadataState.contentKeyBundle ?? null,
@@ -93,6 +93,7 @@ async function persistNamedChildContainerBootstrap(execSql, input, container, na
93
93
  const seeded = await persistProvisionedContainerBootstrap(execSql, {
94
94
  container,
95
95
  icon: null,
96
+ lastCommitLsn: input.commitLsn,
96
97
  name,
97
98
  organizationId: input.organizationId,
98
99
  parentId: container === input.organizationMetadataContainer
@@ -115,6 +116,7 @@ async function persistSystemContainersBootstrap(execSql, input) {
115
116
  await persistProvisionedContainerBootstrap(execSql, {
116
117
  container: systemContainer,
117
118
  icon: systemContainer.icon,
119
+ lastCommitLsn: input.commitLsn,
118
120
  name: systemContainer.name,
119
121
  organizationId: input.organizationId,
120
122
  parentId: input.containerId,
@@ -137,6 +139,7 @@ async function persistProfileDocumentBootstrap(execSql, input, profileDocument,
137
139
  ...profileDocument,
138
140
  documentKind,
139
141
  documentProjectors: input.documentProjectors,
142
+ lastCommitLsn: input.commitLsn,
140
143
  });
141
144
  }
142
145
  export async function persistInitialDocumentBootstrap(execSql, input) {
@@ -164,6 +167,7 @@ export async function persistInitialDocumentBootstrap(execSql, input) {
164
167
  documentKekTargets: input.documentState.documentKekTargets ?? null,
165
168
  documentKind: input.documentKind,
166
169
  documentManifestBundle: input.documentState.documentManifestBundle ?? null,
170
+ lastCommitLsn: input.lastCommitLsn,
167
171
  // The create-only persistence primitive stores this frontier and the
168
172
  // full-history checkpoint in one transaction.
169
173
  snapshotEndVersion: encodeVersionVector(doc),
@@ -1 +1 @@
1
- {"version":3,"file":"persistRegistrationBootstrap.js","sourceRoot":"","sources":["persistRegistrationBootstrap.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,mBAAmB,EACnB,aAAa,GACd,MAAM,iBAAiB,CAAC;AAIzB,OAAO,EAAE,yBAAyB,EAAE,MAAM,mCAAmC,CAAC;AAC9E,OAAO,EAEL,+BAA+B,GAChC,MAAM,wEAAwE,CAAC;AAChF,OAAO,EAAE,wBAAwB,EAAE,MAAM,kFAAkF,CAAC;AAC5H,OAAO,EAEL,mCAAmC,GACpC,MAAM,uEAAuE,CAAC;AAC/E,OAAO,EACL,kBAAkB,EAClB,uBAAuB,GACxB,MAAM,uDAAuD,CAAC;AAG/D,OAAO,EAAE,iCA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CAAC;YACF,MAAM,+BAA+B,CACnC,aAAa,EACb,SAAS,EACT,KAAK,CAAC,qBAAqB,EAC3B,4BAA4B,CAC7B,CAAC;YACF,MAAM,mCAAmC,CACvC,aAAa,EACb,SAAS,EACT,KAAK,CAAC,6BAA6B,EACnC,oCAAoC,CACrC,CAAC;YACF,MAAM,+BAA+B,CACnC,aAAa,EACb,SAAS,EACT,KAAK,CAAC,2BAA2B,EACjC,kCAAkC,CACnC,CAAC;YACF,MAAM,gCAAgC,CAAC,aAAa,EAAE,SAAS,CAAC,CAAC;YACjE,mEAAmE;YACnE,sDAAsD;YACtD,MAAM,mCAAmC,CACvC,aAAa,EACb,KAAK,CAAC,sBAAsB,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAC3C,OAAO,CAAC,UAAU,EAAE,IAAI,CAAC,UAAU,CAAC,CACrC,CACF,CAAC;YACF,MAAM,KAAK,CAAC,2BAA2B,EAAE,CAAC,aAAa,CAAC,CAAC;QAC3D,CAAC,EACD,GAAG,EAAE,CAAC,CAAC,KAAK,CAAC,uBAAuB,IAAI,KAAK,CAAC,uBAAuB,EAAE,CACxE,CAAC;QACF,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,4BAA4B,CAChD,MAAyB,EACzB,KAAiC;IAEjC,MAAM,uCAAuC,CAAC,aAAa,CAAC,MAAM,CAAC,EAAE,KAAK,CAAC,CAAC;AAC9E,CAAC","sourcesContent":["import {\n createDocument,\n encodeVersionVector,\n importUpdates,\n} from \"@tearleads/loro\";\nimport type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport type { DocumentProjectorRegistryInput } from \"../../data/documents/documentKinds\";\nimport { createPendingUpdateFields } from \"../../data/documents/documentSync\";\nimport {\n type ContainerMetadataRecord,\n sqlContainerContentsPersistence,\n} from \"../../data/persistence/container-contents/containerContentsPersistence\";\nimport { deleteDocumentPlacements } from \"../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport {\n type AuthoredDiscoveryHead,\n primeAuthoredDocumentDiscoveryHeads,\n} from \"../../data/persistence/documents/documentDiscoveryEvidencePersistence\";\nimport {\n DOCUMENTS_APP_KIND,\n sqlDocumentsPersistence,\n} from \"../../data/persistence/documents/documentsPersistence\";\nimport type { DocumentRecord } from \"../../data/persistence/documents/records\";\nimport type { LocallyAcknowledgedAccessManifestHead } from \"../../data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence\";\nimport { documentContainerProjectionTables } from \"../../data/sqlite/schema/documentProjectionSchema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../data/sqlite/sqlitePersistenceRuntime\";\nimport {\n createExecSql,\n type ExecSql,\n type ExecSqlClientLike,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../../data/sqlite/sqlSchema\";\nimport { getScopedPeerSeed } from \"../../data/sync/crdtPeerSeed\";\nimport { persistDocumentState } from \"../documents/persistence\";\nimport { ORGANIZATION_PROFILE_DOCUMENT_KIND } from \"../organizations/organizationProfile\";\nimport {\n ORGANIZATION_METADATA_CONTAINER_NAME,\n ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n ROSTER_PROFILE_DOCUMENT_KIND,\n} from \"../organizations/rosterProfileContainer\";\nimport { seedRegistrationAccessHeads } from \"./registrationAccessHeadPersistence\";\nimport { enqueueInitialContainerMetadataUpdate } from \"./registrationBootstrapPendingUpdates\";\nimport { persistMissingContainerBootstrap } from \"./registrationContainerBootstrap\";\nimport { persistRegistrationPrincipalPolicies } from \"./registrationPrincipalPolicyPersistence\";\n\ninterface ProvisionedContainerBootstrapInput {\n accessEpoch: number;\n accessStateHash: string;\n containerId: string;\n createdAt: string;\n metadataDocumentId: string;\n metadataSnapshot: string;\n metadataState: Pick<\n DocumentRecord,\n | \"documentId\"\n | \"contentKeyBundle\"\n | \"documentKekTargets\"\n | \"documentManifestBundle\"\n >;\n systemSlot: ContainerSystemSlot;\n updatedAt: string;\n}\n\ninterface ProvisionedProfileDocumentBootstrapInput {\n accessEpoch: number;\n accessStateHash: string;\n containerId: string;\n documentId: string;\n documentState: ProvisionedContainerBootstrapInput[\"metadataState\"];\n initialUpdate: Uint8Array;\n initialUpdateCommitted: boolean;\n localId: string;\n}\n\nexport interface RegistrationBootstrapInput {\n /** @internal Completes the caller's journal inside the bootstrap transaction. */\n completeProvisioningAttempt?:\n | ((execSql: ExecSql) => Promise<void>)\n | undefined;\n acknowledgedAccessHeads: readonly LocallyAcknowledgedAccessManifestHead[];\n /** Seeded documents' acknowledged signed heads; see the discovery cache. */\n authoredDiscoveryHeads: readonly AuthoredDiscoveryHead[];\n /** Checked inside the mutation queue claim; false skips every write. */\n canStartDurableMutation?: (() => boolean) | undefined;\n /**\n * @internal Test-only synchronization seam. Invoked synchronously,\n * immediately before this persist joins the serialized mutation queue —\n * no interleaving can separate the two. Lets identity-race tests\n * deterministically place an identity replacement inside the queue-wait\n * window instead of sleeping.\n */\n onPersistQueued?: (() => void) | undefined;\n containerId: string;\n initialAdminGroupPolicy: PrincipalPolicyBundleResponse;\n initialMemberGroupPolicy: PrincipalPolicyBundleResponse;\n initialOrganizationPolicy: PrincipalPolicyBundleResponse;\n rootMetadataAccessEpoch: number;\n rootMetadataAccessStateHash: string;\n rootContainerServerTimestamp: string;\n rootMetadataDocumentId: string;\n rootMetadataInitialUpdate: Uint8Array;\n rootMetadataInitialUpdateCommitted?: boolean | undefined;\n rootMetadataSnapshot: string;\n rootMetadataState: ProvisionedContainerBootstrapInput[\"metadataState\"];\n rosterProfileContainer?: ProvisionedContainerBootstrapInput & {\n metadataInitialUpdate: Uint8Array;\n metadataInitialUpdateCommitted?: boolean | undefined;\n };\n organizationMetadataContainer?: ProvisionedContainerBootstrapInput & {\n metadataInitialUpdate: Uint8Array;\n metadataInitialUpdateCommitted?: boolean | undefined;\n };\n organizationProfileDocument?: ProvisionedProfileDocumentBootstrapInput;\n rosterProfileDocument?: ProvisionedProfileDocumentBootstrapInput;\n // Additional app-owned system containers provisioned with the organization\n // (e.g. a trash bin). Each carries its own display name and icon (unlike the\n // roster/organization-metadata containers, whose names are fixed), since the\n // caller declares them.\n systemContainers?: Array<\n ProvisionedContainerBootstrapInput & {\n icon: string | null;\n name: string;\n }\n >;\n documentProjectors?: DocumentProjectorRegistryInput | undefined;\n organizationId: string;\n userId: string;\n}\ntype CurrentBootstrap = RegistrationBootstrapInput & {\n canSeed: Awaited<ReturnType<typeof seedRegistrationAccessHeads>>;\n};\nasync function persistProvisionedContainerBootstrap(\n execSql: ExecSql,\n input: {\n container: ProvisionedContainerBootstrapInput;\n icon: string | null;\n name: string;\n organizationId: string;\n parentId: string | null;\n },\n): Promise<boolean> {\n const { container } = input;\n const metadataState = container.metadataState;\n const record: ContainerMetadataRecord = {\n accessEpoch: container.accessEpoch,\n accessStateHash: container.accessStateHash,\n documentId: container.metadataDocumentId,\n id: container.containerId,\n lastCommitLsn: null,\n metadataUpdates: container.metadataSnapshot,\n snapshotEndVersion: \"\",\n contentKeyBundle: metadataState.contentKeyBundle ?? null,\n documentKekTargets: metadataState.documentKekTargets ?? null,\n documentManifestBundle: metadataState.documentManifestBundle ?? null,\n };\n return persistMissingContainerBootstrap(\n execSql,\n {\n id: container.containerId,\n effectiveAccessLevel: \"admin\",\n organizationId: input.organizationId,\n parentId: input.parentId,\n metadataDocumentId: container.metadataDocumentId,\n systemSlot: container.systemSlot,\n name: input.name,\n icon: input.icon,\n },\n record,\n {\n localUpdatedAt: container.updatedAt,\n serverTimestamps: {\n createdAt: container.createdAt,\n updatedAt: container.updatedAt,\n },\n },\n );\n}\n\nasync function persistRootContainerBootstrap(\n execSql: ExecSql,\n input: CurrentBootstrap,\n): Promise<void> {\n if (\n !input.canSeed(\"container\", input.containerId) ||\n !input.canSeed(\"document\", input.rootMetadataDocumentId)\n )\n return;\n const rootRecord: ContainerMetadataRecord = {\n accessEpoch: input.rootMetadataAccessEpoch,\n accessStateHash: input.rootMetadataAccessStateHash,\n documentId: input.rootMetadataDocumentId,\n id: input.containerId,\n lastCommitLsn: null,\n metadataUpdates: input.rootMetadataSnapshot,\n snapshotEndVersion: \"\",\n contentKeyBundle: input.rootMetadataState.contentKeyBundle ?? null,\n documentKekTargets: input.rootMetadataState.documentKekTargets ?? null,\n documentManifestBundle:\n input.rootMetadataState.documentManifestBundle ?? null,\n };\n const seeded = await persistMissingContainerBootstrap(\n execSql,\n {\n id: input.containerId,\n effectiveAccessLevel: \"admin\",\n organizationId: input.organizationId,\n parentId: null,\n metadataDocumentId: input.rootMetadataDocumentId,\n name: \"/\",\n icon: null,\n },\n rootRecord,\n {\n localUpdatedAt: input.rootContainerServerTimestamp,\n serverTimestamps: {\n createdAt: input.rootContainerServerTimestamp,\n updatedAt: input.rootContainerServerTimestamp,\n },\n },\n );\n if (!seeded) return;\n await enqueueInitialContainerMetadataUpdate(\n execSql,\n input.containerId,\n input.rootMetadataInitialUpdate,\n input.rootMetadataInitialUpdateCommitted,\n );\n}\n\n// Persist reserved profile containers using their fixed topology: roster profiles\n// inherit the personal root; shared organization metadata has an independent root.\nasync function persistNamedChildContainerBootstrap(\n execSql: ExecSql,\n input: CurrentBootstrap,\n container: RegistrationBootstrapInput[\"rosterProfileContainer\"],\n name: string,\n): Promise<void> {\n if (\n !container ||\n !input.canSeed(\"container\", container.containerId) ||\n !input.canSeed(\"document\", container.metadataDocumentId)\n ) {\n return;\n }\n\n const seeded = await persistProvisionedContainerBootstrap(execSql, {\n container,\n icon: null,\n name,\n organizationId: input.organizationId,\n parentId:\n container === input.organizationMetadataContainer\n ? null\n : input.containerId,\n });\n if (!seeded) return;\n await enqueueInitialContainerMetadataUpdate(\n execSql,\n container.containerId,\n container.metadataInitialUpdate,\n container.metadataInitialUpdateCommitted,\n );\n}\n\nasync function persistSystemContainersBootstrap(\n execSql: ExecSql,\n input: CurrentBootstrap,\n): Promise<void> {\n const systemContainers = input.systemContainers;\n if (!systemContainers) {\n return;\n }\n\n for (const systemContainer of systemContainers) {\n if (\n !input.canSeed(\"container\", systemContainer.containerId) ||\n !input.canSeed(\"document\", systemContainer.metadataDocumentId)\n )\n continue;\n await persistProvisionedContainerBootstrap(execSql, {\n container: systemContainer,\n icon: systemContainer.icon,\n name: systemContainer.name,\n organizationId: input.organizationId,\n parentId: input.containerId,\n });\n // Provisioned system-container metadata is already committed remotely in\n // the organization transaction. Persist the initialized snapshot locally,\n // but do not queue a duplicate write with a second update id.\n }\n}\n\n// The ONE persist shape for the provisioned profile documents (organization\n// profile and roster profile): the input carries exactly the bootstrap\n// fields, so only the document kind and the host's projectors join it.\nasync function persistProfileDocumentBootstrap(\n execSql: ExecSql,\n input: CurrentBootstrap,\n profileDocument: ProvisionedProfileDocumentBootstrapInput | undefined,\n documentKind: string,\n): Promise<void> {\n if (\n !profileDocument ||\n !input.canSeed(\"document\", profileDocument.documentId) ||\n !input.canSeed(\"container\", profileDocument.containerId)\n ) {\n return;\n }\n\n await persistInitialDocumentBootstrap(execSql, {\n ...profileDocument,\n documentKind,\n documentProjectors: input.documentProjectors,\n });\n}\n\nexport async function persistInitialDocumentBootstrap(\n execSql: ExecSql,\n input: {\n accessEpoch: number;\n accessStateHash: string;\n containerId: string;\n documentId: string;\n documentKind: string;\n documentProjectors: DocumentProjectorRegistryInput | undefined;\n documentState: Pick<\n DocumentRecord,\n \"contentKeyBundle\" | \"documentKekTargets\" | \"documentManifestBundle\"\n >;\n initialUpdate: Uint8Array;\n initialUpdateCommitted: boolean;\n localId: string;\n },\n): Promise<void> {\n const doc = await createDocument(await getScopedPeerSeed(DOCUMENTS_APP_KIND));\n importUpdates(doc, [input.initialUpdate]);\n const pendingUpdate = input.initialUpdateCommitted\n ? undefined\n : (createPendingUpdateFields(input.initialUpdate) ?? undefined);\n\n await persistDocumentState({\n currentDoc: doc,\n currentRecord: null,\n deleteDocumentPlacements,\n documentProjectors: input.documentProjectors ?? [],\n execSql,\n localId: input.localId,\n patch: {\n accessEpoch: input.accessEpoch,\n accessStateHash: input.accessStateHash,\n containerId: input.containerId,\n contentKeyBundle: input.documentState.contentKeyBundle ?? null,\n documentId: input.documentId,\n // Successful provisioning makes this device's user the founding admin.\n // Stores can open before discovery returns the same access level.\n effectiveAccessLevel: \"admin\",\n documentKekTargets: input.documentState.documentKekTargets ?? null,\n documentKind: input.documentKind,\n documentManifestBundle:\n input.documentState.documentManifestBundle ?? null,\n // The create-only persistence primitive stores this frontier and the\n // full-history checkpoint in one transaction.\n snapshotEndVersion: encodeVersionVector(doc),\n },\n pendingUpdate,\n persistence: sqlDocumentsPersistence,\n });\n}\n\n/**\n * Persists the local root-container bootstrap created during successful\n * registration so container contents can initialize from SQLite on first\n * login — atomically: every write lands inside ONE transaction whose last\n * act re-checks identity currency, so an identity replaced anywhere between\n * the queue claim and the commit rolls the entire bootstrap back instead of\n * leaving a partial one. Resolves false when either currency check rejected\n * the write, so callers do not report a bootstrap that was never persisted.\n */\nexport async function persistRegistrationBootstrapFromExecSql(\n execSql: ExecSql,\n input: RegistrationBootstrapInput,\n): Promise<boolean> {\n input.onPersistQueued?.();\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n // In-mutex currency check, adjacent to the serialized-mutation claim\n // (see persistDocumentState): the identity can be replaced while this\n // persist waits for the queue, and its bootstrap must not be written\n // through a client the replacement closed or renewed.\n if (input.canStartDurableMutation && !input.canStartDurableMutation()) {\n return false;\n }\n // Idempotent DDL stays outside the atomic boundary.\n await sqlContainerContentsPersistence.ensureSchema(lockedExecSql);\n await sqlDocumentsPersistence.ensureSchema(lockedExecSql);\n await ensureSqlTables(lockedExecSql, documentContainerProjectionTables);\n // Pre-commit currency guard: the write sequence awaits real work, so\n // the identity can be replaced mid-sequence. The guard runs\n // synchronously with the COMMIT dispatch, so a refusal rolls the whole\n // write set back and a pass cannot go stale before the commit is sent —\n // the partial-persist window a single entry check leaves open.\n const { committed } = await getClientSQLitePersistenceRuntime(\n lockedExecSql,\n ).guardedTransaction(\n async () => {\n const canSeed = await seedRegistrationAccessHeads({\n execSql: lockedExecSql,\n heads: input.acknowledgedAccessHeads,\n organizationId: input.organizationId,\n });\n const bootstrap = { ...input, canSeed };\n await persistRegistrationPrincipalPolicies({\n adminGroup: input.initialAdminGroupPolicy,\n execSql: lockedExecSql,\n memberGroup: input.initialMemberGroupPolicy,\n organization: input.initialOrganizationPolicy,\n });\n await persistRootContainerBootstrap(lockedExecSql, bootstrap);\n await persistNamedChildContainerBootstrap(\n lockedExecSql,\n bootstrap,\n input.rosterProfileContainer,\n ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n );\n await persistProfileDocumentBootstrap(\n lockedExecSql,\n bootstrap,\n input.rosterProfileDocument,\n ROSTER_PROFILE_DOCUMENT_KIND,\n );\n await persistNamedChildContainerBootstrap(\n lockedExecSql,\n bootstrap,\n input.organizationMetadataContainer,\n ORGANIZATION_METADATA_CONTAINER_NAME,\n );\n await persistProfileDocumentBootstrap(\n lockedExecSql,\n bootstrap,\n input.organizationProfileDocument,\n ORGANIZATION_PROFILE_DOCUMENT_KIND,\n );\n await persistSystemContainersBootstrap(lockedExecSql, bootstrap);\n // After the checkpoints above: discovery reuses a cached head only\n // while its access-manifest checkpoint still matches.\n await primeAuthoredDocumentDiscoveryHeads(\n lockedExecSql,\n input.authoredDiscoveryHeads.filter((head) =>\n canSeed(\"document\", head.documentId),\n ),\n );\n await input.completeProvisioningAttempt?.(lockedExecSql);\n },\n () => !input.canStartDurableMutation || input.canStartDurableMutation(),\n );\n return committed;\n });\n}\n\nexport async function persistRegistrationBootstrap(\n client: ExecSqlClientLike,\n input: RegistrationBootstrapInput,\n): Promise<void> {\n await persistRegistrationBootstrapFromExecSql(createExecSql(client), input);\n}\n"]}
1
+ {"version":3,"file":"persistRegistrationBootstrap.js","sourceRoot":"","sources":["persistRegistrationBootstrap.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,mBAAmB,EACnB,aAAa,GACd,MAAM,iBAAiB,C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,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,4BAA4B,CAChD,MAAyB,EACzB,KAAiC;IAEjC,MAAM,uCAAuC,CAAC,aAAa,CAAC,MAAM,CAAC,EAAE,KAAK,CAAC,CAAC;AAC9E,CAAC","sourcesContent":["import {\n createDocument,\n encodeVersionVector,\n importUpdates,\n} from \"@tearleads/loro\";\nimport type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport type { DocumentProjectorRegistryInput } from \"../../data/documents/documentKinds\";\nimport { createPendingUpdateFields } from \"../../data/documents/documentSync\";\nimport {\n type ContainerMetadataRecord,\n sqlContainerContentsPersistence,\n} from \"../../data/persistence/container-contents/containerContentsPersistence\";\nimport { deleteDocumentPlacements } from \"../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport {\n type AuthoredDiscoveryHead,\n primeAuthoredDocumentDiscoveryHeads,\n} from \"../../data/persistence/documents/documentDiscoveryEvidencePersistence\";\nimport {\n DOCUMENTS_APP_KIND,\n sqlDocumentsPersistence,\n} from \"../../data/persistence/documents/documentsPersistence\";\nimport type { DocumentRecord } from \"../../data/persistence/documents/records\";\nimport type { LocallyAcknowledgedAccessManifestHead } from \"../../data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence\";\nimport { documentContainerProjectionTables } from \"../../data/sqlite/schema/documentProjectionSchema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../data/sqlite/sqlitePersistenceRuntime\";\nimport {\n createExecSql,\n type ExecSql,\n type ExecSqlClientLike,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../../data/sqlite/sqlSchema\";\nimport { getScopedPeerSeed } from \"../../data/sync/crdtPeerSeed\";\nimport { persistDocumentState } from \"../documents/persistence\";\nimport { ORGANIZATION_PROFILE_DOCUMENT_KIND } from \"../organizations/organizationProfile\";\nimport {\n ORGANIZATION_METADATA_CONTAINER_NAME,\n ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n ROSTER_PROFILE_DOCUMENT_KIND,\n} from \"../organizations/rosterProfileContainer\";\nimport { seedRegistrationAccessHeads } from \"./registrationAccessHeadPersistence\";\nimport { enqueueInitialContainerMetadataUpdate } from \"./registrationBootstrapPendingUpdates\";\nimport { persistMissingContainerBootstrap } from \"./registrationContainerBootstrap\";\nimport { persistRegistrationPrincipalPolicies } from \"./registrationPrincipalPolicyPersistence\";\n\ninterface ProvisionedContainerBootstrapInput {\n accessEpoch: number;\n accessStateHash: string;\n containerId: string;\n createdAt: string;\n metadataDocumentId: string;\n metadataSnapshot: string;\n metadataState: Pick<\n DocumentRecord,\n | \"documentId\"\n | \"contentKeyBundle\"\n | \"documentKekTargets\"\n | \"documentManifestBundle\"\n >;\n systemSlot: ContainerSystemSlot;\n updatedAt: string;\n}\n\ninterface ProvisionedProfileDocumentBootstrapInput {\n accessEpoch: number;\n accessStateHash: string;\n containerId: string;\n documentId: string;\n documentState: ProvisionedContainerBootstrapInput[\"metadataState\"];\n initialUpdate: Uint8Array;\n initialUpdateCommitted: boolean;\n localId: string;\n}\n\nexport interface RegistrationBootstrapInput {\n /** @internal Completes the caller's journal inside the bootstrap transaction. */\n completeProvisioningAttempt?:\n | ((execSql: ExecSql) => Promise<void>)\n | undefined;\n acknowledgedAccessHeads: readonly LocallyAcknowledgedAccessManifestHead[];\n /** Seeded documents' acknowledged signed heads; see the discovery cache. */\n authoredDiscoveryHeads: readonly AuthoredDiscoveryHead[];\n /** Checked inside the mutation queue claim; false skips every write. */\n canStartDurableMutation?: (() => boolean) | undefined;\n /**\n * The provisioning's commit position, read after its transaction. Every\n * seeded document keeps it as its last commit, so its first read passes it\n * as `minLsn` and a clean seed needs no read at all.\n */\n commitLsn: string | null;\n /**\n * @internal Test-only synchronization seam. Invoked synchronously,\n * immediately before this persist joins the serialized mutation queue —\n * no interleaving can separate the two. Lets identity-race tests\n * deterministically place an identity replacement inside the queue-wait\n * window instead of sleeping.\n */\n onPersistQueued?: (() => void) | undefined;\n containerId: string;\n initialAdminGroupPolicy: PrincipalPolicyBundleResponse;\n initialMemberGroupPolicy: PrincipalPolicyBundleResponse;\n initialOrganizationPolicy: PrincipalPolicyBundleResponse;\n rootMetadataAccessEpoch: number;\n rootMetadataAccessStateHash: string;\n rootContainerServerTimestamp: string;\n rootMetadataDocumentId: string;\n rootMetadataInitialUpdate: Uint8Array;\n rootMetadataInitialUpdateCommitted?: boolean | undefined;\n rootMetadataSnapshot: string;\n rootMetadataState: ProvisionedContainerBootstrapInput[\"metadataState\"];\n rosterProfileContainer?: ProvisionedContainerBootstrapInput & {\n metadataInitialUpdate: Uint8Array;\n metadataInitialUpdateCommitted?: boolean | undefined;\n };\n organizationMetadataContainer?: ProvisionedContainerBootstrapInput & {\n metadataInitialUpdate: Uint8Array;\n metadataInitialUpdateCommitted?: boolean | undefined;\n };\n organizationProfileDocument?: ProvisionedProfileDocumentBootstrapInput;\n rosterProfileDocument?: ProvisionedProfileDocumentBootstrapInput;\n // Additional app-owned system containers provisioned with the organization\n // (e.g. a trash bin). Each carries its own display name and icon (unlike the\n // roster/organization-metadata containers, whose names are fixed), since the\n // caller declares them.\n systemContainers?: Array<\n ProvisionedContainerBootstrapInput & {\n icon: string | null;\n name: string;\n }\n >;\n documentProjectors?: DocumentProjectorRegistryInput | undefined;\n organizationId: string;\n userId: string;\n}\ntype CurrentBootstrap = RegistrationBootstrapInput & {\n canSeed: Awaited<ReturnType<typeof seedRegistrationAccessHeads>>;\n};\nasync function persistProvisionedContainerBootstrap(\n execSql: ExecSql,\n input: {\n container: ProvisionedContainerBootstrapInput;\n icon: string | null;\n lastCommitLsn: string | null;\n name: string;\n organizationId: string;\n parentId: string | null;\n },\n): Promise<boolean> {\n const { container } = input;\n const metadataState = container.metadataState;\n const record: ContainerMetadataRecord = {\n accessEpoch: container.accessEpoch,\n accessStateHash: container.accessStateHash,\n documentId: container.metadataDocumentId,\n id: container.containerId,\n lastCommitLsn: input.lastCommitLsn,\n metadataUpdates: container.metadataSnapshot,\n snapshotEndVersion: \"\",\n contentKeyBundle: metadataState.contentKeyBundle ?? null,\n documentKekTargets: metadataState.documentKekTargets ?? null,\n documentManifestBundle: metadataState.documentManifestBundle ?? null,\n };\n return persistMissingContainerBootstrap(\n execSql,\n {\n id: container.containerId,\n effectiveAccessLevel: \"admin\",\n organizationId: input.organizationId,\n parentId: input.parentId,\n metadataDocumentId: container.metadataDocumentId,\n systemSlot: container.systemSlot,\n name: input.name,\n icon: input.icon,\n },\n record,\n {\n localUpdatedAt: container.updatedAt,\n serverTimestamps: {\n createdAt: container.createdAt,\n updatedAt: container.updatedAt,\n },\n },\n );\n}\n\nasync function persistRootContainerBootstrap(\n execSql: ExecSql,\n input: CurrentBootstrap,\n): Promise<void> {\n if (\n !input.canSeed(\"container\", input.containerId) ||\n !input.canSeed(\"document\", input.rootMetadataDocumentId)\n )\n return;\n const rootRecord: ContainerMetadataRecord = {\n accessEpoch: input.rootMetadataAccessEpoch,\n accessStateHash: input.rootMetadataAccessStateHash,\n documentId: input.rootMetadataDocumentId,\n id: input.containerId,\n lastCommitLsn: input.commitLsn,\n metadataUpdates: input.rootMetadataSnapshot,\n snapshotEndVersion: \"\",\n contentKeyBundle: input.rootMetadataState.contentKeyBundle ?? null,\n documentKekTargets: input.rootMetadataState.documentKekTargets ?? null,\n documentManifestBundle:\n input.rootMetadataState.documentManifestBundle ?? null,\n };\n const seeded = await persistMissingContainerBootstrap(\n execSql,\n {\n id: input.containerId,\n effectiveAccessLevel: \"admin\",\n organizationId: input.organizationId,\n parentId: null,\n metadataDocumentId: input.rootMetadataDocumentId,\n name: \"/\",\n icon: null,\n },\n rootRecord,\n {\n localUpdatedAt: input.rootContainerServerTimestamp,\n serverTimestamps: {\n createdAt: input.rootContainerServerTimestamp,\n updatedAt: input.rootContainerServerTimestamp,\n },\n },\n );\n if (!seeded) return;\n await enqueueInitialContainerMetadataUpdate(\n execSql,\n input.containerId,\n input.rootMetadataInitialUpdate,\n input.rootMetadataInitialUpdateCommitted,\n );\n}\n\n// Persist reserved profile containers using their fixed topology: roster profiles\n// inherit the personal root; shared organization metadata has an independent root.\nasync function persistNamedChildContainerBootstrap(\n execSql: ExecSql,\n input: CurrentBootstrap,\n container: RegistrationBootstrapInput[\"rosterProfileContainer\"],\n name: string,\n): Promise<void> {\n if (\n !container ||\n !input.canSeed(\"container\", container.containerId) ||\n !input.canSeed(\"document\", container.metadataDocumentId)\n ) {\n return;\n }\n\n const seeded = await persistProvisionedContainerBootstrap(execSql, {\n container,\n icon: null,\n lastCommitLsn: input.commitLsn,\n name,\n organizationId: input.organizationId,\n parentId:\n container === input.organizationMetadataContainer\n ? null\n : input.containerId,\n });\n if (!seeded) return;\n await enqueueInitialContainerMetadataUpdate(\n execSql,\n container.containerId,\n container.metadataInitialUpdate,\n container.metadataInitialUpdateCommitted,\n );\n}\n\nasync function persistSystemContainersBootstrap(\n execSql: ExecSql,\n input: CurrentBootstrap,\n): Promise<void> {\n const systemContainers = input.systemContainers;\n if (!systemContainers) {\n return;\n }\n\n for (const systemContainer of systemContainers) {\n if (\n !input.canSeed(\"container\", systemContainer.containerId) ||\n !input.canSeed(\"document\", systemContainer.metadataDocumentId)\n )\n continue;\n await persistProvisionedContainerBootstrap(execSql, {\n container: systemContainer,\n icon: systemContainer.icon,\n lastCommitLsn: input.commitLsn,\n name: systemContainer.name,\n organizationId: input.organizationId,\n parentId: input.containerId,\n });\n // Provisioned system-container metadata is already committed remotely in\n // the organization transaction. Persist the initialized snapshot locally,\n // but do not queue a duplicate write with a second update id.\n }\n}\n\n// The ONE persist shape for the provisioned profile documents (organization\n// profile and roster profile): the input carries exactly the bootstrap\n// fields, so only the document kind and the host's projectors join it.\nasync function persistProfileDocumentBootstrap(\n execSql: ExecSql,\n input: CurrentBootstrap,\n profileDocument: ProvisionedProfileDocumentBootstrapInput | undefined,\n documentKind: string,\n): Promise<void> {\n if (\n !profileDocument ||\n !input.canSeed(\"document\", profileDocument.documentId) ||\n !input.canSeed(\"container\", profileDocument.containerId)\n ) {\n return;\n }\n\n await persistInitialDocumentBootstrap(execSql, {\n ...profileDocument,\n documentKind,\n documentProjectors: input.documentProjectors,\n lastCommitLsn: input.commitLsn,\n });\n}\n\nexport async function persistInitialDocumentBootstrap(\n execSql: ExecSql,\n input: {\n accessEpoch: number;\n accessStateHash: string;\n containerId: string;\n documentId: string;\n documentKind: string;\n documentProjectors: DocumentProjectorRegistryInput | undefined;\n documentState: Pick<\n DocumentRecord,\n \"contentKeyBundle\" | \"documentKekTargets\" | \"documentManifestBundle\"\n >;\n initialUpdate: Uint8Array;\n initialUpdateCommitted: boolean;\n lastCommitLsn: string | null;\n localId: string;\n },\n): Promise<void> {\n const doc = await createDocument(await getScopedPeerSeed(DOCUMENTS_APP_KIND));\n importUpdates(doc, [input.initialUpdate]);\n const pendingUpdate = input.initialUpdateCommitted\n ? undefined\n : (createPendingUpdateFields(input.initialUpdate) ?? undefined);\n\n await persistDocumentState({\n currentDoc: doc,\n currentRecord: null,\n deleteDocumentPlacements,\n documentProjectors: input.documentProjectors ?? [],\n execSql,\n localId: input.localId,\n patch: {\n accessEpoch: input.accessEpoch,\n accessStateHash: input.accessStateHash,\n containerId: input.containerId,\n contentKeyBundle: input.documentState.contentKeyBundle ?? null,\n documentId: input.documentId,\n // Successful provisioning makes this device's user the founding admin.\n // Stores can open before discovery returns the same access level.\n effectiveAccessLevel: \"admin\",\n documentKekTargets: input.documentState.documentKekTargets ?? null,\n documentKind: input.documentKind,\n documentManifestBundle:\n input.documentState.documentManifestBundle ?? null,\n lastCommitLsn: input.lastCommitLsn,\n // The create-only persistence primitive stores this frontier and the\n // full-history checkpoint in one transaction.\n snapshotEndVersion: encodeVersionVector(doc),\n },\n pendingUpdate,\n persistence: sqlDocumentsPersistence,\n });\n}\n\n/**\n * Persists the local root-container bootstrap created during successful\n * registration so container contents can initialize from SQLite on first\n * login — atomically: every write lands inside ONE transaction whose last\n * act re-checks identity currency, so an identity replaced anywhere between\n * the queue claim and the commit rolls the entire bootstrap back instead of\n * leaving a partial one. Resolves false when either currency check rejected\n * the write, so callers do not report a bootstrap that was never persisted.\n */\nexport async function persistRegistrationBootstrapFromExecSql(\n execSql: ExecSql,\n input: RegistrationBootstrapInput,\n): Promise<boolean> {\n input.onPersistQueued?.();\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n // In-mutex currency check, adjacent to the serialized-mutation claim\n // (see persistDocumentState): the identity can be replaced while this\n // persist waits for the queue, and its bootstrap must not be written\n // through a client the replacement closed or renewed.\n if (input.canStartDurableMutation && !input.canStartDurableMutation()) {\n return false;\n }\n // Idempotent DDL stays outside the atomic boundary.\n await sqlContainerContentsPersistence.ensureSchema(lockedExecSql);\n await sqlDocumentsPersistence.ensureSchema(lockedExecSql);\n await ensureSqlTables(lockedExecSql, documentContainerProjectionTables);\n // Pre-commit currency guard: the write sequence awaits real work, so\n // the identity can be replaced mid-sequence. The guard runs\n // synchronously with the COMMIT dispatch, so a refusal rolls the whole\n // write set back and a pass cannot go stale before the commit is sent —\n // the partial-persist window a single entry check leaves open.\n const { committed } = await getClientSQLitePersistenceRuntime(\n lockedExecSql,\n ).guardedTransaction(\n async () => {\n const canSeed = await seedRegistrationAccessHeads({\n execSql: lockedExecSql,\n heads: input.acknowledgedAccessHeads,\n organizationId: input.organizationId,\n });\n const bootstrap = { ...input, canSeed };\n await persistRegistrationPrincipalPolicies({\n adminGroup: input.initialAdminGroupPolicy,\n execSql: lockedExecSql,\n memberGroup: input.initialMemberGroupPolicy,\n organization: input.initialOrganizationPolicy,\n });\n await persistRootContainerBootstrap(lockedExecSql, bootstrap);\n await persistNamedChildContainerBootstrap(\n lockedExecSql,\n bootstrap,\n input.rosterProfileContainer,\n ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n );\n await persistProfileDocumentBootstrap(\n lockedExecSql,\n bootstrap,\n input.rosterProfileDocument,\n ROSTER_PROFILE_DOCUMENT_KIND,\n );\n await persistNamedChildContainerBootstrap(\n lockedExecSql,\n bootstrap,\n input.organizationMetadataContainer,\n ORGANIZATION_METADATA_CONTAINER_NAME,\n );\n await persistProfileDocumentBootstrap(\n lockedExecSql,\n bootstrap,\n input.organizationProfileDocument,\n ORGANIZATION_PROFILE_DOCUMENT_KIND,\n );\n await persistSystemContainersBootstrap(lockedExecSql, bootstrap);\n // After the checkpoints above: discovery reuses a cached head only\n // while its access-manifest checkpoint still matches.\n await primeAuthoredDocumentDiscoveryHeads(\n lockedExecSql,\n input.authoredDiscoveryHeads.filter((head) =>\n canSeed(\"document\", head.documentId),\n ),\n );\n await input.completeProvisioningAttempt?.(lockedExecSql);\n },\n () => !input.canStartDurableMutation || input.canStartDurableMutation(),\n );\n return committed;\n });\n}\n\nexport async function persistRegistrationBootstrap(\n client: ExecSqlClientLike,\n input: RegistrationBootstrapInput,\n): Promise<void> {\n await persistRegistrationBootstrapFromExecSql(createExecSql(client), input);\n}\n"]}
@@ -46,6 +46,7 @@ export async function registerIdentity(input) {
46
46
  await persistOrganizationProvisioningState({
47
47
  bootstrap: artifacts.bootstrap,
48
48
  canStartDurableMutation: input.isIdentityCurrent,
49
+ commitLsn: response.commitLsn,
49
50
  onPersistQueued: input.onPersistQueued,
50
51
  containerId: input.containerId,
51
52
  dbClient: input.dbClient,