@open-mercato/documents 0.9.1-develop.7575.1.8480826a9b → 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.
Files changed (97) hide show
  1. package/dist/contentSecurityPolicy.js +23 -0
  2. package/dist/contentSecurityPolicy.js.map +7 -0
  3. package/dist/modules/documents/api/[id]/comments/access-check/route.js +13 -6
  4. package/dist/modules/documents/api/[id]/comments/access-check/route.js.map +2 -2
  5. package/dist/modules/documents/api/[id]/comments/route.js +2 -0
  6. package/dist/modules/documents/api/[id]/comments/route.js.map +2 -2
  7. package/dist/modules/documents/api/[id]/content/route.js +2 -0
  8. package/dist/modules/documents/api/[id]/content/route.js.map +2 -2
  9. package/dist/modules/documents/api/[id]/route.js +3 -0
  10. package/dist/modules/documents/api/[id]/route.js.map +2 -2
  11. package/dist/modules/documents/api/[id]/shares/route.js +2 -0
  12. package/dist/modules/documents/api/[id]/shares/route.js.map +2 -2
  13. package/dist/modules/documents/api/[id]/versions/route.js +2 -0
  14. package/dist/modules/documents/api/[id]/versions/route.js.map +2 -2
  15. package/dist/modules/documents/api/_shared.js +10 -27
  16. package/dist/modules/documents/api/_shared.js.map +3 -3
  17. package/dist/modules/documents/backend/documents/[id]/DocumentCanvas.js +3 -1
  18. package/dist/modules/documents/backend/documents/[id]/DocumentCanvas.js.map +2 -2
  19. package/dist/modules/documents/backend/documents/[id]/DocumentEditorIsland.js +1 -1
  20. package/dist/modules/documents/backend/documents/[id]/DocumentEditorIsland.js.map +2 -2
  21. package/dist/modules/documents/backend/documents/[id]/DocumentEditorSurface.js +15 -1
  22. package/dist/modules/documents/backend/documents/[id]/DocumentEditorSurface.js.map +2 -2
  23. package/dist/modules/documents/backend/documents/[id]/DocumentPageClient.js +15 -1
  24. package/dist/modules/documents/backend/documents/[id]/DocumentPageClient.js.map +2 -2
  25. package/dist/modules/documents/backend/documents/[id]/VersionHistoryPanel.js +20 -8
  26. package/dist/modules/documents/backend/documents/[id]/VersionHistoryPanel.js.map +2 -2
  27. package/dist/modules/documents/backend/documents/[id]/VersionPreviewDialog.js +3 -0
  28. package/dist/modules/documents/backend/documents/[id]/VersionPreviewDialog.js.map +2 -2
  29. package/dist/modules/documents/backend/documents/[id]/editorTypes.js.map +2 -2
  30. package/dist/modules/documents/backend/documents/[id]/saveCollaborativeContent.js +46 -0
  31. package/dist/modules/documents/backend/documents/[id]/saveCollaborativeContent.js.map +7 -0
  32. package/dist/modules/documents/backend/documents/[id]/useDocumentComments.js +14 -6
  33. package/dist/modules/documents/backend/documents/[id]/useDocumentComments.js.map +2 -2
  34. package/dist/modules/documents/backend/documents/[id]/useDocumentEditor.js +3 -0
  35. package/dist/modules/documents/backend/documents/[id]/useDocumentEditor.js.map +2 -2
  36. package/dist/modules/documents/backend/documents/components/TemplateBodyEditor.js +3 -0
  37. package/dist/modules/documents/backend/documents/components/TemplateBodyEditor.js.map +2 -2
  38. package/dist/modules/documents/backend/documents/components/TemplatePreview.js +3 -0
  39. package/dist/modules/documents/backend/documents/components/TemplatePreview.js.map +2 -2
  40. package/dist/modules/documents/commands/comments.js +2 -2
  41. package/dist/modules/documents/commands/comments.js.map +2 -2
  42. package/dist/modules/documents/commands/folders.js +1 -0
  43. package/dist/modules/documents/commands/folders.js.map +2 -2
  44. package/dist/modules/documents/commands/interceptors.js +11 -0
  45. package/dist/modules/documents/commands/interceptors.js.map +2 -2
  46. package/dist/modules/documents/data/attachment-access.js +84 -0
  47. package/dist/modules/documents/data/attachment-access.js.map +7 -0
  48. package/dist/modules/documents/data/validators.js +11 -0
  49. package/dist/modules/documents/data/validators.js.map +2 -2
  50. package/dist/modules/documents/lib/actor.js +32 -0
  51. package/dist/modules/documents/lib/actor.js.map +7 -0
  52. package/dist/modules/documents/lib/collabMaterializer.js +52 -9
  53. package/dist/modules/documents/lib/collabMaterializer.js.map +2 -2
  54. package/dist/modules/documents/lib/collabPersistence.js +13 -0
  55. package/dist/modules/documents/lib/collabPersistence.js.map +7 -0
  56. package/dist/modules/documents/lib/permissions.js +35 -2
  57. package/dist/modules/documents/lib/permissions.js.map +2 -2
  58. package/dist/modules/documents/widgets/injection/related-documents/widget.client.js +3 -2
  59. package/dist/modules/documents/widgets/injection/related-documents/widget.client.js.map +2 -2
  60. package/dist/modules/documents/widgets/injection-table.js +12 -3
  61. package/dist/modules/documents/widgets/injection-table.js.map +2 -2
  62. package/dist/server/documents-collab-server.js +74 -1
  63. package/dist/server/documents-collab-server.js.map +2 -2
  64. package/jest.config.cjs +1 -1
  65. package/package.json +37 -37
  66. package/server/documents-collab-server.ts +79 -0
  67. package/src/contentSecurityPolicy.ts +21 -0
  68. package/src/modules/documents/api/[id]/comments/access-check/route.ts +13 -6
  69. package/src/modules/documents/api/[id]/comments/route.ts +2 -0
  70. package/src/modules/documents/api/[id]/content/route.ts +2 -0
  71. package/src/modules/documents/api/[id]/route.ts +3 -0
  72. package/src/modules/documents/api/[id]/shares/route.ts +2 -0
  73. package/src/modules/documents/api/[id]/versions/route.ts +2 -0
  74. package/src/modules/documents/api/_shared.ts +10 -36
  75. package/src/modules/documents/backend/documents/[id]/DocumentCanvas.tsx +3 -1
  76. package/src/modules/documents/backend/documents/[id]/DocumentEditorIsland.tsx +4 -1
  77. package/src/modules/documents/backend/documents/[id]/DocumentEditorSurface.tsx +19 -1
  78. package/src/modules/documents/backend/documents/[id]/DocumentPageClient.tsx +14 -0
  79. package/src/modules/documents/backend/documents/[id]/VersionHistoryPanel.tsx +23 -8
  80. package/src/modules/documents/backend/documents/[id]/VersionPreviewDialog.tsx +3 -0
  81. package/src/modules/documents/backend/documents/[id]/editorTypes.ts +1 -0
  82. package/src/modules/documents/backend/documents/[id]/saveCollaborativeContent.ts +43 -0
  83. package/src/modules/documents/backend/documents/[id]/useDocumentComments.ts +17 -7
  84. package/src/modules/documents/backend/documents/[id]/useDocumentEditor.ts +3 -0
  85. package/src/modules/documents/backend/documents/components/TemplateBodyEditor.tsx +3 -0
  86. package/src/modules/documents/backend/documents/components/TemplatePreview.tsx +3 -0
  87. package/src/modules/documents/commands/comments.ts +2 -2
  88. package/src/modules/documents/commands/folders.ts +1 -3
  89. package/src/modules/documents/commands/interceptors.ts +11 -0
  90. package/src/modules/documents/data/attachment-access.ts +83 -0
  91. package/src/modules/documents/data/validators.ts +12 -0
  92. package/src/modules/documents/lib/actor.ts +39 -0
  93. package/src/modules/documents/lib/collabMaterializer.ts +62 -11
  94. package/src/modules/documents/lib/collabPersistence.ts +10 -0
  95. package/src/modules/documents/lib/permissions.ts +52 -0
  96. package/src/modules/documents/widgets/injection/related-documents/widget.client.tsx +3 -2
  97. package/src/modules/documents/widgets/injection-table.ts +17 -3
@@ -0,0 +1,23 @@
1
+ import { createLogger } from "@open-mercato/shared/lib/logger";
2
+ import { resolveDocumentsCollaborationEndpoint } from "./modules/documents/lib/collabEndpoint.js";
3
+ let warnedAboutExcludedEndpoint = false;
4
+ function resolveDocumentsCollaborationCspOrigins() {
5
+ const endpoint = resolveDocumentsCollaborationEndpoint();
6
+ if (!endpoint) return [];
7
+ const url = new URL(endpoint);
8
+ if (url.username || url.password || !/^(?:[a-z0-9.-]+|\[[0-9a-f:]+\])$/i.test(url.hostname)) {
9
+ if (!warnedAboutExcludedEndpoint) {
10
+ warnedAboutExcludedEndpoint = true;
11
+ createLogger("documents:csp").warn(
12
+ "[internal] Collaboration endpoint excluded from CSP; use a credential-free DNS or IPv6 URL",
13
+ { configuration: "NEXT_PUBLIC_DOCUMENTS_COLLAB_URL" }
14
+ );
15
+ }
16
+ return [];
17
+ }
18
+ return [url.origin];
19
+ }
20
+ export {
21
+ resolveDocumentsCollaborationCspOrigins
22
+ };
23
+ //# sourceMappingURL=contentSecurityPolicy.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/contentSecurityPolicy.ts"],
4
+ "sourcesContent": ["import { createLogger } from '@open-mercato/shared/lib/logger'\nimport { resolveDocumentsCollaborationEndpoint } from './modules/documents/lib/collabEndpoint'\n\nlet warnedAboutExcludedEndpoint = false\n\nexport function resolveDocumentsCollaborationCspOrigins(): string[] {\n const endpoint = resolveDocumentsCollaborationEndpoint()\n if (!endpoint) return []\n const url = new URL(endpoint)\n if (url.username || url.password || !/^(?:[a-z0-9.-]+|\\[[0-9a-f:]+\\])$/i.test(url.hostname)) {\n if (!warnedAboutExcludedEndpoint) {\n warnedAboutExcludedEndpoint = true\n createLogger('documents:csp').warn(\n '[internal] Collaboration endpoint excluded from CSP; use a credential-free DNS or IPv6 URL',\n { configuration: 'NEXT_PUBLIC_DOCUMENTS_COLLAB_URL' },\n )\n }\n return []\n }\n return [url.origin]\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,6CAA6C;AAEtD,IAAI,8BAA8B;AAE3B,SAAS,0CAAoD;AAClE,QAAM,WAAW,sCAAsC;AACvD,MAAI,CAAC,SAAU,QAAO,CAAC;AACvB,QAAM,MAAM,IAAI,IAAI,QAAQ;AAC5B,MAAI,IAAI,YAAY,IAAI,YAAY,CAAC,oCAAoC,KAAK,IAAI,QAAQ,GAAG;AAC3F,QAAI,CAAC,6BAA6B;AAChC,oCAA8B;AAC9B,mBAAa,eAAe,EAAE;AAAA,QAC5B;AAAA,QACA,EAAE,eAAe,mCAAmC;AAAA,MACtD;AAAA,IACF;AACA,WAAO,CAAC;AAAA,EACV;AACA,SAAO,CAAC,IAAI,MAAM;AACpB;",
6
+ "names": []
7
+ }
@@ -1,6 +1,6 @@
1
1
  import { NextResponse } from "next/server";
2
2
  import { z } from "zod";
3
- import { assertTier, resolveUserAccess } from "../../../../lib/permissions.js";
3
+ import { assertTier, hasUserDocumentViewPermission, resolveUserDocumentTier } from "../../../../lib/permissions.js";
4
4
  import {
5
5
  handleDocumentsRouteError,
6
6
  readBody,
@@ -13,6 +13,7 @@ const accessCheckSchema = z.object({
13
13
  });
14
14
  const accessCheckResponseSchema = z.object({
15
15
  withoutAccess: z.array(z.string().uuid()),
16
+ shareableUserIds: z.array(z.string().uuid()).optional(),
16
17
  withoutAccessUsers: z.array(
17
18
  z.object({
18
19
  userId: z.string().uuid(),
@@ -38,22 +39,28 @@ async function POST(request, context) {
38
39
  const input = accessCheckSchema.parse(await readBody(request));
39
40
  const uniqueUserIds = Array.from(new Set(input.userIds.map((userId) => userId.toLowerCase())));
40
41
  const withoutAccess = [];
42
+ const shareableUserIds = [];
43
+ const scope = { tenantId: ctx.tenantId, organizationId: ctx.organizationId };
41
44
  for (const userId of uniqueUserIds) {
42
- const tier = await resolveUserAccess(
45
+ const canView = await hasUserDocumentViewPermission(scope, userId, ctx.container);
46
+ const tier = canView ? await resolveUserDocumentTier(
43
47
  ctx.em,
44
48
  documentId,
45
- { tenantId: ctx.tenantId, organizationId: ctx.organizationId },
49
+ scope,
46
50
  userId,
47
51
  ctx.container
48
- );
49
- if (!tier) withoutAccess.push(userId);
52
+ ) : null;
53
+ if (!tier) {
54
+ withoutAccess.push(userId);
55
+ if (canView) shareableUserIds.push(userId);
56
+ }
50
57
  }
51
58
  const withoutAccessUsers = withoutAccess.map((userId) => ({
52
59
  userId,
53
60
  label: null,
54
61
  secondary: null
55
62
  }));
56
- return NextResponse.json({ withoutAccess, withoutAccessUsers });
63
+ return NextResponse.json({ withoutAccess, withoutAccessUsers, shareableUserIds });
57
64
  } catch (error) {
58
65
  return handleDocumentsRouteError(error, "documents.comments.accessCheck");
59
66
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../../src/modules/documents/api/%5Bid%5D/comments/access-check/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { assertTier, resolveUserAccess } from '../../../../lib/permissions'\nimport {\n handleDocumentsRouteError,\n readBody,\n resolveDocumentsContext,\n routeErrorSchema,\n withDocumentsContextErrors,\n} from '../../../_shared'\n\ntype RouteContext = {\n params: Promise<{ id: string }> | { id: string }\n}\n\nconst accessCheckSchema = z.object({\n userIds: z.array(z.string().uuid()).max(50),\n})\n\nconst accessCheckResponseSchema = z.object({\n withoutAccess: z.array(z.string().uuid()),\n withoutAccessUsers: z.array(\n z.object({\n userId: z.string().uuid(),\n // Keep the published nullable-string contract for generated clients;\n // this route deliberately returns null values to avoid identity lookup.\n label: z.string().nullable(),\n secondary: z.string().nullable(),\n }),\n ),\n})\n\nexport const metadata = {\n POST: { requireAuth: true, requireFeatures: ['documents.view'] },\n}\n\nasync function resolveId(context: RouteContext): Promise<string> {\n const params = await context.params\n return params.id\n}\n\nexport async function POST(request: Request, context: RouteContext): Promise<Response> {\n try {\n const documentId = await resolveId(context)\n const ctx = await resolveDocumentsContext(request, ['documents.view'])\n await assertTier(ctx.em, documentId, ctx.auth, 'commenter')\n const input = accessCheckSchema.parse(await readBody(request))\n const uniqueUserIds = Array.from(new Set(input.userIds.map((userId) => userId.toLowerCase())))\n const withoutAccess: string[] = []\n\n for (const userId of uniqueUserIds) {\n const tier = await resolveUserAccess(\n ctx.em,\n documentId,\n { tenantId: ctx.tenantId, organizationId: ctx.organizationId },\n userId,\n ctx.container,\n )\n if (!tier) withoutAccess.push(userId)\n }\n // Keep the historical response shape for clients, but never turn this\n // authorization probe into a user-directory/PII lookup. The caller\n // already supplied these IDs and owns their local mention labels.\n const withoutAccessUsers = withoutAccess.map((userId) => ({\n userId,\n label: null,\n secondary: null,\n }))\n\n return NextResponse.json({ withoutAccess, withoutAccessUsers })\n } catch (error) {\n return handleDocumentsRouteError(error, 'documents.comments.accessCheck')\n }\n}\n\nexport const openApi: OpenApiRouteDoc = withDocumentsContextErrors({\n tag: 'Documents',\n summary: 'Check mentioned user document access',\n pathParams: z.object({ id: z.string().uuid() }),\n methods: {\n POST: {\n summary: 'Check which mentioned users lack access',\n requestBody: { contentType: 'application/json', schema: accessCheckSchema },\n responses: [{ status: 200, description: 'Mention access check result', schema: accessCheckResponseSchema }],\n errors: [\n { status: 400, description: 'Validation failed', schema: routeErrorSchema },\n { status: 401, description: 'Unauthorized', schema: routeErrorSchema },\n { status: 403, description: 'Forbidden', schema: routeErrorSchema },\n { status: 413, description: 'Request body exceeds the safe resource bound', schema: routeErrorSchema },\n ],\n },\n },\n})\n\nexport default { POST }\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,YAAY,yBAAyB;AAC9C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAMP,MAAM,oBAAoB,EAAE,OAAO;AAAA,EACjC,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC,EAAE,IAAI,EAAE;AAC5C,CAAC;AAED,MAAM,4BAA4B,EAAE,OAAO;AAAA,EACzC,eAAe,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC;AAAA,EACxC,oBAAoB,EAAE;AAAA,IACpB,EAAE,OAAO;AAAA,MACP,QAAQ,EAAE,OAAO,EAAE,KAAK;AAAA;AAAA;AAAA,MAGxB,OAAO,EAAE,OAAO,EAAE,SAAS;AAAA,MAC3B,WAAW,EAAE,OAAO,EAAE,SAAS;AAAA,IACjC,CAAC;AAAA,EACH;AACF,CAAC;AAEM,MAAM,WAAW;AAAA,EACtB,MAAM,EAAE,aAAa,MAAM,iBAAiB,CAAC,gBAAgB,EAAE;AACjE;AAEA,eAAe,UAAU,SAAwC;AAC/D,QAAM,SAAS,MAAM,QAAQ;AAC7B,SAAO,OAAO;AAChB;AAEA,eAAsB,KAAK,SAAkB,SAA0C;AACrF,MAAI;AACF,UAAM,aAAa,MAAM,UAAU,OAAO;AAC1C,UAAM,MAAM,MAAM,wBAAwB,SAAS,CAAC,gBAAgB,CAAC;AACrE,UAAM,WAAW,IAAI,IAAI,YAAY,IAAI,MAAM,WAAW;AAC1D,UAAM,QAAQ,kBAAkB,MAAM,MAAM,SAAS,OAAO,CAAC;AAC7D,UAAM,gBAAgB,MAAM,KAAK,IAAI,IAAI,MA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["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { assertTier, hasUserDocumentViewPermission, resolveUserDocumentTier } from '../../../../lib/permissions'\nimport {\n handleDocumentsRouteError,\n readBody,\n resolveDocumentsContext,\n routeErrorSchema,\n withDocumentsContextErrors,\n} from '../../../_shared'\n\ntype RouteContext = {\n params: Promise<{ id: string }> | { id: string }\n}\n\nconst accessCheckSchema = z.object({\n userIds: z.array(z.string().uuid()).max(50),\n})\n\nconst accessCheckResponseSchema = z.object({\n withoutAccess: z.array(z.string().uuid()),\n shareableUserIds: z.array(z.string().uuid()).optional(),\n withoutAccessUsers: z.array(\n z.object({\n userId: z.string().uuid(),\n // Keep the published nullable-string contract for generated clients;\n // this route deliberately returns null values to avoid identity lookup.\n label: z.string().nullable(),\n secondary: z.string().nullable(),\n }),\n ),\n})\n\nexport const metadata = {\n POST: { requireAuth: true, requireFeatures: ['documents.view'] },\n}\n\nasync function resolveId(context: RouteContext): Promise<string> {\n const params = await context.params\n return params.id\n}\n\nexport async function POST(request: Request, context: RouteContext): Promise<Response> {\n try {\n const documentId = await resolveId(context)\n const ctx = await resolveDocumentsContext(request, ['documents.view'])\n await assertTier(ctx.em, documentId, ctx.auth, 'commenter')\n const input = accessCheckSchema.parse(await readBody(request))\n const uniqueUserIds = Array.from(new Set(input.userIds.map((userId) => userId.toLowerCase())))\n const withoutAccess: string[] = []\n const shareableUserIds: string[] = []\n const scope = { tenantId: ctx.tenantId, organizationId: ctx.organizationId }\n\n for (const userId of uniqueUserIds) {\n const canView = await hasUserDocumentViewPermission(scope, userId, ctx.container)\n const tier = canView ? await resolveUserDocumentTier(\n ctx.em,\n documentId,\n scope,\n userId,\n ctx.container,\n ) : null\n if (!tier) {\n withoutAccess.push(userId)\n if (canView) shareableUserIds.push(userId)\n }\n }\n // Keep the historical response shape for clients, but never turn this\n // authorization probe into a user-directory/PII lookup. The caller\n // already supplied these IDs and owns their local mention labels.\n const withoutAccessUsers = withoutAccess.map((userId) => ({\n userId,\n label: null,\n secondary: null,\n }))\n\n return NextResponse.json({ withoutAccess, withoutAccessUsers, shareableUserIds })\n } catch (error) {\n return handleDocumentsRouteError(error, 'documents.comments.accessCheck')\n }\n}\n\nexport const openApi: OpenApiRouteDoc = withDocumentsContextErrors({\n tag: 'Documents',\n summary: 'Check mentioned user document access',\n pathParams: z.object({ id: z.string().uuid() }),\n methods: {\n POST: {\n summary: 'Check which mentioned users lack access',\n requestBody: { contentType: 'application/json', schema: accessCheckSchema },\n responses: [{ status: 200, description: 'Mention access check result', schema: accessCheckResponseSchema }],\n errors: [\n { status: 400, description: 'Validation failed', schema: routeErrorSchema },\n { status: 401, description: 'Unauthorized', schema: routeErrorSchema },\n { status: 403, description: 'Forbidden', schema: routeErrorSchema },\n { status: 413, description: 'Request body exceeds the safe resource bound', schema: routeErrorSchema },\n ],\n },\n },\n})\n\nexport default { POST }\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,YAAY,+BAA+B,+BAA+B;AACnF;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAMP,MAAM,oBAAoB,EAAE,OAAO;AAAA,EACjC,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC,EAAE,IAAI,EAAE;AAC5C,CAAC;AAED,MAAM,4BAA4B,EAAE,OAAO;AAAA,EACzC,eAAe,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC;AAAA,EACxC,kBAAkB,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC,EAAE,SAAS;AAAA,EACtD,oBAAoB,EAAE;AAAA,IACpB,EAAE,OAAO;AAAA,MACP,QAAQ,EAAE,OAAO,EAAE,KAAK;AAAA;AAAA;AAAA,MAGxB,OAAO,EAAE,OAAO,EAAE,SAAS;AAAA,MAC3B,WAAW,EAAE,OAAO,EAAE,SAAS;A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C1E;AACF;AAEO,MAAM,UAA2B,2BAA2B;AAAA,EACjE,KAAK;AAAA,EACL,SAAS;AAAA,EACT,YAAY,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAAA,EAC9C,SAAS;AAAA,IACP,MAAM;AAAA,MACJ,SAAS;AAAA,MACT,aAAa,EAAE,aAAa,oBAAoB,QAAQ,kBAAkB;AAAA,MAC1E,WAAW,CAAC,EAAE,QAAQ,KAAK,aAAa,+BAA+B,QAAQ,0BAA0B,CAAC;AAAA,MAC1G,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,iBAAiB;AAAA,QAC1E,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,iBAAiB;AAAA,QACrE,EAAE,QAAQ,KAAK,aAAa,aAAa,QAAQ,iBAAiB;AAAA,QAClE,EAAE,QAAQ,KAAK,aAAa,gDAAgD,QAAQ,iBAAiB;AAAA,MACvG;AAAA,IACF;AAAA,EACF;AACF,CAAC;AAED,IAAO,gBAAQ,EAAE,KAAK;",
6
6
  "names": []
7
7
  }
@@ -19,6 +19,7 @@ import {
19
19
  resolveDocumentsCommandBus
20
20
  } from "../../_commands.js";
21
21
  import {
22
+ assertDocumentId,
22
23
  assertDocumentNotArchived,
23
24
  handleDocumentsRouteError,
24
25
  readBody,
@@ -188,6 +189,7 @@ async function GET(request, context) {
188
189
  try {
189
190
  const documentId = await resolveId(context);
190
191
  const ctx = await resolveDocumentsContext(request, ["documents.view"]);
192
+ assertDocumentId(documentId);
191
193
  const tier = await assertTier(ctx.em, documentId, ctx.auth, "viewer");
192
194
  const userId = resolveActorUserId(ctx.auth);
193
195
  const url = new URL(request.url);
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/modules/documents/api/%5Bid%5D/comments/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { randomUUID } from 'node:crypto'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { enforceCommandOptimisticLockWithGuards } from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { DocumentComment } from '../../../data/entities'\nimport { documentCommentCreateSchema } from '../../../data/validators'\nimport { DOCUMENTS_ENTITY_IDS } from '../../../lib/constants'\nimport {\n DOCUMENTS_COMMENT_LIST_PAGE_SIZE,\n DOCUMENTS_MAX_COMMENTS_PER_DOCUMENT,\n} from '../../../lib/historyLimits'\nimport { assertTier, hasTier } from '../../../lib/permissions'\nimport { resolveViewerSafeUserLabels } from '../../../lib/userLabels'\nimport type {\n CommentCreateCommandInput,\n CommentCreateCommandResult,\n CommentResolveCommandInput,\n CommentResolveCommandResult,\n} from '../../../commands/comments'\nimport {\n attachDocumentsOperationMetadata,\n buildDocumentsCommandRuntimeContext,\n resolveDocumentsCommandBus,\n} from '../../_commands'\nimport {\n assertDocumentNotArchived,\n handleDocumentsRouteError,\n readBody,\n resolveActorUserId,\n resolveDocumentsContext,\n routeErrorSchema,\n runMutationGuardAfterSuccess,\n validateMutationGuard,\n withDocumentsContextErrors,\n} from '../../_shared'\n\ntype RouteContext = {\n params: Promise<{ id: string }> | { id: string }\n}\n\ntype SerializedComment = {\n id: string\n documentId: string\n parentCommentId: string | null\n authorUserId: string\n body: string\n anchor: Record<string, unknown> | null\n mentions: { userId: string }[]\n resolvedAt: string | null\n resolvedByUserId: string | null\n createdAt: string\n updatedAt: string\n canResolve: boolean\n replies: SerializedComment[]\n}\n\nconst commentResolveSchema = z.object({\n id: z.string().uuid(),\n resolved: z.boolean(),\n})\n\nexport const commentListQuerySchema = z.object({\n page: z.coerce.number().int().min(1).max(10_000).default(1),\n pageSize: z.coerce.number().int().min(1).default(DOCUMENTS_COMMENT_LIST_PAGE_SIZE)\n .transform((value) => Math.min(value, DOCUMENTS_COMMENT_LIST_PAGE_SIZE)),\n})\n\nconst commentMentionSchema = z.object({\n userId: z.string().uuid(),\n})\n\nconst userLabelSchema = z.object({\n label: z.string(),\n})\n\nconst commentNodeSchema: z.ZodType<SerializedComment> = z.lazy(() =>\n z.object({\n id: z.string().uuid(),\n documentId: z.string().uuid(),\n parentCommentId: z.string().uuid().nullable(),\n authorUserId: z.string().uuid(),\n body: z.string(),\n anchor: z.record(z.string(), z.unknown()).nullable(),\n mentions: z.array(commentMentionSchema),\n resolvedAt: z.string().nullable(),\n resolvedByUserId: z.string().uuid().nullable(),\n createdAt: z.string(),\n updatedAt: z.string(),\n canResolve: z.boolean(),\n replies: z.array(commentNodeSchema),\n }),\n)\n\nconst commentListResponseSchema = z.object({\n items: z.array(commentNodeSchema),\n userLabels: z.record(z.string(), userLabelSchema),\n page: z.number().int().positive(),\n pageSize: z.number().int().positive(),\n total: z.number().int().nonnegative(),\n totalPages: z.number().int().positive(),\n totalComments: z.number().int().nonnegative(),\n truncated: z.boolean(),\n})\n\nconst commentCreateResponseSchema = z.object({\n id: z.string().uuid(),\n updatedAt: z.string(),\n})\n\nconst commentResolveResponseSchema = z.object({\n id: z.string().uuid(),\n resolvedAt: z.string().nullable(),\n resolvedByUserId: z.string().uuid().nullable(),\n updatedAt: z.string(),\n})\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['documents.view'] },\n POST: { requireAuth: true, requireFeatures: ['documents.view'] },\n PATCH: { requireAuth: true, requireFeatures: ['documents.view'] },\n}\n\nasync function resolveId(context: RouteContext): Promise<string> {\n const params = await context.params\n return params.id\n}\n\nfunction serializeComment(comment: DocumentComment, canResolve: boolean): SerializedComment {\n return {\n id: comment.id,\n documentId: comment.documentId,\n parentCommentId: comment.parentCommentId ?? null,\n authorUserId: comment.authorUserId,\n body: comment.body,\n anchor: comment.anchor ?? null,\n mentions: comment.mentions ?? [],\n resolvedAt: comment.resolvedAt ? comment.resolvedAt.toISOString() : null,\n resolvedByUserId: comment.resolvedByUserId ?? null,\n createdAt: comment.createdAt.toISOString(),\n updatedAt: comment.updatedAt.toISOString(),\n canResolve,\n replies: [],\n }\n}\n\nfunction buildThreadedComments(\n comments: DocumentComment[],\n options: { tier: Awaited<ReturnType<typeof assertTier>>; userId: string },\n): SerializedComment[] {\n const nodes = new Map<string, SerializedComment>()\n for (const comment of comments) {\n nodes.set(comment.id, serializeComment(\n comment,\n hasTier(options.tier, 'commenter') || comment.authorUserId === options.userId,\n ))\n }\n\n const roots: SerializedComment[] = []\n for (const comment of comments) {\n const node = nodes.get(comment.id)\n if (!node) continue\n const parentId = comment.parentCommentId ?? null\n const parent = parentId ? nodes.get(parentId) : null\n if (parent) {\n parent.replies.push(node)\n } else {\n roots.push(node)\n }\n }\n return roots\n}\n\nexport function paginateNewestThreadRoots<T>(roots: T[], page: number, pageSize: number): T[] {\n const end = Math.max(0, roots.length - ((page - 1) * pageSize))\n const start = Math.max(0, end - pageSize)\n return roots.slice(start, end)\n}\n\nfunction collectSerializedCommentIds(comments: SerializedComment[]): Set<string> {\n const ids = new Set<string>()\n const visit = (nodes: SerializedComment[]) => {\n for (const comment of nodes) {\n ids.add(comment.id)\n visit(comment.replies)\n }\n }\n visit(comments)\n return ids\n}\n\nfunction extractMentionedUserIds(body: string): string[] {\n const mentionTokenPattern =\n /@\\[([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(\n new Set(\n Array.from(body.matchAll(mentionTokenPattern))\n .map((match) => match[1])\n .filter((value): value is string => typeof value === 'string' && value.length > 0)\n .map((value) => value.toLowerCase()),\n ),\n )\n}\n\nfunction dedupeUserIds(userIds: string[]): string[] {\n return Array.from(new Set(userIds.map((userId) => userId.toLowerCase())))\n}\n\nfunction collectCommentLabelUserIds(comments: DocumentComment[]): string[] {\n const userIds: string[] = []\n for (const comment of comments) {\n userIds.push(comment.authorUserId)\n if (comment.resolvedByUserId) userIds.push(comment.resolvedByUserId)\n for (const mention of comment.mentions ?? []) {\n userIds.push(mention.userId)\n }\n userIds.push(...extractMentionedUserIds(comment.body))\n }\n return dedupeUserIds(userIds)\n}\n\nasync function loadScopedComment(documentId: string, commentId: string, ctx: Awaited<ReturnType<typeof resolveDocumentsContext>>): Promise<DocumentComment> {\n const comment = await findOneWithDecryption(\n ctx.em,\n DocumentComment,\n {\n id: commentId,\n documentId,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n deletedAt: null,\n },\n undefined,\n { tenantId: ctx.tenantId, organizationId: ctx.organizationId },\n )\n if (!comment) throw new CrudHttpError(404, { error: 'Comment not found' })\n return comment\n}\n\nexport async function GET(request: Request, context: RouteContext): Promise<Response> {\n try {\n const documentId = await resolveId(context)\n const ctx = await resolveDocumentsContext(request, ['documents.view'])\n const tier = await assertTier(ctx.em, documentId, ctx.auth, 'viewer')\n const userId = resolveActorUserId(ctx.auth)\n const url = new URL(request.url)\n const query = commentListQuerySchema.parse(Object.fromEntries(url.searchParams.entries()))\n\n const loadedComments = await findWithDecryption(\n ctx.em,\n DocumentComment,\n {\n documentId,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n deletedAt: null,\n },\n {\n orderBy: { createdAt: 'DESC', id: 'DESC' },\n limit: DOCUMENTS_MAX_COMMENTS_PER_DOCUMENT + 1,\n },\n { tenantId: ctx.tenantId, organizationId: ctx.organizationId },\n )\n const truncated = loadedComments.length > DOCUMENTS_MAX_COMMENTS_PER_DOCUMENT\n const comments = loadedComments.slice(0, DOCUMENTS_MAX_COMMENTS_PER_DOCUMENT).reverse()\n const roots = buildThreadedComments(comments, { tier, userId })\n const items = paginateNewestThreadRoots(roots, query.page, query.pageSize)\n const visibleCommentIds = collectSerializedCommentIds(items)\n const userLabels = await resolveViewerSafeUserLabels(\n ctx.container,\n { tenantId: ctx.tenantId, organizationId: ctx.organizationId },\n collectCommentLabelUserIds(comments.filter((comment) => visibleCommentIds.has(comment.id))),\n )\n\n return NextResponse.json({\n items,\n userLabels: Object.fromEntries(userLabels.entries()),\n page: query.page,\n pageSize: query.pageSize,\n total: roots.length,\n totalPages: Math.max(1, Math.ceil(roots.length / query.pageSize)),\n totalComments: comments.length,\n truncated,\n })\n } catch (error) {\n return handleDocumentsRouteError(error, 'documents.comments.list')\n }\n}\n\nexport async function POST(request: Request, context: RouteContext): Promise<Response> {\n try {\n const documentId = await resolveId(context)\n const ctx = await resolveDocumentsContext(request, ['documents.view'])\n await assertTier(ctx.em, documentId, ctx.auth, 'commenter')\n await assertDocumentNotArchived(ctx, documentId)\n const input = documentCommentCreateSchema.parse(await readBody(request))\n const userId = resolveActorUserId(ctx.auth)\n const guardResult = await validateMutationGuard(ctx, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentComment,\n resourceId: documentId,\n operation: 'create',\n mutationPayload: input,\n mutationPayloadSchema: documentCommentCreateSchema,\n })\n\n const commandInput: CommentCreateCommandInput = {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n documentId,\n commentId: randomUUID(),\n actorUserId: userId,\n comment: input,\n grantShares: dedupeUserIds(input.grantAccessTo ?? []).map((mentionedUserId) => ({\n userId: mentionedUserId,\n shareId: randomUUID(),\n })),\n }\n const execution = await resolveDocumentsCommandBus(ctx).execute<CommentCreateCommandInput, CommentCreateCommandResult>(\n 'documents.comment.create',\n { input: commandInput, ctx: buildDocumentsCommandRuntimeContext(ctx) },\n )\n await runMutationGuardAfterSuccess(ctx, guardResult, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentComment,\n resourceId: documentId,\n operation: 'create',\n })\n\n return attachDocumentsOperationMetadata(\n NextResponse.json({ id: execution.result.id, updatedAt: execution.result.updatedAt }, { status: 201 }),\n execution.logEntry,\n { resourceKind: DOCUMENTS_ENTITY_IDS.documentComment, resourceId: execution.result.id },\n )\n } catch (error) {\n return handleDocumentsRouteError(error, 'documents.comments.create')\n }\n}\n\nexport async function PATCH(request: Request, context: RouteContext): Promise<Response> {\n try {\n const documentId = await resolveId(context)\n const ctx = await resolveDocumentsContext(request, ['documents.view'])\n const tier = await assertTier(ctx.em, documentId, ctx.auth, 'viewer')\n await assertDocumentNotArchived(ctx, documentId)\n const input = commentResolveSchema.parse(await readBody(request))\n const comment = await loadScopedComment(documentId, input.id, ctx)\n const userId = resolveActorUserId(ctx.auth)\n if (!hasTier(tier, 'commenter') && comment.authorUserId !== userId) {\n throw new CrudHttpError(403, { error: 'Forbidden' })\n }\n await enforceCommandOptimisticLockWithGuards(ctx.container, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentComment,\n resourceId: comment.id,\n current: comment.updatedAt,\n request,\n })\n\n const guardResult = await validateMutationGuard(ctx, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentComment,\n resourceId: comment.id,\n operation: 'update',\n mutationPayload: input,\n mutationPayloadSchema: commentResolveSchema,\n })\n\n const commandInput: CommentResolveCommandInput = {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n documentId,\n actorUserId: userId,\n expectedUpdatedAt: comment.updatedAt.toISOString(),\n comment: input,\n }\n const execution = await resolveDocumentsCommandBus(ctx).execute<CommentResolveCommandInput, CommentResolveCommandResult>(\n 'documents.comment.resolve',\n { input: commandInput, ctx: buildDocumentsCommandRuntimeContext(ctx) },\n )\n await runMutationGuardAfterSuccess(ctx, guardResult, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentComment,\n resourceId: comment.id,\n operation: 'update',\n })\n\n return attachDocumentsOperationMetadata(\n NextResponse.json({\n id: execution.result.id,\n resolvedAt: execution.result.resolvedAt,\n resolvedByUserId: execution.result.resolvedByUserId,\n updatedAt: execution.result.updatedAt,\n }),\n execution.logEntry,\n { resourceKind: DOCUMENTS_ENTITY_IDS.documentComment, resourceId: execution.result.id },\n )\n } catch (error) {\n return handleDocumentsRouteError(error, 'documents.comments.resolve')\n }\n}\n\nexport const openApi: OpenApiRouteDoc = withDocumentsContextErrors({\n tag: 'Documents',\n summary: 'Document comments',\n pathParams: z.object({ id: z.string().uuid() }),\n methods: {\n GET: {\n summary: 'List document comments',\n query: commentListQuerySchema,\n responses: [{ status: 200, description: 'Threaded document comments', schema: commentListResponseSchema }],\n errors: [\n { status: 401, description: 'Unauthorized', schema: routeErrorSchema },\n { status: 403, description: 'Forbidden', schema: routeErrorSchema },\n ],\n },\n POST: {\n summary: 'Create document comment',\n description: 'Mentions may be sent out-of-band as mentions: [{ userId }]. Legacy bracketed @[user-uuid] tokens in the comment body are still honored.',\n requestBody: { contentType: 'application/json', schema: documentCommentCreateSchema },\n responses: [{ status: 201, description: 'Comment created', schema: commentCreateResponseSchema }],\n errors: [\n { status: 400, description: 'Validation failed', schema: routeErrorSchema },\n { status: 401, description: 'Unauthorized', schema: routeErrorSchema },\n { status: 403, description: 'Forbidden', schema: routeErrorSchema },\n { status: 413, description: 'Request body or document comment limit exceeds the safe resource bound', schema: routeErrorSchema },\n ],\n },\n PATCH: {\n summary: 'Resolve or unresolve document comment',\n requestBody: { contentType: 'application/json', schema: commentResolveSchema },\n responses: [{ status: 200, description: 'Comment resolution updated', schema: commentResolveResponseSchema }],\n errors: [\n { status: 400, description: 'Validation failed', schema: routeErrorSchema },\n { status: 401, description: 'Unauthorized', schema: routeErrorSchema },\n { status: 403, description: 'Forbidden', schema: routeErrorSchema },\n { status: 404, description: 'Comment not found', schema: routeErrorSchema },\n { status: 409, description: 'Optimistic lock conflict', schema: routeErrorSchema },\n { status: 413, description: 'Request body exceeds the safe resource bound', schema: routeErrorSchema },\n ],\n },\n },\n})\n\nexport default { GET, POST, PATCH }\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,kBAAkB;AAE3B,SAAS,qBAAqB;AAC9B,SAAS,8CAA8C;AACvD,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,uBAAuB;AAChC,SAAS,mCAAmC;AAC5C,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,YAAY,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\nimport { z } from 'zod'\nimport { randomUUID } from 'node:crypto'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { enforceCommandOptimisticLockWithGuards } from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { DocumentComment } from '../../../data/entities'\nimport { documentCommentCreateSchema } from '../../../data/validators'\nimport { DOCUMENTS_ENTITY_IDS } from '../../../lib/constants'\nimport {\n DOCUMENTS_COMMENT_LIST_PAGE_SIZE,\n DOCUMENTS_MAX_COMMENTS_PER_DOCUMENT,\n} from '../../../lib/historyLimits'\nimport { assertTier, hasTier } from '../../../lib/permissions'\nimport { resolveViewerSafeUserLabels } from '../../../lib/userLabels'\nimport type {\n CommentCreateCommandInput,\n CommentCreateCommandResult,\n CommentResolveCommandInput,\n CommentResolveCommandResult,\n} from '../../../commands/comments'\nimport {\n attachDocumentsOperationMetadata,\n buildDocumentsCommandRuntimeContext,\n resolveDocumentsCommandBus,\n} from '../../_commands'\nimport {\n assertDocumentId,\n assertDocumentNotArchived,\n handleDocumentsRouteError,\n readBody,\n resolveActorUserId,\n resolveDocumentsContext,\n routeErrorSchema,\n runMutationGuardAfterSuccess,\n validateMutationGuard,\n withDocumentsContextErrors,\n} from '../../_shared'\n\ntype RouteContext = {\n params: Promise<{ id: string }> | { id: string }\n}\n\ntype SerializedComment = {\n id: string\n documentId: string\n parentCommentId: string | null\n authorUserId: string\n body: string\n anchor: Record<string, unknown> | null\n mentions: { userId: string }[]\n resolvedAt: string | null\n resolvedByUserId: string | null\n createdAt: string\n updatedAt: string\n canResolve: boolean\n replies: SerializedComment[]\n}\n\nconst commentResolveSchema = z.object({\n id: z.string().uuid(),\n resolved: z.boolean(),\n})\n\nexport const commentListQuerySchema = z.object({\n page: z.coerce.number().int().min(1).max(10_000).default(1),\n pageSize: z.coerce.number().int().min(1).default(DOCUMENTS_COMMENT_LIST_PAGE_SIZE)\n .transform((value) => Math.min(value, DOCUMENTS_COMMENT_LIST_PAGE_SIZE)),\n})\n\nconst commentMentionSchema = z.object({\n userId: z.string().uuid(),\n})\n\nconst userLabelSchema = z.object({\n label: z.string(),\n})\n\nconst commentNodeSchema: z.ZodType<SerializedComment> = z.lazy(() =>\n z.object({\n id: z.string().uuid(),\n documentId: z.string().uuid(),\n parentCommentId: z.string().uuid().nullable(),\n authorUserId: z.string().uuid(),\n body: z.string(),\n anchor: z.record(z.string(), z.unknown()).nullable(),\n mentions: z.array(commentMentionSchema),\n resolvedAt: z.string().nullable(),\n resolvedByUserId: z.string().uuid().nullable(),\n createdAt: z.string(),\n updatedAt: z.string(),\n canResolve: z.boolean(),\n replies: z.array(commentNodeSchema),\n }),\n)\n\nconst commentListResponseSchema = z.object({\n items: z.array(commentNodeSchema),\n userLabels: z.record(z.string(), userLabelSchema),\n page: z.number().int().positive(),\n pageSize: z.number().int().positive(),\n total: z.number().int().nonnegative(),\n totalPages: z.number().int().positive(),\n totalComments: z.number().int().nonnegative(),\n truncated: z.boolean(),\n})\n\nconst commentCreateResponseSchema = z.object({\n id: z.string().uuid(),\n updatedAt: z.string(),\n})\n\nconst commentResolveResponseSchema = z.object({\n id: z.string().uuid(),\n resolvedAt: z.string().nullable(),\n resolvedByUserId: z.string().uuid().nullable(),\n updatedAt: z.string(),\n})\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['documents.view'] },\n POST: { requireAuth: true, requireFeatures: ['documents.view'] },\n PATCH: { requireAuth: true, requireFeatures: ['documents.view'] },\n}\n\nasync function resolveId(context: RouteContext): Promise<string> {\n const params = await context.params\n return params.id\n}\n\nfunction serializeComment(comment: DocumentComment, canResolve: boolean): SerializedComment {\n return {\n id: comment.id,\n documentId: comment.documentId,\n parentCommentId: comment.parentCommentId ?? null,\n authorUserId: comment.authorUserId,\n body: comment.body,\n anchor: comment.anchor ?? null,\n mentions: comment.mentions ?? [],\n resolvedAt: comment.resolvedAt ? comment.resolvedAt.toISOString() : null,\n resolvedByUserId: comment.resolvedByUserId ?? null,\n createdAt: comment.createdAt.toISOString(),\n updatedAt: comment.updatedAt.toISOString(),\n canResolve,\n replies: [],\n }\n}\n\nfunction buildThreadedComments(\n comments: DocumentComment[],\n options: { tier: Awaited<ReturnType<typeof assertTier>>; userId: string },\n): SerializedComment[] {\n const nodes = new Map<string, SerializedComment>()\n for (const comment of comments) {\n nodes.set(comment.id, serializeComment(\n comment,\n hasTier(options.tier, 'commenter') || comment.authorUserId === options.userId,\n ))\n }\n\n const roots: SerializedComment[] = []\n for (const comment of comments) {\n const node = nodes.get(comment.id)\n if (!node) continue\n const parentId = comment.parentCommentId ?? null\n const parent = parentId ? nodes.get(parentId) : null\n if (parent) {\n parent.replies.push(node)\n } else {\n roots.push(node)\n }\n }\n return roots\n}\n\nexport function paginateNewestThreadRoots<T>(roots: T[], page: number, pageSize: number): T[] {\n const end = Math.max(0, roots.length - ((page - 1) * pageSize))\n const start = Math.max(0, end - pageSize)\n return roots.slice(start, end)\n}\n\nfunction collectSerializedCommentIds(comments: SerializedComment[]): Set<string> {\n const ids = new Set<string>()\n const visit = (nodes: SerializedComment[]) => {\n for (const comment of nodes) {\n ids.add(comment.id)\n visit(comment.replies)\n }\n }\n visit(comments)\n return ids\n}\n\nfunction extractMentionedUserIds(body: string): string[] {\n const mentionTokenPattern =\n /@\\[([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(\n new Set(\n Array.from(body.matchAll(mentionTokenPattern))\n .map((match) => match[1])\n .filter((value): value is string => typeof value === 'string' && value.length > 0)\n .map((value) => value.toLowerCase()),\n ),\n )\n}\n\nfunction dedupeUserIds(userIds: string[]): string[] {\n return Array.from(new Set(userIds.map((userId) => userId.toLowerCase())))\n}\n\nfunction collectCommentLabelUserIds(comments: DocumentComment[]): string[] {\n const userIds: string[] = []\n for (const comment of comments) {\n userIds.push(comment.authorUserId)\n if (comment.resolvedByUserId) userIds.push(comment.resolvedByUserId)\n for (const mention of comment.mentions ?? []) {\n userIds.push(mention.userId)\n }\n userIds.push(...extractMentionedUserIds(comment.body))\n }\n return dedupeUserIds(userIds)\n}\n\nasync function loadScopedComment(documentId: string, commentId: string, ctx: Awaited<ReturnType<typeof resolveDocumentsContext>>): Promise<DocumentComment> {\n const comment = await findOneWithDecryption(\n ctx.em,\n DocumentComment,\n {\n id: commentId,\n documentId,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n deletedAt: null,\n },\n undefined,\n { tenantId: ctx.tenantId, organizationId: ctx.organizationId },\n )\n if (!comment) throw new CrudHttpError(404, { error: 'Comment not found' })\n return comment\n}\n\nexport async function GET(request: Request, context: RouteContext): Promise<Response> {\n try {\n const documentId = await resolveId(context)\n const ctx = await resolveDocumentsContext(request, ['documents.view'])\n assertDocumentId(documentId)\n const tier = await assertTier(ctx.em, documentId, ctx.auth, 'viewer')\n const userId = resolveActorUserId(ctx.auth)\n const url = new URL(request.url)\n const query = commentListQuerySchema.parse(Object.fromEntries(url.searchParams.entries()))\n\n const loadedComments = await findWithDecryption(\n ctx.em,\n DocumentComment,\n {\n documentId,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n deletedAt: null,\n },\n {\n orderBy: { createdAt: 'DESC', id: 'DESC' },\n limit: DOCUMENTS_MAX_COMMENTS_PER_DOCUMENT + 1,\n },\n { tenantId: ctx.tenantId, organizationId: ctx.organizationId },\n )\n const truncated = loadedComments.length > DOCUMENTS_MAX_COMMENTS_PER_DOCUMENT\n const comments = loadedComments.slice(0, DOCUMENTS_MAX_COMMENTS_PER_DOCUMENT).reverse()\n const roots = buildThreadedComments(comments, { tier, userId })\n const items = paginateNewestThreadRoots(roots, query.page, query.pageSize)\n const visibleCommentIds = collectSerializedCommentIds(items)\n const userLabels = await resolveViewerSafeUserLabels(\n ctx.container,\n { tenantId: ctx.tenantId, organizationId: ctx.organizationId },\n collectCommentLabelUserIds(comments.filter((comment) => visibleCommentIds.has(comment.id))),\n )\n\n return NextResponse.json({\n items,\n userLabels: Object.fromEntries(userLabels.entries()),\n page: query.page,\n pageSize: query.pageSize,\n total: roots.length,\n totalPages: Math.max(1, Math.ceil(roots.length / query.pageSize)),\n totalComments: comments.length,\n truncated,\n })\n } catch (error) {\n return handleDocumentsRouteError(error, 'documents.comments.list')\n }\n}\n\nexport async function POST(request: Request, context: RouteContext): Promise<Response> {\n try {\n const documentId = await resolveId(context)\n const ctx = await resolveDocumentsContext(request, ['documents.view'])\n await assertTier(ctx.em, documentId, ctx.auth, 'commenter')\n await assertDocumentNotArchived(ctx, documentId)\n const input = documentCommentCreateSchema.parse(await readBody(request))\n const userId = resolveActorUserId(ctx.auth)\n const guardResult = await validateMutationGuard(ctx, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentComment,\n resourceId: documentId,\n operation: 'create',\n mutationPayload: input,\n mutationPayloadSchema: documentCommentCreateSchema,\n })\n\n const commandInput: CommentCreateCommandInput = {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n documentId,\n commentId: randomUUID(),\n actorUserId: userId,\n comment: input,\n grantShares: dedupeUserIds(input.grantAccessTo ?? []).map((mentionedUserId) => ({\n userId: mentionedUserId,\n shareId: randomUUID(),\n })),\n }\n const execution = await resolveDocumentsCommandBus(ctx).execute<CommentCreateCommandInput, CommentCreateCommandResult>(\n 'documents.comment.create',\n { input: commandInput, ctx: buildDocumentsCommandRuntimeContext(ctx) },\n )\n await runMutationGuardAfterSuccess(ctx, guardResult, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentComment,\n resourceId: documentId,\n operation: 'create',\n })\n\n return attachDocumentsOperationMetadata(\n NextResponse.json({ id: execution.result.id, updatedAt: execution.result.updatedAt }, { status: 201 }),\n execution.logEntry,\n { resourceKind: DOCUMENTS_ENTITY_IDS.documentComment, resourceId: execution.result.id },\n )\n } catch (error) {\n return handleDocumentsRouteError(error, 'documents.comments.create')\n }\n}\n\nexport async function PATCH(request: Request, context: RouteContext): Promise<Response> {\n try {\n const documentId = await resolveId(context)\n const ctx = await resolveDocumentsContext(request, ['documents.view'])\n const tier = await assertTier(ctx.em, documentId, ctx.auth, 'viewer')\n await assertDocumentNotArchived(ctx, documentId)\n const input = commentResolveSchema.parse(await readBody(request))\n const comment = await loadScopedComment(documentId, input.id, ctx)\n const userId = resolveActorUserId(ctx.auth)\n if (!hasTier(tier, 'commenter') && comment.authorUserId !== userId) {\n throw new CrudHttpError(403, { error: 'Forbidden' })\n }\n await enforceCommandOptimisticLockWithGuards(ctx.container, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentComment,\n resourceId: comment.id,\n current: comment.updatedAt,\n request,\n })\n\n const guardResult = await validateMutationGuard(ctx, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentComment,\n resourceId: comment.id,\n operation: 'update',\n mutationPayload: input,\n mutationPayloadSchema: commentResolveSchema,\n })\n\n const commandInput: CommentResolveCommandInput = {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n documentId,\n actorUserId: userId,\n expectedUpdatedAt: comment.updatedAt.toISOString(),\n comment: input,\n }\n const execution = await resolveDocumentsCommandBus(ctx).execute<CommentResolveCommandInput, CommentResolveCommandResult>(\n 'documents.comment.resolve',\n { input: commandInput, ctx: buildDocumentsCommandRuntimeContext(ctx) },\n )\n await runMutationGuardAfterSuccess(ctx, guardResult, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentComment,\n resourceId: comment.id,\n operation: 'update',\n })\n\n return attachDocumentsOperationMetadata(\n NextResponse.json({\n id: execution.result.id,\n resolvedAt: execution.result.resolvedAt,\n resolvedByUserId: execution.result.resolvedByUserId,\n updatedAt: execution.result.updatedAt,\n }),\n execution.logEntry,\n { resourceKind: DOCUMENTS_ENTITY_IDS.documentComment, resourceId: execution.result.id },\n )\n } catch (error) {\n return handleDocumentsRouteError(error, 'documents.comments.resolve')\n }\n}\n\nexport const openApi: OpenApiRouteDoc = withDocumentsContextErrors({\n tag: 'Documents',\n summary: 'Document comments',\n pathParams: z.object({ id: z.string().uuid() }),\n methods: {\n GET: {\n summary: 'List document comments',\n query: commentListQuerySchema,\n responses: [{ status: 200, description: 'Threaded document comments', schema: commentListResponseSchema }],\n errors: [\n { status: 401, description: 'Unauthorized', schema: routeErrorSchema },\n { status: 403, description: 'Forbidden', schema: routeErrorSchema },\n ],\n },\n POST: {\n summary: 'Create document comment',\n description: 'Mentions may be sent out-of-band as mentions: [{ userId }]. Legacy bracketed @[user-uuid] tokens in the comment body are still honored.',\n requestBody: { contentType: 'application/json', schema: documentCommentCreateSchema },\n responses: [{ status: 201, description: 'Comment created', schema: commentCreateResponseSchema }],\n errors: [\n { status: 400, description: 'Validation failed', schema: routeErrorSchema },\n { status: 401, description: 'Unauthorized', schema: routeErrorSchema },\n { status: 403, description: 'Forbidden', schema: routeErrorSchema },\n { status: 413, description: 'Request body or document comment limit exceeds the safe resource bound', schema: routeErrorSchema },\n ],\n },\n PATCH: {\n summary: 'Resolve or unresolve document comment',\n requestBody: { contentType: 'application/json', schema: commentResolveSchema },\n responses: [{ status: 200, description: 'Comment resolution updated', schema: commentResolveResponseSchema }],\n errors: [\n { status: 400, description: 'Validation failed', schema: routeErrorSchema },\n { status: 401, description: 'Unauthorized', schema: routeErrorSchema },\n { status: 403, description: 'Forbidden', schema: routeErrorSchema },\n { status: 404, description: 'Comment not found', schema: routeErrorSchema },\n { status: 409, description: 'Optimistic lock conflict', schema: routeErrorSchema },\n { status: 413, description: 'Request body exceeds the safe resource bound', schema: routeErrorSchema },\n ],\n },\n },\n})\n\nexport default { GET, POST, PATCH }\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,kBAAkB;AAE3B,SAAS,qBAAqB;AAC9B,SAAS,8CAA8C;AACvD,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,uBAAuB;AAChC,SAAS,mCAAmC;AAC5C,SAAS,4B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F;AACF,CAAC;AAED,IAAO,gBAAQ,EAAE,KAAK,MAAM,MAAM;",
6
6
  "names": []
7
7
  }
@@ -8,6 +8,7 @@ import { loadDocumentContent } from "../../../lib/contentService.js";
8
8
  import { assertDocumentContentResourceLimits } from "../../../lib/resourceLimits.js";
9
9
  import { DOCUMENTS_JSON_BODY_LIMITS } from "../../../lib/requestBody.js";
10
10
  import {
11
+ assertDocumentId,
11
12
  assertDocumentNotArchived,
12
13
  handleDocumentsRouteError,
13
14
  readBody,
@@ -44,6 +45,7 @@ async function GET(request, context) {
44
45
  try {
45
46
  const id = await resolveId(context);
46
47
  const ctx = await resolveDocumentsContext(request, ["documents.view"]);
48
+ assertDocumentId(id);
47
49
  await assertTier(ctx.em, id, ctx.auth, "viewer");
48
50
  const content = await loadDocumentContent(ctx.em, id, {
49
51
  tenantId: ctx.tenantId,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/modules/documents/api/%5Bid%5D/content/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { randomUUID } from 'node:crypto'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { documentContentPutSchema } from '../../../data/validators'\nimport { DOCUMENTS_ENTITY_IDS } from '../../../lib/constants'\nimport { assertTier } from '../../../lib/permissions'\nimport { loadDocumentContent } from '../../../lib/contentService'\nimport { assertDocumentContentResourceLimits } from '../../../lib/resourceLimits'\nimport { DOCUMENTS_JSON_BODY_LIMITS } from '../../../lib/requestBody'\nimport type {\n ReplaceDocumentContentCommandInput,\n ReplaceDocumentContentCommandResult,\n} from '../../../commands/content'\nimport {\n assertDocumentNotArchived,\n handleDocumentsRouteError,\n readBody,\n resolveDocumentsContext,\n routeErrorSchema,\n runMutationGuardAfterSuccess,\n serializeContent,\n validateMutationGuard,\n withDocumentsContextErrors,\n} from '../../_shared'\nimport {\n attachDocumentsOperationMetadata,\n buildDocumentsCommandRuntimeContext,\n resolveDocumentsCommandBus,\n} from '../../_commands'\n\ntype RouteContext = {\n params: Promise<{ id: string }> | { id: string }\n}\n\nconst contentResponseSchema = z.object({\n contentHtml: z.string(),\n contentText: z.string(),\n updatedAt: z.string().nullable(),\n})\n\nconst contentPutResponseSchema = z.object({\n ok: z.boolean(),\n updatedAt: z.string().nullable(),\n})\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['documents.view'] },\n PUT: { requireAuth: true, requireFeatures: ['documents.edit'] },\n}\n\nasync function resolveId(context: RouteContext): Promise<string> {\n const params = await context.params\n return params.id\n}\n\nexport async function GET(request: Request, context: RouteContext): Promise<Response> {\n try {\n const id = await resolveId(context)\n const ctx = await resolveDocumentsContext(request, ['documents.view'])\n await assertTier(ctx.em, id, ctx.auth, 'viewer')\n const content = await loadDocumentContent(ctx.em, id, {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n })\n assertDocumentContentResourceLimits({\n yjsState: content?.yjsState,\n contentHtml: content?.contentHtml,\n contentText: content?.contentText,\n })\n return NextResponse.json(serializeContent(content))\n } catch (error) {\n return handleDocumentsRouteError(error, 'documents.content.get')\n }\n}\n\nexport async function PUT(request: Request, context: RouteContext): Promise<Response> {\n try {\n const id = await resolveId(context)\n const ctx = await resolveDocumentsContext(request, ['documents.edit'])\n await assertTier(ctx.em, id, ctx.auth, 'editor')\n await assertDocumentNotArchived(ctx, id)\n const input = documentContentPutSchema.parse(await readBody(\n request,\n DOCUMENTS_JSON_BODY_LIMITS.content,\n ))\n const guardResult = await validateMutationGuard(ctx, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentContent,\n resourceId: id,\n operation: 'update',\n mutationPayload: input,\n mutationPayloadSchema: documentContentPutSchema,\n })\n const scope = { tenantId: ctx.tenantId, organizationId: ctx.organizationId }\n const currentContent = await loadDocumentContent(ctx.em, id, scope)\n const commandInput: ReplaceDocumentContentCommandInput = {\n ...input,\n documentId: id,\n contentId: currentContent?.id ?? randomUUID(),\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n }\n const { result, logEntry } = await resolveDocumentsCommandBus(ctx).execute<\n ReplaceDocumentContentCommandInput,\n ReplaceDocumentContentCommandResult\n >('documents.content.replace', {\n input: commandInput,\n ctx: buildDocumentsCommandRuntimeContext(ctx),\n })\n await runMutationGuardAfterSuccess(ctx, guardResult, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentContent,\n resourceId: id,\n operation: 'update',\n })\n\n const response = NextResponse.json({ ok: true, updatedAt: result.updatedAt })\n return attachDocumentsOperationMetadata(response, logEntry, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentContent,\n resourceId: result.id,\n })\n } catch (error) {\n return handleDocumentsRouteError(error, 'documents.content.put')\n }\n}\n\nexport const openApi: OpenApiRouteDoc = withDocumentsContextErrors({\n tag: 'Documents',\n summary: 'Document content',\n pathParams: z.object({ id: z.string().uuid() }),\n methods: {\n GET: {\n summary: 'Get document content',\n responses: [{ status: 200, description: 'Document content', schema: contentResponseSchema }],\n errors: [\n { status: 401, description: 'Unauthorized', schema: routeErrorSchema },\n { status: 403, description: 'Forbidden', schema: routeErrorSchema },\n { status: 404, description: 'Not found', schema: routeErrorSchema },\n { status: 413, description: 'Stored document content exceeds the safe resource bound', schema: routeErrorSchema },\n ],\n },\n PUT: {\n summary: 'Update document content',\n requestBody: { contentType: 'application/json', schema: documentContentPutSchema },\n responses: [{ status: 200, description: 'Content persisted', schema: contentPutResponseSchema }],\n errors: [\n { status: 400, description: 'Validation failed', schema: routeErrorSchema },\n { status: 401, description: 'Unauthorized', schema: routeErrorSchema },\n { status: 403, description: 'Forbidden', schema: routeErrorSchema },\n { status: 409, description: 'Content changed since it was loaded', schema: routeErrorSchema },\n { status: 413, description: 'Document content exceeds the safe resource bound', schema: routeErrorSchema },\n ],\n },\n },\n})\n\nexport default { GET, PUT }\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,kBAAkB;AAC3B,SAAS,SAAS;AAElB,S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AK,IAAI;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { randomUUID } from 'node:crypto'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { documentContentPutSchema } from '../../../data/validators'\nimport { DOCUMENTS_ENTITY_IDS } from '../../../lib/constants'\nimport { assertTier } from '../../../lib/permissions'\nimport { loadDocumentContent } from '../../../lib/contentService'\nimport { assertDocumentContentResourceLimits } from '../../../lib/resourceLimits'\nimport { DOCUMENTS_JSON_BODY_LIMITS } from '../../../lib/requestBody'\nimport type {\n ReplaceDocumentContentCommandInput,\n ReplaceDocumentContentCommandResult,\n} from '../../../commands/content'\nimport {\n assertDocumentId,\n assertDocumentNotArchived,\n handleDocumentsRouteError,\n readBody,\n resolveDocumentsContext,\n routeErrorSchema,\n runMutationGuardAfterSuccess,\n serializeContent,\n validateMutationGuard,\n withDocumentsContextErrors,\n} from '../../_shared'\nimport {\n attachDocumentsOperationMetadata,\n buildDocumentsCommandRuntimeContext,\n resolveDocumentsCommandBus,\n} from '../../_commands'\n\ntype RouteContext = {\n params: Promise<{ id: string }> | { id: string }\n}\n\nconst contentResponseSchema = z.object({\n contentHtml: z.string(),\n contentText: z.string(),\n updatedAt: z.string().nullable(),\n})\n\nconst contentPutResponseSchema = z.object({\n ok: z.boolean(),\n updatedAt: z.string().nullable(),\n})\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['documents.view'] },\n PUT: { requireAuth: true, requireFeatures: ['documents.edit'] },\n}\n\nasync function resolveId(context: RouteContext): Promise<string> {\n const params = await context.params\n return params.id\n}\n\nexport async function GET(request: Request, context: RouteContext): Promise<Response> {\n try {\n const id = await resolveId(context)\n const ctx = await resolveDocumentsContext(request, ['documents.view'])\n assertDocumentId(id)\n await assertTier(ctx.em, id, ctx.auth, 'viewer')\n const content = await loadDocumentContent(ctx.em, id, {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n })\n assertDocumentContentResourceLimits({\n yjsState: content?.yjsState,\n contentHtml: content?.contentHtml,\n contentText: content?.contentText,\n })\n return NextResponse.json(serializeContent(content))\n } catch (error) {\n return handleDocumentsRouteError(error, 'documents.content.get')\n }\n}\n\nexport async function PUT(request: Request, context: RouteContext): Promise<Response> {\n try {\n const id = await resolveId(context)\n const ctx = await resolveDocumentsContext(request, ['documents.edit'])\n await assertTier(ctx.em, id, ctx.auth, 'editor')\n await assertDocumentNotArchived(ctx, id)\n const input = documentContentPutSchema.parse(await readBody(\n request,\n DOCUMENTS_JSON_BODY_LIMITS.content,\n ))\n const guardResult = await validateMutationGuard(ctx, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentContent,\n resourceId: id,\n operation: 'update',\n mutationPayload: input,\n mutationPayloadSchema: documentContentPutSchema,\n })\n const scope = { tenantId: ctx.tenantId, organizationId: ctx.organizationId }\n const currentContent = await loadDocumentContent(ctx.em, id, scope)\n const commandInput: ReplaceDocumentContentCommandInput = {\n ...input,\n documentId: id,\n contentId: currentContent?.id ?? randomUUID(),\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n }\n const { result, logEntry } = await resolveDocumentsCommandBus(ctx).execute<\n ReplaceDocumentContentCommandInput,\n ReplaceDocumentContentCommandResult\n >('documents.content.replace', {\n input: commandInput,\n ctx: buildDocumentsCommandRuntimeContext(ctx),\n })\n await runMutationGuardAfterSuccess(ctx, guardResult, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentContent,\n resourceId: id,\n operation: 'update',\n })\n\n const response = NextResponse.json({ ok: true, updatedAt: result.updatedAt })\n return attachDocumentsOperationMetadata(response, logEntry, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentContent,\n resourceId: result.id,\n })\n } catch (error) {\n return handleDocumentsRouteError(error, 'documents.content.put')\n }\n}\n\nexport const openApi: OpenApiRouteDoc = withDocumentsContextErrors({\n tag: 'Documents',\n summary: 'Document content',\n pathParams: z.object({ id: z.string().uuid() }),\n methods: {\n GET: {\n summary: 'Get document content',\n responses: [{ status: 200, description: 'Document content', schema: contentResponseSchema }],\n errors: [\n { status: 401, description: 'Unauthorized', schema: routeErrorSchema },\n { status: 403, description: 'Forbidden', schema: routeErrorSchema },\n { status: 404, description: 'Not found', schema: routeErrorSchema },\n { status: 413, description: 'Stored document content exceeds the safe resource bound', schema: routeErrorSchema },\n ],\n },\n PUT: {\n summary: 'Update document content',\n requestBody: { contentType: 'application/json', schema: documentContentPutSchema },\n responses: [{ status: 200, description: 'Content persisted', schema: contentPutResponseSchema }],\n errors: [\n { status: 400, description: 'Validation failed', schema: routeErrorSchema },\n { status: 401, description: 'Unauthorized', schema: routeErrorSchema },\n { status: 403, description: 'Forbidden', schema: routeErrorSchema },\n { status: 409, description: 'Content changed since it was loaded', schema: routeErrorSchema },\n { status: 413, description: 'Document content exceeds the safe resource bound', schema: routeErrorSchema },\n ],\n },\n },\n})\n\nexport default { GET, PUT }\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,kBAAkB;AAC3B,SAAS,SAAS;AAElB,SAAS,gCAAgC;AACzC,SAAS,4BAA4B;AACrC,SAAS,kBAAkB;AAC3B,SAAS,2BAA2B;AACpC,SAAS,2CAA2C;AACpD,SAAS,kCAAkC;AAK3C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAMP,MAAM,wBAAwB,EAAE,OAAO;AAAA,EACrC,aAAa,EAAE,OAAO;AAAA,EACtB,aAAa,EAAE,OAAO;AAAA,EACtB,WAAW,EAAE,OAAO,EAAE,SAAS;AACjC,CAAC;AAED,MAAM,2BAA2B,EAAE,OAAO;AAAA,EACxC,IAAI,EAAE,QAAQ;AAAA,EACd,WAAW,EAAE,OAAO,EAAE,SAAS;AACjC,CAAC;AAEM,MAAM,WAAW;AAAA,EACtB,KAA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AAa,aAAa,QAAQ,iBAAiB;AAAA,QAClE,EAAE,QAAQ,KAAK,aAAa,2DAA2D,QAAQ,iBAAiB;AAAA,MAClH;AAAA,IACF;AAAA,IACA,KAAK;AAAA,MACH,SAAS;AAAA,MACT,aAAa,EAAE,aAAa,oBAAoB,QAAQ,yBAAyB;AAAA,MACjF,WAAW,CAAC,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,yBAAyB,CAAC;AAAA,MAC/F,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,iBAAiB;AAAA,QAC1E,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,iBAAiB;AAAA,QACrE,EAAE,QAAQ,KAAK,aAAa,aAAa,QAAQ,iBAAiB;AAAA,QAClE,EAAE,QAAQ,KAAK,aAAa,uCAAuC,QAAQ,iBAAiB;AAAA,QAC5F,EAAE,QAAQ,KAAK,aAAa,oDAAoD,QAAQ,iBAAiB;AAAA,MAC3G;AAAA,IACF;AAAA,EACF;AACF,CAAC;AAED,IAAO,gBAAQ,EAAE,KAAK,IAAI;",
6
6
  "names": []
7
7
  }
@@ -76,6 +76,9 @@ async function GET(request, context) {
76
76
  try {
77
77
  const id = await resolveId(context);
78
78
  const ctx = await resolveDocumentsContext(request, ["documents.view"]);
79
+ if (!z.string().uuid().safeParse(id).success) {
80
+ throw new CrudHttpError(404, { error: "documents.documents.notFound" });
81
+ }
79
82
  const projection = await resolveDocumentCapabilityProjection(ctx, id);
80
83
  if (!projection.relationshipTier && await isRemovedDocumentVisibleToActor(ctx, id)) {
81
84
  throw new CrudHttpError(404, { error: "documents.documents.notFound" });
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/documents/api/%5Bid%5D/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { documentUpdateSchema } from '../../data/validators'\nimport { DOCUMENTS_ENTITY_IDS } from '../../lib/constants'\nimport { deriveDocumentCapabilities } from '../../lib/capabilities'\nimport { isDocumentFavorite } from '../../lib/favorites'\nimport { isDocumentWatched } from '../../lib/watchers'\nimport {\n assertDocumentNotArchived,\n handleDocumentsRouteError,\n hasDocumentsFeature,\n isRemovedDocumentVisibleToActor,\n loadScopedDocument,\n readBody,\n resolveActorUserId,\n resolveDocumentCapabilityProjection,\n resolveDocumentsContext,\n routeErrorSchema,\n runMutationGuardAfterSuccess,\n serializeDocument,\n validateMutationGuard,\n withDocumentsContextErrors,\n} from '../_shared'\nimport {\n attachDocumentsOperationMetadata,\n buildDocumentsCommandRuntimeContext,\n resolveDocumentsCommandBus,\n} from '../_commands'\nimport type {\n DocumentDeleteCommandInput,\n DocumentUpdateCommandInput,\n} from '../../commands/document-crud'\n\ntype RouteContext = {\n params: Promise<{ id: string }> | { id: string }\n}\n\nconst capabilitiesSchema = z.object({\n canView: z.boolean(),\n canComment: z.boolean(),\n canEdit: z.boolean(),\n canShare: z.boolean(),\n canDelete: z.boolean(),\n canCreate: z.boolean(),\n canManageTemplates: z.boolean(),\n canArchive: z.boolean(),\n canDuplicate: z.boolean(),\n})\n\nconst detailResponseSchema = z.object({\n id: z.string().uuid(),\n title: z.string(),\n folderId: z.string().uuid().nullable(),\n ownerUserId: z.string().uuid(),\n createdByUserId: z.string().uuid(),\n isActive: z.boolean(),\n archivedAt: z.string().nullable(),\n isFavorite: z.boolean(),\n isWatching: z.boolean(),\n createdAt: z.string(),\n updatedAt: z.string(),\n tier: z.enum(['owner', 'editor', 'commenter', 'viewer']),\n canShare: z.boolean(),\n capabilities: capabilitiesSchema,\n})\n\nconst mutationResponseSchema = z.object({\n id: z.string().uuid(),\n updatedAt: z.string(),\n})\n\nconst deleteResponseSchema = z.object({\n ok: z.boolean(),\n id: z.string().uuid(),\n updatedAt: z.string(),\n})\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['documents.view'] },\n PUT: { requireAuth: true, requireFeatures: ['documents.edit'] },\n DELETE: { requireAuth: true, requireFeatures: ['documents.delete'] },\n}\n\nasync function resolveId(context: RouteContext): Promise<string> {\n const params = await context.params\n return params.id\n}\n\nexport async function GET(request: Request, context: RouteContext): Promise<Response> {\n try {\n const id = await resolveId(context)\n const ctx = await resolveDocumentsContext(request, ['documents.view'])\n const projection = await resolveDocumentCapabilityProjection(ctx, id)\n if (!projection.relationshipTier && await isRemovedDocumentVisibleToActor(ctx, id)) {\n throw new CrudHttpError(404, { error: 'documents.documents.notFound' })\n }\n if (!projection.relationshipTier || !projection.capabilities.canView) {\n throw new CrudHttpError(403, { error: 'Forbidden' })\n }\n const document = await loadScopedDocument(ctx, id)\n const archivedAt = document.archivedAt?.toISOString() ?? null\n const capabilities = deriveDocumentCapabilities({\n relationshipTier: projection.relationshipTier,\n managerOverride: hasDocumentsFeature(ctx.auth, 'documents.manage'),\n archived: archivedAt !== null,\n userFeatures: ctx.auth.features,\n })\n const isFavorite = await isDocumentFavorite(\n ctx.em,\n {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n userId: resolveActorUserId(ctx.auth),\n },\n id,\n )\n const isWatching = await isDocumentWatched(\n ctx.em,\n {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n userId: resolveActorUserId(ctx.auth),\n },\n id,\n )\n return NextResponse.json({\n ...serializeDocument(document),\n archivedAt,\n isFavorite,\n isWatching,\n tier: projection.relationshipTier,\n canShare: capabilities.canShare,\n capabilities,\n })\n } catch (error) {\n return handleDocumentsRouteError(error, 'documents.detail')\n }\n}\n\nexport async function PUT(request: Request, context: RouteContext): Promise<Response> {\n try {\n const id = await resolveId(context)\n const ctx = await resolveDocumentsContext(request, ['documents.edit'])\n const projection = await resolveDocumentCapabilityProjection(ctx, id)\n if (!projection.capabilities.canEdit) {\n throw new CrudHttpError(403, { error: 'Forbidden' })\n }\n await assertDocumentNotArchived(ctx, id)\n const body = await readBody(request)\n const input = documentUpdateSchema.parse({ ...body, id })\n const guardResult = await validateMutationGuard(ctx, {\n resourceKind: DOCUMENTS_ENTITY_IDS.document,\n resourceId: id,\n operation: 'update',\n mutationPayload: input,\n mutationPayloadSchema: documentUpdateSchema,\n })\n\n const commandInput: DocumentUpdateCommandInput = {\n ...input,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n }\n const { result, logEntry } = await resolveDocumentsCommandBus(ctx).execute<\n DocumentUpdateCommandInput,\n { id: string; updatedAt: string }\n >('documents.document.update', {\n input: commandInput,\n ctx: buildDocumentsCommandRuntimeContext(ctx),\n })\n await runMutationGuardAfterSuccess(ctx, guardResult, {\n resourceKind: DOCUMENTS_ENTITY_IDS.document,\n resourceId: id,\n operation: 'update',\n })\n\n const response = NextResponse.json({ id: result.id, updatedAt: result.updatedAt })\n return attachDocumentsOperationMetadata(response, logEntry, {\n resourceKind: DOCUMENTS_ENTITY_IDS.document,\n resourceId: result.id,\n })\n } catch (error) {\n return handleDocumentsRouteError(error, 'documents.update')\n }\n}\n\nexport async function DELETE(request: Request, context: RouteContext): Promise<Response> {\n try {\n const id = await resolveId(context)\n const ctx = await resolveDocumentsContext(request, ['documents.delete'])\n const projection = await resolveDocumentCapabilityProjection(ctx, id)\n if (!projection.capabilities.canDelete) {\n throw new CrudHttpError(403, { error: 'Forbidden' })\n }\n const guardResult = await validateMutationGuard(ctx, {\n resourceKind: DOCUMENTS_ENTITY_IDS.document,\n resourceId: id,\n operation: 'delete',\n })\n\n const commandInput: DocumentDeleteCommandInput = {\n id,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n }\n const { result, logEntry } = await resolveDocumentsCommandBus(ctx).execute<\n DocumentDeleteCommandInput,\n { id: string; updatedAt: string }\n >('documents.document.delete', {\n input: commandInput,\n ctx: buildDocumentsCommandRuntimeContext(ctx),\n })\n await runMutationGuardAfterSuccess(ctx, guardResult, {\n resourceKind: DOCUMENTS_ENTITY_IDS.document,\n resourceId: id,\n operation: 'delete',\n })\n\n const response = NextResponse.json({ ok: true, id: result.id, updatedAt: result.updatedAt })\n return attachDocumentsOperationMetadata(response, logEntry, {\n resourceKind: DOCUMENTS_ENTITY_IDS.document,\n resourceId: result.id,\n })\n } catch (error) {\n return handleDocumentsRouteError(error, 'documents.delete')\n }\n}\n\nexport const openApi: OpenApiRouteDoc = withDocumentsContextErrors({\n tag: 'Documents',\n summary: 'Document detail',\n pathParams: z.object({ id: z.string().uuid() }),\n methods: {\n GET: {\n summary: 'Get document metadata',\n responses: [{ status: 200, description: 'Document metadata', schema: detailResponseSchema }],\n errors: [\n { status: 401, description: 'Unauthorized', schema: routeErrorSchema },\n { status: 403, description: 'Forbidden', schema: routeErrorSchema },\n { status: 404, description: 'Not found', schema: routeErrorSchema },\n ],\n },\n PUT: {\n summary: 'Update document metadata',\n requestBody: { contentType: 'application/json', schema: documentUpdateSchema },\n responses: [{ status: 200, description: 'Document updated', schema: mutationResponseSchema }],\n errors: [\n { status: 400, description: 'Validation failed', schema: routeErrorSchema },\n { status: 401, description: 'Unauthorized', schema: routeErrorSchema },\n { status: 403, description: 'Forbidden', schema: routeErrorSchema },\n { status: 409, description: 'Optimistic lock conflict', schema: routeErrorSchema },\n { status: 413, description: 'Request body exceeds the safe resource bound', schema: routeErrorSchema },\n ],\n },\n DELETE: {\n summary: 'Delete document',\n description: 'Transactionally releases every document-owned attachment row and its quota usage, soft-deletes the document record, then runs reference-checked provider cleanup after commit. Because attachment bytes cannot be restored, this operation is intentionally not undoable.',\n responses: [{ status: 200, description: 'Document deleted', schema: deleteResponseSchema }],\n errors: [\n { status: 401, description: 'Unauthorized', schema: routeErrorSchema },\n { status: 403, description: 'Forbidden', schema: routeErrorSchema },\n { status: 404, description: 'Not found', schema: routeErrorSchema },\n { status: 409, description: 'Optimistic lock conflict', schema: routeErrorSchema },\n ],\n },\n },\n})\n\nexport default { GET, PUT, DELETE }\n"],
5
- "mappings": "AAAA,SAAS,oB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,KAAK,aAAa,aAAa,QAAQ,iBAAiB;AAAA,QAClE,EAAE,QAAQ,KAAK,aAAa,4BAA4B,QAAQ,iBAAiB;AAAA,QACjF,EAAE,QAAQ,KAAK,aAAa,gDAAgD,QAAQ,iBAAiB;AAAA,MACvG;AAAA,IACF;AAAA,IACA,QAAQ;AAAA,MACN,SAAS;AAAA,MACT,aAAa;AAAA,MACb,WAAW,CAAC,EAAE,QAAQ,KAAK,aAAa,oBAAoB,QAAQ,qBAAqB,CAAC;AAAA,MAC1F,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,iBAAiB;AAAA,QACrE,EAAE,QAAQ,KAAK,aAAa,aAAa,QAAQ,iBAAiB;AAAA,QAClE,EAAE,QAAQ,KAAK,aAAa,aAAa,QAAQ,iBAAiB;AAAA,QAClE,EAAE,QAAQ,KAAK,aAAa,4BAA4B,QAAQ,iBAAiB;AAAA,MACnF;AAAA,IACF;AAAA,EACF;AACF,CAAC;AAED,IAAO,gBAAQ,EAAE,KAAK,KAAK,OAAO;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { documentUpdateSchema } from '../../data/validators'\nimport { DOCUMENTS_ENTITY_IDS } from '../../lib/constants'\nimport { deriveDocumentCapabilities } from '../../lib/capabilities'\nimport { isDocumentFavorite } from '../../lib/favorites'\nimport { isDocumentWatched } from '../../lib/watchers'\nimport {\n assertDocumentNotArchived,\n handleDocumentsRouteError,\n hasDocumentsFeature,\n isRemovedDocumentVisibleToActor,\n loadScopedDocument,\n readBody,\n resolveActorUserId,\n resolveDocumentCapabilityProjection,\n resolveDocumentsContext,\n routeErrorSchema,\n runMutationGuardAfterSuccess,\n serializeDocument,\n validateMutationGuard,\n withDocumentsContextErrors,\n} from '../_shared'\nimport {\n attachDocumentsOperationMetadata,\n buildDocumentsCommandRuntimeContext,\n resolveDocumentsCommandBus,\n} from '../_commands'\nimport type {\n DocumentDeleteCommandInput,\n DocumentUpdateCommandInput,\n} from '../../commands/document-crud'\n\ntype RouteContext = {\n params: Promise<{ id: string }> | { id: string }\n}\n\nconst capabilitiesSchema = z.object({\n canView: z.boolean(),\n canComment: z.boolean(),\n canEdit: z.boolean(),\n canShare: z.boolean(),\n canDelete: z.boolean(),\n canCreate: z.boolean(),\n canManageTemplates: z.boolean(),\n canArchive: z.boolean(),\n canDuplicate: z.boolean(),\n})\n\nconst detailResponseSchema = z.object({\n id: z.string().uuid(),\n title: z.string(),\n folderId: z.string().uuid().nullable(),\n ownerUserId: z.string().uuid(),\n createdByUserId: z.string().uuid(),\n isActive: z.boolean(),\n archivedAt: z.string().nullable(),\n isFavorite: z.boolean(),\n isWatching: z.boolean(),\n createdAt: z.string(),\n updatedAt: z.string(),\n tier: z.enum(['owner', 'editor', 'commenter', 'viewer']),\n canShare: z.boolean(),\n capabilities: capabilitiesSchema,\n})\n\nconst mutationResponseSchema = z.object({\n id: z.string().uuid(),\n updatedAt: z.string(),\n})\n\nconst deleteResponseSchema = z.object({\n ok: z.boolean(),\n id: z.string().uuid(),\n updatedAt: z.string(),\n})\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['documents.view'] },\n PUT: { requireAuth: true, requireFeatures: ['documents.edit'] },\n DELETE: { requireAuth: true, requireFeatures: ['documents.delete'] },\n}\n\nasync function resolveId(context: RouteContext): Promise<string> {\n const params = await context.params\n return params.id\n}\n\nexport async function GET(request: Request, context: RouteContext): Promise<Response> {\n try {\n const id = await resolveId(context)\n const ctx = await resolveDocumentsContext(request, ['documents.view'])\n if (!z.string().uuid().safeParse(id).success) {\n throw new CrudHttpError(404, { error: 'documents.documents.notFound' })\n }\n const projection = await resolveDocumentCapabilityProjection(ctx, id)\n if (!projection.relationshipTier && await isRemovedDocumentVisibleToActor(ctx, id)) {\n throw new CrudHttpError(404, { error: 'documents.documents.notFound' })\n }\n if (!projection.relationshipTier || !projection.capabilities.canView) {\n throw new CrudHttpError(403, { error: 'Forbidden' })\n }\n const document = await loadScopedDocument(ctx, id)\n const archivedAt = document.archivedAt?.toISOString() ?? null\n const capabilities = deriveDocumentCapabilities({\n relationshipTier: projection.relationshipTier,\n managerOverride: hasDocumentsFeature(ctx.auth, 'documents.manage'),\n archived: archivedAt !== null,\n userFeatures: ctx.auth.features,\n })\n const isFavorite = await isDocumentFavorite(\n ctx.em,\n {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n userId: resolveActorUserId(ctx.auth),\n },\n id,\n )\n const isWatching = await isDocumentWatched(\n ctx.em,\n {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n userId: resolveActorUserId(ctx.auth),\n },\n id,\n )\n return NextResponse.json({\n ...serializeDocument(document),\n archivedAt,\n isFavorite,\n isWatching,\n tier: projection.relationshipTier,\n canShare: capabilities.canShare,\n capabilities,\n })\n } catch (error) {\n return handleDocumentsRouteError(error, 'documents.detail')\n }\n}\n\nexport async function PUT(request: Request, context: RouteContext): Promise<Response> {\n try {\n const id = await resolveId(context)\n const ctx = await resolveDocumentsContext(request, ['documents.edit'])\n const projection = await resolveDocumentCapabilityProjection(ctx, id)\n if (!projection.capabilities.canEdit) {\n throw new CrudHttpError(403, { error: 'Forbidden' })\n }\n await assertDocumentNotArchived(ctx, id)\n const body = await readBody(request)\n const input = documentUpdateSchema.parse({ ...body, id })\n const guardResult = await validateMutationGuard(ctx, {\n resourceKind: DOCUMENTS_ENTITY_IDS.document,\n resourceId: id,\n operation: 'update',\n mutationPayload: input,\n mutationPayloadSchema: documentUpdateSchema,\n })\n\n const commandInput: DocumentUpdateCommandInput = {\n ...input,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n }\n const { result, logEntry } = await resolveDocumentsCommandBus(ctx).execute<\n DocumentUpdateCommandInput,\n { id: string; updatedAt: string }\n >('documents.document.update', {\n input: commandInput,\n ctx: buildDocumentsCommandRuntimeContext(ctx),\n })\n await runMutationGuardAfterSuccess(ctx, guardResult, {\n resourceKind: DOCUMENTS_ENTITY_IDS.document,\n resourceId: id,\n operation: 'update',\n })\n\n const response = NextResponse.json({ id: result.id, updatedAt: result.updatedAt })\n return attachDocumentsOperationMetadata(response, logEntry, {\n resourceKind: DOCUMENTS_ENTITY_IDS.document,\n resourceId: result.id,\n })\n } catch (error) {\n return handleDocumentsRouteError(error, 'documents.update')\n }\n}\n\nexport async function DELETE(request: Request, context: RouteContext): Promise<Response> {\n try {\n const id = await resolveId(context)\n const ctx = await resolveDocumentsContext(request, ['documents.delete'])\n const projection = await resolveDocumentCapabilityProjection(ctx, id)\n if (!projection.capabilities.canDelete) {\n throw new CrudHttpError(403, { error: 'Forbidden' })\n }\n const guardResult = await validateMutationGuard(ctx, {\n resourceKind: DOCUMENTS_ENTITY_IDS.document,\n resourceId: id,\n operation: 'delete',\n })\n\n const commandInput: DocumentDeleteCommandInput = {\n id,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n }\n const { result, logEntry } = await resolveDocumentsCommandBus(ctx).execute<\n DocumentDeleteCommandInput,\n { id: string; updatedAt: string }\n >('documents.document.delete', {\n input: commandInput,\n ctx: buildDocumentsCommandRuntimeContext(ctx),\n })\n await runMutationGuardAfterSuccess(ctx, guardResult, {\n resourceKind: DOCUMENTS_ENTITY_IDS.document,\n resourceId: id,\n operation: 'delete',\n })\n\n const response = NextResponse.json({ ok: true, id: result.id, updatedAt: result.updatedAt })\n return attachDocumentsOperationMetadata(response, logEntry, {\n resourceKind: DOCUMENTS_ENTITY_IDS.document,\n resourceId: result.id,\n })\n } catch (error) {\n return handleDocumentsRouteError(error, 'documents.delete')\n }\n}\n\nexport const openApi: OpenApiRouteDoc = withDocumentsContextErrors({\n tag: 'Documents',\n summary: 'Document detail',\n pathParams: z.object({ id: z.string().uuid() }),\n methods: {\n GET: {\n summary: 'Get document metadata',\n responses: [{ status: 200, description: 'Document metadata', schema: detailResponseSchema }],\n errors: [\n { status: 401, description: 'Unauthorized', schema: routeErrorSchema },\n { status: 403, description: 'Forbidden', schema: routeErrorSchema },\n { status: 404, description: 'Not found', schema: routeErrorSchema },\n ],\n },\n PUT: {\n summary: 'Update document metadata',\n requestBody: { contentType: 'application/json', schema: documentUpdateSchema },\n responses: [{ status: 200, description: 'Document updated', schema: mutationResponseSchema }],\n errors: [\n { status: 400, description: 'Validation failed', schema: routeErrorSchema },\n { status: 401, description: 'Unauthorized', schema: routeErrorSchema },\n { status: 403, description: 'Forbidden', schema: routeErrorSchema },\n { status: 409, description: 'Optimistic lock conflict', schema: routeErrorSchema },\n { status: 413, description: 'Request body exceeds the safe resource bound', schema: routeErrorSchema },\n ],\n },\n DELETE: {\n summary: 'Delete document',\n description: 'Transactionally releases every document-owned attachment row and its quota usage, soft-deletes the document record, then runs reference-checked provider cleanup after commit. Because attachment bytes cannot be restored, this operation is intentionally not undoable.',\n responses: [{ status: 200, description: 'Document deleted', schema: deleteResponseSchema }],\n errors: [\n { status: 401, description: 'Unauthorized', schema: routeErrorSchema },\n { status: 403, description: 'Forbidden', schema: routeErrorSchema },\n { status: 404, description: 'Not found', schema: routeErrorSchema },\n { status: 409, description: 'Optimistic lock conflict', schema: routeErrorSchema },\n ],\n },\n },\n})\n\nexport default { GET, PUT, DELETE }\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,qBAAqB;AAC9B,SAAS,4BAA4B;AACrC,SAAS,4BAA4B;AACrC,SAAS,kCAAkC;AAC3C,SAAS,0BAA0B;AACnC,SAAS,yBAAyB;AAClC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAUP,MAAM,qBAAqB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AW,CAAC,EAAE,QAAQ,KAAK,aAAa,oBAAoB,QAAQ,qBAAqB,CAAC;AAAA,MAC1F,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,iBAAiB;AAAA,QACrE,EAAE,QAAQ,KAAK,aAAa,aAAa,QAAQ,iBAAiB;AAAA,QAClE,EAAE,QAAQ,KAAK,aAAa,aAAa,QAAQ,iBAAiB;AAAA,QAClE,EAAE,QAAQ,KAAK,aAAa,4BAA4B,QAAQ,iBAAiB;AAAA,MACnF;AAAA,IACF;AAAA,EACF;AACF,CAAC;AAED,IAAO,gBAAQ,EAAE,KAAK,KAAK,OAAO;",
6
6
  "names": []
7
7
  }
@@ -16,6 +16,7 @@ import {
16
16
  resolveDocumentsCommandBus
17
17
  } from "../../_commands.js";
18
18
  import {
19
+ assertDocumentId,
19
20
  assertDocumentNotArchived,
20
21
  handleDocumentsRouteError,
21
22
  loadScopedShare,
@@ -106,6 +107,7 @@ async function GET(request, context) {
106
107
  try {
107
108
  const documentId = await resolveId(context);
108
109
  const ctx = await resolveDocumentsContext(request, ["documents.share"]);
110
+ assertDocumentId(documentId);
109
111
  await assertCanShare(ctx, documentId);
110
112
  const loadedShares = await findWithDecryption(
111
113
  ctx.em,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/modules/documents/api/%5Bid%5D/shares/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { randomUUID } from 'node:crypto'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { enforceCommandOptimisticLockWithGuards } from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { DocumentShare } from '../../../data/entities'\nimport { documentShareCreateSchema, documentShareUpdateSchema } from '../../../data/validators'\nimport { DOCUMENTS_ENTITY_IDS, DOCUMENTS_MAX_LISTED_SHARES } from '../../../lib/constants'\nimport { sanitizeDocumentsDisplayLabel } from '../../../lib/displayLabels'\nimport { resolveUserLabels } from '../../../lib/userLabels'\nimport { resolveAuthPrincipalService } from '../../../lib/platformServices'\nimport type {\n ShareCreateCommandInput,\n ShareDeleteCommandInput,\n ShareUpdateCommandInput,\n ShareCommandResult,\n} from '../../../commands/shares'\nimport {\n attachDocumentsOperationMetadata,\n buildDocumentsCommandRuntimeContext,\n resolveDocumentsCommandBus,\n} from '../../_commands'\nimport {\n assertDocumentNotArchived,\n handleDocumentsRouteError,\n loadScopedShare,\n readBody,\n resolveActorUserId,\n resolveDocumentCapabilityProjection,\n resolveDocumentsContext,\n routeErrorSchema,\n runMutationGuardAfterSuccess,\n serializeShare,\n validateMutationGuard,\n withDocumentsContextErrors,\n} from '../../_shared'\n\ntype RouteContext = {\n params: Promise<{ id: string }> | { id: string }\n}\n\nconst shareDeleteSchema = z.object({\n id: z.string().uuid(),\n})\n\nconst shareListResponseSchema = z.object({\n items: z.array(z.object({\n id: z.string().uuid(),\n documentId: z.string().uuid(),\n principalType: z.enum(['user', 'role']),\n principalId: z.string().uuid(),\n permission: z.enum(['viewer', 'commenter', 'editor']),\n createdByUserId: z.string().uuid(),\n createdAt: z.string(),\n updatedAt: z.string(),\n principalLabel: z.string().nullable(),\n principalSecondary: z.string().nullable(),\n })),\n truncated: z.boolean(),\n})\n\nconst shareMutationResponseSchema = z.object({\n id: z.string().uuid(),\n updatedAt: z.string(),\n})\n\nconst shareDeleteResponseSchema = z.object({\n ok: z.boolean(),\n id: z.string().uuid(),\n updatedAt: z.string(),\n})\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['documents.share'] },\n POST: { requireAuth: true, requireFeatures: ['documents.share'] },\n PUT: { requireAuth: true, requireFeatures: ['documents.share'] },\n DELETE: { requireAuth: true, requireFeatures: ['documents.share'] },\n}\n\nasync function resolveId(context: RouteContext): Promise<string> {\n const params = await context.params\n return params.id\n}\n\nasync function assertCanShare(\n ctx: Awaited<ReturnType<typeof resolveDocumentsContext>>,\n documentId: string,\n): Promise<void> {\n const projection = await resolveDocumentCapabilityProjection(ctx, documentId)\n if (!projection.capabilities.canShare) {\n throw new CrudHttpError(403, { error: 'Forbidden' })\n }\n}\n\nasync function assertCanMutateShares(\n ctx: Awaited<ReturnType<typeof resolveDocumentsContext>>,\n documentId: string,\n): Promise<void> {\n await assertCanShare(ctx, documentId)\n await assertDocumentNotArchived(ctx, documentId)\n}\n\ntype PrincipalLabel = { label: string; secondary?: string | null }\n\nfunction cleanString(value: unknown): string | null {\n return sanitizeDocumentsDisplayLabel(value)\n}\n\nasync function resolvePrincipalLabels(\n container: Awaited<ReturnType<typeof resolveDocumentsContext>>['container'],\n scope: { tenantId: string; organizationId: string },\n shares: DocumentShare[],\n): Promise<Map<string, PrincipalLabel>> {\n const labels = new Map<string, PrincipalLabel>()\n const userIds = [...new Set(shares.filter((s) => s.principalType === 'user').map((s) => s.principalId))]\n const roleIds = [...new Set(shares.filter((s) => s.principalType === 'role').map((s) => s.principalId))]\n\n if (userIds.length > 0) {\n const userLabels = await resolveUserLabels(container, scope, userIds)\n for (const [userId, label] of userLabels.entries()) {\n labels.set(userId, label)\n }\n }\n\n if (roleIds.length > 0) {\n const roles = await resolveAuthPrincipalService(container)?.resolveLabels({\n type: 'role', ids: roleIds, scope,\n }) ?? []\n for (const role of roles) {\n const name = cleanString(role.label)\n if (name) labels.set(role.id, { label: name, secondary: null })\n }\n }\n\n return labels\n}\n\nexport async function GET(request: Request, context: RouteContext): Promise<Response> {\n try {\n const documentId = await resolveId(context)\n const ctx = await resolveDocumentsContext(request, ['documents.share'])\n await assertCanShare(ctx, documentId)\n const loadedShares = await findWithDecryption(\n ctx.em,\n DocumentShare,\n {\n documentId,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n deletedAt: null,\n },\n { orderBy: { createdAt: 'ASC', id: 'ASC' }, limit: DOCUMENTS_MAX_LISTED_SHARES + 1 },\n { tenantId: ctx.tenantId, organizationId: ctx.organizationId },\n )\n const truncated = loadedShares.length > DOCUMENTS_MAX_LISTED_SHARES\n const shares = loadedShares.slice(0, DOCUMENTS_MAX_LISTED_SHARES)\n const labels = await resolvePrincipalLabels(\n ctx.container,\n { tenantId: ctx.tenantId, organizationId: ctx.organizationId },\n shares,\n )\n const items = shares.map((share) => {\n const resolved = labels.get(share.principalId) ?? null\n return {\n ...serializeShare(share),\n principalLabel: resolved?.label ?? null,\n principalSecondary: resolved?.secondary ?? null,\n }\n })\n return NextResponse.json({ items, truncated })\n } catch (error) {\n return handleDocumentsRouteError(error, 'documents.shares.list')\n }\n}\n\nexport async function POST(request: Request, context: RouteContext): Promise<Response> {\n try {\n const documentId = await resolveId(context)\n const ctx = await resolveDocumentsContext(request, ['documents.share'])\n await assertCanMutateShares(ctx, documentId)\n const input = documentShareCreateSchema.parse(await readBody(request))\n const guardResourceId = `${documentId}:${input.principalType}:${input.principalId}`\n const guardResult = await validateMutationGuard(ctx, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentShare,\n resourceId: guardResourceId,\n operation: 'create',\n mutationPayload: input,\n mutationPayloadSchema: documentShareCreateSchema,\n })\n\n const existing = await findOneWithDecryption(\n ctx.em,\n DocumentShare,\n {\n documentId,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n principalType: input.principalType,\n principalId: input.principalId,\n },\n { filters: false, orderBy: { updatedAt: 'DESC' } },\n { tenantId: ctx.tenantId, organizationId: ctx.organizationId },\n )\n const commandInput: ShareCreateCommandInput = {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n documentId,\n shareId: existing?.id ?? randomUUID(),\n actorUserId: resolveActorUserId(ctx.auth),\n expectedUpdatedAt: existing?.updatedAt.toISOString() ?? null,\n share: input,\n }\n const execution = await resolveDocumentsCommandBus(ctx).execute<ShareCreateCommandInput, ShareCommandResult>(\n 'documents.share.create',\n { input: commandInput, ctx: buildDocumentsCommandRuntimeContext(ctx) },\n )\n await runMutationGuardAfterSuccess(ctx, guardResult, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentShare,\n resourceId: guardResourceId,\n operation: 'create',\n })\n\n return attachDocumentsOperationMetadata(\n NextResponse.json({ id: execution.result.id, updatedAt: execution.result.updatedAt }, { status: 201 }),\n execution.logEntry,\n { resourceKind: DOCUMENTS_ENTITY_IDS.documentShare, resourceId: execution.result.id },\n )\n } catch (error) {\n return handleDocumentsRouteError(error, 'documents.shares.create')\n }\n}\n\nexport async function PUT(request: Request, context: RouteContext): Promise<Response> {\n try {\n const documentId = await resolveId(context)\n const ctx = await resolveDocumentsContext(request, ['documents.share'])\n await assertCanMutateShares(ctx, documentId)\n const input = documentShareUpdateSchema.parse(await readBody(request))\n const share = await loadScopedShare(ctx, documentId, input.id)\n await enforceCommandOptimisticLockWithGuards(ctx.container, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentShare,\n resourceId: share.id,\n current: share.updatedAt,\n request,\n })\n const guardResult = await validateMutationGuard(ctx, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentShare,\n resourceId: share.id,\n operation: 'update',\n mutationPayload: input,\n mutationPayloadSchema: documentShareUpdateSchema,\n })\n\n const commandInput: ShareUpdateCommandInput = {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n documentId,\n actorUserId: resolveActorUserId(ctx.auth),\n expectedUpdatedAt: share.updatedAt.toISOString(),\n share: input,\n }\n const execution = await resolveDocumentsCommandBus(ctx).execute<ShareUpdateCommandInput, ShareCommandResult>(\n 'documents.share.update',\n { input: commandInput, ctx: buildDocumentsCommandRuntimeContext(ctx) },\n )\n await runMutationGuardAfterSuccess(ctx, guardResult, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentShare,\n resourceId: share.id,\n operation: 'update',\n })\n\n return attachDocumentsOperationMetadata(\n NextResponse.json({ id: execution.result.id, updatedAt: execution.result.updatedAt }),\n execution.logEntry,\n { resourceKind: DOCUMENTS_ENTITY_IDS.documentShare, resourceId: execution.result.id },\n )\n } catch (error) {\n return handleDocumentsRouteError(error, 'documents.shares.update')\n }\n}\n\nexport async function DELETE(request: Request, context: RouteContext): Promise<Response> {\n try {\n const documentId = await resolveId(context)\n const ctx = await resolveDocumentsContext(request, ['documents.share'])\n await assertCanMutateShares(ctx, documentId)\n const input = shareDeleteSchema.parse(await readBody(request))\n const share = await loadScopedShare(ctx, documentId, input.id)\n await enforceCommandOptimisticLockWithGuards(ctx.container, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentShare,\n resourceId: share.id,\n current: share.updatedAt,\n request,\n })\n const guardResult = await validateMutationGuard(ctx, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentShare,\n resourceId: share.id,\n operation: 'delete',\n })\n\n const commandInput: ShareDeleteCommandInput = {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n documentId,\n shareId: share.id,\n actorUserId: resolveActorUserId(ctx.auth),\n expectedUpdatedAt: share.updatedAt.toISOString(),\n }\n const execution = await resolveDocumentsCommandBus(ctx).execute<ShareDeleteCommandInput, ShareCommandResult>(\n 'documents.share.delete',\n { input: commandInput, ctx: buildDocumentsCommandRuntimeContext(ctx) },\n )\n await runMutationGuardAfterSuccess(ctx, guardResult, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentShare,\n resourceId: share.id,\n operation: 'delete',\n })\n\n return attachDocumentsOperationMetadata(\n NextResponse.json({ ok: true, id: execution.result.id, updatedAt: execution.result.updatedAt }),\n execution.logEntry,\n { resourceKind: DOCUMENTS_ENTITY_IDS.documentShare, resourceId: execution.result.id },\n )\n } catch (error) {\n return handleDocumentsRouteError(error, 'documents.shares.delete')\n }\n}\n\nexport const openApi: OpenApiRouteDoc = withDocumentsContextErrors({\n tag: 'Documents',\n summary: 'Document shares',\n pathParams: z.object({ id: z.string().uuid() }),\n methods: {\n GET: {\n summary: 'List document shares',\n responses: [{ status: 200, description: 'Document shares', schema: shareListResponseSchema }],\n errors: [{ status: 403, description: 'Forbidden', schema: routeErrorSchema }],\n },\n POST: {\n summary: 'Share document',\n requestBody: { contentType: 'application/json', schema: documentShareCreateSchema },\n responses: [{ status: 201, description: 'Document shared', schema: shareMutationResponseSchema }],\n errors: [\n { status: 400, description: 'Validation failed', schema: routeErrorSchema },\n { status: 413, description: 'Request body exceeds the safe resource bound', schema: routeErrorSchema },\n ],\n },\n PUT: {\n summary: 'Update document share',\n requestBody: { contentType: 'application/json', schema: documentShareUpdateSchema },\n responses: [{ status: 200, description: 'Share updated', schema: shareMutationResponseSchema }],\n errors: [\n { status: 409, description: 'Optimistic lock conflict', schema: routeErrorSchema },\n { status: 413, description: 'Request body exceeds the safe resource bound', schema: routeErrorSchema },\n ],\n },\n DELETE: {\n summary: 'Remove document share',\n requestBody: { contentType: 'application/json', schema: shareDeleteSchema },\n responses: [{ status: 200, description: 'Share removed', schema: shareDeleteResponseSchema }],\n errors: [\n { status: 409, description: 'Optimistic lock conflict', schema: routeErrorSchema },\n { status: 413, description: 'Request body exceeds the safe resource bound', schema: routeErrorSchema },\n ],\n },\n },\n})\n\nexport default { GET, POST, PUT, DELETE }\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,kBAAkB;AAG3B,SAAS,8CAA8C;AACvD,SAAS,qBAAqB;AAC9B,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B,iCAAiC;AACrE,SAAS,sBAAsB,mCAAmC;AAClE,SAAS,qCAAqC;AAC9C,SAAS,yBAAyB;AAClC,SAAS,mCAAmC;AAO5C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AA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S;AAAA,MACT,aAAa,EAAE,aAAa,oBAAoB,QAAQ,kBAAkB;AAAA,MAC1E,WAAW,CAAC,EAAE,QAAQ,KAAK,aAAa,iBAAiB,QAAQ,0BAA0B,CAAC;AAAA,MAC5F,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,4BAA4B,QAAQ,iBAAiB;AAAA,QACjF,EAAE,QAAQ,KAAK,aAAa,gDAAgD,QAAQ,iBAAiB;AAAA,MACvG;AAAA,IACF;AAAA,EACF;AACF,CAAC;AAED,IAAO,gBAAQ,EAAE,KAAK,MAAM,KAAK,OAAO;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { randomUUID } from 'node:crypto'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { enforceCommandOptimisticLockWithGuards } from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { DocumentShare } from '../../../data/entities'\nimport { documentShareCreateSchema, documentShareUpdateSchema } from '../../../data/validators'\nimport { DOCUMENTS_ENTITY_IDS, DOCUMENTS_MAX_LISTED_SHARES } from '../../../lib/constants'\nimport { sanitizeDocumentsDisplayLabel } from '../../../lib/displayLabels'\nimport { resolveUserLabels } from '../../../lib/userLabels'\nimport { resolveAuthPrincipalService } from '../../../lib/platformServices'\nimport type {\n ShareCreateCommandInput,\n ShareDeleteCommandInput,\n ShareUpdateCommandInput,\n ShareCommandResult,\n} from '../../../commands/shares'\nimport {\n attachDocumentsOperationMetadata,\n buildDocumentsCommandRuntimeContext,\n resolveDocumentsCommandBus,\n} from '../../_commands'\nimport {\n assertDocumentId,\n assertDocumentNotArchived,\n handleDocumentsRouteError,\n loadScopedShare,\n readBody,\n resolveActorUserId,\n resolveDocumentCapabilityProjection,\n resolveDocumentsContext,\n routeErrorSchema,\n runMutationGuardAfterSuccess,\n serializeShare,\n validateMutationGuard,\n withDocumentsContextErrors,\n} from '../../_shared'\n\ntype RouteContext = {\n params: Promise<{ id: string }> | { id: string }\n}\n\nconst shareDeleteSchema = z.object({\n id: z.string().uuid(),\n})\n\nconst shareListResponseSchema = z.object({\n items: z.array(z.object({\n id: z.string().uuid(),\n documentId: z.string().uuid(),\n principalType: z.enum(['user', 'role']),\n principalId: z.string().uuid(),\n permission: z.enum(['viewer', 'commenter', 'editor']),\n createdByUserId: z.string().uuid(),\n createdAt: z.string(),\n updatedAt: z.string(),\n principalLabel: z.string().nullable(),\n principalSecondary: z.string().nullable(),\n })),\n truncated: z.boolean(),\n})\n\nconst shareMutationResponseSchema = z.object({\n id: z.string().uuid(),\n updatedAt: z.string(),\n})\n\nconst shareDeleteResponseSchema = z.object({\n ok: z.boolean(),\n id: z.string().uuid(),\n updatedAt: z.string(),\n})\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['documents.share'] },\n POST: { requireAuth: true, requireFeatures: ['documents.share'] },\n PUT: { requireAuth: true, requireFeatures: ['documents.share'] },\n DELETE: { requireAuth: true, requireFeatures: ['documents.share'] },\n}\n\nasync function resolveId(context: RouteContext): Promise<string> {\n const params = await context.params\n return params.id\n}\n\nasync function assertCanShare(\n ctx: Awaited<ReturnType<typeof resolveDocumentsContext>>,\n documentId: string,\n): Promise<void> {\n const projection = await resolveDocumentCapabilityProjection(ctx, documentId)\n if (!projection.capabilities.canShare) {\n throw new CrudHttpError(403, { error: 'Forbidden' })\n }\n}\n\nasync function assertCanMutateShares(\n ctx: Awaited<ReturnType<typeof resolveDocumentsContext>>,\n documentId: string,\n): Promise<void> {\n await assertCanShare(ctx, documentId)\n await assertDocumentNotArchived(ctx, documentId)\n}\n\ntype PrincipalLabel = { label: string; secondary?: string | null }\n\nfunction cleanString(value: unknown): string | null {\n return sanitizeDocumentsDisplayLabel(value)\n}\n\nasync function resolvePrincipalLabels(\n container: Awaited<ReturnType<typeof resolveDocumentsContext>>['container'],\n scope: { tenantId: string; organizationId: string },\n shares: DocumentShare[],\n): Promise<Map<string, PrincipalLabel>> {\n const labels = new Map<string, PrincipalLabel>()\n const userIds = [...new Set(shares.filter((s) => s.principalType === 'user').map((s) => s.principalId))]\n const roleIds = [...new Set(shares.filter((s) => s.principalType === 'role').map((s) => s.principalId))]\n\n if (userIds.length > 0) {\n const userLabels = await resolveUserLabels(container, scope, userIds)\n for (const [userId, label] of userLabels.entries()) {\n labels.set(userId, label)\n }\n }\n\n if (roleIds.length > 0) {\n const roles = await resolveAuthPrincipalService(container)?.resolveLabels({\n type: 'role', ids: roleIds, scope,\n }) ?? []\n for (const role of roles) {\n const name = cleanString(role.label)\n if (name) labels.set(role.id, { label: name, secondary: null })\n }\n }\n\n return labels\n}\n\nexport async function GET(request: Request, context: RouteContext): Promise<Response> {\n try {\n const documentId = await resolveId(context)\n const ctx = await resolveDocumentsContext(request, ['documents.share'])\n assertDocumentId(documentId)\n await assertCanShare(ctx, documentId)\n const loadedShares = await findWithDecryption(\n ctx.em,\n DocumentShare,\n {\n documentId,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n deletedAt: null,\n },\n { orderBy: { createdAt: 'ASC', id: 'ASC' }, limit: DOCUMENTS_MAX_LISTED_SHARES + 1 },\n { tenantId: ctx.tenantId, organizationId: ctx.organizationId },\n )\n const truncated = loadedShares.length > DOCUMENTS_MAX_LISTED_SHARES\n const shares = loadedShares.slice(0, DOCUMENTS_MAX_LISTED_SHARES)\n const labels = await resolvePrincipalLabels(\n ctx.container,\n { tenantId: ctx.tenantId, organizationId: ctx.organizationId },\n shares,\n )\n const items = shares.map((share) => {\n const resolved = labels.get(share.principalId) ?? null\n return {\n ...serializeShare(share),\n principalLabel: resolved?.label ?? null,\n principalSecondary: resolved?.secondary ?? null,\n }\n })\n return NextResponse.json({ items, truncated })\n } catch (error) {\n return handleDocumentsRouteError(error, 'documents.shares.list')\n }\n}\n\nexport async function POST(request: Request, context: RouteContext): Promise<Response> {\n try {\n const documentId = await resolveId(context)\n const ctx = await resolveDocumentsContext(request, ['documents.share'])\n await assertCanMutateShares(ctx, documentId)\n const input = documentShareCreateSchema.parse(await readBody(request))\n const guardResourceId = `${documentId}:${input.principalType}:${input.principalId}`\n const guardResult = await validateMutationGuard(ctx, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentShare,\n resourceId: guardResourceId,\n operation: 'create',\n mutationPayload: input,\n mutationPayloadSchema: documentShareCreateSchema,\n })\n\n const existing = await findOneWithDecryption(\n ctx.em,\n DocumentShare,\n {\n documentId,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n principalType: input.principalType,\n principalId: input.principalId,\n },\n { filters: false, orderBy: { updatedAt: 'DESC' } },\n { tenantId: ctx.tenantId, organizationId: ctx.organizationId },\n )\n const commandInput: ShareCreateCommandInput = {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n documentId,\n shareId: existing?.id ?? randomUUID(),\n actorUserId: resolveActorUserId(ctx.auth),\n expectedUpdatedAt: existing?.updatedAt.toISOString() ?? null,\n share: input,\n }\n const execution = await resolveDocumentsCommandBus(ctx).execute<ShareCreateCommandInput, ShareCommandResult>(\n 'documents.share.create',\n { input: commandInput, ctx: buildDocumentsCommandRuntimeContext(ctx) },\n )\n await runMutationGuardAfterSuccess(ctx, guardResult, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentShare,\n resourceId: guardResourceId,\n operation: 'create',\n })\n\n return attachDocumentsOperationMetadata(\n NextResponse.json({ id: execution.result.id, updatedAt: execution.result.updatedAt }, { status: 201 }),\n execution.logEntry,\n { resourceKind: DOCUMENTS_ENTITY_IDS.documentShare, resourceId: execution.result.id },\n )\n } catch (error) {\n return handleDocumentsRouteError(error, 'documents.shares.create')\n }\n}\n\nexport async function PUT(request: Request, context: RouteContext): Promise<Response> {\n try {\n const documentId = await resolveId(context)\n const ctx = await resolveDocumentsContext(request, ['documents.share'])\n await assertCanMutateShares(ctx, documentId)\n const input = documentShareUpdateSchema.parse(await readBody(request))\n const share = await loadScopedShare(ctx, documentId, input.id)\n await enforceCommandOptimisticLockWithGuards(ctx.container, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentShare,\n resourceId: share.id,\n current: share.updatedAt,\n request,\n })\n const guardResult = await validateMutationGuard(ctx, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentShare,\n resourceId: share.id,\n operation: 'update',\n mutationPayload: input,\n mutationPayloadSchema: documentShareUpdateSchema,\n })\n\n const commandInput: ShareUpdateCommandInput = {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n documentId,\n actorUserId: resolveActorUserId(ctx.auth),\n expectedUpdatedAt: share.updatedAt.toISOString(),\n share: input,\n }\n const execution = await resolveDocumentsCommandBus(ctx).execute<ShareUpdateCommandInput, ShareCommandResult>(\n 'documents.share.update',\n { input: commandInput, ctx: buildDocumentsCommandRuntimeContext(ctx) },\n )\n await runMutationGuardAfterSuccess(ctx, guardResult, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentShare,\n resourceId: share.id,\n operation: 'update',\n })\n\n return attachDocumentsOperationMetadata(\n NextResponse.json({ id: execution.result.id, updatedAt: execution.result.updatedAt }),\n execution.logEntry,\n { resourceKind: DOCUMENTS_ENTITY_IDS.documentShare, resourceId: execution.result.id },\n )\n } catch (error) {\n return handleDocumentsRouteError(error, 'documents.shares.update')\n }\n}\n\nexport async function DELETE(request: Request, context: RouteContext): Promise<Response> {\n try {\n const documentId = await resolveId(context)\n const ctx = await resolveDocumentsContext(request, ['documents.share'])\n await assertCanMutateShares(ctx, documentId)\n const input = shareDeleteSchema.parse(await readBody(request))\n const share = await loadScopedShare(ctx, documentId, input.id)\n await enforceCommandOptimisticLockWithGuards(ctx.container, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentShare,\n resourceId: share.id,\n current: share.updatedAt,\n request,\n })\n const guardResult = await validateMutationGuard(ctx, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentShare,\n resourceId: share.id,\n operation: 'delete',\n })\n\n const commandInput: ShareDeleteCommandInput = {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n documentId,\n shareId: share.id,\n actorUserId: resolveActorUserId(ctx.auth),\n expectedUpdatedAt: share.updatedAt.toISOString(),\n }\n const execution = await resolveDocumentsCommandBus(ctx).execute<ShareDeleteCommandInput, ShareCommandResult>(\n 'documents.share.delete',\n { input: commandInput, ctx: buildDocumentsCommandRuntimeContext(ctx) },\n )\n await runMutationGuardAfterSuccess(ctx, guardResult, {\n resourceKind: DOCUMENTS_ENTITY_IDS.documentShare,\n resourceId: share.id,\n operation: 'delete',\n })\n\n return attachDocumentsOperationMetadata(\n NextResponse.json({ ok: true, id: execution.result.id, updatedAt: execution.result.updatedAt }),\n execution.logEntry,\n { resourceKind: DOCUMENTS_ENTITY_IDS.documentShare, resourceId: execution.result.id },\n )\n } catch (error) {\n return handleDocumentsRouteError(error, 'documents.shares.delete')\n }\n}\n\nexport const openApi: OpenApiRouteDoc = withDocumentsContextErrors({\n tag: 'Documents',\n summary: 'Document shares',\n pathParams: z.object({ id: z.string().uuid() }),\n methods: {\n GET: {\n summary: 'List document shares',\n responses: [{ status: 200, description: 'Document shares', schema: shareListResponseSchema }],\n errors: [{ status: 403, description: 'Forbidden', schema: routeErrorSchema }],\n },\n POST: {\n summary: 'Share document',\n requestBody: { contentType: 'application/json', schema: documentShareCreateSchema },\n responses: [{ status: 201, description: 'Document shared', schema: shareMutationResponseSchema }],\n errors: [\n { status: 400, description: 'Validation failed', schema: routeErrorSchema },\n { status: 413, description: 'Request body exceeds the safe resource bound', schema: routeErrorSchema },\n ],\n },\n PUT: {\n summary: 'Update document share',\n requestBody: { contentType: 'application/json', schema: documentShareUpdateSchema },\n responses: [{ status: 200, description: 'Share updated', schema: shareMutationResponseSchema }],\n errors: [\n { status: 409, description: 'Optimistic lock conflict', schema: routeErrorSchema },\n { status: 413, description: 'Request body exceeds the safe resource bound', schema: routeErrorSchema },\n ],\n },\n DELETE: {\n summary: 'Remove document share',\n requestBody: { contentType: 'application/json', schema: shareDeleteSchema },\n responses: [{ status: 200, description: 'Share removed', schema: shareDeleteResponseSchema }],\n errors: [\n { status: 409, description: 'Optimistic lock conflict', schema: routeErrorSchema },\n { status: 413, description: 'Request body exceeds the safe resource bound', schema: routeErrorSchema },\n ],\n },\n },\n})\n\nexport default { GET, POST, PUT, DELETE }\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,kBAAkB;AAG3B,SAAS,8CAA8C;AACvD,SAAS,qBAAqB;AAC9B,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B,iCAAiC;AACrE,SAAS,sBAAsB,mCAAmC;AAClE,SAAS,qCAAqC;AAC9C,SAAS,yBAAyB;AAClC,SAAS,mCAAmC;AAO5C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAMP,MAAM,oBAAoB,EAAE,OAAO;AAAA,EACjC,IAAI,EAAE,OAAO,EAAE,KAAK;AACtB,CAAC;AAED,MAAM,0BAA0B,EAAE,OAAO;AAAA,EACvC,OAAO,EAAE,MAAM,EAAE,OAAO;AAAA,IACtB,IAAI,EAAE,OAAO,EAAE,KAAK;AAAA,IACpB,YAAY,EAAE,OAAO,EAAE,KAAK;AAAA,IAC5B,eAAe,EAAE,KAAK,CAAC,QAAQ,MAAM,CAAC;AAAA,IACtC,aAAa,EAAE,OAAO,EAAE,KAAK;AAAA,IAC7B,YAAY,EAAE,KAAK,CAAC,UAAU,aAAa,QAAQ,CAAC;AAAA,IACpD,iBAAiB,EAAE,OAAO,EAAE,KAAK;AAAA,IACjC,WA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GE_SIZE } from "../../../lib/historyLimits.js"
8
8
  import { assertTier } from "../../../lib/permissions.js";
9
9
  import { resolveUserLabels } from "../../../lib/userLabels.js";
10
10
  import {
11
+ assertDocumentId,
11
12
  assertDocumentNotArchived,
12
13
  handleDocumentsRouteError,
13
14
  readBody,
@@ -71,6 +72,7 @@ async function GET(request, context) {
71
72
  try {
72
73
  const documentId = await resolveId(context);
73
74
  const ctx = await resolveDocumentsContext(request, ["documents.view"]);
75
+ assertDocumentId(documentId);
74
76
  await assertTier(ctx.em, documentId, ctx.auth, "viewer");
75
77
  const url = new URL(request.url);
76
78
  const query = versionListQuerySchema.parse(Object.fromEntries(url.searchParams.entries()));