@open-mercato/documents 0.9.1-develop.7574.1.837288eec1 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/contentSecurityPolicy.js +23 -0
- package/dist/contentSecurityPolicy.js.map +7 -0
- package/dist/modules/documents/api/[id]/comments/access-check/route.js +13 -6
- package/dist/modules/documents/api/[id]/comments/access-check/route.js.map +2 -2
- package/dist/modules/documents/api/[id]/comments/route.js +2 -0
- package/dist/modules/documents/api/[id]/comments/route.js.map +2 -2
- package/dist/modules/documents/api/[id]/content/route.js +2 -0
- package/dist/modules/documents/api/[id]/content/route.js.map +2 -2
- package/dist/modules/documents/api/[id]/route.js +3 -0
- package/dist/modules/documents/api/[id]/route.js.map +2 -2
- package/dist/modules/documents/api/[id]/shares/route.js +2 -0
- package/dist/modules/documents/api/[id]/shares/route.js.map +2 -2
- package/dist/modules/documents/api/[id]/versions/route.js +2 -0
- package/dist/modules/documents/api/[id]/versions/route.js.map +2 -2
- package/dist/modules/documents/api/_shared.js +10 -27
- package/dist/modules/documents/api/_shared.js.map +3 -3
- package/dist/modules/documents/backend/documents/[id]/DocumentCanvas.js +3 -1
- package/dist/modules/documents/backend/documents/[id]/DocumentCanvas.js.map +2 -2
- package/dist/modules/documents/backend/documents/[id]/DocumentEditorIsland.js +1 -1
- package/dist/modules/documents/backend/documents/[id]/DocumentEditorIsland.js.map +2 -2
- package/dist/modules/documents/backend/documents/[id]/DocumentEditorSurface.js +15 -1
- package/dist/modules/documents/backend/documents/[id]/DocumentEditorSurface.js.map +2 -2
- package/dist/modules/documents/backend/documents/[id]/DocumentPageClient.js +15 -1
- package/dist/modules/documents/backend/documents/[id]/DocumentPageClient.js.map +2 -2
- package/dist/modules/documents/backend/documents/[id]/VersionHistoryPanel.js +20 -8
- package/dist/modules/documents/backend/documents/[id]/VersionHistoryPanel.js.map +2 -2
- package/dist/modules/documents/backend/documents/[id]/VersionPreviewDialog.js +3 -0
- package/dist/modules/documents/backend/documents/[id]/VersionPreviewDialog.js.map +2 -2
- package/dist/modules/documents/backend/documents/[id]/editorTypes.js.map +2 -2
- package/dist/modules/documents/backend/documents/[id]/saveCollaborativeContent.js +46 -0
- package/dist/modules/documents/backend/documents/[id]/saveCollaborativeContent.js.map +7 -0
- package/dist/modules/documents/backend/documents/[id]/useDocumentComments.js +14 -6
- package/dist/modules/documents/backend/documents/[id]/useDocumentComments.js.map +2 -2
- package/dist/modules/documents/backend/documents/[id]/useDocumentEditor.js +3 -0
- package/dist/modules/documents/backend/documents/[id]/useDocumentEditor.js.map +2 -2
- package/dist/modules/documents/backend/documents/components/TemplateBodyEditor.js +3 -0
- package/dist/modules/documents/backend/documents/components/TemplateBodyEditor.js.map +2 -2
- package/dist/modules/documents/backend/documents/components/TemplatePreview.js +3 -0
- package/dist/modules/documents/backend/documents/components/TemplatePreview.js.map +2 -2
- package/dist/modules/documents/commands/comments.js +2 -2
- package/dist/modules/documents/commands/comments.js.map +2 -2
- package/dist/modules/documents/commands/folders.js +1 -0
- package/dist/modules/documents/commands/folders.js.map +2 -2
- package/dist/modules/documents/commands/interceptors.js +11 -0
- package/dist/modules/documents/commands/interceptors.js.map +2 -2
- package/dist/modules/documents/data/attachment-access.js +84 -0
- package/dist/modules/documents/data/attachment-access.js.map +7 -0
- package/dist/modules/documents/data/validators.js +11 -0
- package/dist/modules/documents/data/validators.js.map +2 -2
- package/dist/modules/documents/lib/actor.js +32 -0
- package/dist/modules/documents/lib/actor.js.map +7 -0
- package/dist/modules/documents/lib/collabMaterializer.js +52 -9
- package/dist/modules/documents/lib/collabMaterializer.js.map +2 -2
- package/dist/modules/documents/lib/collabPersistence.js +13 -0
- package/dist/modules/documents/lib/collabPersistence.js.map +7 -0
- package/dist/modules/documents/lib/permissions.js +35 -2
- package/dist/modules/documents/lib/permissions.js.map +2 -2
- package/dist/modules/documents/widgets/injection/related-documents/widget.client.js +3 -2
- package/dist/modules/documents/widgets/injection/related-documents/widget.client.js.map +2 -2
- package/dist/modules/documents/widgets/injection-table.js +12 -3
- package/dist/modules/documents/widgets/injection-table.js.map +2 -2
- package/dist/server/documents-collab-server.js +74 -1
- package/dist/server/documents-collab-server.js.map +2 -2
- package/jest.config.cjs +1 -1
- package/package.json +37 -37
- package/server/documents-collab-server.ts +79 -0
- package/src/contentSecurityPolicy.ts +21 -0
- package/src/modules/documents/api/[id]/comments/access-check/route.ts +13 -6
- package/src/modules/documents/api/[id]/comments/route.ts +2 -0
- package/src/modules/documents/api/[id]/content/route.ts +2 -0
- package/src/modules/documents/api/[id]/route.ts +3 -0
- package/src/modules/documents/api/[id]/shares/route.ts +2 -0
- package/src/modules/documents/api/[id]/versions/route.ts +2 -0
- package/src/modules/documents/api/_shared.ts +10 -36
- package/src/modules/documents/backend/documents/[id]/DocumentCanvas.tsx +3 -1
- package/src/modules/documents/backend/documents/[id]/DocumentEditorIsland.tsx +4 -1
- package/src/modules/documents/backend/documents/[id]/DocumentEditorSurface.tsx +19 -1
- package/src/modules/documents/backend/documents/[id]/DocumentPageClient.tsx +14 -0
- package/src/modules/documents/backend/documents/[id]/VersionHistoryPanel.tsx +23 -8
- package/src/modules/documents/backend/documents/[id]/VersionPreviewDialog.tsx +3 -0
- package/src/modules/documents/backend/documents/[id]/editorTypes.ts +1 -0
- package/src/modules/documents/backend/documents/[id]/saveCollaborativeContent.ts +43 -0
- package/src/modules/documents/backend/documents/[id]/useDocumentComments.ts +17 -7
- package/src/modules/documents/backend/documents/[id]/useDocumentEditor.ts +3 -0
- package/src/modules/documents/backend/documents/components/TemplateBodyEditor.tsx +3 -0
- package/src/modules/documents/backend/documents/components/TemplatePreview.tsx +3 -0
- package/src/modules/documents/commands/comments.ts +2 -2
- package/src/modules/documents/commands/folders.ts +1 -3
- package/src/modules/documents/commands/interceptors.ts +11 -0
- package/src/modules/documents/data/attachment-access.ts +83 -0
- package/src/modules/documents/data/validators.ts +12 -0
- package/src/modules/documents/lib/actor.ts +39 -0
- package/src/modules/documents/lib/collabMaterializer.ts +62 -11
- package/src/modules/documents/lib/collabPersistence.ts +10 -0
- package/src/modules/documents/lib/permissions.ts +52 -0
- package/src/modules/documents/widgets/injection/related-documents/widget.client.tsx +3 -2
- package/src/modules/documents/widgets/injection-table.ts +17 -3
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/documents/commands/comments.ts"],
|
|
4
|
-
"sourcesContent": ["import { LockMode } from '@mikro-orm/core'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { z } from 'zod'\nimport { registerCommand, type CommandHandler } from '@open-mercato/shared/lib/commands'\nimport { withAtomicFlush } from '@open-mercato/shared/lib/commands/flush'\nimport { extractUndoPayload } from '@open-mercato/shared/lib/commands/undo'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport {\n assertOptimisticLock,\n buildOptimisticLockConflictBody,\n} from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport {\n findOneWithDecryption,\n findWithDecryption,\n} from '@open-mercato/shared/lib/encryption/find'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { Document, DocumentComment, DocumentShare } from '../data/entities'\nimport {\n documentCommentCreateSchema,\n documentSharePermissionSchema,\n} from '../data/validators'\nimport { DOCUMENTS_ENTITY_IDS } from '../lib/constants'\nimport { assertDocumentCommentCapacity } from '../lib/historyLimits'\nimport { resolveUserAccess } from '../lib/permissions'\nimport { resolveWatcherRecipients } from '../lib/watchers'\nimport type { DocumentsProjectionDescriptor } from './projection-types'\nimport {\n assertDocumentCommandCapability,\n resolveDocumentsCommandActor,\n resolveDocumentsCommandScope,\n} from './shared'\nimport { nextDocumentVersion } from './mutation-helpers'\nimport { resolveAuthPrincipalService, type DocumentsServiceContainer } from '../lib/platformServices'\n\nconst scopeSchema = z.object({\n tenantId: z.string().uuid(),\n organizationId: z.string().uuid(),\n})\n\nconst commentStateSchema = z.object({\n id: z.string().uuid(),\n existed: z.boolean(),\n parentCommentId: z.string().uuid().nullable(),\n authorUserId: z.string().uuid(),\n body: z.string(),\n // Snapshots must remain permissive for legacy anchors. New command input is\n // still validated by documentCommentCreateSchema's strict write union.\n anchor: z.record(z.string(), z.unknown()).nullable(),\n mentions: z.array(z.object({ userId: z.string().uuid() })).nullable(),\n resolvedAt: z.string().datetime().nullable(),\n resolvedByUserId: z.string().uuid().nullable(),\n deletedAt: z.string().datetime().nullable(),\n updatedAt: z.string().datetime().nullable(),\n})\n\nconst mentionShareStateSchema = z.object({\n id: z.string().uuid(),\n userId: z.string().uuid(),\n existed: z.boolean(),\n permission: documentSharePermissionSchema,\n createdByUserId: z.string().uuid(),\n deletedAt: z.string().datetime().nullable(),\n updatedAt: z.string().datetime().nullable(),\n})\n\nconst commentRedoExpectationSchema = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('snapshot'), state: commentStateSchema }),\n z.object({ kind: z.literal('soft-deleted-created'), state: commentStateSchema }),\n])\n\nconst commentCommandBaseSchema = scopeSchema.extend({\n documentId: z.string().uuid(),\n actorUserId: z.string().uuid(),\n})\n\nexport const commentCreateCommandSchema = commentCommandBaseSchema.extend({\n commentId: z.string().uuid(),\n comment: documentCommentCreateSchema,\n grantShares: z.array(z.object({ userId: z.string().uuid(), shareId: z.string().uuid() })).max(50),\n redoExpectation: commentRedoExpectationSchema.optional(),\n}).superRefine((input, context) => {\n const grantIds = Array.from(new Set((input.comment.grantAccessTo ?? []).map((id) => id.toLowerCase())))\n const identities = Array.from(new Set(input.grantShares.map((grant) => grant.userId.toLowerCase())))\n if (grantIds.length !== identities.length || grantIds.some((id) => !identities.includes(id))) {\n context.addIssue({ code: 'custom', message: 'documents.comments.grantIdentityMismatch' })\n }\n})\n\nexport const commentResolveCommandSchema = commentCommandBaseSchema.extend({\n comment: z.object({ id: z.string().uuid(), resolved: z.boolean() }),\n expectedUpdatedAt: z.string().datetime().nullable().optional(),\n redoExpectation: commentRedoExpectationSchema.optional(),\n})\n\nexport type CommentCreateCommandInput = z.infer<typeof commentCreateCommandSchema>\nexport type CommentResolveCommandInput = z.infer<typeof commentResolveCommandSchema>\nexport type CommentState = z.infer<typeof commentStateSchema>\nexport type MentionShareState = z.infer<typeof mentionShareStateSchema>\n\nexport type CommentCreateCommandResult = {\n id: string\n updatedAt: string\n projections?: DocumentsProjectionDescriptor[]\n undo: CommentCreateUndoPayload\n}\n\nexport type CommentResolveCommandResult = {\n id: string\n resolvedAt: string | null\n resolvedByUserId: string | null\n updatedAt: string\n before: CommentState\n after: CommentState\n projections?: DocumentsProjectionDescriptor[]\n}\n\ntype MentionShareMutation = {\n before: MentionShareState\n after: MentionShareState\n}\n\ntype PendingMentionShareMutation = {\n before: MentionShareState\n share: DocumentShare\n fallback: { shareId: string; userId: string; actorUserId: string }\n}\n\ntype CommentCreateUndoPayload = {\n before?: CommentState | null\n after?: CommentState | null\n shareMutations: MentionShareMutation[]\n projectionsAfterUndo?: DocumentsProjectionDescriptor[]\n}\n\ntype CommentResolveUndoPayload = {\n before?: CommentState | null\n after?: CommentState | null\n projectionsAfterUndo?: DocumentsProjectionDescriptor[]\n}\n\nfunction extractMentionedUserIds(body: string): string[] {\n const pattern = /@\\[([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\\]/gi\n return Array.from(new Set(\n Array.from(body.matchAll(pattern))\n .map((match) => match[1])\n .filter((value): value is string => typeof value === 'string')\n .map((value) => value.toLowerCase()),\n ))\n}\n\nfunction dedupeUserIds(values: string[]): string[] {\n return Array.from(new Set(values.map((value) => value.toLowerCase())))\n}\n\nfunction commentFallback(input: CommentCreateCommandInput): Omit<CommentState, 'existed' | 'deletedAt' | 'updatedAt'> {\n const mentionUserIds = dedupeUserIds([\n ...(input.comment.mentions ?? []).map((mention) => mention.userId),\n ...extractMentionedUserIds(input.comment.body),\n ])\n return {\n id: input.commentId,\n parentCommentId: input.comment.parentCommentId ?? null,\n authorUserId: input.actorUserId,\n body: input.comment.body,\n anchor: input.comment.anchor ?? null,\n mentions: mentionUserIds.length ? mentionUserIds.map((userId) => ({ userId })) : null,\n resolvedAt: null,\n resolvedByUserId: null,\n }\n}\n\nfunction captureCommentState(\n comment: DocumentComment | null,\n fallback: Omit<CommentState, 'existed' | 'deletedAt' | 'updatedAt'>,\n): CommentState {\n return {\n id: comment?.id ?? fallback.id,\n existed: comment !== null,\n parentCommentId: comment?.parentCommentId ?? fallback.parentCommentId,\n authorUserId: comment?.authorUserId ?? fallback.authorUserId,\n body: comment?.body ?? fallback.body,\n anchor: (comment?.anchor ?? fallback.anchor) as CommentState['anchor'],\n mentions: comment?.mentions ?? fallback.mentions,\n resolvedAt: comment?.resolvedAt?.toISOString() ?? fallback.resolvedAt,\n resolvedByUserId: comment?.resolvedByUserId ?? fallback.resolvedByUserId,\n deletedAt: comment?.deletedAt?.toISOString() ?? null,\n updatedAt: comment?.updatedAt?.toISOString() ?? null,\n }\n}\n\nfunction captureMentionShareState(\n share: DocumentShare | null,\n fallback: { shareId: string; userId: string; actorUserId: string },\n): MentionShareState {\n return {\n id: share?.id ?? fallback.shareId,\n userId: share?.principalId ?? fallback.userId,\n existed: share !== null,\n permission: share?.permission ?? 'commenter',\n createdByUserId: share?.createdByUserId ?? fallback.actorUserId,\n deletedAt: share?.deletedAt?.toISOString() ?? null,\n updatedAt: share?.updatedAt?.toISOString() ?? null,\n }\n}\n\nfunction assertActor(input: { actorUserId: string }, ctx: Parameters<CommandHandler['execute']>[1]): void {\n if (resolveDocumentsCommandActor(ctx) !== input.actorUserId) {\n throw new CrudHttpError(403, { error: 'Forbidden' })\n }\n}\n\nasync function loadLockedDocument(\n em: EntityManager,\n input: { tenantId: string; organizationId: string; documentId: string },\n): Promise<Document> {\n const document = await findOneWithDecryption(\n em,\n Document,\n {\n id: input.documentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n deletedAt: null,\n },\n { lockMode: LockMode.PESSIMISTIC_WRITE },\n { tenantId: input.tenantId, organizationId: input.organizationId },\n )\n if (!document) throw new CrudHttpError(404, { error: 'Document not found' })\n return document\n}\n\nasync function loadComment(\n em: EntityManager,\n input: { tenantId: string; organizationId: string; documentId: string },\n commentId: string,\n lock = false,\n): Promise<DocumentComment | null> {\n return findOneWithDecryption(\n em,\n DocumentComment,\n {\n id: commentId,\n documentId: input.documentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n },\n {\n filters: false,\n ...(lock ? { lockMode: LockMode.PESSIMISTIC_WRITE } : {}),\n },\n { tenantId: input.tenantId, organizationId: input.organizationId },\n )\n}\n\nasync function assertNoActiveReplies(\n em: EntityManager,\n input: { tenantId: string; organizationId: string; documentId: string },\n commentId: string,\n): Promise<void> {\n const replies = await findWithDecryption(\n em,\n DocumentComment,\n {\n documentId: input.documentId,\n parentCommentId: commentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n deletedAt: null,\n },\n { limit: 1 },\n { tenantId: input.tenantId, organizationId: input.organizationId },\n )\n if (replies.length > 0) {\n throw new CrudHttpError(409, { error: 'Record changed by another user' })\n }\n}\n\nasync function loadMentionShare(\n em: EntityManager,\n input: { tenantId: string; organizationId: string; documentId: string },\n userId: string,\n lock = false,\n): Promise<DocumentShare | null> {\n return findOneWithDecryption(\n em,\n DocumentShare,\n {\n documentId: input.documentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n principalType: 'user',\n principalId: userId,\n },\n {\n filters: false,\n orderBy: { updatedAt: 'DESC' },\n ...(lock ? { lockMode: LockMode.PESSIMISTIC_WRITE } : {}),\n },\n { tenantId: input.tenantId, organizationId: input.organizationId },\n )\n}\n\nasync function assertUserPrincipal(\n container: DocumentsServiceContainer,\n input: { tenantId: string; organizationId: string },\n userId: string,\n): Promise<void> {\n const exists = await resolveAuthPrincipalService(container)?.principalExists({\n type: 'user',\n id: userId,\n scope: { tenantId: input.tenantId, organizationId: input.organizationId },\n }) ?? false\n if (!exists) throw new CrudHttpError(400, { error: 'Share principal not found in this organization' })\n}\n\nasync function hasDocumentCapability(\n ctx: Parameters<CommandHandler['execute']>[1],\n em: EntityManager,\n input: { tenantId: string; organizationId: string; documentId: string },\n capability: 'canComment' | 'canShare',\n): Promise<boolean> {\n try {\n await assertDocumentCommandCapability(\n ctx,\n em,\n input.documentId,\n resolveDocumentsCommandScope(ctx, input),\n capability,\n )\n return true\n } catch (error) {\n if (isCrudHttpError(error) && error.status === 403) return false\n throw error\n }\n}\n\nasync function assertCanCreateComment(\n ctx: Parameters<CommandHandler['execute']>[1],\n em: EntityManager,\n input: CommentCreateCommandInput,\n): Promise<void> {\n resolveDocumentsCommandScope(ctx, input)\n if (!(await hasDocumentCapability(ctx, em, input, 'canComment'))) {\n throw new CrudHttpError(403, { error: 'Forbidden' })\n }\n}\n\nasync function assertCanMutateMentionShares(\n ctx: Parameters<CommandHandler['execute']>[1],\n em: EntityManager,\n input: CommentCreateCommandInput,\n): Promise<void> {\n const scope = resolveDocumentsCommandScope(ctx, input)\n await assertDocumentCommandCapability(ctx, em, input.documentId, scope, 'canShare')\n}\n\nasync function assertCanResolveComment(\n ctx: Parameters<CommandHandler['execute']>[1],\n em: EntityManager,\n input: CommentResolveCommandInput,\n comment: DocumentComment,\n): Promise<void> {\n const scope = resolveDocumentsCommandScope(ctx, input)\n await assertDocumentCommandCapability(ctx, em, input.documentId, scope, 'canView')\n if (comment.authorUserId === resolveDocumentsCommandActor(ctx)) return\n if (!(await hasDocumentCapability(ctx, em, input, 'canComment'))) {\n throw new CrudHttpError(403, { error: 'Forbidden' })\n }\n}\n\nfunction assertCommentMatchesState(\n comment: DocumentComment | null,\n expected: CommentState,\n softDeletedCreated = false,\n): void {\n if (!comment || !expected.existed) throw new CrudHttpError(409, { error: 'Record changed by another user' })\n const scalarsMatch = comment.id === expected.id\n && (comment.parentCommentId ?? null) === expected.parentCommentId\n && comment.authorUserId === expected.authorUserId\n && comment.body === expected.body\n && JSON.stringify(comment.anchor ?? null) === JSON.stringify(expected.anchor)\n && JSON.stringify(comment.mentions ?? null) === JSON.stringify(expected.mentions)\n && (comment.resolvedAt?.toISOString() ?? null) === expected.resolvedAt\n && (comment.resolvedByUserId ?? null) === expected.resolvedByUserId\n const deletedAt = comment.deletedAt?.toISOString() ?? null\n const deletionMatches = softDeletedCreated ? deletedAt !== null : deletedAt === expected.deletedAt\n if (!scalarsMatch || !deletionMatches) {\n throw new CrudHttpError(409, buildOptimisticLockConflictBody(\n comment.updatedAt.toISOString(),\n expected.updatedAt ?? comment.updatedAt.toISOString(),\n ))\n }\n}\n\nfunction assertCommentUnchanged(\n comment: DocumentComment | null,\n expected: CommentState,\n): asserts comment is DocumentComment {\n if (!comment || !expected.existed || !expected.updatedAt) {\n throw new CrudHttpError(409, { error: 'Record changed by another user' })\n }\n assertOptimisticLock({\n resourceKind: DOCUMENTS_ENTITY_IDS.documentComment,\n resourceId: expected.id,\n current: comment.updatedAt,\n expected: expected.updatedAt,\n envValue: 'all',\n })\n assertCommentMatchesState(comment, expected)\n}\n\nfunction assertMentionShareUnchanged(share: DocumentShare | null, expected: MentionShareState): asserts share is DocumentShare {\n if (!share || !expected.existed || !expected.updatedAt) {\n throw new CrudHttpError(409, { error: 'Record changed by another user' })\n }\n assertOptimisticLock({\n resourceKind: DOCUMENTS_ENTITY_IDS.documentShare,\n resourceId: expected.id,\n current: share.updatedAt,\n expected: expected.updatedAt,\n envValue: 'all',\n })\n if (\n share.id !== expected.id\n || share.principalType !== 'user'\n || share.principalId !== expected.userId\n || share.permission !== expected.permission\n || share.createdByUserId !== expected.createdByUserId\n || (share.deletedAt?.toISOString() ?? null) !== expected.deletedAt\n ) {\n throw new CrudHttpError(409, { error: 'Record changed by another user' })\n }\n}\n\nfunction restoreCommentState(comment: DocumentComment, before: CommentState): void {\n const now = nextDocumentVersion(comment.updatedAt)\n if (!before.existed) {\n comment.deletedAt = now\n comment.updatedAt = now\n return\n }\n comment.parentCommentId = before.parentCommentId\n comment.authorUserId = before.authorUserId\n comment.body = before.body\n comment.anchor = before.anchor\n comment.mentions = before.mentions\n comment.resolvedAt = before.resolvedAt ? new Date(before.resolvedAt) : null\n comment.resolvedByUserId = before.resolvedByUserId\n comment.deletedAt = before.deletedAt ? new Date(before.deletedAt) : null\n comment.updatedAt = now\n}\n\nfunction restoreMentionShareState(share: DocumentShare, before: MentionShareState): void {\n const now = nextDocumentVersion(share.updatedAt)\n if (!before.existed) {\n share.deletedAt = now\n share.updatedAt = now\n return\n }\n share.permission = before.permission\n share.createdByUserId = before.createdByUserId\n share.deletedAt = before.deletedAt ? new Date(before.deletedAt) : null\n share.updatedAt = now\n}\n\nfunction shareProjection(\n eventId: 'documents.document.shared' | 'documents.document.unshared',\n input: CommentCreateCommandInput,\n state: MentionShareState,\n includeActor = true,\n): DocumentsProjectionDescriptor {\n return {\n kind: 'event',\n eventId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n payload: {\n id: input.documentId,\n shareId: state.id,\n principalType: 'user',\n principalId: state.userId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n ...(includeActor ? { userId: input.actorUserId } : {}),\n },\n }\n}\n\nfunction resolutionProjection(\n input: CommentResolveCommandInput,\n state: CommentState,\n includeActor = true,\n): DocumentsProjectionDescriptor {\n return {\n kind: 'event',\n eventId: 'documents.comment.resolved',\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n payload: {\n id: state.id,\n documentId: input.documentId,\n resolved: state.resolvedAt !== null,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n ...(includeActor ? { userId: input.actorUserId } : {}),\n },\n }\n}\n\nfunction mentionProjections(\n input: CommentCreateCommandInput,\n document: Document,\n mentionedUserIds: string[],\n): DocumentsProjectionDescriptor[] {\n return mentionedUserIds.flatMap((recipientUserId): DocumentsProjectionDescriptor[] => [\n {\n kind: 'event',\n eventId: 'documents.comment.mentioned',\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n payload: {\n id: input.commentId,\n documentId: input.documentId,\n mentionedUserId: recipientUserId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n userId: input.actorUserId,\n },\n },\n {\n kind: 'mention-notification',\n recipientUserId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n documentId: input.documentId,\n documentTitle: document.title,\n commentId: input.commentId,\n authorUserId: input.actorUserId,\n },\n ])\n}\n\nfunction watchCommentProjections(\n input: { tenantId: string; organizationId: string; documentId: string; commentId: string },\n documentTitle: string,\n recipientUserIds: readonly string[],\n bodyKey: string,\n): DocumentsProjectionDescriptor[] {\n return recipientUserIds.map((recipientUserId) => ({\n kind: 'watch-notification',\n recipientUserId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n documentId: input.documentId,\n documentTitle,\n notificationType: 'documents.watch.commented',\n bodyKey,\n sourceEntityType: DOCUMENTS_ENTITY_IDS.documentComment,\n sourceEntityId: input.commentId,\n linkHref: `/backend/documents/${encodeURIComponent(input.documentId)}?commentId=${encodeURIComponent(input.commentId)}`,\n }))\n}\n\nfunction commentCreatedProjection(\n input: CommentCreateCommandInput,\n): DocumentsProjectionDescriptor {\n return {\n kind: 'event',\n eventId: 'documents.comment.created',\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n payload: {\n id: input.commentId,\n documentId: input.documentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n userId: input.actorUserId,\n },\n }\n}\n\nfunction readRedoInput<T>(logEntry: { commandPayload?: unknown }, schema: z.ZodType<T>): T {\n const raw = logEntry.commandPayload && typeof logEntry.commandPayload === 'object'\n ? (logEntry.commandPayload as { __redoInput?: unknown }).__redoInput\n : null\n return schema.parse(raw)\n}\n\nexport const createCommentCommand: CommandHandler<CommentCreateCommandInput, CommentCreateCommandResult> = {\n id: 'documents.comment.create',\n async prepare(rawInput, ctx) {\n const input = commentCreateCommandSchema.parse(rawInput)\n assertActor(input, ctx)\n const em = ctx.container.resolve('em') as EntityManager\n await assertCanCreateComment(ctx, em, input)\n return null\n },\n async execute(rawInput, ctx) {\n const input = commentCreateCommandSchema.parse(rawInput)\n const em = ctx.transactionalEm ?? (ctx.container.resolve('em') as EntityManager).fork()\n const fallback = commentFallback(input)\n const mentionUserIds = fallback.mentions?.map((mention) => mention.userId) ?? []\n const grantIdentityByUserId = new Map(input.grantShares.map((grant) => [grant.userId.toLowerCase(), grant]))\n const shareMutations: MentionShareMutation[] = []\n const pendingShareMutations: PendingMentionShareMutation[] = []\n const notifyMentionedIds: string[] = []\n let document: Document | null = null\n let comment: DocumentComment | null = null\n let before: CommentState | null = null\n let after: CommentState | null = null\n await withAtomicFlush(em, [async () => {\n document = await loadLockedDocument(em, input)\n assertActor(input, ctx)\n await assertCanCreateComment(ctx, em, input)\n comment = await loadComment(em, input, input.commentId, true)\n if (input.redoExpectation) {\n assertCommentMatchesState(\n comment,\n input.redoExpectation.state,\n input.redoExpectation.kind === 'soft-deleted-created',\n )\n } else if (comment) {\n throw new CrudHttpError(409, { error: 'Record changed by another user' })\n }\n before = captureCommentState(comment, fallback)\n if (fallback.parentCommentId) {\n const parent = await loadComment(em, input, fallback.parentCommentId, true)\n if (!parent || parent.deletedAt) throw new CrudHttpError(404, { error: 'Comment not found' })\n }\n await assertDocumentCommentCapacity(em, input)\n\n const canShare = await hasDocumentCapability(ctx, em, input, 'canShare')\n // An explicit grant request from an actor without the share capability\n // must fail loudly instead of returning 201 with the grants silently\n // dropped. Redo replays are exempt: their grants either already exist\n // (mentioned users resolve a tier below) or were legitimately created\n // by the original execution.\n if (input.grantShares.length > 0 && !canShare && !input.redoExpectation) {\n throw new CrudHttpError(403, { error: 'Forbidden' })\n }\n for (const mentionedUserId of mentionUserIds) {\n const grantIdentity = grantIdentityByUserId.get(mentionedUserId)\n if (!grantIdentity || !canShare) continue\n const tier = await resolveUserAccess(em, input.documentId, input, mentionedUserId, ctx.container)\n if (tier) continue\n await assertUserPrincipal(ctx.container, input, mentionedUserId)\n let share = await loadMentionShare(em, input, mentionedUserId, true)\n const shareFallback = {\n shareId: share?.id ?? grantIdentity.shareId,\n userId: mentionedUserId,\n actorUserId: input.actorUserId,\n }\n const shareBefore = captureMentionShareState(share, shareFallback)\n const created = !share\n share = share ?? em.create(DocumentShare, {\n id: grantIdentity.shareId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n documentId: input.documentId,\n principalType: 'user',\n principalId: mentionedUserId,\n permission: 'commenter',\n createdByUserId: input.actorUserId,\n })\n share.permission = 'commenter'\n share.deletedAt = null\n share.updatedAt = nextDocumentVersion(share.updatedAt)\n if (created) em.persist(share)\n pendingShareMutations.push({ before: shareBefore, share, fallback: shareFallback })\n }\n\n const created = !comment\n comment = comment ?? em.create(DocumentComment, {\n id: input.commentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n documentId: input.documentId,\n parentCommentId: fallback.parentCommentId,\n authorUserId: fallback.authorUserId,\n body: fallback.body,\n anchor: fallback.anchor,\n mentions: fallback.mentions,\n })\n comment.parentCommentId = fallback.parentCommentId\n comment.authorUserId = fallback.authorUserId\n comment.body = fallback.body\n comment.anchor = fallback.anchor\n comment.mentions = fallback.mentions\n comment.resolvedAt = null\n comment.resolvedByUserId = null\n comment.deletedAt = null\n comment.updatedAt = nextDocumentVersion(comment.updatedAt)\n if (created) em.persist(comment)\n }, async () => {\n after = captureCommentState(comment, fallback)\n for (const mutation of pendingShareMutations) {\n shareMutations.push({\n before: mutation.before,\n after: captureMentionShareState(mutation.share, mutation.fallback),\n })\n }\n for (const mentionedUserId of mentionUserIds) {\n const tier = await resolveUserAccess(em, input.documentId, input, mentionedUserId, ctx.container)\n if (tier) notifyMentionedIds.push(mentionedUserId)\n }\n }], { transaction: true, label: 'documents.comment.create' })\n\n const finalDocument = document as Document | null\n const finalComment = comment as DocumentComment | null\n const beforeState = before as CommentState | null\n if (!finalDocument || !finalComment || !beforeState) {\n throw new Error('[internal] comment create produced no row')\n }\n const afterState = after as CommentState | null\n if (!afterState) throw new Error('[internal] comment create produced no after snapshot')\n const watcherRecipientIds = await resolveWatcherRecipients({\n em,\n container: ctx.container,\n scope: { tenantId: input.tenantId, organizationId: input.organizationId },\n documentId: input.documentId,\n actorUserId: input.actorUserId,\n excludeUserIds: notifyMentionedIds,\n })\n const projections = [\n commentCreatedProjection(input),\n ...shareMutations.map((mutation) => shareProjection('documents.document.shared', input, mutation.after)),\n ...mentionProjections(input, finalDocument, notifyMentionedIds),\n ...watchCommentProjections(\n { ...input, commentId: input.commentId },\n finalDocument.title,\n watcherRecipientIds,\n 'documents.notifications.watch.commented.body',\n ),\n ]\n const projectionsAfterUndo: DocumentsProjectionDescriptor[] = [\n ...shareMutations.map((mutation) => shareProjection(\n mutation.before.existed && mutation.before.deletedAt === null\n ? 'documents.document.shared'\n : 'documents.document.unshared',\n input,\n mutation.before,\n false,\n )),\n {\n kind: 'mention-notification-delete',\n commentId: input.commentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n },\n ]\n return {\n id: finalComment.id,\n updatedAt: finalComment.updatedAt.toISOString(),\n projections,\n undo: { before: beforeState, after: afterState, shareMutations, projectionsAfterUndo },\n }\n },\n async buildLog({ input, result }) {\n const before = commentStateSchema.parse(result.undo.before)\n const after = commentStateSchema.parse(result.undo.after)\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('documents.audit.commentCreated', 'Add comment'),\n resourceKind: DOCUMENTS_ENTITY_IDS.documentComment,\n resourceId: result.id,\n parentResourceKind: DOCUMENTS_ENTITY_IDS.document,\n parentResourceId: input.documentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n snapshotBefore: before,\n snapshotAfter: after,\n payload: {\n undo: result.undo,\n __redoInput: {\n ...input,\n redoExpectation: before.existed\n ? { kind: 'snapshot', state: before }\n : { kind: 'soft-deleted-created', state: after },\n } satisfies CommentCreateCommandInput,\n },\n }\n },\n async undo({ logEntry, ctx }) {\n const undo = extractUndoPayload<CommentCreateUndoPayload>(logEntry)\n if (!undo?.before || !undo.after) return\n const input = readRedoInput(logEntry, commentCreateCommandSchema)\n const em = ctx.transactionalEm ?? (ctx.container.resolve('em') as EntityManager).fork()\n await withAtomicFlush(em, [async () => {\n await loadLockedDocument(em, input)\n if (undo.shareMutations.length > 0) {\n await assertCanMutateMentionShares(ctx, em, input)\n }\n const comment = await loadComment(em, input, undo.after!.id, true)\n if (!comment) throw new CrudHttpError(409, { error: 'Record changed by another user' })\n await assertCanResolveComment(ctx, em, {\n ...input,\n comment: { id: comment.id, resolved: false },\n expectedUpdatedAt: null,\n }, comment)\n assertCommentUnchanged(comment, undo.after!)\n await assertNoActiveReplies(em, input, comment.id)\n for (const mutation of undo.shareMutations) {\n const share = await loadMentionShare(em, input, mutation.after.userId, true)\n assertMentionShareUnchanged(share, mutation.after)\n restoreMentionShareState(share, mutation.before)\n }\n restoreCommentState(comment, undo.before!)\n }], { transaction: true, label: 'documents.comment.create.undo' })\n },\n}\n\nexport const resolveCommentCommand: CommandHandler<CommentResolveCommandInput, CommentResolveCommandResult> = {\n id: 'documents.comment.resolve',\n async prepare(rawInput, ctx) {\n const input = commentResolveCommandSchema.parse(rawInput)\n assertActor(input, ctx)\n const em = ctx.container.resolve('em') as EntityManager\n const comment = await loadComment(em, input, input.comment.id)\n if (!comment || comment.deletedAt) throw new CrudHttpError(404, { error: 'Comment not found' })\n await assertCanResolveComment(ctx, em, input, comment)\n return null\n },\n async execute(rawInput, ctx) {\n const input = commentResolveCommandSchema.parse(rawInput)\n const em = ctx.transactionalEm ?? (ctx.container.resolve('em') as EntityManager).fork()\n let comment: DocumentComment | null = null\n let before: CommentState | null = null\n let after: CommentState | null = null\n await withAtomicFlush(em, [async () => {\n await loadLockedDocument(em, input)\n assertActor(input, ctx)\n comment = await loadComment(em, input, input.comment.id, true)\n if (!comment || comment.deletedAt) throw new CrudHttpError(404, { error: 'Comment not found' })\n await assertCanResolveComment(ctx, em, input, comment)\n if (input.redoExpectation) {\n assertCommentMatchesState(comment, input.redoExpectation.state)\n } else {\n assertOptimisticLock({\n resourceKind: DOCUMENTS_ENTITY_IDS.documentComment,\n resourceId: comment.id,\n current: comment.updatedAt,\n expected: input.expectedUpdatedAt,\n })\n }\n before = captureCommentState(comment, {\n id: comment.id,\n parentCommentId: comment.parentCommentId ?? null,\n authorUserId: comment.authorUserId,\n body: comment.body,\n anchor: comment.anchor as CommentState['anchor'],\n mentions: comment.mentions ?? null,\n resolvedAt: comment.resolvedAt?.toISOString() ?? null,\n resolvedByUserId: comment.resolvedByUserId ?? null,\n })\n const now = new Date()\n ;(comment as DocumentComment).resolvedAt = input.comment.resolved ? now : null\n ;(comment as DocumentComment).resolvedByUserId = input.comment.resolved ? input.actorUserId : null\n ;(comment as DocumentComment).updatedAt = nextDocumentVersion(\n (comment as DocumentComment).updatedAt,\n now,\n )\n }, async () => {\n const finalComment = comment as DocumentComment | null\n if (!finalComment) throw new Error('[internal] comment resolve produced no row')\n after = captureCommentState(finalComment, {\n id: finalComment.id,\n parentCommentId: finalComment.parentCommentId ?? null,\n authorUserId: finalComment.authorUserId,\n body: finalComment.body,\n anchor: finalComment.anchor as CommentState['anchor'],\n mentions: finalComment.mentions ?? null,\n resolvedAt: finalComment.resolvedAt?.toISOString() ?? null,\n resolvedByUserId: finalComment.resolvedByUserId ?? null,\n })\n }], { transaction: true, label: 'documents.comment.resolve' })\n const finalComment = comment as DocumentComment | null\n const beforeState = before as CommentState | null\n const afterState = after as CommentState | null\n if (!finalComment || !beforeState || !afterState) throw new Error('[internal] comment resolve produced no row')\n const resolvedDocument = await findOneWithDecryption(\n em,\n Document,\n {\n id: input.documentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n deletedAt: null,\n },\n { fields: ['id', 'title'] },\n { tenantId: input.tenantId, organizationId: input.organizationId },\n )\n const watcherRecipientIds = resolvedDocument\n ? await resolveWatcherRecipients({\n em,\n container: ctx.container,\n scope: { tenantId: input.tenantId, organizationId: input.organizationId },\n documentId: input.documentId,\n actorUserId: input.actorUserId,\n })\n : []\n return {\n id: finalComment.id,\n resolvedAt: afterState.resolvedAt,\n resolvedByUserId: afterState.resolvedByUserId,\n updatedAt: finalComment.updatedAt.toISOString(),\n before: beforeState,\n after: afterState,\n projections: [\n resolutionProjection(input, afterState),\n ...(resolvedDocument\n ? watchCommentProjections(\n { ...input, commentId: finalComment.id },\n resolvedDocument.title,\n watcherRecipientIds,\n 'documents.notifications.watch.commented.resolvedBody',\n )\n : []),\n ],\n }\n },\n async buildLog({ input, result }) {\n const before = commentStateSchema.parse(result.before)\n const after = commentStateSchema.parse(result.after)\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('documents.audit.commentResolved', 'Resolve comment'),\n resourceKind: DOCUMENTS_ENTITY_IDS.documentComment,\n resourceId: result.id,\n parentResourceKind: DOCUMENTS_ENTITY_IDS.document,\n parentResourceId: input.documentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n snapshotBefore: before,\n snapshotAfter: after,\n payload: {\n undo: {\n before,\n after,\n projectionsAfterUndo: [resolutionProjection(input, before, false)],\n } satisfies CommentResolveUndoPayload,\n __redoInput: {\n ...input,\n expectedUpdatedAt: null,\n redoExpectation: { kind: 'snapshot', state: before },\n } satisfies CommentResolveCommandInput,\n },\n }\n },\n async undo({ logEntry, ctx }) {\n const undo = extractUndoPayload<CommentResolveUndoPayload>(logEntry)\n if (!undo?.before || !undo.after) return\n const input = readRedoInput(logEntry, commentResolveCommandSchema)\n const em = ctx.transactionalEm ?? (ctx.container.resolve('em') as EntityManager).fork()\n await withAtomicFlush(em, [async () => {\n await loadLockedDocument(em, input)\n const comment = await loadComment(em, input, undo.after!.id, true)\n if (!comment) throw new CrudHttpError(409, { error: 'Record changed by another user' })\n await assertCanResolveComment(ctx, em, input, comment)\n assertCommentUnchanged(comment, undo.after!)\n restoreCommentState(comment, undo.before!)\n }], { transaction: true, label: 'documents.comment.resolve.undo' })\n },\n}\n\nregisterCommand(createCommentCommand)\nregisterCommand(resolveCommentCommand)\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,gBAAgB;AAEzB,SAAS,SAAS;AAClB,SAAS,uBAA4C;AACrD,SAAS,uBAAuB;AAChC,SAAS,0BAA0B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AA,QACA,aAAa;AAAA,UACX,GAAG;AAAA,UACH,mBAAmB;AAAA,UACnB,iBAAiB,EAAE,MAAM,YAAY,OAAO,OAAO;AAAA,QACrD;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAAA,EACA,MAAM,KAAK,EAAE,UAAU,IAAI,GAAG;AAC5B,UAAM,OAAO,mBAA8C,QAAQ;AACnE,QAAI,CAAC,MAAM,UAAU,CAAC,KAAK,MAAO;AAClC,UAAM,QAAQ,cAAc,UAAU,2BAA2B;AACjE,UAAM,KAAK,IAAI,mBAAoB,IAAI,UAAU,QAAQ,IAAI,EAAoB,KAAK;AACtF,UAAM,gBAAgB,IAAI,CAAC,YAAY;AACrC,YAAM,mBAAmB,IAAI,KAAK;AAClC,YAAM,UAAU,MAAM,YAAY,IAAI,OAAO,KAAK,MAAO,IAAI,IAAI;AACjE,UAAI,CAAC,QAAS,OAAM,IAAI,cAAc,KAAK,EAAE,OAAO,iCAAiC,CAAC;AACtF,YAAM,wBAAwB,KAAK,IAAI,OAAO,OAAO;AACrD,6BAAuB,SAAS,KAAK,KAAM;AAC3C,0BAAoB,SAAS,KAAK,MAAO;AAAA,IAC3C,CAAC,GAAG,EAAE,aAAa,MAAM,OAAO,iCAAiC,CAAC;AAAA,EACpE;AACF;AAEA,gBAAgB,oBAAoB;AACpC,gBAAgB,qBAAqB;",
|
|
4
|
+
"sourcesContent": ["import { LockMode } from '@mikro-orm/core'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { z } from 'zod'\nimport { registerCommand, type CommandHandler } from '@open-mercato/shared/lib/commands'\nimport { withAtomicFlush } from '@open-mercato/shared/lib/commands/flush'\nimport { extractUndoPayload } from '@open-mercato/shared/lib/commands/undo'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport {\n assertOptimisticLock,\n buildOptimisticLockConflictBody,\n} from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport {\n findOneWithDecryption,\n findWithDecryption,\n} from '@open-mercato/shared/lib/encryption/find'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { Document, DocumentComment, DocumentShare } from '../data/entities'\nimport {\n documentCommentCreateSchema,\n documentSharePermissionSchema,\n} from '../data/validators'\nimport { DOCUMENTS_ENTITY_IDS } from '../lib/constants'\nimport { assertDocumentCommentCapacity } from '../lib/historyLimits'\nimport { resolveUserAccess, resolveUserDocumentTier } from '../lib/permissions'\nimport { resolveWatcherRecipients } from '../lib/watchers'\nimport type { DocumentsProjectionDescriptor } from './projection-types'\nimport {\n assertDocumentCommandCapability,\n resolveDocumentsCommandActor,\n resolveDocumentsCommandScope,\n} from './shared'\nimport { nextDocumentVersion } from './mutation-helpers'\nimport { resolveAuthPrincipalService, type DocumentsServiceContainer } from '../lib/platformServices'\n\nconst scopeSchema = z.object({\n tenantId: z.string().uuid(),\n organizationId: z.string().uuid(),\n})\n\nconst commentStateSchema = z.object({\n id: z.string().uuid(),\n existed: z.boolean(),\n parentCommentId: z.string().uuid().nullable(),\n authorUserId: z.string().uuid(),\n body: z.string(),\n // Snapshots must remain permissive for legacy anchors. New command input is\n // still validated by documentCommentCreateSchema's strict write union.\n anchor: z.record(z.string(), z.unknown()).nullable(),\n mentions: z.array(z.object({ userId: z.string().uuid() })).nullable(),\n resolvedAt: z.string().datetime().nullable(),\n resolvedByUserId: z.string().uuid().nullable(),\n deletedAt: z.string().datetime().nullable(),\n updatedAt: z.string().datetime().nullable(),\n})\n\nconst mentionShareStateSchema = z.object({\n id: z.string().uuid(),\n userId: z.string().uuid(),\n existed: z.boolean(),\n permission: documentSharePermissionSchema,\n createdByUserId: z.string().uuid(),\n deletedAt: z.string().datetime().nullable(),\n updatedAt: z.string().datetime().nullable(),\n})\n\nconst commentRedoExpectationSchema = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('snapshot'), state: commentStateSchema }),\n z.object({ kind: z.literal('soft-deleted-created'), state: commentStateSchema }),\n])\n\nconst commentCommandBaseSchema = scopeSchema.extend({\n documentId: z.string().uuid(),\n actorUserId: z.string().uuid(),\n})\n\nexport const commentCreateCommandSchema = commentCommandBaseSchema.extend({\n commentId: z.string().uuid(),\n comment: documentCommentCreateSchema,\n grantShares: z.array(z.object({ userId: z.string().uuid(), shareId: z.string().uuid() })).max(50),\n redoExpectation: commentRedoExpectationSchema.optional(),\n}).superRefine((input, context) => {\n const grantIds = Array.from(new Set((input.comment.grantAccessTo ?? []).map((id) => id.toLowerCase())))\n const identities = Array.from(new Set(input.grantShares.map((grant) => grant.userId.toLowerCase())))\n if (grantIds.length !== identities.length || grantIds.some((id) => !identities.includes(id))) {\n context.addIssue({ code: 'custom', message: 'documents.comments.grantIdentityMismatch' })\n }\n})\n\nexport const commentResolveCommandSchema = commentCommandBaseSchema.extend({\n comment: z.object({ id: z.string().uuid(), resolved: z.boolean() }),\n expectedUpdatedAt: z.string().datetime().nullable().optional(),\n redoExpectation: commentRedoExpectationSchema.optional(),\n})\n\nexport type CommentCreateCommandInput = z.infer<typeof commentCreateCommandSchema>\nexport type CommentResolveCommandInput = z.infer<typeof commentResolveCommandSchema>\nexport type CommentState = z.infer<typeof commentStateSchema>\nexport type MentionShareState = z.infer<typeof mentionShareStateSchema>\n\nexport type CommentCreateCommandResult = {\n id: string\n updatedAt: string\n projections?: DocumentsProjectionDescriptor[]\n undo: CommentCreateUndoPayload\n}\n\nexport type CommentResolveCommandResult = {\n id: string\n resolvedAt: string | null\n resolvedByUserId: string | null\n updatedAt: string\n before: CommentState\n after: CommentState\n projections?: DocumentsProjectionDescriptor[]\n}\n\ntype MentionShareMutation = {\n before: MentionShareState\n after: MentionShareState\n}\n\ntype PendingMentionShareMutation = {\n before: MentionShareState\n share: DocumentShare\n fallback: { shareId: string; userId: string; actorUserId: string }\n}\n\ntype CommentCreateUndoPayload = {\n before?: CommentState | null\n after?: CommentState | null\n shareMutations: MentionShareMutation[]\n projectionsAfterUndo?: DocumentsProjectionDescriptor[]\n}\n\ntype CommentResolveUndoPayload = {\n before?: CommentState | null\n after?: CommentState | null\n projectionsAfterUndo?: DocumentsProjectionDescriptor[]\n}\n\nfunction extractMentionedUserIds(body: string): string[] {\n const pattern = /@\\[([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\\]/gi\n return Array.from(new Set(\n Array.from(body.matchAll(pattern))\n .map((match) => match[1])\n .filter((value): value is string => typeof value === 'string')\n .map((value) => value.toLowerCase()),\n ))\n}\n\nfunction dedupeUserIds(values: string[]): string[] {\n return Array.from(new Set(values.map((value) => value.toLowerCase())))\n}\n\nfunction commentFallback(input: CommentCreateCommandInput): Omit<CommentState, 'existed' | 'deletedAt' | 'updatedAt'> {\n const mentionUserIds = dedupeUserIds([\n ...(input.comment.mentions ?? []).map((mention) => mention.userId),\n ...extractMentionedUserIds(input.comment.body),\n ])\n return {\n id: input.commentId,\n parentCommentId: input.comment.parentCommentId ?? null,\n authorUserId: input.actorUserId,\n body: input.comment.body,\n anchor: input.comment.anchor ?? null,\n mentions: mentionUserIds.length ? mentionUserIds.map((userId) => ({ userId })) : null,\n resolvedAt: null,\n resolvedByUserId: null,\n }\n}\n\nfunction captureCommentState(\n comment: DocumentComment | null,\n fallback: Omit<CommentState, 'existed' | 'deletedAt' | 'updatedAt'>,\n): CommentState {\n return {\n id: comment?.id ?? fallback.id,\n existed: comment !== null,\n parentCommentId: comment?.parentCommentId ?? fallback.parentCommentId,\n authorUserId: comment?.authorUserId ?? fallback.authorUserId,\n body: comment?.body ?? fallback.body,\n anchor: (comment?.anchor ?? fallback.anchor) as CommentState['anchor'],\n mentions: comment?.mentions ?? fallback.mentions,\n resolvedAt: comment?.resolvedAt?.toISOString() ?? fallback.resolvedAt,\n resolvedByUserId: comment?.resolvedByUserId ?? fallback.resolvedByUserId,\n deletedAt: comment?.deletedAt?.toISOString() ?? null,\n updatedAt: comment?.updatedAt?.toISOString() ?? null,\n }\n}\n\nfunction captureMentionShareState(\n share: DocumentShare | null,\n fallback: { shareId: string; userId: string; actorUserId: string },\n): MentionShareState {\n return {\n id: share?.id ?? fallback.shareId,\n userId: share?.principalId ?? fallback.userId,\n existed: share !== null,\n permission: share?.permission ?? 'commenter',\n createdByUserId: share?.createdByUserId ?? fallback.actorUserId,\n deletedAt: share?.deletedAt?.toISOString() ?? null,\n updatedAt: share?.updatedAt?.toISOString() ?? null,\n }\n}\n\nfunction assertActor(input: { actorUserId: string }, ctx: Parameters<CommandHandler['execute']>[1]): void {\n if (resolveDocumentsCommandActor(ctx) !== input.actorUserId) {\n throw new CrudHttpError(403, { error: 'Forbidden' })\n }\n}\n\nasync function loadLockedDocument(\n em: EntityManager,\n input: { tenantId: string; organizationId: string; documentId: string },\n): Promise<Document> {\n const document = await findOneWithDecryption(\n em,\n Document,\n {\n id: input.documentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n deletedAt: null,\n },\n { lockMode: LockMode.PESSIMISTIC_WRITE },\n { tenantId: input.tenantId, organizationId: input.organizationId },\n )\n if (!document) throw new CrudHttpError(404, { error: 'Document not found' })\n return document\n}\n\nasync function loadComment(\n em: EntityManager,\n input: { tenantId: string; organizationId: string; documentId: string },\n commentId: string,\n lock = false,\n): Promise<DocumentComment | null> {\n return findOneWithDecryption(\n em,\n DocumentComment,\n {\n id: commentId,\n documentId: input.documentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n },\n {\n filters: false,\n ...(lock ? { lockMode: LockMode.PESSIMISTIC_WRITE } : {}),\n },\n { tenantId: input.tenantId, organizationId: input.organizationId },\n )\n}\n\nasync function assertNoActiveReplies(\n em: EntityManager,\n input: { tenantId: string; organizationId: string; documentId: string },\n commentId: string,\n): Promise<void> {\n const replies = await findWithDecryption(\n em,\n DocumentComment,\n {\n documentId: input.documentId,\n parentCommentId: commentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n deletedAt: null,\n },\n { limit: 1 },\n { tenantId: input.tenantId, organizationId: input.organizationId },\n )\n if (replies.length > 0) {\n throw new CrudHttpError(409, { error: 'Record changed by another user' })\n }\n}\n\nasync function loadMentionShare(\n em: EntityManager,\n input: { tenantId: string; organizationId: string; documentId: string },\n userId: string,\n lock = false,\n): Promise<DocumentShare | null> {\n return findOneWithDecryption(\n em,\n DocumentShare,\n {\n documentId: input.documentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n principalType: 'user',\n principalId: userId,\n },\n {\n filters: false,\n orderBy: { updatedAt: 'DESC' },\n ...(lock ? { lockMode: LockMode.PESSIMISTIC_WRITE } : {}),\n },\n { tenantId: input.tenantId, organizationId: input.organizationId },\n )\n}\n\nasync function assertUserPrincipal(\n container: DocumentsServiceContainer,\n input: { tenantId: string; organizationId: string },\n userId: string,\n): Promise<void> {\n const exists = await resolveAuthPrincipalService(container)?.principalExists({\n type: 'user',\n id: userId,\n scope: { tenantId: input.tenantId, organizationId: input.organizationId },\n }) ?? false\n if (!exists) throw new CrudHttpError(400, { error: 'Share principal not found in this organization' })\n}\n\nasync function hasDocumentCapability(\n ctx: Parameters<CommandHandler['execute']>[1],\n em: EntityManager,\n input: { tenantId: string; organizationId: string; documentId: string },\n capability: 'canComment' | 'canShare',\n): Promise<boolean> {\n try {\n await assertDocumentCommandCapability(\n ctx,\n em,\n input.documentId,\n resolveDocumentsCommandScope(ctx, input),\n capability,\n )\n return true\n } catch (error) {\n if (isCrudHttpError(error) && error.status === 403) return false\n throw error\n }\n}\n\nasync function assertCanCreateComment(\n ctx: Parameters<CommandHandler['execute']>[1],\n em: EntityManager,\n input: CommentCreateCommandInput,\n): Promise<void> {\n resolveDocumentsCommandScope(ctx, input)\n if (!(await hasDocumentCapability(ctx, em, input, 'canComment'))) {\n throw new CrudHttpError(403, { error: 'Forbidden' })\n }\n}\n\nasync function assertCanMutateMentionShares(\n ctx: Parameters<CommandHandler['execute']>[1],\n em: EntityManager,\n input: CommentCreateCommandInput,\n): Promise<void> {\n const scope = resolveDocumentsCommandScope(ctx, input)\n await assertDocumentCommandCapability(ctx, em, input.documentId, scope, 'canShare')\n}\n\nasync function assertCanResolveComment(\n ctx: Parameters<CommandHandler['execute']>[1],\n em: EntityManager,\n input: CommentResolveCommandInput,\n comment: DocumentComment,\n): Promise<void> {\n const scope = resolveDocumentsCommandScope(ctx, input)\n await assertDocumentCommandCapability(ctx, em, input.documentId, scope, 'canView')\n if (comment.authorUserId === resolveDocumentsCommandActor(ctx)) return\n if (!(await hasDocumentCapability(ctx, em, input, 'canComment'))) {\n throw new CrudHttpError(403, { error: 'Forbidden' })\n }\n}\n\nfunction assertCommentMatchesState(\n comment: DocumentComment | null,\n expected: CommentState,\n softDeletedCreated = false,\n): void {\n if (!comment || !expected.existed) throw new CrudHttpError(409, { error: 'Record changed by another user' })\n const scalarsMatch = comment.id === expected.id\n && (comment.parentCommentId ?? null) === expected.parentCommentId\n && comment.authorUserId === expected.authorUserId\n && comment.body === expected.body\n && JSON.stringify(comment.anchor ?? null) === JSON.stringify(expected.anchor)\n && JSON.stringify(comment.mentions ?? null) === JSON.stringify(expected.mentions)\n && (comment.resolvedAt?.toISOString() ?? null) === expected.resolvedAt\n && (comment.resolvedByUserId ?? null) === expected.resolvedByUserId\n const deletedAt = comment.deletedAt?.toISOString() ?? null\n const deletionMatches = softDeletedCreated ? deletedAt !== null : deletedAt === expected.deletedAt\n if (!scalarsMatch || !deletionMatches) {\n throw new CrudHttpError(409, buildOptimisticLockConflictBody(\n comment.updatedAt.toISOString(),\n expected.updatedAt ?? comment.updatedAt.toISOString(),\n ))\n }\n}\n\nfunction assertCommentUnchanged(\n comment: DocumentComment | null,\n expected: CommentState,\n): asserts comment is DocumentComment {\n if (!comment || !expected.existed || !expected.updatedAt) {\n throw new CrudHttpError(409, { error: 'Record changed by another user' })\n }\n assertOptimisticLock({\n resourceKind: DOCUMENTS_ENTITY_IDS.documentComment,\n resourceId: expected.id,\n current: comment.updatedAt,\n expected: expected.updatedAt,\n envValue: 'all',\n })\n assertCommentMatchesState(comment, expected)\n}\n\nfunction assertMentionShareUnchanged(share: DocumentShare | null, expected: MentionShareState): asserts share is DocumentShare {\n if (!share || !expected.existed || !expected.updatedAt) {\n throw new CrudHttpError(409, { error: 'Record changed by another user' })\n }\n assertOptimisticLock({\n resourceKind: DOCUMENTS_ENTITY_IDS.documentShare,\n resourceId: expected.id,\n current: share.updatedAt,\n expected: expected.updatedAt,\n envValue: 'all',\n })\n if (\n share.id !== expected.id\n || share.principalType !== 'user'\n || share.principalId !== expected.userId\n || share.permission !== expected.permission\n || share.createdByUserId !== expected.createdByUserId\n || (share.deletedAt?.toISOString() ?? null) !== expected.deletedAt\n ) {\n throw new CrudHttpError(409, { error: 'Record changed by another user' })\n }\n}\n\nfunction restoreCommentState(comment: DocumentComment, before: CommentState): void {\n const now = nextDocumentVersion(comment.updatedAt)\n if (!before.existed) {\n comment.deletedAt = now\n comment.updatedAt = now\n return\n }\n comment.parentCommentId = before.parentCommentId\n comment.authorUserId = before.authorUserId\n comment.body = before.body\n comment.anchor = before.anchor\n comment.mentions = before.mentions\n comment.resolvedAt = before.resolvedAt ? new Date(before.resolvedAt) : null\n comment.resolvedByUserId = before.resolvedByUserId\n comment.deletedAt = before.deletedAt ? new Date(before.deletedAt) : null\n comment.updatedAt = now\n}\n\nfunction restoreMentionShareState(share: DocumentShare, before: MentionShareState): void {\n const now = nextDocumentVersion(share.updatedAt)\n if (!before.existed) {\n share.deletedAt = now\n share.updatedAt = now\n return\n }\n share.permission = before.permission\n share.createdByUserId = before.createdByUserId\n share.deletedAt = before.deletedAt ? new Date(before.deletedAt) : null\n share.updatedAt = now\n}\n\nfunction shareProjection(\n eventId: 'documents.document.shared' | 'documents.document.unshared',\n input: CommentCreateCommandInput,\n state: MentionShareState,\n includeActor = true,\n): DocumentsProjectionDescriptor {\n return {\n kind: 'event',\n eventId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n payload: {\n id: input.documentId,\n shareId: state.id,\n principalType: 'user',\n principalId: state.userId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n ...(includeActor ? { userId: input.actorUserId } : {}),\n },\n }\n}\n\nfunction resolutionProjection(\n input: CommentResolveCommandInput,\n state: CommentState,\n includeActor = true,\n): DocumentsProjectionDescriptor {\n return {\n kind: 'event',\n eventId: 'documents.comment.resolved',\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n payload: {\n id: state.id,\n documentId: input.documentId,\n resolved: state.resolvedAt !== null,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n ...(includeActor ? { userId: input.actorUserId } : {}),\n },\n }\n}\n\nfunction mentionProjections(\n input: CommentCreateCommandInput,\n document: Document,\n mentionedUserIds: string[],\n): DocumentsProjectionDescriptor[] {\n return mentionedUserIds.flatMap((recipientUserId): DocumentsProjectionDescriptor[] => [\n {\n kind: 'event',\n eventId: 'documents.comment.mentioned',\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n payload: {\n id: input.commentId,\n documentId: input.documentId,\n mentionedUserId: recipientUserId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n userId: input.actorUserId,\n },\n },\n {\n kind: 'mention-notification',\n recipientUserId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n documentId: input.documentId,\n documentTitle: document.title,\n commentId: input.commentId,\n authorUserId: input.actorUserId,\n },\n ])\n}\n\nfunction watchCommentProjections(\n input: { tenantId: string; organizationId: string; documentId: string; commentId: string },\n documentTitle: string,\n recipientUserIds: readonly string[],\n bodyKey: string,\n): DocumentsProjectionDescriptor[] {\n return recipientUserIds.map((recipientUserId) => ({\n kind: 'watch-notification',\n recipientUserId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n documentId: input.documentId,\n documentTitle,\n notificationType: 'documents.watch.commented',\n bodyKey,\n sourceEntityType: DOCUMENTS_ENTITY_IDS.documentComment,\n sourceEntityId: input.commentId,\n linkHref: `/backend/documents/${encodeURIComponent(input.documentId)}?commentId=${encodeURIComponent(input.commentId)}`,\n }))\n}\n\nfunction commentCreatedProjection(\n input: CommentCreateCommandInput,\n): DocumentsProjectionDescriptor {\n return {\n kind: 'event',\n eventId: 'documents.comment.created',\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n payload: {\n id: input.commentId,\n documentId: input.documentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n userId: input.actorUserId,\n },\n }\n}\n\nfunction readRedoInput<T>(logEntry: { commandPayload?: unknown }, schema: z.ZodType<T>): T {\n const raw = logEntry.commandPayload && typeof logEntry.commandPayload === 'object'\n ? (logEntry.commandPayload as { __redoInput?: unknown }).__redoInput\n : null\n return schema.parse(raw)\n}\n\nexport const createCommentCommand: CommandHandler<CommentCreateCommandInput, CommentCreateCommandResult> = {\n id: 'documents.comment.create',\n async prepare(rawInput, ctx) {\n const input = commentCreateCommandSchema.parse(rawInput)\n assertActor(input, ctx)\n const em = ctx.container.resolve('em') as EntityManager\n await assertCanCreateComment(ctx, em, input)\n return null\n },\n async execute(rawInput, ctx) {\n const input = commentCreateCommandSchema.parse(rawInput)\n const em = ctx.transactionalEm ?? (ctx.container.resolve('em') as EntityManager).fork()\n const fallback = commentFallback(input)\n const mentionUserIds = fallback.mentions?.map((mention) => mention.userId) ?? []\n const grantIdentityByUserId = new Map(input.grantShares.map((grant) => [grant.userId.toLowerCase(), grant]))\n const shareMutations: MentionShareMutation[] = []\n const pendingShareMutations: PendingMentionShareMutation[] = []\n const notifyMentionedIds: string[] = []\n let document: Document | null = null\n let comment: DocumentComment | null = null\n let before: CommentState | null = null\n let after: CommentState | null = null\n await withAtomicFlush(em, [async () => {\n document = await loadLockedDocument(em, input)\n assertActor(input, ctx)\n await assertCanCreateComment(ctx, em, input)\n comment = await loadComment(em, input, input.commentId, true)\n if (input.redoExpectation) {\n assertCommentMatchesState(\n comment,\n input.redoExpectation.state,\n input.redoExpectation.kind === 'soft-deleted-created',\n )\n } else if (comment) {\n throw new CrudHttpError(409, { error: 'Record changed by another user' })\n }\n before = captureCommentState(comment, fallback)\n if (fallback.parentCommentId) {\n const parent = await loadComment(em, input, fallback.parentCommentId, true)\n if (!parent || parent.deletedAt) throw new CrudHttpError(404, { error: 'Comment not found' })\n }\n await assertDocumentCommentCapacity(em, input)\n\n const canShare = await hasDocumentCapability(ctx, em, input, 'canShare')\n // An explicit grant request from an actor without the share capability\n // must fail loudly instead of returning 201 with the grants silently\n // dropped. Redo replays are exempt: their grants either already exist\n // (mentioned users resolve a tier below) or were legitimately created\n // by the original execution.\n if (input.grantShares.length > 0 && !canShare && !input.redoExpectation) {\n throw new CrudHttpError(403, { error: 'Forbidden' })\n }\n for (const mentionedUserId of mentionUserIds) {\n const grantIdentity = grantIdentityByUserId.get(mentionedUserId)\n if (!grantIdentity || !canShare) continue\n const tier = await resolveUserDocumentTier(em, input.documentId, input, mentionedUserId, ctx.container)\n if (tier) continue\n await assertUserPrincipal(ctx.container, input, mentionedUserId)\n let share = await loadMentionShare(em, input, mentionedUserId, true)\n const shareFallback = {\n shareId: share?.id ?? grantIdentity.shareId,\n userId: mentionedUserId,\n actorUserId: input.actorUserId,\n }\n const shareBefore = captureMentionShareState(share, shareFallback)\n const created = !share\n share = share ?? em.create(DocumentShare, {\n id: grantIdentity.shareId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n documentId: input.documentId,\n principalType: 'user',\n principalId: mentionedUserId,\n permission: 'commenter',\n createdByUserId: input.actorUserId,\n })\n share.permission = 'commenter'\n share.deletedAt = null\n share.updatedAt = nextDocumentVersion(share.updatedAt)\n if (created) em.persist(share)\n pendingShareMutations.push({ before: shareBefore, share, fallback: shareFallback })\n }\n\n const created = !comment\n comment = comment ?? em.create(DocumentComment, {\n id: input.commentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n documentId: input.documentId,\n parentCommentId: fallback.parentCommentId,\n authorUserId: fallback.authorUserId,\n body: fallback.body,\n anchor: fallback.anchor,\n mentions: fallback.mentions,\n })\n comment.parentCommentId = fallback.parentCommentId\n comment.authorUserId = fallback.authorUserId\n comment.body = fallback.body\n comment.anchor = fallback.anchor\n comment.mentions = fallback.mentions\n comment.resolvedAt = null\n comment.resolvedByUserId = null\n comment.deletedAt = null\n comment.updatedAt = nextDocumentVersion(comment.updatedAt)\n if (created) em.persist(comment)\n }, async () => {\n after = captureCommentState(comment, fallback)\n for (const mutation of pendingShareMutations) {\n shareMutations.push({\n before: mutation.before,\n after: captureMentionShareState(mutation.share, mutation.fallback),\n })\n }\n for (const mentionedUserId of mentionUserIds) {\n const tier = await resolveUserAccess(em, input.documentId, input, mentionedUserId, ctx.container)\n if (tier) notifyMentionedIds.push(mentionedUserId)\n }\n }], { transaction: true, label: 'documents.comment.create' })\n\n const finalDocument = document as Document | null\n const finalComment = comment as DocumentComment | null\n const beforeState = before as CommentState | null\n if (!finalDocument || !finalComment || !beforeState) {\n throw new Error('[internal] comment create produced no row')\n }\n const afterState = after as CommentState | null\n if (!afterState) throw new Error('[internal] comment create produced no after snapshot')\n const watcherRecipientIds = await resolveWatcherRecipients({\n em,\n container: ctx.container,\n scope: { tenantId: input.tenantId, organizationId: input.organizationId },\n documentId: input.documentId,\n actorUserId: input.actorUserId,\n excludeUserIds: notifyMentionedIds,\n })\n const projections = [\n commentCreatedProjection(input),\n ...shareMutations.map((mutation) => shareProjection('documents.document.shared', input, mutation.after)),\n ...mentionProjections(input, finalDocument, notifyMentionedIds),\n ...watchCommentProjections(\n { ...input, commentId: input.commentId },\n finalDocument.title,\n watcherRecipientIds,\n 'documents.notifications.watch.commented.body',\n ),\n ]\n const projectionsAfterUndo: DocumentsProjectionDescriptor[] = [\n ...shareMutations.map((mutation) => shareProjection(\n mutation.before.existed && mutation.before.deletedAt === null\n ? 'documents.document.shared'\n : 'documents.document.unshared',\n input,\n mutation.before,\n false,\n )),\n {\n kind: 'mention-notification-delete',\n commentId: input.commentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n },\n ]\n return {\n id: finalComment.id,\n updatedAt: finalComment.updatedAt.toISOString(),\n projections,\n undo: { before: beforeState, after: afterState, shareMutations, projectionsAfterUndo },\n }\n },\n async buildLog({ input, result }) {\n const before = commentStateSchema.parse(result.undo.before)\n const after = commentStateSchema.parse(result.undo.after)\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('documents.audit.commentCreated', 'Add comment'),\n resourceKind: DOCUMENTS_ENTITY_IDS.documentComment,\n resourceId: result.id,\n parentResourceKind: DOCUMENTS_ENTITY_IDS.document,\n parentResourceId: input.documentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n snapshotBefore: before,\n snapshotAfter: after,\n payload: {\n undo: result.undo,\n __redoInput: {\n ...input,\n redoExpectation: before.existed\n ? { kind: 'snapshot', state: before }\n : { kind: 'soft-deleted-created', state: after },\n } satisfies CommentCreateCommandInput,\n },\n }\n },\n async undo({ logEntry, ctx }) {\n const undo = extractUndoPayload<CommentCreateUndoPayload>(logEntry)\n if (!undo?.before || !undo.after) return\n const input = readRedoInput(logEntry, commentCreateCommandSchema)\n const em = ctx.transactionalEm ?? (ctx.container.resolve('em') as EntityManager).fork()\n await withAtomicFlush(em, [async () => {\n await loadLockedDocument(em, input)\n if (undo.shareMutations.length > 0) {\n await assertCanMutateMentionShares(ctx, em, input)\n }\n const comment = await loadComment(em, input, undo.after!.id, true)\n if (!comment) throw new CrudHttpError(409, { error: 'Record changed by another user' })\n await assertCanResolveComment(ctx, em, {\n ...input,\n comment: { id: comment.id, resolved: false },\n expectedUpdatedAt: null,\n }, comment)\n assertCommentUnchanged(comment, undo.after!)\n await assertNoActiveReplies(em, input, comment.id)\n for (const mutation of undo.shareMutations) {\n const share = await loadMentionShare(em, input, mutation.after.userId, true)\n assertMentionShareUnchanged(share, mutation.after)\n restoreMentionShareState(share, mutation.before)\n }\n restoreCommentState(comment, undo.before!)\n }], { transaction: true, label: 'documents.comment.create.undo' })\n },\n}\n\nexport const resolveCommentCommand: CommandHandler<CommentResolveCommandInput, CommentResolveCommandResult> = {\n id: 'documents.comment.resolve',\n async prepare(rawInput, ctx) {\n const input = commentResolveCommandSchema.parse(rawInput)\n assertActor(input, ctx)\n const em = ctx.container.resolve('em') as EntityManager\n const comment = await loadComment(em, input, input.comment.id)\n if (!comment || comment.deletedAt) throw new CrudHttpError(404, { error: 'Comment not found' })\n await assertCanResolveComment(ctx, em, input, comment)\n return null\n },\n async execute(rawInput, ctx) {\n const input = commentResolveCommandSchema.parse(rawInput)\n const em = ctx.transactionalEm ?? (ctx.container.resolve('em') as EntityManager).fork()\n let comment: DocumentComment | null = null\n let before: CommentState | null = null\n let after: CommentState | null = null\n await withAtomicFlush(em, [async () => {\n await loadLockedDocument(em, input)\n assertActor(input, ctx)\n comment = await loadComment(em, input, input.comment.id, true)\n if (!comment || comment.deletedAt) throw new CrudHttpError(404, { error: 'Comment not found' })\n await assertCanResolveComment(ctx, em, input, comment)\n if (input.redoExpectation) {\n assertCommentMatchesState(comment, input.redoExpectation.state)\n } else {\n assertOptimisticLock({\n resourceKind: DOCUMENTS_ENTITY_IDS.documentComment,\n resourceId: comment.id,\n current: comment.updatedAt,\n expected: input.expectedUpdatedAt,\n })\n }\n before = captureCommentState(comment, {\n id: comment.id,\n parentCommentId: comment.parentCommentId ?? null,\n authorUserId: comment.authorUserId,\n body: comment.body,\n anchor: comment.anchor as CommentState['anchor'],\n mentions: comment.mentions ?? null,\n resolvedAt: comment.resolvedAt?.toISOString() ?? null,\n resolvedByUserId: comment.resolvedByUserId ?? null,\n })\n const now = new Date()\n ;(comment as DocumentComment).resolvedAt = input.comment.resolved ? now : null\n ;(comment as DocumentComment).resolvedByUserId = input.comment.resolved ? input.actorUserId : null\n ;(comment as DocumentComment).updatedAt = nextDocumentVersion(\n (comment as DocumentComment).updatedAt,\n now,\n )\n }, async () => {\n const finalComment = comment as DocumentComment | null\n if (!finalComment) throw new Error('[internal] comment resolve produced no row')\n after = captureCommentState(finalComment, {\n id: finalComment.id,\n parentCommentId: finalComment.parentCommentId ?? null,\n authorUserId: finalComment.authorUserId,\n body: finalComment.body,\n anchor: finalComment.anchor as CommentState['anchor'],\n mentions: finalComment.mentions ?? null,\n resolvedAt: finalComment.resolvedAt?.toISOString() ?? null,\n resolvedByUserId: finalComment.resolvedByUserId ?? null,\n })\n }], { transaction: true, label: 'documents.comment.resolve' })\n const finalComment = comment as DocumentComment | null\n const beforeState = before as CommentState | null\n const afterState = after as CommentState | null\n if (!finalComment || !beforeState || !afterState) throw new Error('[internal] comment resolve produced no row')\n const resolvedDocument = await findOneWithDecryption(\n em,\n Document,\n {\n id: input.documentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n deletedAt: null,\n },\n { fields: ['id', 'title'] },\n { tenantId: input.tenantId, organizationId: input.organizationId },\n )\n const watcherRecipientIds = resolvedDocument\n ? await resolveWatcherRecipients({\n em,\n container: ctx.container,\n scope: { tenantId: input.tenantId, organizationId: input.organizationId },\n documentId: input.documentId,\n actorUserId: input.actorUserId,\n })\n : []\n return {\n id: finalComment.id,\n resolvedAt: afterState.resolvedAt,\n resolvedByUserId: afterState.resolvedByUserId,\n updatedAt: finalComment.updatedAt.toISOString(),\n before: beforeState,\n after: afterState,\n projections: [\n resolutionProjection(input, afterState),\n ...(resolvedDocument\n ? watchCommentProjections(\n { ...input, commentId: finalComment.id },\n resolvedDocument.title,\n watcherRecipientIds,\n 'documents.notifications.watch.commented.resolvedBody',\n )\n : []),\n ],\n }\n },\n async buildLog({ input, result }) {\n const before = commentStateSchema.parse(result.before)\n const after = commentStateSchema.parse(result.after)\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('documents.audit.commentResolved', 'Resolve comment'),\n resourceKind: DOCUMENTS_ENTITY_IDS.documentComment,\n resourceId: result.id,\n parentResourceKind: DOCUMENTS_ENTITY_IDS.document,\n parentResourceId: input.documentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n snapshotBefore: before,\n snapshotAfter: after,\n payload: {\n undo: {\n before,\n after,\n projectionsAfterUndo: [resolutionProjection(input, before, false)],\n } satisfies CommentResolveUndoPayload,\n __redoInput: {\n ...input,\n expectedUpdatedAt: null,\n redoExpectation: { kind: 'snapshot', state: before },\n } satisfies CommentResolveCommandInput,\n },\n }\n },\n async undo({ logEntry, ctx }) {\n const undo = extractUndoPayload<CommentResolveUndoPayload>(logEntry)\n if (!undo?.before || !undo.after) return\n const input = readRedoInput(logEntry, commentResolveCommandSchema)\n const em = ctx.transactionalEm ?? (ctx.container.resolve('em') as EntityManager).fork()\n await withAtomicFlush(em, [async () => {\n await loadLockedDocument(em, input)\n const comment = await loadComment(em, input, undo.after!.id, true)\n if (!comment) throw new CrudHttpError(409, { error: 'Record changed by another user' })\n await assertCanResolveComment(ctx, em, input, comment)\n assertCommentUnchanged(comment, undo.after!)\n restoreCommentState(comment, undo.before!)\n }], { transaction: true, label: 'documents.comment.resolve.undo' })\n },\n}\n\nregisterCommand(createCommentCommand)\nregisterCommand(resolveCommentCommand)\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,gBAAgB;AAEzB,SAAS,SAAS;AAClB,SAAS,uBAA4C;AACrD,SAAS,uBAAuB;AAChC,SAAS,0BAA0B;AACnC,SAAS,eAAe,uBAAuB;AAC/C;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AACpC,SAAS,UAAU,iBAAiB,qBAAqB;AACzD;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,4BAA4B;AACrC,SAAS,qCAAqC;AAC9C,SAAS,mBAAmB,+BAA+B;AAC3D,SAAS,gCAAgC;AAEzC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AACpC,SAAS,mCAAmE;AAE5E,MAAM,cAAc,EAAE,OAAO;AAAA,EAC3B,UAAU,EAAE,OAAO,EAAE,KAAK;AAAA,EAC1B,gBAAgB,EAAE,OAAO,EAAE,KAAK;AAClC,CAAC;AAED,MAAM,qBAAqB,EAAE,OAAO;AAAA,EAClC,IAAI,EAAE,OAAO,EAAE,KAAK;AAAA,EACpB,SAAS,EAAE,QAAQ;AAAA,EACnB,iBAAiB,EAAE,OAAO,E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O;AACrD,6BAAuB,SAAS,KAAK,KAAM;AAC3C,0BAAoB,SAAS,KAAK,MAAO;AAAA,IAC3C,CAAC,GAAG,EAAE,aAAa,MAAM,OAAO,iCAAiC,CAAC;AAAA,EACpE;AACF;AAEA,gBAAgB,oBAAoB;AACpC,gBAAgB,qBAAqB;",
|
|
6
6
|
"names": ["created", "finalComment"]
|
|
7
7
|
}
|
|
@@ -394,6 +394,7 @@ const deleteFolderCommand = {
|
|
|
394
394
|
assertCommandFeature(features, "documents.edit");
|
|
395
395
|
await assertFolderOwnerOrManager(undo.before.ownerUserId, actorUserId, features);
|
|
396
396
|
assertVersionedSnapshot(folder, undo.after, DOCUMENTS_ENTITY_IDS.documentFolder);
|
|
397
|
+
await assertOrganizationFolderCapacity(em, scope);
|
|
397
398
|
await assertWritableParent(em, undo.before.parentFolderId, scope, actorUserId, features);
|
|
398
399
|
await assertValidPlacement(em, scope, input.id, undo.before.parentFolderId);
|
|
399
400
|
if (folder) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/documents/commands/folders.ts"],
|
|
4
|
-
"sourcesContent": ["import { LockMode } from '@mikro-orm/core'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { isDeepStrictEqual } from 'node:util'\nimport { z } from 'zod'\nimport { registerCommand, type CommandHandler } from '@open-mercato/shared/lib/commands'\nimport { withAtomicFlush } from '@open-mercato/shared/lib/commands/flush'\nimport { extractUndoPayload } from '@open-mercato/shared/lib/commands/undo'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { enforceCommandOptimisticLockWithGuards } from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { hasAllFeatures } from '@open-mercato/shared/lib/auth/featureMatch'\nimport { DocumentFolder } from '../data/entities'\nimport { documentFolderCreateSchema, documentFolderUpdateSchema } from '../data/validators'\nimport { DOCUMENTS_ENTITY_IDS, DOCUMENTS_MAX_FOLDERS_PER_ORGANIZATION } from '../lib/constants'\nimport { acquireFolderHierarchyMutationLock } from '../lib/folderHierarchySerialization'\nimport { getFolderPlacementIssue, hasActiveFolderContents } from '../lib/visibility'\nimport {\n assertCommandFeature,\n resolveDocumentsCommandActor,\n resolveDocumentsCommandEntityManager,\n resolveDocumentsCommandFeatures,\n resolveDocumentsCommandScope,\n type DocumentsCommandScope,\n} from './shared'\nimport {\n assertVersionedSnapshot,\n documentsScopedCommandSchema,\n nextDocumentVersion,\n readCommandRedoInput,\n} from './mutation-helpers'\n\nconst folderSnapshotSchema = z.object({\n id: z.string().uuid(),\n tenantId: z.string().uuid(),\n organizationId: z.string().uuid(),\n name: z.string(),\n parentFolderId: z.string().uuid().nullable(),\n ownerUserId: z.string().uuid(),\n createdAt: z.string().datetime(),\n updatedAt: z.string().datetime(),\n deletedAt: z.string().datetime().nullable(),\n})\n\nconst folderUpdateRedoExpectationSchema = z.object({\n kind: z.literal('folder-update-post-undo'),\n folder: folderSnapshotSchema,\n})\n\nconst folderDeleteRedoExpectationSchema = z.object({\n kind: z.literal('folder-delete-post-undo'),\n folder: folderSnapshotSchema,\n})\n\nexport const folderCreateCommandSchema = documentsScopedCommandSchema\n .merge(documentFolderCreateSchema)\n .extend({ folderId: z.string().uuid() })\n\nexport const folderUpdateCommandSchema = documentsScopedCommandSchema\n .merge(documentFolderUpdateSchema)\n .extend({ redoExpectation: folderUpdateRedoExpectationSchema.optional() })\n\nexport const folderDeleteCommandSchema = documentsScopedCommandSchema.extend({\n id: z.string().uuid(),\n redoExpectation: folderDeleteRedoExpectationSchema.optional(),\n})\n\nexport type FolderCreateCommandInput = z.infer<typeof folderCreateCommandSchema>\nexport type FolderUpdateCommandInput = z.infer<typeof folderUpdateCommandSchema>\nexport type FolderDeleteCommandInput = z.infer<typeof folderDeleteCommandSchema>\n\ntype FolderSnapshot = z.infer<typeof folderSnapshotSchema>\n\ntype FolderUndoPayload = {\n before?: FolderSnapshot | null\n after?: FolderSnapshot | null\n}\n\ntype FolderCommandResult = {\n id: string\n updatedAt: string\n before: FolderSnapshot | null\n after: FolderSnapshot\n}\n\nfunction snapshotFolder(folder: DocumentFolder | null): FolderSnapshot | null {\n if (!folder) return null\n return {\n id: folder.id,\n tenantId: folder.tenantId,\n organizationId: folder.organizationId,\n name: folder.name,\n parentFolderId: folder.parentFolderId ?? null,\n ownerUserId: folder.ownerUserId,\n createdAt: folder.createdAt.toISOString(),\n updatedAt: folder.updatedAt.toISOString(),\n deletedAt: folder.deletedAt?.toISOString() ?? null,\n }\n}\n\nfunction changedError(): CrudHttpError {\n return new CrudHttpError(409, { error: 'Record changed by another user' })\n}\n\nfunction nextSnapshotVersion(updatedAt: string): string {\n return nextDocumentVersion(new Date(updatedAt), new Date(0)).toISOString()\n}\n\nfunction assertFolderStateMatches(folder: DocumentFolder, expected: FolderSnapshot): void {\n if (!isDeepStrictEqual(snapshotFolder(folder), expected)) throw changedError()\n}\n\nfunction resolveExactUndoVersion(current: Date, expectedUpdatedAt?: string): Date {\n if (!expectedUpdatedAt) return nextDocumentVersion(current)\n const expected = new Date(expectedUpdatedAt)\n if (!Number.isFinite(expected.getTime()) || expected.getTime() <= current.getTime()) {\n throw changedError()\n }\n return expected\n}\n\nfunction buildFolderUpdateRedoExpectation(\n before: FolderSnapshot,\n after: FolderSnapshot,\n): z.infer<typeof folderUpdateRedoExpectationSchema> {\n return {\n kind: 'folder-update-post-undo',\n folder: { ...before, updatedAt: nextSnapshotVersion(after.updatedAt) },\n }\n}\n\nfunction buildFolderDeleteRedoExpectation(\n before: FolderSnapshot,\n after: FolderSnapshot,\n): z.infer<typeof folderDeleteRedoExpectationSchema> {\n return {\n kind: 'folder-delete-post-undo',\n folder: { ...before, updatedAt: nextSnapshotVersion(after.updatedAt) },\n }\n}\n\nasync function loadLockedFolder(\n em: EntityManager,\n id: string,\n scope: DocumentsCommandScope,\n includeDeleted = false,\n): Promise<DocumentFolder | null> {\n return findOneWithDecryption(\n em,\n DocumentFolder,\n {\n id,\n ...scope,\n ...(includeDeleted ? {} : { deletedAt: null }),\n },\n {\n lockMode: LockMode.PESSIMISTIC_WRITE,\n ...(includeDeleted ? { filters: false } : {}),\n },\n scope,\n )\n}\n\nasync function assertFolderOwnerOrManager(\n ownerUserId: string,\n actorUserId: string,\n features: readonly string[],\n): Promise<void> {\n if (ownerUserId === actorUserId || hasAllFeatures(['documents.manage'], Array.from(features))) return\n throw new CrudHttpError(403, { error: 'Forbidden' })\n}\n\nasync function assertWritableParent(\n em: EntityManager,\n parentFolderId: string | null | undefined,\n scope: DocumentsCommandScope,\n actorUserId: string,\n features: readonly string[],\n): Promise<void> {\n if (!parentFolderId) return\n const parent = await loadLockedFolder(em, parentFolderId, scope)\n if (!parent) throw new CrudHttpError(404, { error: 'documents.folders.notFound' })\n await assertFolderOwnerOrManager(parent.ownerUserId, actorUserId, features)\n}\n\n/**\n * Call only while holding the folder hierarchy mutation lock, so the count and\n * the insert that follows it cannot interleave with a competing create.\n */\nasync function assertOrganizationFolderCapacity(\n em: EntityManager,\n scope: DocumentsCommandScope,\n): Promise<void> {\n const activeCount = await em.count(DocumentFolder, { ...scope, deletedAt: null })\n if (activeCount < DOCUMENTS_MAX_FOLDERS_PER_ORGANIZATION) return\n throw new CrudHttpError(422, { error: 'documents.errors.folderLimitReached' })\n}\n\nasync function assertValidPlacement(\n em: EntityManager,\n scope: DocumentsCommandScope,\n folderId: string | null,\n parentFolderId: string | null,\n): Promise<void> {\n const issue = await getFolderPlacementIssue({ em, ...scope, folderId, parentFolderId })\n if (issue) throw new CrudHttpError(400, { error: 'documents.folders.error.invalidPlacement' })\n}\n\nfunction applyFolderSnapshot(\n folder: DocumentFolder,\n snapshot: FolderSnapshot,\n expectedUpdatedAt?: string,\n): void {\n folder.name = snapshot.name\n folder.parentFolderId = snapshot.parentFolderId\n folder.ownerUserId = snapshot.ownerUserId\n folder.deletedAt = snapshot.deletedAt ? new Date(snapshot.deletedAt) : null\n folder.updatedAt = resolveExactUndoVersion(folder.updatedAt, expectedUpdatedAt)\n}\n\nfunction buildFolderLog(\n actionLabel: string,\n input: DocumentsCommandScope,\n result: FolderCommandResult,\n redoInput?: FolderUpdateCommandInput | FolderDeleteCommandInput,\n) {\n return {\n actionLabel,\n resourceKind: DOCUMENTS_ENTITY_IDS.documentFolder,\n resourceId: result.id,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n snapshotBefore: result.before,\n snapshotAfter: result.after,\n payload: {\n undo: { before: result.before, after: result.after } satisfies FolderUndoPayload,\n ...(redoInput ? { __redoInput: redoInput } : {}),\n },\n }\n}\n\nconst createFolderCommand: CommandHandler<FolderCreateCommandInput, FolderCommandResult> = {\n id: 'documents.folder.create',\n async execute(rawInput, ctx) {\n const input = folderCreateCommandSchema.parse(rawInput)\n const scope = resolveDocumentsCommandScope(ctx, input)\n const actorUserId = resolveDocumentsCommandActor(ctx)\n const em = resolveDocumentsCommandEntityManager(ctx)\n let folder!: DocumentFolder\n let before: FolderSnapshot | null = null\n await withAtomicFlush(em, [async () => {\n await acquireFolderHierarchyMutationLock(em, scope)\n const existing = await loadLockedFolder(em, input.folderId, scope, true)\n const features = await resolveDocumentsCommandFeatures(ctx, scope)\n assertCommandFeature(features, 'documents.edit')\n before = snapshotFolder(existing)\n if (existing && !existing.deletedAt) {\n throw new CrudHttpError(409, { error: 'Record changed by another user' })\n }\n // Reviving a soft-deleted row adds an active folder just like a fresh\n // insert, so both paths answer to the same organization-wide cap. Undo\n // stays exempt: it only restores state the organization already held.\n await assertOrganizationFolderCapacity(em, scope)\n await assertWritableParent(em, input.parentFolderId ?? null, scope, actorUserId, features)\n await assertValidPlacement(em, scope, null, input.parentFolderId ?? null)\n folder = existing ?? em.create(DocumentFolder, {\n id: input.folderId,\n ...scope,\n name: input.name,\n parentFolderId: input.parentFolderId ?? null,\n ownerUserId: actorUserId,\n })\n if (!existing) em.persist(folder)\n folder.name = input.name\n folder.parentFolderId = input.parentFolderId ?? null\n folder.ownerUserId = actorUserId\n folder.deletedAt = null\n if (existing) folder.updatedAt = nextDocumentVersion(folder.updatedAt)\n }], { transaction: true, label: 'documents.folder.create' })\n return {\n id: folder.id,\n updatedAt: folder.updatedAt.toISOString(),\n before,\n after: snapshotFolder(folder)!,\n }\n },\n async buildLog({ input, result }) {\n const { translate } = await resolveTranslations()\n return buildFolderLog(\n translate('documents.audit.folderCreated', 'Create folder'),\n input,\n result,\n )\n },\n async undo({ logEntry, ctx }) {\n const undo = extractUndoPayload<FolderUndoPayload>(logEntry)\n if (!undo?.after) return\n const input = folderCreateCommandSchema.parse(readCommandRedoInput(logEntry))\n const scope = resolveDocumentsCommandScope(ctx, input)\n const actorUserId = resolveDocumentsCommandActor(ctx)\n const em = resolveDocumentsCommandEntityManager(ctx)\n await withAtomicFlush(em, [async () => {\n await acquireFolderHierarchyMutationLock(em, scope)\n const folder = await loadLockedFolder(em, input.folderId, scope, true)\n const features = await resolveDocumentsCommandFeatures(ctx, scope)\n assertCommandFeature(features, 'documents.edit')\n await assertFolderOwnerOrManager(undo.after!.ownerUserId, actorUserId, features)\n assertVersionedSnapshot(folder, undo.after, DOCUMENTS_ENTITY_IDS.documentFolder)\n if (await hasActiveFolderContents({ em, ...scope, folderId: input.folderId })) {\n throw new CrudHttpError(409, { error: 'Record changed by another user' })\n }\n if (undo.before && folder) applyFolderSnapshot(folder, undo.before)\n else if (folder) {\n const now = nextDocumentVersion(folder.updatedAt)\n folder.deletedAt = now\n folder.updatedAt = now\n }\n }], { transaction: true, label: 'documents.folder.create.undo' })\n },\n}\n\nconst updateFolderCommand: CommandHandler<FolderUpdateCommandInput, FolderCommandResult> = {\n id: 'documents.folder.update',\n async execute(rawInput, ctx) {\n const input = folderUpdateCommandSchema.parse(rawInput)\n const scope = resolveDocumentsCommandScope(ctx, input)\n const actorUserId = resolveDocumentsCommandActor(ctx)\n const em = resolveDocumentsCommandEntityManager(ctx)\n let folder!: DocumentFolder\n let before!: FolderSnapshot\n await withAtomicFlush(em, [async () => {\n await acquireFolderHierarchyMutationLock(em, scope)\n const loaded = await loadLockedFolder(\n em,\n input.id,\n scope,\n input.redoExpectation !== undefined,\n )\n if (!loaded) throw new CrudHttpError(404, { error: 'documents.folders.notFound' })\n folder = loaded\n const features = await resolveDocumentsCommandFeatures(ctx, scope)\n assertCommandFeature(features, 'documents.edit')\n await assertFolderOwnerOrManager(folder.ownerUserId, actorUserId, features)\n if (input.redoExpectation) {\n assertFolderStateMatches(folder, input.redoExpectation.folder)\n } else {\n await enforceCommandOptimisticLockWithGuards(ctx.container, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentFolder,\n resourceId: folder.id,\n current: folder.updatedAt,\n request: ctx.request ?? null,\n })\n }\n before = snapshotFolder(folder)!\n if (Object.prototype.hasOwnProperty.call(input, 'parentFolderId')) {\n await assertWritableParent(em, input.parentFolderId ?? null, scope, actorUserId, features)\n await assertValidPlacement(em, scope, folder.id, input.parentFolderId ?? null)\n }\n if (input.name !== undefined) folder.name = input.name\n if (Object.prototype.hasOwnProperty.call(input, 'parentFolderId')) {\n folder.parentFolderId = input.parentFolderId ?? null\n }\n folder.updatedAt = nextDocumentVersion(folder.updatedAt)\n }], { transaction: true, label: 'documents.folder.update' })\n return {\n id: folder.id,\n updatedAt: folder.updatedAt.toISOString(),\n before,\n after: snapshotFolder(folder)!,\n }\n },\n async buildLog({ input, result }) {\n const { translate } = await resolveTranslations()\n if (!result.before) throw new Error('[internal] folder update produced no before snapshot')\n const redoInput: FolderUpdateCommandInput = {\n ...input,\n redoExpectation: buildFolderUpdateRedoExpectation(result.before, result.after),\n }\n return buildFolderLog(\n translate('documents.audit.folderUpdated', 'Update folder'),\n input,\n result,\n redoInput,\n )\n },\n async undo({ logEntry, ctx }) {\n const undo = extractUndoPayload<FolderUndoPayload>(logEntry)\n if (!undo?.before || !undo.after) return\n const before = undo.before\n const after = undo.after\n const input = folderUpdateCommandSchema.parse(readCommandRedoInput(logEntry))\n const scope = resolveDocumentsCommandScope(ctx, input)\n const actorUserId = resolveDocumentsCommandActor(ctx)\n const em = resolveDocumentsCommandEntityManager(ctx)\n await withAtomicFlush(em, [async () => {\n await acquireFolderHierarchyMutationLock(em, scope)\n const folder = await loadLockedFolder(em, input.id, scope)\n if (!folder) throw new CrudHttpError(404, { error: 'documents.folders.notFound' })\n const features = await resolveDocumentsCommandFeatures(ctx, scope)\n assertCommandFeature(features, 'documents.edit')\n await assertFolderOwnerOrManager(folder.ownerUserId, actorUserId, features)\n assertVersionedSnapshot(folder, after, DOCUMENTS_ENTITY_IDS.documentFolder)\n await assertWritableParent(em, before.parentFolderId, scope, actorUserId, features)\n await assertValidPlacement(em, scope, folder.id, before.parentFolderId)\n applyFolderSnapshot(\n folder,\n before,\n input.redoExpectation?.folder.updatedAt,\n )\n }], { transaction: true, label: 'documents.folder.update.undo' })\n },\n}\n\nconst deleteFolderCommand: CommandHandler<FolderDeleteCommandInput, FolderCommandResult> = {\n id: 'documents.folder.delete',\n async execute(rawInput, ctx) {\n const input = folderDeleteCommandSchema.parse(rawInput)\n const scope = resolveDocumentsCommandScope(ctx, input)\n const actorUserId = resolveDocumentsCommandActor(ctx)\n const em = resolveDocumentsCommandEntityManager(ctx)\n let folder!: DocumentFolder\n let before!: FolderSnapshot\n await withAtomicFlush(em, [async () => {\n await acquireFolderHierarchyMutationLock(em, scope)\n const loaded = await loadLockedFolder(\n em,\n input.id,\n scope,\n input.redoExpectation !== undefined,\n )\n if (!loaded) throw new CrudHttpError(404, { error: 'documents.folders.notFound' })\n folder = loaded\n const features = await resolveDocumentsCommandFeatures(ctx, scope)\n assertCommandFeature(features, 'documents.edit')\n await assertFolderOwnerOrManager(folder.ownerUserId, actorUserId, features)\n if (input.redoExpectation) {\n assertFolderStateMatches(folder, input.redoExpectation.folder)\n } else {\n await enforceCommandOptimisticLockWithGuards(ctx.container, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentFolder,\n resourceId: folder.id,\n current: folder.updatedAt,\n request: ctx.request ?? null,\n })\n }\n before = snapshotFolder(folder)!\n if (await hasActiveFolderContents({ em, ...scope, folderId: folder.id })) {\n throw new CrudHttpError(409, { error: 'documents.folders.error.delete' })\n }\n const now = nextDocumentVersion(folder.updatedAt)\n folder.deletedAt = now\n folder.updatedAt = now\n }], { transaction: true, label: 'documents.folder.delete' })\n return {\n id: folder.id,\n updatedAt: folder.updatedAt.toISOString(),\n before,\n after: snapshotFolder(folder)!,\n }\n },\n async buildLog({ input, result }) {\n const { translate } = await resolveTranslations()\n if (!result.before) throw new Error('[internal] folder delete produced no before snapshot')\n const redoInput: FolderDeleteCommandInput = {\n ...input,\n redoExpectation: buildFolderDeleteRedoExpectation(result.before, result.after),\n }\n return buildFolderLog(\n translate('documents.audit.folderDeleted', 'Delete folder'),\n input,\n result,\n redoInput,\n )\n },\n async undo({ logEntry, ctx }) {\n const undo = extractUndoPayload<FolderUndoPayload>(logEntry)\n if (!undo?.before || !undo.after) return\n const input = folderDeleteCommandSchema.parse(readCommandRedoInput(logEntry))\n const scope = resolveDocumentsCommandScope(ctx, input)\n const actorUserId = resolveDocumentsCommandActor(ctx)\n const em = resolveDocumentsCommandEntityManager(ctx)\n await withAtomicFlush(em, [async () => {\n await acquireFolderHierarchyMutationLock(em, scope)\n const folder = await loadLockedFolder(em, input.id, scope, true)\n const features = await resolveDocumentsCommandFeatures(ctx, scope)\n assertCommandFeature(features, 'documents.edit')\n await assertFolderOwnerOrManager(undo.before!.ownerUserId, actorUserId, features)\n assertVersionedSnapshot(folder, undo.after, DOCUMENTS_ENTITY_IDS.documentFolder)\n await assertWritableParent(em, undo.before!.parentFolderId, scope, actorUserId, features)\n await assertValidPlacement(em, scope, input.id, undo.before!.parentFolderId)\n if (folder) {\n applyFolderSnapshot(\n folder,\n undo.before!,\n input.redoExpectation?.folder.updatedAt,\n )\n }\n }], { transaction: true, label: 'documents.folder.delete.undo' })\n },\n}\n\nregisterCommand(createFolderCommand)\nregisterCommand(updateFolderCommand)\nregisterCommand(deleteFolderCommand)\n\nexport { createFolderCommand, updateFolderCommand, deleteFolderCommand }\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,gBAAgB;AAEzB,SAAS,yBAAyB;AAClC,SAAS,SAAS;AAClB,SAAS,uBAA4C;AACrD,SAAS,uBAAuB;AAChC,SAAS,0BAA0B;AACnC,SAAS,qBAAqB;AAC9B,SAAS,8CAA8C;AACvD,SAAS,6BAA6B;AACtC,SAAS,2BAA2B;AACpC,SAAS,sBAAsB;AAC/B,SAAS,sBAAsB;AAC/B,SAAS,4BAA4B,kCAAkC;AACvE,SAAS,sBAAsB,8CAA8C;AAC7E,SAAS,0CAA0C;AACnD,SAAS,yBAAyB,+BAA+B;AACjE;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,MAAM,uBAAuB,EAAE,OAAO;AAAA,EACpC,IAAI,EAAE,OAAO,EAAE,KAAK;AAAA,EACpB,UAAU,EAAE,OAAO,EAAE,KAAK;AAAA,EAC1B,gBAAgB,EAAE,OAAO,EAAE,KAAK;AAAA,EAChC,MAAM,EAAE,OAAO;AAAA,EACf,gBAAgB,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS;AAAA,EAC3C,aAAa,EAAE,OAAO,EAAE,KAAK;AAAA,EAC7B,WAAW,EAAE,OAAO,EAAE,SAAS;AAAA,EAC/B,WAAW,EAAE,OAAO,EAAE,SAAS;AAAA,EAC/B,WAAW,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS;AAC5C,CAAC;AAED,MAAM,oCAAoC,EAAE,OAAO;AAAA,EACjD,MAAM,EAAE,QAAQ,yBAAyB;AAAA,EACzC,QAAQ;AACV,CAAC;AAED,MAAM,oCAAoC,EAAE,OAAO;AAAA,EACjD,MAAM,EAAE,QAAQ,yBAAyB;AAAA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,QAChC;AAAA,MACF;AAAA,IACF,CAAC,GAAG,EAAE,aAAa,MAAM,OAAO,+BAA+B,CAAC;AAAA,EAClE;AACF;AAEA,gBAAgB,mBAAmB;AACnC,gBAAgB,mBAAmB;AACnC,gBAAgB,mBAAmB;",
|
|
4
|
+
"sourcesContent": ["import { LockMode } from '@mikro-orm/core'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { isDeepStrictEqual } from 'node:util'\nimport { z } from 'zod'\nimport { registerCommand, type CommandHandler } from '@open-mercato/shared/lib/commands'\nimport { withAtomicFlush } from '@open-mercato/shared/lib/commands/flush'\nimport { extractUndoPayload } from '@open-mercato/shared/lib/commands/undo'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { enforceCommandOptimisticLockWithGuards } from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { hasAllFeatures } from '@open-mercato/shared/lib/auth/featureMatch'\nimport { DocumentFolder } from '../data/entities'\nimport { documentFolderCreateSchema, documentFolderUpdateSchema } from '../data/validators'\nimport { DOCUMENTS_ENTITY_IDS, DOCUMENTS_MAX_FOLDERS_PER_ORGANIZATION } from '../lib/constants'\nimport { acquireFolderHierarchyMutationLock } from '../lib/folderHierarchySerialization'\nimport { getFolderPlacementIssue, hasActiveFolderContents } from '../lib/visibility'\nimport {\n assertCommandFeature,\n resolveDocumentsCommandActor,\n resolveDocumentsCommandEntityManager,\n resolveDocumentsCommandFeatures,\n resolveDocumentsCommandScope,\n type DocumentsCommandScope,\n} from './shared'\nimport {\n assertVersionedSnapshot,\n documentsScopedCommandSchema,\n nextDocumentVersion,\n readCommandRedoInput,\n} from './mutation-helpers'\n\nconst folderSnapshotSchema = z.object({\n id: z.string().uuid(),\n tenantId: z.string().uuid(),\n organizationId: z.string().uuid(),\n name: z.string(),\n parentFolderId: z.string().uuid().nullable(),\n ownerUserId: z.string().uuid(),\n createdAt: z.string().datetime(),\n updatedAt: z.string().datetime(),\n deletedAt: z.string().datetime().nullable(),\n})\n\nconst folderUpdateRedoExpectationSchema = z.object({\n kind: z.literal('folder-update-post-undo'),\n folder: folderSnapshotSchema,\n})\n\nconst folderDeleteRedoExpectationSchema = z.object({\n kind: z.literal('folder-delete-post-undo'),\n folder: folderSnapshotSchema,\n})\n\nexport const folderCreateCommandSchema = documentsScopedCommandSchema\n .merge(documentFolderCreateSchema)\n .extend({ folderId: z.string().uuid() })\n\nexport const folderUpdateCommandSchema = documentsScopedCommandSchema\n .merge(documentFolderUpdateSchema)\n .extend({ redoExpectation: folderUpdateRedoExpectationSchema.optional() })\n\nexport const folderDeleteCommandSchema = documentsScopedCommandSchema.extend({\n id: z.string().uuid(),\n redoExpectation: folderDeleteRedoExpectationSchema.optional(),\n})\n\nexport type FolderCreateCommandInput = z.infer<typeof folderCreateCommandSchema>\nexport type FolderUpdateCommandInput = z.infer<typeof folderUpdateCommandSchema>\nexport type FolderDeleteCommandInput = z.infer<typeof folderDeleteCommandSchema>\n\ntype FolderSnapshot = z.infer<typeof folderSnapshotSchema>\n\ntype FolderUndoPayload = {\n before?: FolderSnapshot | null\n after?: FolderSnapshot | null\n}\n\ntype FolderCommandResult = {\n id: string\n updatedAt: string\n before: FolderSnapshot | null\n after: FolderSnapshot\n}\n\nfunction snapshotFolder(folder: DocumentFolder | null): FolderSnapshot | null {\n if (!folder) return null\n return {\n id: folder.id,\n tenantId: folder.tenantId,\n organizationId: folder.organizationId,\n name: folder.name,\n parentFolderId: folder.parentFolderId ?? null,\n ownerUserId: folder.ownerUserId,\n createdAt: folder.createdAt.toISOString(),\n updatedAt: folder.updatedAt.toISOString(),\n deletedAt: folder.deletedAt?.toISOString() ?? null,\n }\n}\n\nfunction changedError(): CrudHttpError {\n return new CrudHttpError(409, { error: 'Record changed by another user' })\n}\n\nfunction nextSnapshotVersion(updatedAt: string): string {\n return nextDocumentVersion(new Date(updatedAt), new Date(0)).toISOString()\n}\n\nfunction assertFolderStateMatches(folder: DocumentFolder, expected: FolderSnapshot): void {\n if (!isDeepStrictEqual(snapshotFolder(folder), expected)) throw changedError()\n}\n\nfunction resolveExactUndoVersion(current: Date, expectedUpdatedAt?: string): Date {\n if (!expectedUpdatedAt) return nextDocumentVersion(current)\n const expected = new Date(expectedUpdatedAt)\n if (!Number.isFinite(expected.getTime()) || expected.getTime() <= current.getTime()) {\n throw changedError()\n }\n return expected\n}\n\nfunction buildFolderUpdateRedoExpectation(\n before: FolderSnapshot,\n after: FolderSnapshot,\n): z.infer<typeof folderUpdateRedoExpectationSchema> {\n return {\n kind: 'folder-update-post-undo',\n folder: { ...before, updatedAt: nextSnapshotVersion(after.updatedAt) },\n }\n}\n\nfunction buildFolderDeleteRedoExpectation(\n before: FolderSnapshot,\n after: FolderSnapshot,\n): z.infer<typeof folderDeleteRedoExpectationSchema> {\n return {\n kind: 'folder-delete-post-undo',\n folder: { ...before, updatedAt: nextSnapshotVersion(after.updatedAt) },\n }\n}\n\nasync function loadLockedFolder(\n em: EntityManager,\n id: string,\n scope: DocumentsCommandScope,\n includeDeleted = false,\n): Promise<DocumentFolder | null> {\n return findOneWithDecryption(\n em,\n DocumentFolder,\n {\n id,\n ...scope,\n ...(includeDeleted ? {} : { deletedAt: null }),\n },\n {\n lockMode: LockMode.PESSIMISTIC_WRITE,\n ...(includeDeleted ? { filters: false } : {}),\n },\n scope,\n )\n}\n\nasync function assertFolderOwnerOrManager(\n ownerUserId: string,\n actorUserId: string,\n features: readonly string[],\n): Promise<void> {\n if (ownerUserId === actorUserId || hasAllFeatures(['documents.manage'], Array.from(features))) return\n throw new CrudHttpError(403, { error: 'Forbidden' })\n}\n\nasync function assertWritableParent(\n em: EntityManager,\n parentFolderId: string | null | undefined,\n scope: DocumentsCommandScope,\n actorUserId: string,\n features: readonly string[],\n): Promise<void> {\n if (!parentFolderId) return\n const parent = await loadLockedFolder(em, parentFolderId, scope)\n if (!parent) throw new CrudHttpError(404, { error: 'documents.folders.notFound' })\n await assertFolderOwnerOrManager(parent.ownerUserId, actorUserId, features)\n}\n\n/**\n * Call only while holding the folder hierarchy mutation lock, so the count and\n * the insert that follows it cannot interleave with a competing create.\n */\nasync function assertOrganizationFolderCapacity(\n em: EntityManager,\n scope: DocumentsCommandScope,\n): Promise<void> {\n const activeCount = await em.count(DocumentFolder, { ...scope, deletedAt: null })\n if (activeCount < DOCUMENTS_MAX_FOLDERS_PER_ORGANIZATION) return\n throw new CrudHttpError(422, { error: 'documents.errors.folderLimitReached' })\n}\n\nasync function assertValidPlacement(\n em: EntityManager,\n scope: DocumentsCommandScope,\n folderId: string | null,\n parentFolderId: string | null,\n): Promise<void> {\n const issue = await getFolderPlacementIssue({ em, ...scope, folderId, parentFolderId })\n if (issue) throw new CrudHttpError(400, { error: 'documents.folders.error.invalidPlacement' })\n}\n\nfunction applyFolderSnapshot(\n folder: DocumentFolder,\n snapshot: FolderSnapshot,\n expectedUpdatedAt?: string,\n): void {\n folder.name = snapshot.name\n folder.parentFolderId = snapshot.parentFolderId\n folder.ownerUserId = snapshot.ownerUserId\n folder.deletedAt = snapshot.deletedAt ? new Date(snapshot.deletedAt) : null\n folder.updatedAt = resolveExactUndoVersion(folder.updatedAt, expectedUpdatedAt)\n}\n\nfunction buildFolderLog(\n actionLabel: string,\n input: DocumentsCommandScope,\n result: FolderCommandResult,\n redoInput?: FolderUpdateCommandInput | FolderDeleteCommandInput,\n) {\n return {\n actionLabel,\n resourceKind: DOCUMENTS_ENTITY_IDS.documentFolder,\n resourceId: result.id,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n snapshotBefore: result.before,\n snapshotAfter: result.after,\n payload: {\n undo: { before: result.before, after: result.after } satisfies FolderUndoPayload,\n ...(redoInput ? { __redoInput: redoInput } : {}),\n },\n }\n}\n\nconst createFolderCommand: CommandHandler<FolderCreateCommandInput, FolderCommandResult> = {\n id: 'documents.folder.create',\n async execute(rawInput, ctx) {\n const input = folderCreateCommandSchema.parse(rawInput)\n const scope = resolveDocumentsCommandScope(ctx, input)\n const actorUserId = resolveDocumentsCommandActor(ctx)\n const em = resolveDocumentsCommandEntityManager(ctx)\n let folder!: DocumentFolder\n let before: FolderSnapshot | null = null\n await withAtomicFlush(em, [async () => {\n await acquireFolderHierarchyMutationLock(em, scope)\n const existing = await loadLockedFolder(em, input.folderId, scope, true)\n const features = await resolveDocumentsCommandFeatures(ctx, scope)\n assertCommandFeature(features, 'documents.edit')\n before = snapshotFolder(existing)\n if (existing && !existing.deletedAt) {\n throw new CrudHttpError(409, { error: 'Record changed by another user' })\n }\n await assertOrganizationFolderCapacity(em, scope)\n await assertWritableParent(em, input.parentFolderId ?? null, scope, actorUserId, features)\n await assertValidPlacement(em, scope, null, input.parentFolderId ?? null)\n folder = existing ?? em.create(DocumentFolder, {\n id: input.folderId,\n ...scope,\n name: input.name,\n parentFolderId: input.parentFolderId ?? null,\n ownerUserId: actorUserId,\n })\n if (!existing) em.persist(folder)\n folder.name = input.name\n folder.parentFolderId = input.parentFolderId ?? null\n folder.ownerUserId = actorUserId\n folder.deletedAt = null\n if (existing) folder.updatedAt = nextDocumentVersion(folder.updatedAt)\n }], { transaction: true, label: 'documents.folder.create' })\n return {\n id: folder.id,\n updatedAt: folder.updatedAt.toISOString(),\n before,\n after: snapshotFolder(folder)!,\n }\n },\n async buildLog({ input, result }) {\n const { translate } = await resolveTranslations()\n return buildFolderLog(\n translate('documents.audit.folderCreated', 'Create folder'),\n input,\n result,\n )\n },\n async undo({ logEntry, ctx }) {\n const undo = extractUndoPayload<FolderUndoPayload>(logEntry)\n if (!undo?.after) return\n const input = folderCreateCommandSchema.parse(readCommandRedoInput(logEntry))\n const scope = resolveDocumentsCommandScope(ctx, input)\n const actorUserId = resolveDocumentsCommandActor(ctx)\n const em = resolveDocumentsCommandEntityManager(ctx)\n await withAtomicFlush(em, [async () => {\n await acquireFolderHierarchyMutationLock(em, scope)\n const folder = await loadLockedFolder(em, input.folderId, scope, true)\n const features = await resolveDocumentsCommandFeatures(ctx, scope)\n assertCommandFeature(features, 'documents.edit')\n await assertFolderOwnerOrManager(undo.after!.ownerUserId, actorUserId, features)\n assertVersionedSnapshot(folder, undo.after, DOCUMENTS_ENTITY_IDS.documentFolder)\n if (await hasActiveFolderContents({ em, ...scope, folderId: input.folderId })) {\n throw new CrudHttpError(409, { error: 'Record changed by another user' })\n }\n if (undo.before && folder) applyFolderSnapshot(folder, undo.before)\n else if (folder) {\n const now = nextDocumentVersion(folder.updatedAt)\n folder.deletedAt = now\n folder.updatedAt = now\n }\n }], { transaction: true, label: 'documents.folder.create.undo' })\n },\n}\n\nconst updateFolderCommand: CommandHandler<FolderUpdateCommandInput, FolderCommandResult> = {\n id: 'documents.folder.update',\n async execute(rawInput, ctx) {\n const input = folderUpdateCommandSchema.parse(rawInput)\n const scope = resolveDocumentsCommandScope(ctx, input)\n const actorUserId = resolveDocumentsCommandActor(ctx)\n const em = resolveDocumentsCommandEntityManager(ctx)\n let folder!: DocumentFolder\n let before!: FolderSnapshot\n await withAtomicFlush(em, [async () => {\n await acquireFolderHierarchyMutationLock(em, scope)\n const loaded = await loadLockedFolder(\n em,\n input.id,\n scope,\n input.redoExpectation !== undefined,\n )\n if (!loaded) throw new CrudHttpError(404, { error: 'documents.folders.notFound' })\n folder = loaded\n const features = await resolveDocumentsCommandFeatures(ctx, scope)\n assertCommandFeature(features, 'documents.edit')\n await assertFolderOwnerOrManager(folder.ownerUserId, actorUserId, features)\n if (input.redoExpectation) {\n assertFolderStateMatches(folder, input.redoExpectation.folder)\n } else {\n await enforceCommandOptimisticLockWithGuards(ctx.container, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentFolder,\n resourceId: folder.id,\n current: folder.updatedAt,\n request: ctx.request ?? null,\n })\n }\n before = snapshotFolder(folder)!\n if (Object.prototype.hasOwnProperty.call(input, 'parentFolderId')) {\n await assertWritableParent(em, input.parentFolderId ?? null, scope, actorUserId, features)\n await assertValidPlacement(em, scope, folder.id, input.parentFolderId ?? null)\n }\n if (input.name !== undefined) folder.name = input.name\n if (Object.prototype.hasOwnProperty.call(input, 'parentFolderId')) {\n folder.parentFolderId = input.parentFolderId ?? null\n }\n folder.updatedAt = nextDocumentVersion(folder.updatedAt)\n }], { transaction: true, label: 'documents.folder.update' })\n return {\n id: folder.id,\n updatedAt: folder.updatedAt.toISOString(),\n before,\n after: snapshotFolder(folder)!,\n }\n },\n async buildLog({ input, result }) {\n const { translate } = await resolveTranslations()\n if (!result.before) throw new Error('[internal] folder update produced no before snapshot')\n const redoInput: FolderUpdateCommandInput = {\n ...input,\n redoExpectation: buildFolderUpdateRedoExpectation(result.before, result.after),\n }\n return buildFolderLog(\n translate('documents.audit.folderUpdated', 'Update folder'),\n input,\n result,\n redoInput,\n )\n },\n async undo({ logEntry, ctx }) {\n const undo = extractUndoPayload<FolderUndoPayload>(logEntry)\n if (!undo?.before || !undo.after) return\n const before = undo.before\n const after = undo.after\n const input = folderUpdateCommandSchema.parse(readCommandRedoInput(logEntry))\n const scope = resolveDocumentsCommandScope(ctx, input)\n const actorUserId = resolveDocumentsCommandActor(ctx)\n const em = resolveDocumentsCommandEntityManager(ctx)\n await withAtomicFlush(em, [async () => {\n await acquireFolderHierarchyMutationLock(em, scope)\n const folder = await loadLockedFolder(em, input.id, scope)\n if (!folder) throw new CrudHttpError(404, { error: 'documents.folders.notFound' })\n const features = await resolveDocumentsCommandFeatures(ctx, scope)\n assertCommandFeature(features, 'documents.edit')\n await assertFolderOwnerOrManager(folder.ownerUserId, actorUserId, features)\n assertVersionedSnapshot(folder, after, DOCUMENTS_ENTITY_IDS.documentFolder)\n await assertWritableParent(em, before.parentFolderId, scope, actorUserId, features)\n await assertValidPlacement(em, scope, folder.id, before.parentFolderId)\n applyFolderSnapshot(\n folder,\n before,\n input.redoExpectation?.folder.updatedAt,\n )\n }], { transaction: true, label: 'documents.folder.update.undo' })\n },\n}\n\nconst deleteFolderCommand: CommandHandler<FolderDeleteCommandInput, FolderCommandResult> = {\n id: 'documents.folder.delete',\n async execute(rawInput, ctx) {\n const input = folderDeleteCommandSchema.parse(rawInput)\n const scope = resolveDocumentsCommandScope(ctx, input)\n const actorUserId = resolveDocumentsCommandActor(ctx)\n const em = resolveDocumentsCommandEntityManager(ctx)\n let folder!: DocumentFolder\n let before!: FolderSnapshot\n await withAtomicFlush(em, [async () => {\n await acquireFolderHierarchyMutationLock(em, scope)\n const loaded = await loadLockedFolder(\n em,\n input.id,\n scope,\n input.redoExpectation !== undefined,\n )\n if (!loaded) throw new CrudHttpError(404, { error: 'documents.folders.notFound' })\n folder = loaded\n const features = await resolveDocumentsCommandFeatures(ctx, scope)\n assertCommandFeature(features, 'documents.edit')\n await assertFolderOwnerOrManager(folder.ownerUserId, actorUserId, features)\n if (input.redoExpectation) {\n assertFolderStateMatches(folder, input.redoExpectation.folder)\n } else {\n await enforceCommandOptimisticLockWithGuards(ctx.container, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentFolder,\n resourceId: folder.id,\n current: folder.updatedAt,\n request: ctx.request ?? null,\n })\n }\n before = snapshotFolder(folder)!\n if (await hasActiveFolderContents({ em, ...scope, folderId: folder.id })) {\n throw new CrudHttpError(409, { error: 'documents.folders.error.delete' })\n }\n const now = nextDocumentVersion(folder.updatedAt)\n folder.deletedAt = now\n folder.updatedAt = now\n }], { transaction: true, label: 'documents.folder.delete' })\n return {\n id: folder.id,\n updatedAt: folder.updatedAt.toISOString(),\n before,\n after: snapshotFolder(folder)!,\n }\n },\n async buildLog({ input, result }) {\n const { translate } = await resolveTranslations()\n if (!result.before) throw new Error('[internal] folder delete produced no before snapshot')\n const redoInput: FolderDeleteCommandInput = {\n ...input,\n redoExpectation: buildFolderDeleteRedoExpectation(result.before, result.after),\n }\n return buildFolderLog(\n translate('documents.audit.folderDeleted', 'Delete folder'),\n input,\n result,\n redoInput,\n )\n },\n async undo({ logEntry, ctx }) {\n const undo = extractUndoPayload<FolderUndoPayload>(logEntry)\n if (!undo?.before || !undo.after) return\n const input = folderDeleteCommandSchema.parse(readCommandRedoInput(logEntry))\n const scope = resolveDocumentsCommandScope(ctx, input)\n const actorUserId = resolveDocumentsCommandActor(ctx)\n const em = resolveDocumentsCommandEntityManager(ctx)\n await withAtomicFlush(em, [async () => {\n await acquireFolderHierarchyMutationLock(em, scope)\n const folder = await loadLockedFolder(em, input.id, scope, true)\n const features = await resolveDocumentsCommandFeatures(ctx, scope)\n assertCommandFeature(features, 'documents.edit')\n await assertFolderOwnerOrManager(undo.before!.ownerUserId, actorUserId, features)\n assertVersionedSnapshot(folder, undo.after, DOCUMENTS_ENTITY_IDS.documentFolder)\n await assertOrganizationFolderCapacity(em, scope)\n await assertWritableParent(em, undo.before!.parentFolderId, scope, actorUserId, features)\n await assertValidPlacement(em, scope, input.id, undo.before!.parentFolderId)\n if (folder) {\n applyFolderSnapshot(\n folder,\n undo.before!,\n input.redoExpectation?.folder.updatedAt,\n )\n }\n }], { transaction: true, label: 'documents.folder.delete.undo' })\n },\n}\n\nregisterCommand(createFolderCommand)\nregisterCommand(updateFolderCommand)\nregisterCommand(deleteFolderCommand)\n\nexport { createFolderCommand, updateFolderCommand, deleteFolderCommand }\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,gBAAgB;AAEzB,SAAS,yBAAyB;AAClC,SAAS,SAAS;AAClB,SAAS,uBAA4C;AACrD,SAAS,uBAAuB;AAChC,SAAS,0BAA0B;AACnC,SAAS,qBAAqB;AAC9B,SAAS,8CAA8C;AACvD,SAAS,6BAA6B;AACtC,SAAS,2BAA2B;AACpC,SAAS,sBAAsB;AAC/B,SAAS,sBAAsB;AAC/B,SAAS,4BAA4B,kCAAkC;AACvE,SAAS,sBAAsB,8CAA8C;AAC7E,SAAS,0CAA0C;AACnD,SAAS,yBAAyB,+BAA+B;AACjE;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAC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QAAQ,6BAA6B,KAAK,KAAK;AACrD,UAAM,cAAc,6BAA6B,GAAG;AACpD,UAAM,KAAK,qCAAqC,GAAG;AACnD,UAAM,gBAAgB,IAAI,CAAC,YAAY;AACrC,YAAM,mCAAmC,IAAI,KAAK;AAClD,YAAM,SAAS,MAAM,iBAAiB,IAAI,MAAM,IAAI,OAAO,IAAI;AAC/D,YAAM,WAAW,MAAM,gCAAgC,KAAK,KAAK;AACjE,2BAAqB,UAAU,gBAAgB;AAC/C,YAAM,2BAA2B,KAAK,OAAQ,aAAa,aAAa,QAAQ;AAChF,8BAAwB,QAAQ,KAAK,OAAO,qBAAqB,cAAc;AAC/E,YAAM,iCAAiC,IAAI,KAAK;AAChD,YAAM,qBAAqB,IAAI,KAAK,OAAQ,gBAAgB,OAAO,aAAa,QAAQ;AACxF,YAAM,qBAAqB,IAAI,OAAO,MAAM,IAAI,KAAK,OAAQ,cAAc;AAC3E,UAAI,QAAQ;AACV;AAAA,UACE;AAAA,UACA,KAAK;AAAA,UACL,MAAM,iBAAiB,OAAO;AAAA,QAChC;AAAA,MACF;AAAA,IACF,CAAC,GAAG,EAAE,aAAa,MAAM,OAAO,+BAA+B,CAAC;AAAA,EAClE;AACF;AAEA,gBAAgB,mBAAmB;AACnC,gBAAgB,mBAAmB;AACnC,gBAAgB,mBAAmB;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -4,6 +4,7 @@ import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find"
|
|
|
4
4
|
import { createLogger } from "@open-mercato/shared/lib/logger";
|
|
5
5
|
import { Document } from "../data/entities.js";
|
|
6
6
|
import { DOCUMENTS_ENTITY_IDS } from "../lib/constants.js";
|
|
7
|
+
import { resolveUserAccess } from "../lib/permissions.js";
|
|
7
8
|
import { resolveWatcherRecipients } from "../lib/watchers.js";
|
|
8
9
|
import { emitDocumentsEvent } from "../events.js";
|
|
9
10
|
const logger = createLogger("documents").child({ component: "command-projections" });
|
|
@@ -53,6 +54,11 @@ async function emitProjectedEvent(descriptor, context, options = {}) {
|
|
|
53
54
|
async function emitMentionProjection(descriptor, context) {
|
|
54
55
|
try {
|
|
55
56
|
const notificationService = resolveDocumentsNotificationService(context.container);
|
|
57
|
+
const em = context.container.resolve("em");
|
|
58
|
+
if (!await resolveUserAccess(em, descriptor.documentId, {
|
|
59
|
+
tenantId: descriptor.tenantId,
|
|
60
|
+
organizationId: descriptor.organizationId
|
|
61
|
+
}, descriptor.recipientUserId, context.container)) return;
|
|
56
62
|
await notificationService.create(
|
|
57
63
|
{
|
|
58
64
|
recipientUserId: descriptor.recipientUserId,
|
|
@@ -90,6 +96,11 @@ const WATCH_NOTIFICATION_TITLE_KEYS = {
|
|
|
90
96
|
async function emitWatchProjection(descriptor, context) {
|
|
91
97
|
try {
|
|
92
98
|
const notificationService = resolveDocumentsNotificationService(context.container);
|
|
99
|
+
const em = context.container.resolve("em");
|
|
100
|
+
if (!await resolveUserAccess(em, descriptor.documentId, {
|
|
101
|
+
tenantId: descriptor.tenantId,
|
|
102
|
+
organizationId: descriptor.organizationId
|
|
103
|
+
}, descriptor.recipientUserId, context.container)) return;
|
|
93
104
|
await notificationService.create(
|
|
94
105
|
{
|
|
95
106
|
recipientUserId: descriptor.recipientUserId,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/documents/commands/interceptors.ts"],
|
|
4
|
-
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type {\n CommandInterceptor,\n CommandInterceptorContext,\n CommandInterceptorUndoContext,\n} from '@open-mercato/shared/lib/commands/command-interceptor'\nimport { extractUndoPayload } from '@open-mercato/shared/lib/commands/undo'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { Document } from '../data/entities'\nimport { DOCUMENTS_ENTITY_IDS } from '../lib/constants'\nimport { resolveWatcherRecipients } from '../lib/watchers'\nimport type { DocumentsServiceContainer } from '../lib/platformServices'\nimport { emitDocumentsEvent } from '../events'\nimport type {\n DocumentsProjectedCommandResult,\n DocumentsProjectionDescriptor,\n DocumentsProjectionUndoPayload,\n} from './projection-types'\n\nconst logger = createLogger('documents').child({ component: 'command-projections' })\n\nconst PROJECTED_COMMAND_IDS = [\n 'documents.content.replace',\n 'documents.share.create',\n 'documents.share.update',\n 'documents.share.delete',\n 'documents.comment.create',\n 'documents.comment.resolve',\n 'documents.version.restore',\n 'documents.document.archive',\n 'documents.document.unarchive',\n 'documents.document.duplicate',\n] as const\n\ntype DocumentsNotificationService = {\n create: (\n input: Record<string, unknown>,\n scope: { tenantId: string; organizationId: string },\n ) => Promise<unknown>\n deleteBySource: (\n sourceEntityType: string,\n sourceEntityId: string,\n scope: { tenantId: string; organizationId: string },\n ) => Promise<unknown>\n}\n\nfunction resolveDocumentsNotificationService(\n container: CommandInterceptorContext['container'],\n): DocumentsNotificationService {\n const service = container.resolve('notificationService') as Partial<DocumentsNotificationService> | null\n if (!service || typeof service.create !== 'function' || typeof service.deleteBySource !== 'function') {\n throw new Error('[internal] Notification service is unavailable')\n }\n return service as DocumentsNotificationService\n}\n\nfunction readResultProjections(result: unknown): DocumentsProjectionDescriptor[] {\n if (!result || typeof result !== 'object' || Array.isArray(result)) return []\n const projections = (result as DocumentsProjectedCommandResult).projections\n return Array.isArray(projections) ? projections : []\n}\n\nasync function emitProjectedEvent(\n descriptor: Extract<DocumentsProjectionDescriptor, { kind: 'event' }>,\n context: CommandInterceptorContext,\n options: { overrideActor?: boolean } = {},\n): Promise<void> {\n const currentActorUserId = context.auth?.userId ?? context.auth?.sub ?? null\n const payload = {\n ...descriptor.payload,\n ...(currentActorUserId && (options.overrideActor || !('userId' in descriptor.payload))\n ? { userId: currentActorUserId }\n : {}),\n }\n try {\n await emitDocumentsEvent(descriptor.eventId, payload, {\n tenantId: descriptor.tenantId,\n organizationId: descriptor.organizationId,\n })\n } catch (error) {\n logger.error('Command event projection failed', {\n commandId: context.commandId,\n eventId: descriptor.eventId,\n err: error,\n })\n }\n}\n\nasync function emitMentionProjection(\n descriptor: Extract<DocumentsProjectionDescriptor, { kind: 'mention-notification' }>,\n context: CommandInterceptorContext,\n): Promise<void> {\n try {\n const notificationService = resolveDocumentsNotificationService(context.container)\n await notificationService.create(\n {\n recipientUserId: descriptor.recipientUserId,\n type: 'documents.comment.mentioned',\n titleKey: 'documents.notifications.comment.mentioned.title',\n bodyKey: 'documents.notifications.comment.mentioned.body',\n severity: 'info',\n titleVariables: { documentTitle: descriptor.documentTitle },\n bodyVariables: {\n documentTitle: descriptor.documentTitle,\n authorUserId: descriptor.authorUserId,\n },\n sourceEntityType: DOCUMENTS_ENTITY_IDS.documentComment,\n sourceEntityId: descriptor.commentId,\n linkHref: `/backend/documents/${encodeURIComponent(descriptor.documentId)}?commentId=${encodeURIComponent(descriptor.commentId)}`,\n },\n {\n tenantId: descriptor.tenantId,\n organizationId: descriptor.organizationId,\n },\n )\n } catch (error) {\n logger.error('Mention notification projection failed', {\n commandId: context.commandId,\n commentId: descriptor.commentId,\n recipientUserId: descriptor.recipientUserId,\n err: error,\n })\n }\n}\n\nconst WATCH_NOTIFICATION_TITLE_KEYS: Record<string, string> = {\n 'documents.watch.commented': 'documents.notifications.watch.commented.title',\n 'documents.watch.changed': 'documents.notifications.watch.changed.title',\n}\n\nasync function emitWatchProjection(\n descriptor: Extract<DocumentsProjectionDescriptor, { kind: 'watch-notification' }>,\n context: CommandInterceptorContext,\n): Promise<void> {\n try {\n const notificationService = resolveDocumentsNotificationService(context.container)\n await notificationService.create(\n {\n recipientUserId: descriptor.recipientUserId,\n type: descriptor.notificationType,\n titleKey: WATCH_NOTIFICATION_TITLE_KEYS[descriptor.notificationType],\n bodyKey: descriptor.bodyKey,\n severity: 'info',\n titleVariables: { documentTitle: descriptor.documentTitle },\n bodyVariables: { documentTitle: descriptor.documentTitle },\n sourceEntityType: descriptor.sourceEntityType,\n sourceEntityId: descriptor.sourceEntityId,\n linkHref: descriptor.linkHref,\n },\n {\n tenantId: descriptor.tenantId,\n organizationId: descriptor.organizationId,\n },\n )\n } catch (error) {\n logger.error('Watch notification projection failed', {\n commandId: context.commandId,\n documentId: descriptor.documentId,\n recipientUserId: descriptor.recipientUserId,\n err: error,\n })\n }\n}\n\nasync function emitWatchFanoutProjection(\n descriptor: Extract<DocumentsProjectionDescriptor, { kind: 'watch-notification-fanout' }>,\n context: CommandInterceptorContext,\n): Promise<void> {\n try {\n const em = context.container.resolve('em') as EntityManager\n const scope = { tenantId: descriptor.tenantId, organizationId: descriptor.organizationId }\n const document = await findOneWithDecryption(\n em,\n Document,\n { id: descriptor.documentId, tenantId: scope.tenantId, organizationId: scope.organizationId, deletedAt: null },\n { fields: ['id', 'title'] },\n scope,\n )\n if (!document) return\n const recipientUserIds = await resolveWatcherRecipients({\n em,\n container: context.container as unknown as DocumentsServiceContainer,\n scope,\n documentId: descriptor.documentId,\n actorUserId: context.auth?.userId ?? context.auth?.sub ?? descriptor.actorUserId,\n })\n for (const recipientUserId of recipientUserIds) {\n await emitWatchProjection(\n {\n kind: 'watch-notification',\n recipientUserId,\n tenantId: descriptor.tenantId,\n organizationId: descriptor.organizationId,\n documentId: descriptor.documentId,\n documentTitle: document.title,\n notificationType: descriptor.notificationType,\n bodyKey: descriptor.bodyKey,\n sourceEntityType: descriptor.sourceEntityType,\n sourceEntityId: descriptor.sourceEntityId,\n linkHref: descriptor.linkHref,\n },\n context,\n )\n }\n } catch (error) {\n logger.error('Watch notification fanout projection failed', {\n commandId: context.commandId,\n documentId: descriptor.documentId,\n err: error,\n })\n }\n}\n\nasync function emitDocumentIndexProjection(\n descriptor: Extract<DocumentsProjectionDescriptor, { kind: 'document-index' }>,\n context: CommandInterceptorContext,\n): Promise<void> {\n try {\n const searchIndexer = context.container.resolve('searchIndexer') as {\n indexRecordById: (input: {\n entityId: string\n recordId: string\n tenantId: string\n organizationId: string\n }) => Promise<unknown>\n }\n await searchIndexer.indexRecordById({\n entityId: DOCUMENTS_ENTITY_IDS.document,\n recordId: descriptor.documentId,\n tenantId: descriptor.tenantId,\n organizationId: descriptor.organizationId,\n })\n } catch (error) {\n logger.error('Document index projection failed', {\n commandId: context.commandId,\n documentId: descriptor.documentId,\n err: error,\n })\n }\n}\n\nasync function deleteMentionNotificationProjection(\n descriptor: Extract<DocumentsProjectionDescriptor, { kind: 'mention-notification-delete' }>,\n context: CommandInterceptorContext,\n): Promise<void> {\n try {\n const notificationService = resolveDocumentsNotificationService(context.container)\n await notificationService.deleteBySource(\n DOCUMENTS_ENTITY_IDS.documentComment,\n descriptor.commentId,\n {\n tenantId: descriptor.tenantId,\n organizationId: descriptor.organizationId,\n },\n )\n } catch (error) {\n logger.error('Mention notification cleanup projection failed', {\n commandId: context.commandId,\n commentId: descriptor.commentId,\n err: error,\n })\n }\n}\n\nasync function projectDescriptors(\n projections: readonly DocumentsProjectionDescriptor[],\n context: CommandInterceptorContext,\n options: { overrideEventActor?: boolean } = {},\n): Promise<void> {\n for (const projection of projections) {\n if (projection.kind === 'event') {\n await emitProjectedEvent(projection, context, { overrideActor: options.overrideEventActor })\n }\n else if (projection.kind === 'mention-notification') await emitMentionProjection(projection, context)\n else if (projection.kind === 'watch-notification') await emitWatchProjection(projection, context)\n else if (projection.kind === 'watch-notification-fanout') await emitWatchFanoutProjection(projection, context)\n else if (projection.kind === 'document-index') await emitDocumentIndexProjection(projection, context)\n else await deleteMentionNotificationProjection(projection, context)\n }\n}\n\nfunction buildProjectionInterceptor(commandId: typeof PROJECTED_COMMAND_IDS[number]): CommandInterceptor {\n return {\n id: `documents.${commandId.slice('documents.'.length).replaceAll('.', '-')}-projections`,\n targetCommand: commandId,\n priority: 90,\n async afterExecute(_input, result, context): Promise<void> {\n await projectDescriptors(readResultProjections(result), context)\n },\n async afterUndo(\n undoContext: CommandInterceptorUndoContext,\n context: CommandInterceptorContext,\n ): Promise<void> {\n const undo = extractUndoPayload<DocumentsProjectionUndoPayload>(\n undoContext.logEntry as Parameters<typeof extractUndoPayload>[0],\n )\n await projectDescriptors(\n undo?.projectionsAfterUndo ?? [],\n context,\n { overrideEventActor: true },\n )\n },\n }\n}\n\nconst ARCHIVED_UNDO_GUARDED_COMMAND_IDS = [\n 'documents.document.update',\n 'documents.share.create',\n 'documents.share.update',\n 'documents.share.delete',\n 'documents.comment.create',\n 'documents.comment.resolve',\n 'documents.link.create',\n 'documents.link.delete',\n 'documents.version.restore',\n] as const\n\ntype UndoLogEntryShape = {\n resourceKind?: string | null\n resourceId?: string | null\n parentResourceKind?: string | null\n parentResourceId?: string | null\n tenantId?: string | null\n organizationId?: string | null\n commandPayload?: unknown\n}\n\nfunction resolveUndoDocumentId(logEntry: UndoLogEntryShape): string | null {\n if (logEntry.parentResourceKind === DOCUMENTS_ENTITY_IDS.document && logEntry.parentResourceId) {\n return logEntry.parentResourceId\n }\n if (logEntry.resourceKind === DOCUMENTS_ENTITY_IDS.document && logEntry.resourceId) {\n return logEntry.resourceId\n }\n const payload = logEntry.commandPayload\n if (payload && typeof payload === 'object') {\n const redoInput = (payload as { __redoInput?: unknown }).__redoInput\n if (redoInput && typeof redoInput === 'object') {\n const documentId = (redoInput as { documentId?: unknown }).documentId\n if (typeof documentId === 'string' && documentId.length > 0) return documentId\n }\n }\n return null\n}\n\n/**\n * Read-only means the undo path too: reversing a pre-archive share, comment,\n * link, or restore would mutate an archived document, so the guard refuses\n * with the same error the execute path uses. Delete-like undos (duplicate,\n * instantiate) stay allowed, matching delete-of-archived semantics.\n */\nfunction buildArchivedUndoGuard(commandId: typeof ARCHIVED_UNDO_GUARDED_COMMAND_IDS[number]): CommandInterceptor {\n return {\n id: `documents.${commandId.slice('documents.'.length).replaceAll('.', '-')}-archived-undo-guard`,\n targetCommand: commandId,\n priority: 100,\n async beforeUndo(\n undoContext: CommandInterceptorUndoContext,\n context: CommandInterceptorContext,\n ): Promise<void> {\n const logEntry = undoContext.logEntry as UndoLogEntryShape\n const documentId = resolveUndoDocumentId(logEntry)\n if (!documentId || !logEntry.tenantId || !logEntry.organizationId) {\n // Every guarded command records the document and its scope. Without\n // them the archived state cannot be read, so refuse the undo instead of\n // waving through a mutation this guard was unable to check.\n logger.error('Archived-undo guard could not resolve the guarded document scope', {\n commandId,\n resourceKind: logEntry.resourceKind ?? null,\n resourceId: logEntry.resourceId ?? null,\n })\n throw new CrudHttpError(403, { error: 'api.errors.forbidden' })\n }\n const em = context.container.resolve('em') as EntityManager\n const scope = { tenantId: logEntry.tenantId, organizationId: logEntry.organizationId }\n const document = await findOneWithDecryption(\n em,\n Document,\n { id: documentId, tenantId: scope.tenantId, organizationId: scope.organizationId },\n { fields: ['id', 'archivedAt'], filters: false },\n scope,\n )\n if (document?.archivedAt) {\n throw new CrudHttpError(403, { error: 'documents.errors.documentArchived' })\n }\n },\n }\n}\n\n/**\n * Projection hooks are deliberately post-command. CommandBus persists the\n * ActionLog (or marks it undone) before these hooks run, so a flaky event bus\n * or notification store can never roll back an acknowledged document write.\n */\nexport const interceptors: CommandInterceptor[] = [\n ...PROJECTED_COMMAND_IDS.map(buildProjectionInterceptor),\n ...ARCHIVED_UNDO_GUARDED_COMMAND_IDS.map(buildArchivedUndoGuard),\n]\n\nexport default interceptors\n"],
|
|
5
|
-
"mappings": "AAMA,SAAS,0BAA0B;AACnC,SAAS,qBAAqB;AAC9B,SAAS,6BAA6B;AACtC,SAAS,oBAAoB;AAC7B,SAAS,gBAAgB;AACzB,SAAS,4BAA4B;AACrC,SAAS,gCAAgC;AAEzC,SAAS,0BAA0B;AAOnC,MAAM,SAAS,aAAa,WAAW,EAAE,MAAM,EAAE,WAAW,sBAAsB,CAAC;AAEnF,MAAM,wBAAwB;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAcA,SAAS,oCACP,WAC8B;AAC9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OAAO,uBAAuB,CAAC;AAAA,MAChE;AACA,YAAM,KAAK,QAAQ,UAAU,QAAQ,IAAI;AACzC,YAAM,QAAQ,EAAE,UAAU,SAAS,UAAU,gBAAgB,SAAS,eAAe;AACrF,YAAM,WAAW,MAAM;AAAA,QACrB;AAAA,QACA;AAAA,QACA,EAAE,IAAI,YAAY,UAAU,MAAM,UAAU,gBAAgB,MAAM,eAAe;AAAA,QACjF,EAAE,QAAQ,CAAC,MAAM,YAAY,GAAG,SAAS,MAAM;AAAA,QAC/C;AAAA,MACF;AACA,UAAI,UAAU,YAAY;AACxB,cAAM,IAAI,cAAc,KAAK,EAAE,OAAO,oCAAoC,CAAC;AAAA,MAC7E;AAAA,IACF;AAAA,EACF;AACF;AAOO,MAAM,eAAqC;AAAA,EAChD,GAAG,sBAAsB,IAAI,0BAA0B;AAAA,EACvD,GAAG,kCAAkC,IAAI,sBAAsB;AACjE;AAEA,IAAO,uBAAQ;",
|
|
4
|
+
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type {\n CommandInterceptor,\n CommandInterceptorContext,\n CommandInterceptorUndoContext,\n} from '@open-mercato/shared/lib/commands/command-interceptor'\nimport { extractUndoPayload } from '@open-mercato/shared/lib/commands/undo'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { Document } from '../data/entities'\nimport { DOCUMENTS_ENTITY_IDS } from '../lib/constants'\nimport { resolveUserAccess } from '../lib/permissions'\nimport { resolveWatcherRecipients } from '../lib/watchers'\nimport type { DocumentsServiceContainer } from '../lib/platformServices'\nimport { emitDocumentsEvent } from '../events'\nimport type {\n DocumentsProjectedCommandResult,\n DocumentsProjectionDescriptor,\n DocumentsProjectionUndoPayload,\n} from './projection-types'\n\nconst logger = createLogger('documents').child({ component: 'command-projections' })\n\nconst PROJECTED_COMMAND_IDS = [\n 'documents.content.replace',\n 'documents.share.create',\n 'documents.share.update',\n 'documents.share.delete',\n 'documents.comment.create',\n 'documents.comment.resolve',\n 'documents.version.restore',\n 'documents.document.archive',\n 'documents.document.unarchive',\n 'documents.document.duplicate',\n] as const\n\ntype DocumentsNotificationService = {\n create: (\n input: Record<string, unknown>,\n scope: { tenantId: string; organizationId: string },\n ) => Promise<unknown>\n deleteBySource: (\n sourceEntityType: string,\n sourceEntityId: string,\n scope: { tenantId: string; organizationId: string },\n ) => Promise<unknown>\n}\n\nfunction resolveDocumentsNotificationService(\n container: CommandInterceptorContext['container'],\n): DocumentsNotificationService {\n const service = container.resolve('notificationService') as Partial<DocumentsNotificationService> | null\n if (!service || typeof service.create !== 'function' || typeof service.deleteBySource !== 'function') {\n throw new Error('[internal] Notification service is unavailable')\n }\n return service as DocumentsNotificationService\n}\n\nfunction readResultProjections(result: unknown): DocumentsProjectionDescriptor[] {\n if (!result || typeof result !== 'object' || Array.isArray(result)) return []\n const projections = (result as DocumentsProjectedCommandResult).projections\n return Array.isArray(projections) ? projections : []\n}\n\nasync function emitProjectedEvent(\n descriptor: Extract<DocumentsProjectionDescriptor, { kind: 'event' }>,\n context: CommandInterceptorContext,\n options: { overrideActor?: boolean } = {},\n): Promise<void> {\n const currentActorUserId = context.auth?.userId ?? context.auth?.sub ?? null\n const payload = {\n ...descriptor.payload,\n ...(currentActorUserId && (options.overrideActor || !('userId' in descriptor.payload))\n ? { userId: currentActorUserId }\n : {}),\n }\n try {\n await emitDocumentsEvent(descriptor.eventId, payload, {\n tenantId: descriptor.tenantId,\n organizationId: descriptor.organizationId,\n })\n } catch (error) {\n logger.error('Command event projection failed', {\n commandId: context.commandId,\n eventId: descriptor.eventId,\n err: error,\n })\n }\n}\n\nasync function emitMentionProjection(\n descriptor: Extract<DocumentsProjectionDescriptor, { kind: 'mention-notification' }>,\n context: CommandInterceptorContext,\n): Promise<void> {\n try {\n const notificationService = resolveDocumentsNotificationService(context.container)\n const em = context.container.resolve('em') as EntityManager\n if (!await resolveUserAccess(em, descriptor.documentId, {\n tenantId: descriptor.tenantId,\n organizationId: descriptor.organizationId,\n }, descriptor.recipientUserId, context.container)) return\n await notificationService.create(\n {\n recipientUserId: descriptor.recipientUserId,\n type: 'documents.comment.mentioned',\n titleKey: 'documents.notifications.comment.mentioned.title',\n bodyKey: 'documents.notifications.comment.mentioned.body',\n severity: 'info',\n titleVariables: { documentTitle: descriptor.documentTitle },\n bodyVariables: {\n documentTitle: descriptor.documentTitle,\n authorUserId: descriptor.authorUserId,\n },\n sourceEntityType: DOCUMENTS_ENTITY_IDS.documentComment,\n sourceEntityId: descriptor.commentId,\n linkHref: `/backend/documents/${encodeURIComponent(descriptor.documentId)}?commentId=${encodeURIComponent(descriptor.commentId)}`,\n },\n {\n tenantId: descriptor.tenantId,\n organizationId: descriptor.organizationId,\n },\n )\n } catch (error) {\n logger.error('Mention notification projection failed', {\n commandId: context.commandId,\n commentId: descriptor.commentId,\n recipientUserId: descriptor.recipientUserId,\n err: error,\n })\n }\n}\n\nconst WATCH_NOTIFICATION_TITLE_KEYS: Record<string, string> = {\n 'documents.watch.commented': 'documents.notifications.watch.commented.title',\n 'documents.watch.changed': 'documents.notifications.watch.changed.title',\n}\n\nasync function emitWatchProjection(\n descriptor: Extract<DocumentsProjectionDescriptor, { kind: 'watch-notification' }>,\n context: CommandInterceptorContext,\n): Promise<void> {\n try {\n const notificationService = resolveDocumentsNotificationService(context.container)\n const em = context.container.resolve('em') as EntityManager\n if (!await resolveUserAccess(em, descriptor.documentId, {\n tenantId: descriptor.tenantId,\n organizationId: descriptor.organizationId,\n }, descriptor.recipientUserId, context.container)) return\n await notificationService.create(\n {\n recipientUserId: descriptor.recipientUserId,\n type: descriptor.notificationType,\n titleKey: WATCH_NOTIFICATION_TITLE_KEYS[descriptor.notificationType],\n bodyKey: descriptor.bodyKey,\n severity: 'info',\n titleVariables: { documentTitle: descriptor.documentTitle },\n bodyVariables: { documentTitle: descriptor.documentTitle },\n sourceEntityType: descriptor.sourceEntityType,\n sourceEntityId: descriptor.sourceEntityId,\n linkHref: descriptor.linkHref,\n },\n {\n tenantId: descriptor.tenantId,\n organizationId: descriptor.organizationId,\n },\n )\n } catch (error) {\n logger.error('Watch notification projection failed', {\n commandId: context.commandId,\n documentId: descriptor.documentId,\n recipientUserId: descriptor.recipientUserId,\n err: error,\n })\n }\n}\n\nasync function emitWatchFanoutProjection(\n descriptor: Extract<DocumentsProjectionDescriptor, { kind: 'watch-notification-fanout' }>,\n context: CommandInterceptorContext,\n): Promise<void> {\n try {\n const em = context.container.resolve('em') as EntityManager\n const scope = { tenantId: descriptor.tenantId, organizationId: descriptor.organizationId }\n const document = await findOneWithDecryption(\n em,\n Document,\n { id: descriptor.documentId, tenantId: scope.tenantId, organizationId: scope.organizationId, deletedAt: null },\n { fields: ['id', 'title'] },\n scope,\n )\n if (!document) return\n const recipientUserIds = await resolveWatcherRecipients({\n em,\n container: context.container as unknown as DocumentsServiceContainer,\n scope,\n documentId: descriptor.documentId,\n actorUserId: context.auth?.userId ?? context.auth?.sub ?? descriptor.actorUserId,\n })\n for (const recipientUserId of recipientUserIds) {\n await emitWatchProjection(\n {\n kind: 'watch-notification',\n recipientUserId,\n tenantId: descriptor.tenantId,\n organizationId: descriptor.organizationId,\n documentId: descriptor.documentId,\n documentTitle: document.title,\n notificationType: descriptor.notificationType,\n bodyKey: descriptor.bodyKey,\n sourceEntityType: descriptor.sourceEntityType,\n sourceEntityId: descriptor.sourceEntityId,\n linkHref: descriptor.linkHref,\n },\n context,\n )\n }\n } catch (error) {\n logger.error('Watch notification fanout projection failed', {\n commandId: context.commandId,\n documentId: descriptor.documentId,\n err: error,\n })\n }\n}\n\nasync function emitDocumentIndexProjection(\n descriptor: Extract<DocumentsProjectionDescriptor, { kind: 'document-index' }>,\n context: CommandInterceptorContext,\n): Promise<void> {\n try {\n const searchIndexer = context.container.resolve('searchIndexer') as {\n indexRecordById: (input: {\n entityId: string\n recordId: string\n tenantId: string\n organizationId: string\n }) => Promise<unknown>\n }\n await searchIndexer.indexRecordById({\n entityId: DOCUMENTS_ENTITY_IDS.document,\n recordId: descriptor.documentId,\n tenantId: descriptor.tenantId,\n organizationId: descriptor.organizationId,\n })\n } catch (error) {\n logger.error('Document index projection failed', {\n commandId: context.commandId,\n documentId: descriptor.documentId,\n err: error,\n })\n }\n}\n\nasync function deleteMentionNotificationProjection(\n descriptor: Extract<DocumentsProjectionDescriptor, { kind: 'mention-notification-delete' }>,\n context: CommandInterceptorContext,\n): Promise<void> {\n try {\n const notificationService = resolveDocumentsNotificationService(context.container)\n await notificationService.deleteBySource(\n DOCUMENTS_ENTITY_IDS.documentComment,\n descriptor.commentId,\n {\n tenantId: descriptor.tenantId,\n organizationId: descriptor.organizationId,\n },\n )\n } catch (error) {\n logger.error('Mention notification cleanup projection failed', {\n commandId: context.commandId,\n commentId: descriptor.commentId,\n err: error,\n })\n }\n}\n\nasync function projectDescriptors(\n projections: readonly DocumentsProjectionDescriptor[],\n context: CommandInterceptorContext,\n options: { overrideEventActor?: boolean } = {},\n): Promise<void> {\n for (const projection of projections) {\n if (projection.kind === 'event') {\n await emitProjectedEvent(projection, context, { overrideActor: options.overrideEventActor })\n }\n else if (projection.kind === 'mention-notification') await emitMentionProjection(projection, context)\n else if (projection.kind === 'watch-notification') await emitWatchProjection(projection, context)\n else if (projection.kind === 'watch-notification-fanout') await emitWatchFanoutProjection(projection, context)\n else if (projection.kind === 'document-index') await emitDocumentIndexProjection(projection, context)\n else await deleteMentionNotificationProjection(projection, context)\n }\n}\n\nfunction buildProjectionInterceptor(commandId: typeof PROJECTED_COMMAND_IDS[number]): CommandInterceptor {\n return {\n id: `documents.${commandId.slice('documents.'.length).replaceAll('.', '-')}-projections`,\n targetCommand: commandId,\n priority: 90,\n async afterExecute(_input, result, context): Promise<void> {\n await projectDescriptors(readResultProjections(result), context)\n },\n async afterUndo(\n undoContext: CommandInterceptorUndoContext,\n context: CommandInterceptorContext,\n ): Promise<void> {\n const undo = extractUndoPayload<DocumentsProjectionUndoPayload>(\n undoContext.logEntry as Parameters<typeof extractUndoPayload>[0],\n )\n await projectDescriptors(\n undo?.projectionsAfterUndo ?? [],\n context,\n { overrideEventActor: true },\n )\n },\n }\n}\n\nconst ARCHIVED_UNDO_GUARDED_COMMAND_IDS = [\n 'documents.document.update',\n 'documents.share.create',\n 'documents.share.update',\n 'documents.share.delete',\n 'documents.comment.create',\n 'documents.comment.resolve',\n 'documents.link.create',\n 'documents.link.delete',\n 'documents.version.restore',\n] as const\n\ntype UndoLogEntryShape = {\n resourceKind?: string | null\n resourceId?: string | null\n parentResourceKind?: string | null\n parentResourceId?: string | null\n tenantId?: string | null\n organizationId?: string | null\n commandPayload?: unknown\n}\n\nfunction resolveUndoDocumentId(logEntry: UndoLogEntryShape): string | null {\n if (logEntry.parentResourceKind === DOCUMENTS_ENTITY_IDS.document && logEntry.parentResourceId) {\n return logEntry.parentResourceId\n }\n if (logEntry.resourceKind === DOCUMENTS_ENTITY_IDS.document && logEntry.resourceId) {\n return logEntry.resourceId\n }\n const payload = logEntry.commandPayload\n if (payload && typeof payload === 'object') {\n const redoInput = (payload as { __redoInput?: unknown }).__redoInput\n if (redoInput && typeof redoInput === 'object') {\n const documentId = (redoInput as { documentId?: unknown }).documentId\n if (typeof documentId === 'string' && documentId.length > 0) return documentId\n }\n }\n return null\n}\n\n/**\n * Read-only means the undo path too: reversing a pre-archive share, comment,\n * link, or restore would mutate an archived document, so the guard refuses\n * with the same error the execute path uses. Delete-like undos (duplicate,\n * instantiate) stay allowed, matching delete-of-archived semantics.\n */\nfunction buildArchivedUndoGuard(commandId: typeof ARCHIVED_UNDO_GUARDED_COMMAND_IDS[number]): CommandInterceptor {\n return {\n id: `documents.${commandId.slice('documents.'.length).replaceAll('.', '-')}-archived-undo-guard`,\n targetCommand: commandId,\n priority: 100,\n async beforeUndo(\n undoContext: CommandInterceptorUndoContext,\n context: CommandInterceptorContext,\n ): Promise<void> {\n const logEntry = undoContext.logEntry as UndoLogEntryShape\n const documentId = resolveUndoDocumentId(logEntry)\n if (!documentId || !logEntry.tenantId || !logEntry.organizationId) {\n // Every guarded command records the document and its scope. Without\n // them the archived state cannot be read, so refuse the undo instead of\n // waving through a mutation this guard was unable to check.\n logger.error('Archived-undo guard could not resolve the guarded document scope', {\n commandId,\n resourceKind: logEntry.resourceKind ?? null,\n resourceId: logEntry.resourceId ?? null,\n })\n throw new CrudHttpError(403, { error: 'api.errors.forbidden' })\n }\n const em = context.container.resolve('em') as EntityManager\n const scope = { tenantId: logEntry.tenantId, organizationId: logEntry.organizationId }\n const document = await findOneWithDecryption(\n em,\n Document,\n { id: documentId, tenantId: scope.tenantId, organizationId: scope.organizationId },\n { fields: ['id', 'archivedAt'], filters: false },\n scope,\n )\n if (document?.archivedAt) {\n throw new CrudHttpError(403, { error: 'documents.errors.documentArchived' })\n }\n },\n }\n}\n\n/**\n * Projection hooks are deliberately post-command. CommandBus persists the\n * ActionLog (or marks it undone) before these hooks run, so a flaky event bus\n * or notification store can never roll back an acknowledged document write.\n */\nexport const interceptors: CommandInterceptor[] = [\n ...PROJECTED_COMMAND_IDS.map(buildProjectionInterceptor),\n ...ARCHIVED_UNDO_GUARDED_COMMAND_IDS.map(buildArchivedUndoGuard),\n]\n\nexport default interceptors\n"],
|
|
5
|
+
"mappings": "AAMA,SAAS,0BAA0B;AACnC,SAAS,qBAAqB;AAC9B,SAAS,6BAA6B;AACtC,SAAS,oBAAoB;AAC7B,SAAS,gBAAgB;AACzB,SAAS,4BAA4B;AACrC,SAAS,yBAAyB;AAClC,SAAS,gCAAgC;AAEzC,SAAS,0BAA0B;AAOnC,MAAM,SAAS,aAAa,WAAW,EAAE,MAAM,EAAE,WAAW,sBAAsB,CAAC;AAEnF,MAAM,wBAAwB;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAcA,SAAS,oCACP,WAC8B;AAC9B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