@tearleads/client-sdk 0.1.237 → 0.1.239

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 (31) hide show
  1. package/data/persistence/documents/records/documentSyncFailurePersistence.d.ts +0 -2
  2. package/data/persistence/documents/records/documentSyncFailurePersistence.js +0 -2
  3. package/data/persistence/documents/records/documentSyncFailurePersistence.js.map +1 -1
  4. package/data/persistence/organizations/organizationReadModelDirectoryPersistence.js +88 -0
  5. package/data/persistence/organizations/organizationReadModelDirectoryPersistence.js.map +1 -0
  6. package/data/persistence/organizations/organizationReadModelPersistence.js +8 -46
  7. package/data/persistence/organizations/organizationReadModelPersistence.js.map +1 -1
  8. package/data/persistence/organizations/organizationReadModelProjection.js +0 -4
  9. package/data/persistence/organizations/organizationReadModelProjection.js.map +1 -1
  10. package/data/sqlite/migrations/localSchemaMigrations.js +30 -1
  11. package/data/sqlite/migrations/localSchemaMigrations.js.map +1 -1
  12. package/data/sqlite/schema/documentRecordSchema.js +4 -6
  13. package/data/sqlite/schema/documentRecordSchema.js.map +1 -1
  14. package/data/sqlite/schema/index.d.ts +0 -55
  15. package/data/sqlite/schema/organizationReadModelSchema.js +4 -3
  16. package/data/sqlite/schema/organizationReadModelSchema.js.map +1 -1
  17. package/data/sqlite/schema/organizationReadModelTableRegistry.d.ts +0 -38
  18. package/internal/api-client/ApiClient.d.ts +0 -6
  19. package/internal/api-client/client/organizations.d.ts +0 -6
  20. package/internal/validators/operation/organizations.d.ts +0 -32
  21. package/internal/validators/response/organization.d.ts +5 -63
  22. package/internal/validators/response/organization.js +5 -7
  23. package/internal/validators/response/organization.js.map +1 -1
  24. package/internal/validators/response/organizationReadModel.d.ts +3 -23
  25. package/internal/validators/response/organizationReadModel.js +4 -7
  26. package/internal/validators/response/organizationReadModel.js.map +1 -1
  27. package/package.json +1 -1
  28. package/stores/documents/documentStore/sync/attachmentUploadFailure.js +0 -1
  29. package/stores/documents/documentStore/sync/attachmentUploadFailure.js.map +1 -1
  30. package/stores/documents/documentStore/sync/syncShared.js +0 -1
  31. package/stores/documents/documentStore/sync/syncShared.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"organizationReadModel.js","sourceRoot":"","sources":["organizationReadModel.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EACL,oCAAoC,EACpC,sBAAsB,GACvB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,+CAA+C,EAAE,MAAM,qCAAqC,CAAC;AACtG,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AACxC,OAAO,EACL,uCAAuC,EACvC,6CAA6C,EAC7C,sCAAsC,EACtC,0CAA0C,EAC1C,oCAAoC,EACpC,qCAAqC,GACtC,MAAM,gBAAgB,CAAC;AAExB,MAAM,gDAAgD,GAAG,CAAC,CAAC,YAAY,CACrE,sCAAsC,CACvC,CAAC;AAEF,MAAM,4CAA4C,GAAG,CAAC,CAAC,YAAY,CAAC;IAClE,cAAc,EAAE,CAAC,CAAC,MAAM,EAAE;IAC1B,iBAAiB,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IACxC,KAAK,EAAE,WAAW,CAAC,gDAAgD,CAAC;CACrE,CAAC,CAAC;AAMH,MAAM,wCAAwC,GAAG,CAAC,CAAC,YAAY,CAC7D,uCAAuC,CACxC,CAAC;AAEF,MAAM,yCAAyC,GAAG,CAAC,CAAC,YAAY,CAAC;IAC/D,MAAM,EAAE,WAAW,CAAC,wCAAwC,CAAC;IAC7D,cAAc,EAAE,CAAC,CAAC,MAAM,EAAE;CAC3B,CAAC,CAAC;AAMH;;;;GAIG;AACH,MAAM,8CAA8C,GAAG,CAAC,CAAC,YAAY,CAAC;IACpE,IAAI,EAAE,oCAAoC,CAAC,IAAI;IAC/C,MAAM,EAAE,oCAAoC,CAAC,MAAM;CACpD,CAAC,CAAC;AAMH,MAAM,kDAAkD,GAAG,C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AK,CAAC,MAAM,CAAC,cAAc,KAAK,cAAc;gBAC7C,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CACvB,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,cAAc,KAAK,cAAc,CACnD,CAAC,CAAC;QACP,CAAC,KAAK,CAAC,kBAAkB,KAAK,SAAS;YACrC,KAAK,CAAC,kBAAkB,CAAC,cAAc,KAAK,cAAc,CAAC,CAC9D,CAAC;AACJ,CAAC;AAED,SAAS,0BAA0B,CACjC,KAAwC;IAExC,IACE,CAAC,sBAAsB,CAAC,KAAK,CAAC;QAC9B,CAAC,KAAK,CAAC,KAAK,CAAC,MAAM,KAAK,SAAS;YAC/B,CAAC,cAAc,CAAC,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QAC7C,CAAC,KAAK,CAAC,KAAK,CAAC,gBAAgB,KAAK,SAAS;YACzC,CAAC,wBAAwB,CAAC,KAAK,CAAC,KAAK,CAAC,gBAAgB,CAAC,CAAC,EAC1D,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,OAAO,CACL,KAAK,CAAC,IAAI,KAAK,OAAO;QACtB,KAAK,CAAC,KAAK,CAAC,gBAAgB,CAAC,eAAe,CAAC,MAAM,KAAK,CAAC,CAC1D,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,MAAM,mCAAmC,GAC9C,oCAAoC,CAClC,sBAAsB,CACpB,uCAAuC,CAAC,MAAM,CAC5C,0BAA0B,CAC3B,EACD,uCAAuC,CACxC,EACD,+CAA+C,CAChD,CAAC;AAMJ,MAAM,UAAU,+BAA+B,CAC7C,KAAc;IAEd,OAAO,mCAAmC,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC;AACtE,CAAC","sourcesContent":["import { z } from \"zod\";\nimport {\n registerJsonSchemaRuntimeRefinements,\n registerJsonSchemaView,\n} from \"../jsonSchema\";\nimport { organizationReadModelResponseRuntimeRefinements } from \"../organizationReadModelRefinements\";\nimport { arraySchema } from \"../schema\";\nimport {\n OrganizationContainerGrantResponseShape,\n OrganizationDirectoryCurrentUserResponseShape,\n OrganizationDirectoryUserResponseShape,\n OrganizationGroupCurrentStateResponseShape,\n OrganizationGroupMemberResponseShape,\n OrganizationGroupSummaryResponseShape,\n} from \"./organization\";\n\nconst OrganizationReadModelDirectoryUserResponseSchema = z.strictObject(\n OrganizationDirectoryUserResponseShape,\n);\n\nconst OrganizationReadModelDirectoryResponseSchema = z.strictObject({\n organizationId: z.string(),\n profileDocumentId: z.string().nullable(),\n users: arraySchema(OrganizationReadModelDirectoryUserResponseSchema),\n});\n\nexport type OrganizationReadModelDirectoryResponse = z.infer<\n typeof OrganizationReadModelDirectoryResponseSchema\n>;\n\nconst OrganizationReadModelGrantResponseSchema = z.strictObject(\n OrganizationContainerGrantResponseShape,\n);\n\nconst OrganizationReadModelGrantsResponseSchema = z.strictObject({\n grants: arraySchema(OrganizationReadModelGrantResponseSchema),\n organizationId: z.string(),\n});\n\nexport type OrganizationReadModelGrantsResponse = z.infer<\n typeof OrganizationReadModelGrantsResponseSchema\n>;\n\n/**\n * A projected member names only the user and role. Public keys live once per\n * user in the directory lane; keying never reads either copy from the read\n * model.\n */\nconst OrganizationReadModelGroupMemberResponseSchema = z.strictObject({\n role: OrganizationGroupMemberResponseShape.role,\n userId: OrganizationGroupMemberResponseShape.userId,\n});\n\nexport type OrganizationReadModelGroupMemberResponse = z.infer<\n typeof OrganizationReadModelGroupMemberResponseSchema\n>;\n\nconst OrganizationReadModelGroupMembershipResponseSchema = z.strictObject({\n groupId: z.string(),\n members: arraySchema(OrganizationReadModelGroupMemberResponseSchema),\n stateHash: z.string().min(1),\n});\n\nexport type OrganizationReadModelGroupMembershipResponse = z.infer<\n typeof OrganizationReadModelGroupMembershipResponseSchema\n>;\n\nconst OrganizationReadModelGroupMembershipsResponseSchema = z.strictObject({\n deletedGroupIds: arraySchema(z.string().min(1)),\n groups: arraySchema(OrganizationReadModelGroupMembershipResponseSchema),\n organizationId: z.string(),\n});\n\nexport type OrganizationReadModelGroupMembershipsResponse = z.infer<\n typeof OrganizationReadModelGroupMembershipsResponseSchema\n>;\n\nconst OrganizationReadModelGroupCurrentStateResponseSchema = z.strictObject(\n OrganizationGroupCurrentStateResponseShape,\n);\n\nconst OrganizationReadModelGroupSummaryResponseSchema = z.strictObject({\n ...OrganizationGroupSummaryResponseShape,\n currentState: OrganizationReadModelGroupCurrentStateResponseSchema.nullable(),\n});\n\nconst OrganizationReadModelGroupsResponseSchema = z.strictObject({\n groups: arraySchema(OrganizationReadModelGroupSummaryResponseSchema),\n memberGroupId: z.string(),\n organizationId: z.string(),\n});\n\nconst OrganizationReadModelOrganizationPolicyResponseSchema = z.strictObject({\n currentState: z.strictObject({\n ...OrganizationGroupCurrentStateResponseShape,\n stateHash: z.string().min(1),\n }),\n organizationId: z.string(),\n});\n\nexport type OrganizationReadModelOrganizationPolicyResponse = z.infer<\n typeof OrganizationReadModelOrganizationPolicyResponseSchema\n>;\n\nconst OrganizationReadModelCurrentUserResponseSchema = z.strictObject(\n OrganizationDirectoryCurrentUserResponseShape,\n);\n\nconst OrganizationReadModelResponseBaseShape = {\n currentUser: OrganizationReadModelCurrentUserResponseSchema,\n hasMore: z.boolean(),\n nextCursor: z.string().min(1),\n organizationId: z.string(),\n version: z.literal(6),\n};\n\nconst OrganizationReadModelSnapshotResponseSchema = z.strictObject({\n ...OrganizationReadModelResponseBaseShape,\n hasMore: z.literal(false),\n lanes: z.strictObject({\n directory: OrganizationReadModelDirectoryResponseSchema,\n grants: OrganizationReadModelGrantsResponseSchema,\n groupMemberships: OrganizationReadModelGroupMembershipsResponseSchema,\n groups: OrganizationReadModelGroupsResponseSchema,\n organizationPolicy: OrganizationReadModelOrganizationPolicyResponseSchema,\n }),\n mode: z.literal(\"snapshot\"),\n});\n\nexport type OrganizationReadModelSnapshotResponse = z.infer<\n typeof OrganizationReadModelSnapshotResponseSchema\n>;\n\nconst OrganizationReadModelDeltaResponseSchema = z.strictObject({\n ...OrganizationReadModelResponseBaseShape,\n lanes: z.strictObject({\n directory: OrganizationReadModelDirectoryResponseSchema.optional(),\n grants: OrganizationReadModelGrantsResponseSchema.optional(),\n groupMemberships:\n OrganizationReadModelGroupMembershipsResponseSchema.optional(),\n groups: OrganizationReadModelGroupsResponseSchema.optional(),\n organizationPolicy:\n OrganizationReadModelOrganizationPolicyResponseSchema.optional(),\n }),\n mode: z.literal(\"delta\"),\n});\n\nexport type OrganizationReadModelDeltaResponse = z.infer<\n typeof OrganizationReadModelDeltaResponseSchema\n>;\n\nconst OrganizationReadModelResponseSchemaView = z.discriminatedUnion(\"mode\", [\n OrganizationReadModelDeltaResponseSchema,\n OrganizationReadModelSnapshotResponseSchema,\n]);\n\ntype OrganizationReadModelResponseView = z.infer<\n typeof OrganizationReadModelResponseSchemaView\n>;\n\nfunction hasValidGrantSubjectFields(\n grant: z.infer<typeof OrganizationReadModelGrantResponseSchema>,\n): boolean {\n if (grant.subjectType === \"user\") {\n return grant.userId === grant.subjectId && grant.groupId === null;\n }\n if (grant.subjectType === \"group\") {\n return (\n grant.userId === null &&\n grant.signingKeyFingerprint === null &&\n grant.groupId === grant.subjectId\n );\n }\n return false;\n}\n\nfunction hasValidGrants(\n grants: OrganizationReadModelGrantsResponse[\"grants\"],\n): boolean {\n const keys = new Set<string>();\n return grants.every((grant) => {\n const key = `${grant.subjectType}:${grant.subjectId}:${grant.containerId}`;\n if (!hasValidGrantSubjectFields(grant) || keys.has(key)) {\n return false;\n }\n keys.add(key);\n return true;\n });\n}\n\nfunction hasValidGroupMemberships(\n lane: OrganizationReadModelGroupMembershipsResponse,\n): boolean {\n const groupIds = new Set<string>();\n const validGroups = lane.groups.every((group) => {\n if (groupIds.has(group.groupId)) {\n return false;\n }\n groupIds.add(group.groupId);\n const memberIds = new Set<string>();\n return group.members.every((member) => {\n if (memberIds.has(member.userId)) {\n return false;\n }\n memberIds.add(member.userId);\n return true;\n });\n });\n if (!validGroups) {\n return false;\n }\n\n const deletedGroupIds = new Set<string>();\n return lane.deletedGroupIds.every((groupId) => {\n if (groupIds.has(groupId) || deletedGroupIds.has(groupId)) {\n return false;\n }\n deletedGroupIds.add(groupId);\n return true;\n });\n}\n\nfunction laneOrganizationsMatch(\n value: OrganizationReadModelResponseView,\n): boolean {\n const { lanes, organizationId } = value;\n return (\n (lanes.directory === undefined ||\n lanes.directory.organizationId === organizationId) &&\n (lanes.grants === undefined ||\n lanes.grants.organizationId === organizationId) &&\n (lanes.groupMemberships === undefined ||\n lanes.groupMemberships.organizationId === organizationId) &&\n (lanes.groups === undefined ||\n (lanes.groups.organizationId === organizationId &&\n lanes.groups.groups.every(\n (group) => group.organizationId === organizationId,\n ))) &&\n (lanes.organizationPolicy === undefined ||\n lanes.organizationPolicy.organizationId === organizationId)\n );\n}\n\nfunction hasValidReadModelSemantics(\n value: OrganizationReadModelResponseView,\n): boolean {\n if (\n !laneOrganizationsMatch(value) ||\n (value.lanes.grants !== undefined &&\n !hasValidGrants(value.lanes.grants.grants)) ||\n (value.lanes.groupMemberships !== undefined &&\n !hasValidGroupMemberships(value.lanes.groupMemberships))\n ) {\n return false;\n }\n\n return (\n value.mode === \"delta\" ||\n value.lanes.groupMemberships.deletedGroupIds.length === 0\n );\n}\n\nexport const OrganizationReadModelResponseSchema =\n registerJsonSchemaRuntimeRefinements(\n registerJsonSchemaView(\n OrganizationReadModelResponseSchemaView.refine(\n hasValidReadModelSemantics,\n ),\n OrganizationReadModelResponseSchemaView,\n ),\n organizationReadModelResponseRuntimeRefinements,\n );\n\nexport type OrganizationReadModelResponse = z.infer<\n typeof OrganizationReadModelResponseSchema\n>;\n\nexport function isOrganizationReadModelResponse(\n value: unknown,\n): value is OrganizationReadModelResponse {\n return OrganizationReadModelResponseSchema.safeParse(value).success;\n}\n"]}
1
+ {"version":3,"file":"organizationReadModel.js","sourceRoot":"","sources":["organizationReadModel.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE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;AACJ,CAAC;AAED,SAAS,0BAA0B,CACjC,KAAwC;IAExC,IACE,CAAC,sBAAsB,CAAC,KAAK,CAAC;QAC9B,CAAC,KAAK,CAAC,KAAK,CAAC,MAAM,KAAK,SAAS;YAC/B,CAAC,cAAc,CAAC,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QAC7C,CAAC,KAAK,CAAC,KAAK,CAAC,gBAAgB,KAAK,SAAS;YACzC,CAAC,wBAAwB,CAAC,KAAK,CAAC,KAAK,CAAC,gBAAgB,CAAC,CAAC,EAC1D,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,OAAO,CACL,KAAK,CAAC,IAAI,KAAK,OAAO;QACtB,KAAK,CAAC,KAAK,CAAC,gBAAgB,CAAC,eAAe,CAAC,MAAM,KAAK,CAAC,CAC1D,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,MAAM,mCAAmC,GAC9C,oCAAoC,CAClC,sBAAsB,CACpB,uCAAuC,CAAC,MAAM,CAC5C,0BAA0B,CAC3B,EACD,uCAAuC,CACxC,EACD,+CAA+C,CAChD,CAAC;AAMJ,MAAM,UAAU,+BAA+B,CAC7C,KAAc;IAEd,OAAO,mCAAmC,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC;AACtE,CAAC","sourcesContent":["import { z } from \"zod\";\nimport {\n registerJsonSchemaRuntimeRefinements,\n registerJsonSchemaView,\n} from \"../jsonSchema\";\nimport { organizationReadModelResponseRuntimeRefinements } from \"../organizationReadModelRefinements\";\nimport { arraySchema } from \"../schema\";\nimport {\n OrganizationContainerGrantResponseShape,\n OrganizationDirectoryCurrentUserResponseShape,\n OrganizationDirectoryUserResponseShape,\n OrganizationGroupCurrentStateResponseShape,\n OrganizationGroupMemberResponseShape,\n OrganizationGroupSummaryResponseShape,\n} from \"./organization\";\n\nconst OrganizationReadModelDirectoryUserResponseSchema = z.strictObject(\n OrganizationDirectoryUserResponseShape,\n);\n\nconst OrganizationReadModelDirectoryResponseSchema = z.strictObject({\n organizationId: z.string(),\n profileDocumentId: z.string().nullable(),\n users: arraySchema(OrganizationReadModelDirectoryUserResponseSchema),\n});\n\nexport type OrganizationReadModelDirectoryResponse = z.infer<\n typeof OrganizationReadModelDirectoryResponseSchema\n>;\n\nconst OrganizationReadModelGrantResponseSchema = z.strictObject(\n OrganizationContainerGrantResponseShape,\n);\n\nconst OrganizationReadModelGrantsResponseSchema = z.strictObject({\n grants: arraySchema(OrganizationReadModelGrantResponseSchema),\n organizationId: z.string(),\n});\n\nexport type OrganizationReadModelGrantsResponse = z.infer<\n typeof OrganizationReadModelGrantsResponseSchema\n>;\n\n/**\n * A projected member names only the user and role. The read model carries no\n * public keys: directory rows carry key fingerprints, and keying takes keys\n * from the trusted identity store.\n */\nconst OrganizationReadModelGroupMemberResponseSchema = z.strictObject(\n OrganizationGroupMemberResponseShape,\n);\n\nexport type OrganizationReadModelGroupMemberResponse = z.infer<\n typeof OrganizationReadModelGroupMemberResponseSchema\n>;\n\nconst OrganizationReadModelGroupMembershipResponseSchema = z.strictObject({\n groupId: z.string(),\n members: arraySchema(OrganizationReadModelGroupMemberResponseSchema),\n stateHash: z.string().min(1),\n});\n\nexport type OrganizationReadModelGroupMembershipResponse = z.infer<\n typeof OrganizationReadModelGroupMembershipResponseSchema\n>;\n\nconst OrganizationReadModelGroupMembershipsResponseSchema = z.strictObject({\n deletedGroupIds: arraySchema(z.string().min(1)),\n groups: arraySchema(OrganizationReadModelGroupMembershipResponseSchema),\n organizationId: z.string(),\n});\n\nexport type OrganizationReadModelGroupMembershipsResponse = z.infer<\n typeof OrganizationReadModelGroupMembershipsResponseSchema\n>;\n\nconst OrganizationReadModelGroupCurrentStateResponseSchema = z.strictObject(\n OrganizationGroupCurrentStateResponseShape,\n);\n\nconst OrganizationReadModelGroupSummaryResponseSchema = z.strictObject({\n ...OrganizationGroupSummaryResponseShape,\n currentState: OrganizationReadModelGroupCurrentStateResponseSchema.nullable(),\n});\n\nconst OrganizationReadModelGroupsResponseSchema = z.strictObject({\n groups: arraySchema(OrganizationReadModelGroupSummaryResponseSchema),\n memberGroupId: z.string(),\n organizationId: z.string(),\n});\n\nconst OrganizationReadModelOrganizationPolicyResponseSchema = z.strictObject({\n currentState: z.strictObject({\n ...OrganizationGroupCurrentStateResponseShape,\n stateHash: z.string().min(1),\n }),\n organizationId: z.string(),\n});\n\nexport type OrganizationReadModelOrganizationPolicyResponse = z.infer<\n typeof OrganizationReadModelOrganizationPolicyResponseSchema\n>;\n\nconst OrganizationReadModelCurrentUserResponseSchema = z.strictObject(\n OrganizationDirectoryCurrentUserResponseShape,\n);\n\nconst OrganizationReadModelResponseBaseShape = {\n currentUser: OrganizationReadModelCurrentUserResponseSchema,\n hasMore: z.boolean(),\n nextCursor: z.string().min(1),\n organizationId: z.string(),\n version: z.literal(6),\n};\n\nconst OrganizationReadModelSnapshotResponseSchema = z.strictObject({\n ...OrganizationReadModelResponseBaseShape,\n hasMore: z.literal(false),\n lanes: z.strictObject({\n directory: OrganizationReadModelDirectoryResponseSchema,\n grants: OrganizationReadModelGrantsResponseSchema,\n groupMemberships: OrganizationReadModelGroupMembershipsResponseSchema,\n groups: OrganizationReadModelGroupsResponseSchema,\n organizationPolicy: OrganizationReadModelOrganizationPolicyResponseSchema,\n }),\n mode: z.literal(\"snapshot\"),\n});\n\nexport type OrganizationReadModelSnapshotResponse = z.infer<\n typeof OrganizationReadModelSnapshotResponseSchema\n>;\n\nconst OrganizationReadModelDeltaResponseSchema = z.strictObject({\n ...OrganizationReadModelResponseBaseShape,\n lanes: z.strictObject({\n directory: OrganizationReadModelDirectoryResponseSchema.optional(),\n grants: OrganizationReadModelGrantsResponseSchema.optional(),\n groupMemberships:\n OrganizationReadModelGroupMembershipsResponseSchema.optional(),\n groups: OrganizationReadModelGroupsResponseSchema.optional(),\n organizationPolicy:\n OrganizationReadModelOrganizationPolicyResponseSchema.optional(),\n }),\n mode: z.literal(\"delta\"),\n});\n\nexport type OrganizationReadModelDeltaResponse = z.infer<\n typeof OrganizationReadModelDeltaResponseSchema\n>;\n\nconst OrganizationReadModelResponseSchemaView = z.discriminatedUnion(\"mode\", [\n OrganizationReadModelDeltaResponseSchema,\n OrganizationReadModelSnapshotResponseSchema,\n]);\n\ntype OrganizationReadModelResponseView = z.infer<\n typeof OrganizationReadModelResponseSchemaView\n>;\n\nfunction hasValidGrantSubjectFields(\n grant: z.infer<typeof OrganizationReadModelGrantResponseSchema>,\n): boolean {\n if (grant.subjectType === \"user\") {\n return grant.userId === grant.subjectId && grant.groupId === null;\n }\n if (grant.subjectType === \"group\") {\n return (\n grant.userId === null &&\n grant.signingKeyFingerprint === null &&\n grant.groupId === grant.subjectId\n );\n }\n return false;\n}\n\nfunction hasValidGrants(\n grants: OrganizationReadModelGrantsResponse[\"grants\"],\n): boolean {\n const keys = new Set<string>();\n return grants.every((grant) => {\n const key = `${grant.subjectType}:${grant.subjectId}:${grant.containerId}`;\n if (!hasValidGrantSubjectFields(grant) || keys.has(key)) {\n return false;\n }\n keys.add(key);\n return true;\n });\n}\n\nfunction hasValidGroupMemberships(\n lane: OrganizationReadModelGroupMembershipsResponse,\n): boolean {\n const groupIds = new Set<string>();\n const validGroups = lane.groups.every((group) => {\n if (groupIds.has(group.groupId)) {\n return false;\n }\n groupIds.add(group.groupId);\n const memberIds = new Set<string>();\n return group.members.every((member) => {\n if (memberIds.has(member.userId)) {\n return false;\n }\n memberIds.add(member.userId);\n return true;\n });\n });\n if (!validGroups) {\n return false;\n }\n\n const deletedGroupIds = new Set<string>();\n return lane.deletedGroupIds.every((groupId) => {\n if (groupIds.has(groupId) || deletedGroupIds.has(groupId)) {\n return false;\n }\n deletedGroupIds.add(groupId);\n return true;\n });\n}\n\nfunction laneOrganizationsMatch(\n value: OrganizationReadModelResponseView,\n): boolean {\n const { lanes, organizationId } = value;\n return (\n (lanes.directory === undefined ||\n lanes.directory.organizationId === organizationId) &&\n (lanes.grants === undefined ||\n lanes.grants.organizationId === organizationId) &&\n (lanes.groupMemberships === undefined ||\n lanes.groupMemberships.organizationId === organizationId) &&\n (lanes.groups === undefined ||\n (lanes.groups.organizationId === organizationId &&\n lanes.groups.groups.every(\n (group) => group.organizationId === organizationId,\n ))) &&\n (lanes.organizationPolicy === undefined ||\n lanes.organizationPolicy.organizationId === organizationId)\n );\n}\n\nfunction hasValidReadModelSemantics(\n value: OrganizationReadModelResponseView,\n): boolean {\n if (\n !laneOrganizationsMatch(value) ||\n (value.lanes.grants !== undefined &&\n !hasValidGrants(value.lanes.grants.grants)) ||\n (value.lanes.groupMemberships !== undefined &&\n !hasValidGroupMemberships(value.lanes.groupMemberships))\n ) {\n return false;\n }\n\n return (\n value.mode === \"delta\" ||\n value.lanes.groupMemberships.deletedGroupIds.length === 0\n );\n}\n\nexport const OrganizationReadModelResponseSchema =\n registerJsonSchemaRuntimeRefinements(\n registerJsonSchemaView(\n OrganizationReadModelResponseSchemaView.refine(\n hasValidReadModelSemantics,\n ),\n OrganizationReadModelResponseSchemaView,\n ),\n organizationReadModelResponseRuntimeRefinements,\n );\n\nexport type OrganizationReadModelResponse = z.infer<\n typeof OrganizationReadModelResponseSchema\n>;\n\nexport function isOrganizationReadModelResponse(\n value: unknown,\n): value is OrganizationReadModelResponse {\n return OrganizationReadModelResponseSchema.safeParse(value).success;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tearleads/client-sdk",
3
- "version": "0.1.237",
3
+ "version": "0.1.239",
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": {
@@ -17,7 +17,6 @@ export function reportAttachmentUploadFailure(input) {
17
17
  await new DocumentRecordRepository(lockedExecSql).recordDocumentSyncFailure({ appKind: DOCUMENTS_APP_KIND, localId: input.state.localId }, {
18
18
  attemptedAt: new Date().toISOString(),
19
19
  message: error.message,
20
- status: null,
21
20
  });
22
21
  }).catch(() => undefined);
23
22
  }
@@ -1 +1 @@
1
- {"version":3,"file":"attachmentUploadFailure.js","sourceRoot":"","sources":["attachmentUploadFailure.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,wBAAwB,EAExB,wBAAwB,GACzB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAEL,iCAAiC,GAClC,MAAM,0CAA0C,CAAC;AAElD,OAAO,EAEL,oCAAoC,GACrC,MAAM,kBAAkB,CAAC;AAE1B,MAAM,UAAU,6BAA6B,CAAC,KAM7C;IACC,MAAM,KAAK,GAAG,iCAAiC,CAC7C,KAAK,CAAC,iBAAiB,EACvB,KAAK,CAAC,KAAK,CACZ,CAAC;IACF,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC7B,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,cAAc,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;IAC5D,4EAA4E;IAC5E,sEAAsE;IACtE,yEAAyE;IACzE,yEAAyE;IACzE,kCAAkC;IAClC,KAAK,wBAAwB,CAC3B,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,EACjC,KAAK,EAAE,aAAa,EAAE,EAAE;QACtB,IACE,CAAC,oCAAoC,CACnC,KAAK,CAAC,KAAK,EACX,KAAK,CAAC,oBAAoB,CAC3B,EACD,CAAC;YACD,OAAO;QACT,CAAC;QACD,MAAM,IAAI,wBAAwB,CAChC,aAAa,CACd,CAAC,yBAAyB,CACzB,EAAE,OAAO,EAAE,kBAAkB,EAAE,OAAO,EAAE,KAAK,CAAC,KAAK,CAAC,OAAO,EAAE,EAC7D;YACE,WAAW,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YACrC,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,MAAM,EAAE,IAAI;SACb,CACF,CAAC;IACJ,CAAC,CACF,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;AAC3B,CAAC","sourcesContent":["import {\n DOCUMENTS_APP_KIND,\n DocumentRecordRepository,\n type PendingAttachmentRecord,\n runSerializedSqlMutation,\n} from \"../../../../workflows/documents\";\nimport {\n type AttachmentUploadLaneReporter,\n createAttachmentUploadFailedError,\n} from \"../attachmentUpload/attachmentUploadLane\";\nimport type { DocumentStoreState } from \"../state\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\n\nexport function reportAttachmentUploadFailure(input: {\n attachmentGeneration: DocumentStoreSyncGeneration;\n error: unknown;\n pendingAttachment: PendingAttachmentRecord;\n state: DocumentStoreState;\n uploadLane: AttachmentUploadLaneReporter;\n}): void {\n const error = createAttachmentUploadFailedError(\n input.pendingAttachment,\n input.error,\n );\n input.uploadLane.fail(error);\n input.state.runtime.util.log(`Documents: ${error.message}`);\n // Surface the stuck upload in the write queue; a later successful sync pass\n // for the document clears the record. Validated inside the serialized\n // mutation: a teardown (reset/discard) racing this pass just cleared the\n // failure row, and re-recording it would resurrect a phantom queue entry\n // for work that no longer exists.\n void runSerializedSqlMutation(\n input.state.runtime.infra.execSql,\n async (lockedExecSql) => {\n if (\n !isDocumentStoreSyncGenerationCurrent(\n input.state,\n input.attachmentGeneration,\n )\n ) {\n return;\n }\n await new DocumentRecordRepository(\n lockedExecSql,\n ).recordDocumentSyncFailure(\n { appKind: DOCUMENTS_APP_KIND, localId: input.state.localId },\n {\n attemptedAt: new Date().toISOString(),\n message: error.message,\n status: null,\n },\n );\n },\n ).catch(() => undefined);\n}\n"]}
1
+ {"version":3,"file":"attachmentUploadFailure.js","sourceRoot":"","sources":["attachmentUploadFailure.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,wBAAwB,EAExB,wBAAwB,GACzB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAEL,iCAAiC,GAClC,MAAM,0CAA0C,CAAC;AAElD,OAAO,EAEL,oCAAoC,GACrC,MAAM,kBAAkB,CAAC;AAE1B,MAAM,UAAU,6BAA6B,CAAC,KAM7C;IACC,MAAM,KAAK,GAAG,iCAAiC,CAC7C,KAAK,CAAC,iBAAiB,EACvB,KAAK,CAAC,KAAK,CACZ,CAAC;IACF,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC7B,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,cAAc,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;IAC5D,4EAA4E;IAC5E,sEAAsE;IACtE,yEAAyE;IACzE,yEAAyE;IACzE,kCAAkC;IAClC,KAAK,wBAAwB,CAC3B,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,EACjC,KAAK,EAAE,aAAa,EAAE,EAAE;QACtB,IACE,CAAC,oCAAoC,CACnC,KAAK,CAAC,KAAK,EACX,KAAK,CAAC,oBAAoB,CAC3B,EACD,CAAC;YACD,OAAO;QACT,CAAC;QACD,MAAM,IAAI,wBAAwB,CAChC,aAAa,CACd,CAAC,yBAAyB,CACzB,EAAE,OAAO,EAAE,kBAAkB,EAAE,OAAO,EAAE,KAAK,CAAC,KAAK,CAAC,OAAO,EAAE,EAC7D;YACE,WAAW,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YACrC,OAAO,EAAE,KAAK,CAAC,OAAO;SACvB,CACF,CAAC;IACJ,CAAC,CACF,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;AAC3B,CAAC","sourcesContent":["import {\n DOCUMENTS_APP_KIND,\n DocumentRecordRepository,\n type PendingAttachmentRecord,\n runSerializedSqlMutation,\n} from \"../../../../workflows/documents\";\nimport {\n type AttachmentUploadLaneReporter,\n createAttachmentUploadFailedError,\n} from \"../attachmentUpload/attachmentUploadLane\";\nimport type { DocumentStoreState } from \"../state\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\n\nexport function reportAttachmentUploadFailure(input: {\n attachmentGeneration: DocumentStoreSyncGeneration;\n error: unknown;\n pendingAttachment: PendingAttachmentRecord;\n state: DocumentStoreState;\n uploadLane: AttachmentUploadLaneReporter;\n}): void {\n const error = createAttachmentUploadFailedError(\n input.pendingAttachment,\n input.error,\n );\n input.uploadLane.fail(error);\n input.state.runtime.util.log(`Documents: ${error.message}`);\n // Surface the stuck upload in the write queue; a later successful sync pass\n // for the document clears the record. Validated inside the serialized\n // mutation: a teardown (reset/discard) racing this pass just cleared the\n // failure row, and re-recording it would resurrect a phantom queue entry\n // for work that no longer exists.\n void runSerializedSqlMutation(\n input.state.runtime.infra.execSql,\n async (lockedExecSql) => {\n if (\n !isDocumentStoreSyncGenerationCurrent(\n input.state,\n input.attachmentGeneration,\n )\n ) {\n return;\n }\n await new DocumentRecordRepository(\n lockedExecSql,\n ).recordDocumentSyncFailure(\n { appKind: DOCUMENTS_APP_KIND, localId: input.state.localId },\n {\n attemptedAt: new Date().toISOString(),\n message: error.message,\n },\n );\n },\n ).catch(() => undefined);\n}\n"]}
@@ -70,7 +70,6 @@ function documentSyncFailureHandler(input) {
70
70
  await new DocumentRecordRepository(lockedExecSql).recordDocumentSyncFailure({ appKind: DOCUMENTS_APP_KIND, localId: state.localId }, {
71
71
  attemptedAt: new Date().toISOString(),
72
72
  message: input.describeFailure(failure),
73
- status: failure.status,
74
73
  });
75
74
  });
76
75
  };
@@ -1 +1 @@
1
- {"version":3,"file":"syncShared.js","sourceRoot":"","sources":["syncShared.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,oDAAoD,CAAC;AAC5F,OAAO,EACL,kBAAkB,EAElB,wBAAwB,EAExB,mCAAmC,EACnC,iCAAiC,EAEjC,qBAAqB,EACrB,2BAA2B,EAC3B,wBAAwB,GACzB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,4BAA4B,EAAE,MAAM,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,EAAE,KAAK,IAAI,EAAE;QAC1C,IAAI,CAAC,mBAAmB,EAAE;YAAE,OAAO,KAAK,CAAC,MAAM,IAAI,UAAU,CAAC;QAE9D,uEAAuE;QACvE,yEAAyE;QACzE,0EAA0E;QAC1E,wEAAwE;QACxE,6DAA6D;QAC7D,MAAM,cAAc,GAAG,KAAK,CAAC,MAAM,EAAE,UAAU,CAAC;QAChD,IAAI,cAAc,IAAI,cAAc,KAAK,OAAO,CAAC,UAAU,EAAE,CAAC;YAC5D,OAAO,KAAK,CAAC,MAAM,CAAC;QACtB,CAAC;QAED,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,qBAAqB,OAAO,CAAC,UAAU,EAAE,CAAC,CAAC;QAC5D,+BAA+B,CAC7B,KAAK,EACL,OAAO,CAAC,gBAAgB,EACxB,0BAA0B,CAC3B,CAAC;QAEF,6EAA6E;QAC7E,4EAA4E;QAC5E,sEAAsE;QACtE,4EAA4E;QAC5E,4EAA4E;QAC5E,2EAA2E;QAC3E,6EAA6E;QAC7E,uEAAuE;QACvE,0EAA0E;QAC1E,yEAAyE;QACzE,gBAAgB;QAChB,MAAM,SAAS,GAAG,MAAM,4BAA4B,CAAC;YACnD,OAAO;YACP,UAAU;YACV,UAAU;YACV,IAAI;YACJ,KAAK;SACN,CAAC,CAAC;QACH,IAAI,SAAS,IAAI,OAAO,CAAC,YAAY,EAAE,CAAC;YACtC,YAAY,EAAE,QAAQ,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;QAC/C,CAAC;QACD,OAAO,SAAS,EAAE,MAAM,IAAI,KAAK,CAAC,MAAM,IAAI,UAAU,CAAC;IACzD,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { deriveStableDocumentId } from \"../../../../data/documents/shared/stableDocumentId\";\nimport {\n DOCUMENTS_APP_KIND,\n type DocumentRecord,\n DocumentRecordRepository,\n type DocumentSyncUpdateIsolationError,\n describeDocumentRevalidationFailure,\n describeDocumentSyncSubmitFailure,\n type PendingUpdateRecord,\n RemoteDocumentService,\n resolveDocumentCreateAuthor,\n runSerializedSqlMutation,\n} from \"../../../../workflows/documents\";\nimport { reportDocumentSyncQuarantine } from \"../../../../workflows/documents/sync/reportDocumentSyncQuarantine\";\nimport type { PrincipalPolicyOperation } from \"../../../../workflows/principals/principalPolicyService\";\nimport { chainIdentityWrite } from \"../identityWriteChain\";\nimport {\n type DocumentState,\n type DocumentStoreState,\n type EncapsulationKeyPair,\n markDocumentStoreRemoved,\n} from \"../state\";\nimport { installDocumentWriterProjection } from \"../writerProjectionGeneration\";\nimport {\n type CreateSeed,\n type DeferredBindSeed,\n persistCreatedRemoteDocument,\n} from \"./createdDocumentPersistence\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\nimport { recordPlannedRemoteDocumentId } from \"./syncRemoteSignals\";\n\n/**\n * Record a refused read-only revalidation on this document's failure row, so\n * a document that can never refresh stops failing silently (edge-case row\n * 13). 403s stay suppressed on purpose — a read-only 403 must never flag\n * unattempted local edits (row 9) — and the row clears on the next clean\n * pass like every other sync failure.\n */\nexport function documentRevalidationFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n return documentSyncFailureHandler({\n describeFailure: describeDocumentRevalidationFailure,\n generation,\n state,\n suppressForbidden: true,\n });\n}\n\n/**\n * Record a terminal submit failure on this document's write-queue row. Shared\n * by every store pass that can submit queued writes (create and sync), so\n * re-key exhaustion and denial failures surface no matter which pass hits\n * them first.\n */\nexport function documentTerminalSubmitFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n return documentSyncFailureHandler({\n describeFailure: describeDocumentSyncSubmitFailure,\n generation,\n state,\n });\n}\n\n/** Persist quarantine and report its Error through the host's diagnostics. */\nexport function documentIncomingUpdateIsolationFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n const recordFailure = documentSyncFailureHandler({\n describeFailure: (failure) => failure.message,\n generation,\n state,\n });\n return async (failure: DocumentSyncUpdateIsolationError) => {\n await recordFailure({ message: failure.message, status: null });\n if (generation && !isDocumentStoreSyncGenerationCurrent(state, generation))\n return;\n reportDocumentSyncQuarantine(\n generation?.currentDoc ?? state.doc ?? state,\n state.runtime.util.logError,\n failure,\n );\n };\n}\n\n/**\n * The generation recheck runs INSIDE the serialized mutation (like the\n * attachment failure path): a teardown (discard/reset) that wins the ordering\n * deletes this document's rows first and invalidates the generation, so a\n * stale handler can never resurrect a deleted or orphan failure row\n * afterwards.\n */\nfunction documentSyncFailureHandler(input: {\n describeFailure: (failure: {\n readonly message: string;\n readonly status: number | null;\n }) => string;\n generation: DocumentStoreSyncGeneration | undefined;\n state: DocumentStoreState;\n suppressForbidden?: boolean;\n}) {\n const { generation, state } = input;\n return async (failure: {\n readonly message: string;\n readonly status: number | null;\n }) => {\n if (input.suppressForbidden && failure.status === 403) {\n return;\n }\n\n await runSerializedSqlMutation(\n generation?.execSql ?? state.runtime.infra.execSql,\n async (lockedExecSql) => {\n if (\n generation &&\n !isDocumentStoreSyncGenerationCurrent(state, generation)\n ) {\n return;\n }\n await new DocumentRecordRepository(\n lockedExecSql,\n ).recordDocumentSyncFailure(\n { appKind: DOCUMENTS_APP_KIND, localId: state.localId },\n {\n attemptedAt: new Date().toISOString(),\n message: input.describeFailure(failure),\n status: failure.status,\n },\n );\n },\n );\n };\n}\n\nfunction hasPersistedRemoteDocumentSyncState(record: DocumentRecord): boolean {\n return (\n record.lastCommitLsn !== null &&\n record.contentKeyBundle !== null &&\n record.documentKekTargets !== null &&\n record.documentManifestBundle !== null\n );\n}\n\nexport function shouldSkipCleanScheduledDocumentSync(input: {\n currentRecord: DocumentRecord;\n pendingUpdates: readonly PendingUpdateRecord[];\n state: DocumentStoreState;\n}): boolean {\n return (\n input.pendingUpdates.length === 0 &&\n input.state.pendingAttachments.length === 0 &&\n input.state.pullContinuation === null &&\n !input.currentRecord.pullContinuationRecoveryRequired &&\n !input.state.remoteUpdatePending &&\n hasPersistedRemoteDocumentSyncState(input.currentRecord)\n );\n}\n\n/**\n * True when the store's container exists locally but has not been created on\n * the server yet (its own create intent is still pending). Creating a document\n * inside it would 404 on the container writer projection and surface a\n * spurious sync error; the container-contents lane re-arms document sync once\n * the container lands. An unknown or unqueryable container resolves false so\n * store-level consumers without container persistence keep creating eagerly.\n */\nexport async function isContainerAwaitingRemoteCreate(\n state: DocumentStoreState,\n): Promise<boolean> {\n const containerId = state.runtime.state.containerId;\n if (!containerId) {\n return false;\n }\n\n try {\n const rows = await state.runtime.infra.execSql(\n \"SELECT server_created_at FROM containers WHERE id = :containerId\",\n { \":containerId\": containerId },\n );\n const row = rows[0];\n return row !== undefined && Reflect.get(row, \"server_created_at\") == null;\n } catch {\n return false;\n }\n}\n\nasync function hasDurableDocumentForCreate(\n state: DocumentStoreState,\n isCurrent: () => boolean,\n): Promise<boolean> {\n // A bulk import can leave this store queued long after trash purged its\n // durable row. The persistence guard runs too late to prevent an orphaned\n // remote create, so check existence before beginning the network work.\n const record = await state.persistence.loadDocument(\n state.runtime.infra.execSql,\n state.localId,\n );\n if (!isCurrent()) return false;\n if (record) return true;\n markDocumentStoreRemoved(state);\n return false;\n}\n\nexport async function ensureRemoteDocument(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n nextRecord: DocumentRecord | null,\n encapsulationKeyPair: EncapsulationKeyPair,\n policyOperation: PrincipalPolicyOperation,\n generation?: DocumentStoreSyncGeneration,\n seed?: CreateSeed,\n deferredSeed?: DeferredBindSeed,\n): Promise<DocumentRecord | null> {\n const generationIsCurrent = () =>\n !generation || isDocumentStoreSyncGenerationCurrent(state, generation);\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n\n if (nextRecord?.documentId) {\n return nextRecord;\n }\n\n const runtime = state.runtime;\n if (!runtime.state.containerId) {\n runtime.util.log(\n \"Documents: cannot create a remote document without a container.\",\n );\n // A local-only document with no container scope (e.g. a last-link orphan\n // from a tombstone cascade, docs/sync-edge-cases.md row 3) can never\n // create; record the stuck state durably so the write queue surfaces it\n // instead of this lane going silent on every trigger.\n await documentTerminalSubmitFailureHandler(\n state,\n generation,\n )({\n message: \"Local document has no container for its remote create\",\n status: null,\n });\n return nextRecord;\n }\n\n const author = resolveDocumentCreateAuthor(runtime);\n if (!author) {\n runtime.util.log(\n \"Documents: skipped remote create because the writer context is unavailable.\",\n );\n return nextRecord;\n }\n\n const documentId =\n nextRecord?.recoveryDocumentId ??\n (await deriveStableDocumentId(state.localId));\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n // Hints for the document can arrive before the create's response installs\n // its id; see recordPlannedRemoteDocumentId.\n recordPlannedRemoteDocumentId(state, documentId);\n\n if (!(await hasDurableDocumentForCreate(state, generationIsCurrent)))\n return state.record;\n\n const writerProjectionGeneration = state.writerProjectionGeneration;\n // The runtime this create read before its awaits, with the pass's key.\n const remoteDocuments = new RemoteDocumentService({\n api: runtime.apiClient,\n encapsulationSecretKey: encapsulationKeyPair.secretKey,\n execSql: runtime.infra.execSql,\n isRemoteSyncBlocked: runtime.util.isRemoteSyncBlocked,\n });\n const created = await remoteDocuments.createRemoteDocument({\n author,\n containerId: runtime.state.containerId,\n deferredSeedUpdate: seed ? undefined : deferredSeed?.update,\n // Derive the remote id from the stable local id so a retry after a lost\n // create response re-sends the same id and adopts the existing remote\n // document instead of creating a duplicate.\n documentId,\n onTerminalSubmitFailure: documentTerminalSubmitFailureHandler(\n state,\n generation,\n ),\n resolveProjectionUserKey: state.resolveProjectionUserKey,\n seedUpdate: seed?.update,\n stillCurrent: generationIsCurrent,\n warmReferencedPrincipalPolicies: runtime.principalPolicies.createWarmer({\n operation: policyOperation,\n }),\n });\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n if (!created) {\n return nextRecord;\n }\n\n return chainIdentityWrite(state, async () => {\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n\n // A concurrent relink (e.g. live duplicate-facade resolution) may have\n // assigned this store a different remote identity while the create round\n // trip was in flight. That identity wins: persisting the created one here\n // would clobber the relink. The just-created remote document is left an\n // orphan, the same benign outcome as a lost create response.\n const liveDocumentId = state.record?.documentId;\n if (liveDocumentId && liveDocumentId !== created.documentId) {\n return state.record;\n }\n\n runtime.util.log(`Created document: ${created.documentId}`);\n installDocumentWriterProjection(\n state,\n created.writerProjection,\n writerProjectionGeneration,\n );\n\n // This persist is a remote-identity write (documentId + content keys), not a\n // content change. It runs after a network round trip, during which the user\n // may have kept typing into a brand-new note. The Loro doc is mutated\n // asynchronously on the write chain, so it can lag the optimistic snapshot;\n // re-deriving text/structured fields from the doc here would republish that\n // stale read over the live editor value and drop the just-typed characters\n // (the new-note \"type immediately\" race). Preserve the optimistic snapshot —\n // documentId/keys still propagate via state.record, independent of the\n // snapshot text — matching finalizeDocumentSync and the keystroke writes.\n // A committed seed settles its row in this persist, so the pass needs no\n // sync request.\n const persisted = await persistCreatedRemoteDocument({\n created,\n currentDoc,\n generation,\n seed,\n state,\n });\n if (persisted && created.deferredSeed) {\n deferredSeed?.onSigned(created.deferredSeed);\n }\n return persisted?.record ?? state.record ?? nextRecord;\n });\n}\n"]}
1
+ {"version":3,"file":"syncShared.js","sourceRoot":"","sources":["syncShared.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,oDAAoD,CAAC;AAC5F,OAAO,EACL,kBAAkB,EAElB,wBAAwB,EAExB,mCAAmC,EACnC,iCAAiC,EAEjC,qBAAqB,EACrB,2BAA2B,EAC3B,wBAAwB,GACzB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,4BAA4B,EAAE,MAAM,mEAAmE,CAAC;AAEjH,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAIL,wBAAwB,GACzB,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,+BAA+B,EAAE,MAAM,+BAA+B,CAAC;AAChF,OAAO,EAGL,4BAA4B,GAC7B,MAAM,8BAA8B,CAAC;AACtC,O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,KAAK,OAAO,CAAC,UAAU,EAAE,CAAC;YAC5D,OAAO,KAAK,CAAC,MAAM,CAAC;QACtB,CAAC;QAED,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,qBAAqB,OAAO,CAAC,UAAU,EAAE,CAAC,CAAC;QAC5D,+BAA+B,CAC7B,KAAK,EACL,OAAO,CAAC,gBAAgB,EACxB,0BAA0B,CAC3B,CAAC;QAEF,6EAA6E;QAC7E,4EAA4E;QAC5E,sEAAsE;QACtE,4EAA4E;QAC5E,4EAA4E;QAC5E,2EAA2E;QAC3E,6EAA6E;QAC7E,uEAAuE;QACvE,0EAA0E;QAC1E,yEAAyE;QACzE,gBAAgB;QAChB,MAAM,SAAS,GAAG,MAAM,4BAA4B,CAAC;YACnD,OAAO;YACP,UAAU;YACV,UAAU;YACV,IAAI;YACJ,KAAK;SACN,CAAC,CAAC;QACH,IAAI,SAAS,IAAI,OAAO,CAAC,YAAY,EAAE,CAAC;YACtC,YAAY,EAAE,QAAQ,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;QAC/C,CAAC;QACD,OAAO,SAAS,EAAE,MAAM,IAAI,KAAK,CAAC,MAAM,IAAI,UAAU,CAAC;IACzD,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { deriveStableDocumentId } from \"../../../../data/documents/shared/stableDocumentId\";\nimport {\n DOCUMENTS_APP_KIND,\n type DocumentRecord,\n DocumentRecordRepository,\n type DocumentSyncUpdateIsolationError,\n describeDocumentRevalidationFailure,\n describeDocumentSyncSubmitFailure,\n type PendingUpdateRecord,\n RemoteDocumentService,\n resolveDocumentCreateAuthor,\n runSerializedSqlMutation,\n} from \"../../../../workflows/documents\";\nimport { reportDocumentSyncQuarantine } from \"../../../../workflows/documents/sync/reportDocumentSyncQuarantine\";\nimport type { PrincipalPolicyOperation } from \"../../../../workflows/principals/principalPolicyService\";\nimport { chainIdentityWrite } from \"../identityWriteChain\";\nimport {\n type DocumentState,\n type DocumentStoreState,\n type EncapsulationKeyPair,\n markDocumentStoreRemoved,\n} from \"../state\";\nimport { installDocumentWriterProjection } from \"../writerProjectionGeneration\";\nimport {\n type CreateSeed,\n type DeferredBindSeed,\n persistCreatedRemoteDocument,\n} from \"./createdDocumentPersistence\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\nimport { recordPlannedRemoteDocumentId } from \"./syncRemoteSignals\";\n\n/**\n * Record a refused read-only revalidation on this document's failure row, so\n * a document that can never refresh stops failing silently (edge-case row\n * 13). 403s stay suppressed on purpose — a read-only 403 must never flag\n * unattempted local edits (row 9) — and the row clears on the next clean\n * pass like every other sync failure.\n */\nexport function documentRevalidationFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n return documentSyncFailureHandler({\n describeFailure: describeDocumentRevalidationFailure,\n generation,\n state,\n suppressForbidden: true,\n });\n}\n\n/**\n * Record a terminal submit failure on this document's write-queue row. Shared\n * by every store pass that can submit queued writes (create and sync), so\n * re-key exhaustion and denial failures surface no matter which pass hits\n * them first.\n */\nexport function documentTerminalSubmitFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n return documentSyncFailureHandler({\n describeFailure: describeDocumentSyncSubmitFailure,\n generation,\n state,\n });\n}\n\n/** Persist quarantine and report its Error through the host's diagnostics. */\nexport function documentIncomingUpdateIsolationFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n const recordFailure = documentSyncFailureHandler({\n describeFailure: (failure) => failure.message,\n generation,\n state,\n });\n return async (failure: DocumentSyncUpdateIsolationError) => {\n await recordFailure({ message: failure.message, status: null });\n if (generation && !isDocumentStoreSyncGenerationCurrent(state, generation))\n return;\n reportDocumentSyncQuarantine(\n generation?.currentDoc ?? state.doc ?? state,\n state.runtime.util.logError,\n failure,\n );\n };\n}\n\n/**\n * The generation recheck runs INSIDE the serialized mutation (like the\n * attachment failure path): a teardown (discard/reset) that wins the ordering\n * deletes this document's rows first and invalidates the generation, so a\n * stale handler can never resurrect a deleted or orphan failure row\n * afterwards.\n */\nfunction documentSyncFailureHandler(input: {\n describeFailure: (failure: {\n readonly message: string;\n readonly status: number | null;\n }) => string;\n generation: DocumentStoreSyncGeneration | undefined;\n state: DocumentStoreState;\n suppressForbidden?: boolean;\n}) {\n const { generation, state } = input;\n return async (failure: {\n readonly message: string;\n readonly status: number | null;\n }) => {\n if (input.suppressForbidden && failure.status === 403) {\n return;\n }\n\n await runSerializedSqlMutation(\n generation?.execSql ?? state.runtime.infra.execSql,\n async (lockedExecSql) => {\n if (\n generation &&\n !isDocumentStoreSyncGenerationCurrent(state, generation)\n ) {\n return;\n }\n await new DocumentRecordRepository(\n lockedExecSql,\n ).recordDocumentSyncFailure(\n { appKind: DOCUMENTS_APP_KIND, localId: state.localId },\n {\n attemptedAt: new Date().toISOString(),\n message: input.describeFailure(failure),\n },\n );\n },\n );\n };\n}\n\nfunction hasPersistedRemoteDocumentSyncState(record: DocumentRecord): boolean {\n return (\n record.lastCommitLsn !== null &&\n record.contentKeyBundle !== null &&\n record.documentKekTargets !== null &&\n record.documentManifestBundle !== null\n );\n}\n\nexport function shouldSkipCleanScheduledDocumentSync(input: {\n currentRecord: DocumentRecord;\n pendingUpdates: readonly PendingUpdateRecord[];\n state: DocumentStoreState;\n}): boolean {\n return (\n input.pendingUpdates.length === 0 &&\n input.state.pendingAttachments.length === 0 &&\n input.state.pullContinuation === null &&\n !input.currentRecord.pullContinuationRecoveryRequired &&\n !input.state.remoteUpdatePending &&\n hasPersistedRemoteDocumentSyncState(input.currentRecord)\n );\n}\n\n/**\n * True when the store's container exists locally but has not been created on\n * the server yet (its own create intent is still pending). Creating a document\n * inside it would 404 on the container writer projection and surface a\n * spurious sync error; the container-contents lane re-arms document sync once\n * the container lands. An unknown or unqueryable container resolves false so\n * store-level consumers without container persistence keep creating eagerly.\n */\nexport async function isContainerAwaitingRemoteCreate(\n state: DocumentStoreState,\n): Promise<boolean> {\n const containerId = state.runtime.state.containerId;\n if (!containerId) {\n return false;\n }\n\n try {\n const rows = await state.runtime.infra.execSql(\n \"SELECT server_created_at FROM containers WHERE id = :containerId\",\n { \":containerId\": containerId },\n );\n const row = rows[0];\n return row !== undefined && Reflect.get(row, \"server_created_at\") == null;\n } catch {\n return false;\n }\n}\n\nasync function hasDurableDocumentForCreate(\n state: DocumentStoreState,\n isCurrent: () => boolean,\n): Promise<boolean> {\n // A bulk import can leave this store queued long after trash purged its\n // durable row. The persistence guard runs too late to prevent an orphaned\n // remote create, so check existence before beginning the network work.\n const record = await state.persistence.loadDocument(\n state.runtime.infra.execSql,\n state.localId,\n );\n if (!isCurrent()) return false;\n if (record) return true;\n markDocumentStoreRemoved(state);\n return false;\n}\n\nexport async function ensureRemoteDocument(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n nextRecord: DocumentRecord | null,\n encapsulationKeyPair: EncapsulationKeyPair,\n policyOperation: PrincipalPolicyOperation,\n generation?: DocumentStoreSyncGeneration,\n seed?: CreateSeed,\n deferredSeed?: DeferredBindSeed,\n): Promise<DocumentRecord | null> {\n const generationIsCurrent = () =>\n !generation || isDocumentStoreSyncGenerationCurrent(state, generation);\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n\n if (nextRecord?.documentId) {\n return nextRecord;\n }\n\n const runtime = state.runtime;\n if (!runtime.state.containerId) {\n runtime.util.log(\n \"Documents: cannot create a remote document without a container.\",\n );\n // A local-only document with no container scope (e.g. a last-link orphan\n // from a tombstone cascade, docs/sync-edge-cases.md row 3) can never\n // create; record the stuck state durably so the write queue surfaces it\n // instead of this lane going silent on every trigger.\n await documentTerminalSubmitFailureHandler(\n state,\n generation,\n )({\n message: \"Local document has no container for its remote create\",\n status: null,\n });\n return nextRecord;\n }\n\n const author = resolveDocumentCreateAuthor(runtime);\n if (!author) {\n runtime.util.log(\n \"Documents: skipped remote create because the writer context is unavailable.\",\n );\n return nextRecord;\n }\n\n const documentId =\n nextRecord?.recoveryDocumentId ??\n (await deriveStableDocumentId(state.localId));\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n // Hints for the document can arrive before the create's response installs\n // its id; see recordPlannedRemoteDocumentId.\n recordPlannedRemoteDocumentId(state, documentId);\n\n if (!(await hasDurableDocumentForCreate(state, generationIsCurrent)))\n return state.record;\n\n const writerProjectionGeneration = state.writerProjectionGeneration;\n // The runtime this create read before its awaits, with the pass's key.\n const remoteDocuments = new RemoteDocumentService({\n api: runtime.apiClient,\n encapsulationSecretKey: encapsulationKeyPair.secretKey,\n execSql: runtime.infra.execSql,\n isRemoteSyncBlocked: runtime.util.isRemoteSyncBlocked,\n });\n const created = await remoteDocuments.createRemoteDocument({\n author,\n containerId: runtime.state.containerId,\n deferredSeedUpdate: seed ? undefined : deferredSeed?.update,\n // Derive the remote id from the stable local id so a retry after a lost\n // create response re-sends the same id and adopts the existing remote\n // document instead of creating a duplicate.\n documentId,\n onTerminalSubmitFailure: documentTerminalSubmitFailureHandler(\n state,\n generation,\n ),\n resolveProjectionUserKey: state.resolveProjectionUserKey,\n seedUpdate: seed?.update,\n stillCurrent: generationIsCurrent,\n warmReferencedPrincipalPolicies: runtime.principalPolicies.createWarmer({\n operation: policyOperation,\n }),\n });\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n if (!created) {\n return nextRecord;\n }\n\n return chainIdentityWrite(state, async () => {\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n\n // A concurrent relink (e.g. live duplicate-facade resolution) may have\n // assigned this store a different remote identity while the create round\n // trip was in flight. That identity wins: persisting the created one here\n // would clobber the relink. The just-created remote document is left an\n // orphan, the same benign outcome as a lost create response.\n const liveDocumentId = state.record?.documentId;\n if (liveDocumentId && liveDocumentId !== created.documentId) {\n return state.record;\n }\n\n runtime.util.log(`Created document: ${created.documentId}`);\n installDocumentWriterProjection(\n state,\n created.writerProjection,\n writerProjectionGeneration,\n );\n\n // This persist is a remote-identity write (documentId + content keys), not a\n // content change. It runs after a network round trip, during which the user\n // may have kept typing into a brand-new note. The Loro doc is mutated\n // asynchronously on the write chain, so it can lag the optimistic snapshot;\n // re-deriving text/structured fields from the doc here would republish that\n // stale read over the live editor value and drop the just-typed characters\n // (the new-note \"type immediately\" race). Preserve the optimistic snapshot —\n // documentId/keys still propagate via state.record, independent of the\n // snapshot text — matching finalizeDocumentSync and the keystroke writes.\n // A committed seed settles its row in this persist, so the pass needs no\n // sync request.\n const persisted = await persistCreatedRemoteDocument({\n created,\n currentDoc,\n generation,\n seed,\n state,\n });\n if (persisted && created.deferredSeed) {\n deferredSeed?.onSigned(created.deferredSeed);\n }\n return persisted?.record ?? state.record ?? nextRecord;\n });\n}\n"]}