@open-mercato/documents 0.11.1-develop.8983.1.8f477e3f83 → 0.11.1-develop.9003.1.ce86c31a07

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -54,6 +54,15 @@ The create-app Docker Compose templates include a `documents-collab` service on
54
54
 
55
55
  If the sidecar is unreachable (or `NEXT_PUBLIC_DOCUMENTS_COLLAB_URL` is unset), a user who still has edit capability gets an **editable single-user fallback**. It persists through the bounded content `PUT` path with the content row's optimistic-lock token, exposes explicit save status/control, and guards navigation while a save is pending. A definitive collaboration authorization rejection, revoked capability, viewer, or commenter remains read-only and fail-closed. PostgreSQL remains authoritative in both modes.
56
56
 
57
+ The editor's **Realtime unavailable** notice links to this setup guide. To enable collaboration, an administrator should:
58
+
59
+ 1. Start the sidecar using the command above (or enable the `documents-collab` Compose profile).
60
+ 2. Set `NEXT_PUBLIC_DOCUMENTS_COLLAB_URL` to the browser-reachable WebSocket endpoint before building the app. HTTPS deployments require `wss://`.
61
+ 3. Configure the same `DOCUMENTS_COLLAB_JWT_SECRET_V2` (at least 32 UTF-8 bytes) on the app and sidecar, and allow the app's browser origin with `DOCUMENTS_COLLAB_ALLOWED_ORIGINS` or `APP_URL`.
62
+ 4. Check the browser can reach the sidecar through the reverse proxy and that WebSocket upgrades are enabled. Review the sidecar logs for rejected origins or authentication failures.
63
+
64
+ After setup, save pending single-user edits before reopening the document to connect. An already connected session retries transient outages automatically; keep it open while queued changes reconnect.
65
+
57
66
  Redis replication is transport-only: the authenticated source replica owns
58
67
  persistence and publishes its exact Yjs state only after that store succeeds.
59
68
  A dedicated command-bounded publisher releases the store lock before fanout;
@@ -13,6 +13,7 @@ import { loadDocumentFavoriteIds } from "../lib/favorites.js";
13
13
  import { getEntityRegistryEntry } from "../lib/entityRegistry.js";
14
14
  import { verifyEntityRegistryTargetAccess } from "../lib/entityRegistry.server.js";
15
15
  import { isDocumentEntityRegistryModuleEnabled } from "../lib/entityRegistryAvailability.server.js";
16
+ import { assertTier } from "../lib/permissions.js";
16
17
  import {
17
18
  handleDocumentsRouteError,
18
19
  hasDocumentsFeature,
@@ -138,13 +139,19 @@ async function GET(request) {
138
139
  if (!registryEntry || !isDocumentEntityRegistryModuleEnabled(registryEntry) || !hasDocumentsFeature(ctx.auth, registryEntry.requiredFeature)) {
139
140
  throw new CrudHttpError(403, { error: "api.errors.forbidden" });
140
141
  }
141
- const verifiedTarget = await verifyEntityRegistryTargetAccess(request, {
142
- entityType: query.entityType,
143
- entityId: query.entityId
144
- });
142
+ let entityId = query.entityId;
143
+ if (query.entityType === "document") {
144
+ await assertTier(ctx.em, entityId, ctx.auth, "viewer");
145
+ } else {
146
+ const verifiedTarget = await verifyEntityRegistryTargetAccess(request, {
147
+ entityType: query.entityType,
148
+ entityId
149
+ });
150
+ entityId = verifiedTarget.id;
151
+ }
145
152
  relationFilter = {
146
153
  entityType: query.entityType,
147
- entityId: verifiedTarget.id
154
+ entityId
148
155
  };
149
156
  }
150
157
  const actorUserId = resolveActorUserId(ctx.auth);
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/documents/api/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 type { QueryEngine } from '@open-mercato/shared/lib/query/types'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { parseBooleanWithDefault } from '@open-mercato/shared/lib/boolean'\nimport { documentCreateSchema, documentEntityTypeSchema } from '../data/validators'\nimport { DOCUMENTS_ENTITY_IDS } from '../lib/constants'\nimport { resolveUserLabels } from '../lib/userLabels'\nimport { deriveDocumentCapabilities } from '../lib/capabilities'\nimport { getVisibleDocumentPage } from '../lib/visibility'\nimport { loadDocumentShareCounts } from '../lib/shareCounts'\nimport { loadDocumentFavoriteIds } from '../lib/favorites'\nimport { getEntityRegistryEntry } from '../lib/entityRegistry'\nimport { verifyEntityRegistryTargetAccess } from '../lib/entityRegistry.server'\nimport { isDocumentEntityRegistryModuleEnabled } from '../lib/entityRegistryAvailability.server'\nimport {\n handleDocumentsRouteError,\n hasDocumentsFeature,\n readBody,\n resolveActorUserId,\n resolveDocumentsContext,\n routeErrorSchema,\n runMutationGuardAfterSuccess,\n validateMutationGuard,\n withDocumentsContextErrors,\n} from './_shared'\nimport {\n attachDocumentsOperationMetadata,\n buildDocumentsCommandRuntimeContext,\n resolveDocumentsCommandBus,\n} from './_commands'\nimport type { DocumentCreateCommandInput } from '../commands/document-crud'\n\nconst listQuerySchema = z.object({\n page: z.coerce.number().int().min(1).default(1),\n pageSize: z.coerce.number().int().min(1).max(100).default(50),\n search: z.string().trim().optional(),\n id: z.string().uuid().optional(),\n archived: z.enum(['exclude', 'include', 'only']).default('exclude'),\n favorite: z.string().optional().transform((value) => parseBooleanWithDefault(value, false)),\n folderId: z.string().uuid().optional().nullable(),\n entityType: documentEntityTypeSchema.optional(),\n entityId: z.string().uuid().optional(),\n}).superRefine((query, context) => {\n if (Boolean(query.entityType) !== Boolean(query.entityId)) {\n context.addIssue({\n code: 'custom',\n message: 'documents.validation.links.entityFilterPairRequired',\n })\n }\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 collectionCapabilitiesSchema = z.object({\n canCreateDocument: z.boolean(),\n canCreateFolder: z.boolean(),\n canLinkDocuments: z.boolean(),\n canInstantiateTemplate: z.boolean(),\n canManageTemplates: z.boolean(),\n})\n\nconst documentListItemSchema = z.object({\n id: z.string().uuid(),\n title: z.string(),\n folderId: z.string().uuid().nullable(),\n ownerUserId: z.string().uuid(),\n ownerLabel: z.string().nullable(),\n createdByUserId: z.string().uuid(),\n isActive: z.boolean(),\n archivedAt: z.string().nullable(),\n isFavorite: z.boolean(),\n sharedWithCount: z.number(),\n createdAt: z.string(),\n updatedAt: z.string(),\n relationshipTier: z.enum(['owner', 'editor', 'commenter', 'viewer']).nullable(),\n capabilities: capabilitiesSchema,\n})\n\nconst listResponseSchema = z.object({\n items: z.array(documentListItemSchema),\n collectionCapabilities: collectionCapabilitiesSchema,\n total: z.number(),\n page: z.number(),\n pageSize: z.number(),\n totalPages: z.number(),\n})\n\nconst createResponseSchema = z.object({\n id: z.string().uuid(),\n updatedAt: z.string(),\n})\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['documents.view'] },\n POST: { requireAuth: true, requireFeatures: ['documents.create'] },\n}\n\nfunction readString(record: Record<string, unknown>, ...keys: string[]): string | null {\n for (const key of keys) {\n const value = record[key]\n if (typeof value === 'string' && value.length > 0) return value\n }\n return null\n}\n\nfunction readBoolean(record: Record<string, unknown>, ...keys: string[]): boolean {\n for (const key of keys) {\n if (typeof record[key] === 'boolean') return record[key] as boolean\n }\n return false\n}\n\nfunction readDate(record: Record<string, unknown>, ...keys: string[]): string {\n for (const key of keys) {\n const value = record[key]\n const date = value instanceof Date\n ? value\n : typeof value === 'string' && value.length > 0\n ? new Date(value)\n : null\n if (date && !Number.isNaN(date.getTime())) return date.toISOString()\n }\n return new Date(0).toISOString()\n}\n\nfunction readNullableDate(record: Record<string, unknown>, ...keys: string[]): string | null {\n for (const key of keys) {\n const value = record[key]\n if (value === null || value === undefined) continue\n const date = value instanceof Date\n ? value\n : typeof value === 'string' && value.length > 0\n ? new Date(value)\n : null\n if (date && !Number.isNaN(date.getTime())) return date.toISOString()\n }\n return null\n}\n\nexport async function GET(request: Request): Promise<Response> {\n try {\n const ctx = await resolveDocumentsContext(request, ['documents.view'])\n const url = new URL(request.url)\n const query = listQuerySchema.parse(Object.fromEntries(url.searchParams.entries()))\n\n let relationFilter: { entityType: z.infer<typeof documentEntityTypeSchema>; entityId: string } | null = null\n if (query.entityType && query.entityId) {\n const registryEntry = getEntityRegistryEntry(query.entityType)\n if (\n !registryEntry\n || !isDocumentEntityRegistryModuleEnabled(registryEntry)\n || !hasDocumentsFeature(ctx.auth, registryEntry.requiredFeature)\n ) {\n throw new CrudHttpError(403, { error: 'api.errors.forbidden' })\n }\n const verifiedTarget = await verifyEntityRegistryTargetAccess(request, {\n entityType: query.entityType,\n entityId: query.entityId,\n })\n relationFilter = {\n entityType: query.entityType,\n entityId: verifiedTarget.id,\n }\n }\n\n const actorUserId = resolveActorUserId(ctx.auth)\n const managerOverride = hasDocumentsFeature(ctx.auth, 'documents.manage')\n const visiblePage = await getVisibleDocumentPage({\n em: ctx.em,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n userId: actorUserId,\n roleIds: ctx.auth.roleIds,\n managerOverride,\n page: query.page,\n pageSize: query.pageSize,\n id: query.id ?? null,\n archived: query.archived,\n favoriteUserId: query.favorite ? actorUserId : null,\n search: query.search ?? null,\n folderId: query.folderId ?? null,\n relationFilter,\n })\n const orderedIds = visiblePage.rows.map((row) => row.id)\n const queryEngine = ctx.container.resolve('queryEngine') as QueryEngine\n const hydration = orderedIds.length > 0\n ? await queryEngine.query<Record<string, unknown>>(DOCUMENTS_ENTITY_IDS.document, {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n filters: { id: { $in: orderedIds } },\n page: { page: 1, pageSize: orderedIds.length },\n extensions: {\n userId: actorUserId,\n container: ctx.container,\n userFeatures: ctx.auth.features,\n resolve: <T = unknown>(name: string) => ctx.container.resolve(name) as T,\n },\n })\n : { items: [] as Record<string, unknown>[] }\n const hydratedById = new Map(\n hydration.items\n .map((item) => [readString(item, 'id'), item] as const)\n .filter((entry): entry is readonly [string, Record<string, unknown>] => entry[0] !== null),\n )\n const pageDocuments = orderedIds\n .map((id) => hydratedById.get(id) ?? null)\n .filter((item): item is Record<string, unknown> => item !== null)\n const ownerLabels = await resolveUserLabels(\n ctx.container,\n { tenantId: ctx.tenantId, organizationId: ctx.organizationId },\n pageDocuments\n .map((document) => readString(document, 'ownerUserId', 'owner_user_id'))\n .filter((id): id is string => id !== null),\n )\n const shareCounts = await loadDocumentShareCounts(\n ctx.em,\n { tenantId: ctx.tenantId, organizationId: ctx.organizationId },\n orderedIds,\n )\n const favoriteDocumentIds = await loadDocumentFavoriteIds(\n ctx.em,\n { tenantId: ctx.tenantId, organizationId: ctx.organizationId, userId: actorUserId },\n orderedIds,\n )\n const visibleRowsById = new Map(visiblePage.rows.map((row) => [row.id, row]))\n const items = pageDocuments.map((document) => {\n const id = readString(document, 'id') ?? ''\n const ownerUserId = readString(document, 'ownerUserId', 'owner_user_id') ?? ''\n const visibleRow = visibleRowsById.get(id)\n const relationshipTier = visibleRow?.relationshipTier ?? null\n const archivedAt = readNullableDate(document, 'archivedAt', 'archived_at')\n return {\n id,\n title: readString(document, 'title') ?? '',\n folderId: readString(document, 'folderId', 'folder_id'),\n ownerUserId,\n ownerLabel: ownerLabels.get(ownerUserId)?.label ?? null,\n createdByUserId: readString(document, 'createdByUserId', 'created_by_user_id') ?? '',\n isActive: readBoolean(document, 'isActive', 'is_active'),\n archivedAt,\n isFavorite: favoriteDocumentIds.has(id),\n sharedWithCount: shareCounts.get(id) ?? 0,\n createdAt: readDate(document, 'createdAt', 'created_at'),\n updatedAt: readDate(document, 'updatedAt', 'updated_at'),\n relationshipTier,\n capabilities: deriveDocumentCapabilities({\n relationshipTier,\n managerOverride,\n archived: archivedAt !== null,\n userFeatures: ctx.auth.features,\n }),\n }\n })\n\n return NextResponse.json({\n items,\n collectionCapabilities: {\n canCreateDocument: hasDocumentsFeature(ctx.auth, 'documents.create'),\n canCreateFolder: hasDocumentsFeature(ctx.auth, 'documents.edit'),\n canLinkDocuments: hasDocumentsFeature(ctx.auth, 'documents.edit'),\n canInstantiateTemplate:\n hasDocumentsFeature(ctx.auth, 'documents.create')\n && hasDocumentsFeature(ctx.auth, 'documents.edit'),\n canManageTemplates: hasDocumentsFeature(ctx.auth, 'documents.templates.manage'),\n },\n total: visiblePage.total,\n page: query.page,\n pageSize: query.pageSize,\n totalPages: Math.max(1, Math.ceil(visiblePage.total / query.pageSize)),\n })\n } catch (error) {\n return handleDocumentsRouteError(error, 'documents.list')\n }\n}\n\nexport async function POST(request: Request): Promise<Response> {\n try {\n const ctx = await resolveDocumentsContext(request, ['documents.create'])\n const body = await readBody(request)\n const input = documentCreateSchema.parse(body)\n const guardResult = await validateMutationGuard(ctx, {\n resourceKind: DOCUMENTS_ENTITY_IDS.document,\n resourceId: 'new',\n operation: 'create',\n mutationPayload: input,\n mutationPayloadSchema: documentCreateSchema,\n })\n\n const commandInput: DocumentCreateCommandInput = {\n ...input,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n documentId: randomUUID(),\n contentId: randomUUID(),\n }\n const { result, logEntry } = await resolveDocumentsCommandBus(ctx).execute<\n DocumentCreateCommandInput,\n { id: string; updatedAt: string }\n >('documents.document.create', {\n input: commandInput,\n ctx: buildDocumentsCommandRuntimeContext(ctx),\n })\n await runMutationGuardAfterSuccess(ctx, guardResult, {\n resourceKind: DOCUMENTS_ENTITY_IDS.document,\n resourceId: 'new',\n operation: 'create',\n })\n\n const response = NextResponse.json(\n { id: result.id, updatedAt: result.updatedAt },\n { status: 201 },\n )\n return attachDocumentsOperationMetadata(response, logEntry, {\n resourceKind: DOCUMENTS_ENTITY_IDS.document,\n resourceId: result.id,\n })\n } catch (error) {\n return handleDocumentsRouteError(error, 'documents.create')\n }\n}\n\nexport const openApi: OpenApiRouteDoc = withDocumentsContextErrors({\n tag: 'Documents',\n summary: 'Document collection',\n methods: {\n GET: {\n summary: 'List visible documents',\n query: listQuerySchema,\n responses: [{ status: 200, description: 'Visible document metadata', schema: listResponseSchema }],\n errors: [\n { status: 401, description: 'Unauthorized', schema: routeErrorSchema },\n { status: 403, description: 'Forbidden', schema: routeErrorSchema },\n ],\n },\n POST: {\n summary: 'Create document',\n requestBody: { contentType: 'application/json', schema: documentCreateSchema },\n responses: [{ status: 201, description: 'Document created', schema: createResponseSchema }],\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 { GET, POST }\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,kBAAkB;AAG3B,SAAS,qBAAqB;AAC9B,SAAS,+BAA+B;AACxC,SAAS,sBAAsB,gCAAgC;AAC/D,SAAS,4BAA4B;AACrC,SAAS,yBAAyB;AAClC,SAAS,kCAAkC;AAC3C,SAAS,8BAA8B;AACvC,SAAS,+BAA+B;AACxC,SAAS,+BAA+B;AACxC,SAAS,8BAA8B;AACvC,SAAS,wCAAwC;AACjD,SAAS,6CAA6C;AACtD;AAAA,EACE;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;AAGP,MAAM,kBAAkB,EAAE,OAAO;AAAA,EAC/B,MAAM,EAAE,OAAO,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,QAAQ,CAAC;AAAA,EAC9C,UAAU,EAAE,OAAO,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG,EAAE,QAAQ,EAAE;AAAA,EAC5D,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS;AAAA,EACnC,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS;AAAA,EAC/B,UAAU,EAAE,KAAK,CAAC,WAAW,WAAW,MAAM,CAAC,EAAE,QAAQ,SAAS;AAAA,EAClE,UAAU,EAAE,OAAO,EAAE,SAAS,EAAE,UAAU,CAAC,UA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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,KAAK;",
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 type { QueryEngine } from '@open-mercato/shared/lib/query/types'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { parseBooleanWithDefault } from '@open-mercato/shared/lib/boolean'\nimport { documentCreateSchema, documentEntityTypeSchema } from '../data/validators'\nimport { DOCUMENTS_ENTITY_IDS } from '../lib/constants'\nimport { resolveUserLabels } from '../lib/userLabels'\nimport { deriveDocumentCapabilities } from '../lib/capabilities'\nimport { getVisibleDocumentPage } from '../lib/visibility'\nimport { loadDocumentShareCounts } from '../lib/shareCounts'\nimport { loadDocumentFavoriteIds } from '../lib/favorites'\nimport { getEntityRegistryEntry } from '../lib/entityRegistry'\nimport { verifyEntityRegistryTargetAccess } from '../lib/entityRegistry.server'\nimport { isDocumentEntityRegistryModuleEnabled } from '../lib/entityRegistryAvailability.server'\nimport { assertTier } from '../lib/permissions'\nimport {\n handleDocumentsRouteError,\n hasDocumentsFeature,\n readBody,\n resolveActorUserId,\n resolveDocumentsContext,\n routeErrorSchema,\n runMutationGuardAfterSuccess,\n validateMutationGuard,\n withDocumentsContextErrors,\n} from './_shared'\nimport {\n attachDocumentsOperationMetadata,\n buildDocumentsCommandRuntimeContext,\n resolveDocumentsCommandBus,\n} from './_commands'\nimport type { DocumentCreateCommandInput } from '../commands/document-crud'\n\nconst listQuerySchema = z.object({\n page: z.coerce.number().int().min(1).default(1),\n pageSize: z.coerce.number().int().min(1).max(100).default(50),\n search: z.string().trim().optional(),\n id: z.string().uuid().optional(),\n archived: z.enum(['exclude', 'include', 'only']).default('exclude'),\n favorite: z.string().optional().transform((value) => parseBooleanWithDefault(value, false)),\n folderId: z.string().uuid().optional().nullable(),\n entityType: documentEntityTypeSchema.optional(),\n entityId: z.string().uuid().optional(),\n}).superRefine((query, context) => {\n if (Boolean(query.entityType) !== Boolean(query.entityId)) {\n context.addIssue({\n code: 'custom',\n message: 'documents.validation.links.entityFilterPairRequired',\n })\n }\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 collectionCapabilitiesSchema = z.object({\n canCreateDocument: z.boolean(),\n canCreateFolder: z.boolean(),\n canLinkDocuments: z.boolean(),\n canInstantiateTemplate: z.boolean(),\n canManageTemplates: z.boolean(),\n})\n\nconst documentListItemSchema = z.object({\n id: z.string().uuid(),\n title: z.string(),\n folderId: z.string().uuid().nullable(),\n ownerUserId: z.string().uuid(),\n ownerLabel: z.string().nullable(),\n createdByUserId: z.string().uuid(),\n isActive: z.boolean(),\n archivedAt: z.string().nullable(),\n isFavorite: z.boolean(),\n sharedWithCount: z.number(),\n createdAt: z.string(),\n updatedAt: z.string(),\n relationshipTier: z.enum(['owner', 'editor', 'commenter', 'viewer']).nullable(),\n capabilities: capabilitiesSchema,\n})\n\nconst listResponseSchema = z.object({\n items: z.array(documentListItemSchema),\n collectionCapabilities: collectionCapabilitiesSchema,\n total: z.number(),\n page: z.number(),\n pageSize: z.number(),\n totalPages: z.number(),\n})\n\nconst createResponseSchema = z.object({\n id: z.string().uuid(),\n updatedAt: z.string(),\n})\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['documents.view'] },\n POST: { requireAuth: true, requireFeatures: ['documents.create'] },\n}\n\nfunction readString(record: Record<string, unknown>, ...keys: string[]): string | null {\n for (const key of keys) {\n const value = record[key]\n if (typeof value === 'string' && value.length > 0) return value\n }\n return null\n}\n\nfunction readBoolean(record: Record<string, unknown>, ...keys: string[]): boolean {\n for (const key of keys) {\n if (typeof record[key] === 'boolean') return record[key] as boolean\n }\n return false\n}\n\nfunction readDate(record: Record<string, unknown>, ...keys: string[]): string {\n for (const key of keys) {\n const value = record[key]\n const date = value instanceof Date\n ? value\n : typeof value === 'string' && value.length > 0\n ? new Date(value)\n : null\n if (date && !Number.isNaN(date.getTime())) return date.toISOString()\n }\n return new Date(0).toISOString()\n}\n\nfunction readNullableDate(record: Record<string, unknown>, ...keys: string[]): string | null {\n for (const key of keys) {\n const value = record[key]\n if (value === null || value === undefined) continue\n const date = value instanceof Date\n ? value\n : typeof value === 'string' && value.length > 0\n ? new Date(value)\n : null\n if (date && !Number.isNaN(date.getTime())) return date.toISOString()\n }\n return null\n}\n\nexport async function GET(request: Request): Promise<Response> {\n try {\n const ctx = await resolveDocumentsContext(request, ['documents.view'])\n const url = new URL(request.url)\n const query = listQuerySchema.parse(Object.fromEntries(url.searchParams.entries()))\n\n let relationFilter: { entityType: z.infer<typeof documentEntityTypeSchema>; entityId: string } | null = null\n if (query.entityType && query.entityId) {\n const registryEntry = getEntityRegistryEntry(query.entityType)\n if (\n !registryEntry\n || !isDocumentEntityRegistryModuleEnabled(registryEntry)\n || !hasDocumentsFeature(ctx.auth, registryEntry.requiredFeature)\n ) {\n throw new CrudHttpError(403, { error: 'api.errors.forbidden' })\n }\n let entityId = query.entityId\n if (query.entityType === 'document') {\n await assertTier(ctx.em, entityId, ctx.auth, 'viewer')\n } else {\n const verifiedTarget = await verifyEntityRegistryTargetAccess(request, {\n entityType: query.entityType,\n entityId,\n })\n entityId = verifiedTarget.id\n }\n relationFilter = {\n entityType: query.entityType,\n entityId,\n }\n }\n\n const actorUserId = resolveActorUserId(ctx.auth)\n const managerOverride = hasDocumentsFeature(ctx.auth, 'documents.manage')\n const visiblePage = await getVisibleDocumentPage({\n em: ctx.em,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n userId: actorUserId,\n roleIds: ctx.auth.roleIds,\n managerOverride,\n page: query.page,\n pageSize: query.pageSize,\n id: query.id ?? null,\n archived: query.archived,\n favoriteUserId: query.favorite ? actorUserId : null,\n search: query.search ?? null,\n folderId: query.folderId ?? null,\n relationFilter,\n })\n const orderedIds = visiblePage.rows.map((row) => row.id)\n const queryEngine = ctx.container.resolve('queryEngine') as QueryEngine\n const hydration = orderedIds.length > 0\n ? await queryEngine.query<Record<string, unknown>>(DOCUMENTS_ENTITY_IDS.document, {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n filters: { id: { $in: orderedIds } },\n page: { page: 1, pageSize: orderedIds.length },\n extensions: {\n userId: actorUserId,\n container: ctx.container,\n userFeatures: ctx.auth.features,\n resolve: <T = unknown>(name: string) => ctx.container.resolve(name) as T,\n },\n })\n : { items: [] as Record<string, unknown>[] }\n const hydratedById = new Map(\n hydration.items\n .map((item) => [readString(item, 'id'), item] as const)\n .filter((entry): entry is readonly [string, Record<string, unknown>] => entry[0] !== null),\n )\n const pageDocuments = orderedIds\n .map((id) => hydratedById.get(id) ?? null)\n .filter((item): item is Record<string, unknown> => item !== null)\n const ownerLabels = await resolveUserLabels(\n ctx.container,\n { tenantId: ctx.tenantId, organizationId: ctx.organizationId },\n pageDocuments\n .map((document) => readString(document, 'ownerUserId', 'owner_user_id'))\n .filter((id): id is string => id !== null),\n )\n const shareCounts = await loadDocumentShareCounts(\n ctx.em,\n { tenantId: ctx.tenantId, organizationId: ctx.organizationId },\n orderedIds,\n )\n const favoriteDocumentIds = await loadDocumentFavoriteIds(\n ctx.em,\n { tenantId: ctx.tenantId, organizationId: ctx.organizationId, userId: actorUserId },\n orderedIds,\n )\n const visibleRowsById = new Map(visiblePage.rows.map((row) => [row.id, row]))\n const items = pageDocuments.map((document) => {\n const id = readString(document, 'id') ?? ''\n const ownerUserId = readString(document, 'ownerUserId', 'owner_user_id') ?? ''\n const visibleRow = visibleRowsById.get(id)\n const relationshipTier = visibleRow?.relationshipTier ?? null\n const archivedAt = readNullableDate(document, 'archivedAt', 'archived_at')\n return {\n id,\n title: readString(document, 'title') ?? '',\n folderId: readString(document, 'folderId', 'folder_id'),\n ownerUserId,\n ownerLabel: ownerLabels.get(ownerUserId)?.label ?? null,\n createdByUserId: readString(document, 'createdByUserId', 'created_by_user_id') ?? '',\n isActive: readBoolean(document, 'isActive', 'is_active'),\n archivedAt,\n isFavorite: favoriteDocumentIds.has(id),\n sharedWithCount: shareCounts.get(id) ?? 0,\n createdAt: readDate(document, 'createdAt', 'created_at'),\n updatedAt: readDate(document, 'updatedAt', 'updated_at'),\n relationshipTier,\n capabilities: deriveDocumentCapabilities({\n relationshipTier,\n managerOverride,\n archived: archivedAt !== null,\n userFeatures: ctx.auth.features,\n }),\n }\n })\n\n return NextResponse.json({\n items,\n collectionCapabilities: {\n canCreateDocument: hasDocumentsFeature(ctx.auth, 'documents.create'),\n canCreateFolder: hasDocumentsFeature(ctx.auth, 'documents.edit'),\n canLinkDocuments: hasDocumentsFeature(ctx.auth, 'documents.edit'),\n canInstantiateTemplate:\n hasDocumentsFeature(ctx.auth, 'documents.create')\n && hasDocumentsFeature(ctx.auth, 'documents.edit'),\n canManageTemplates: hasDocumentsFeature(ctx.auth, 'documents.templates.manage'),\n },\n total: visiblePage.total,\n page: query.page,\n pageSize: query.pageSize,\n totalPages: Math.max(1, Math.ceil(visiblePage.total / query.pageSize)),\n })\n } catch (error) {\n return handleDocumentsRouteError(error, 'documents.list')\n }\n}\n\nexport async function POST(request: Request): Promise<Response> {\n try {\n const ctx = await resolveDocumentsContext(request, ['documents.create'])\n const body = await readBody(request)\n const input = documentCreateSchema.parse(body)\n const guardResult = await validateMutationGuard(ctx, {\n resourceKind: DOCUMENTS_ENTITY_IDS.document,\n resourceId: 'new',\n operation: 'create',\n mutationPayload: input,\n mutationPayloadSchema: documentCreateSchema,\n })\n\n const commandInput: DocumentCreateCommandInput = {\n ...input,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n documentId: randomUUID(),\n contentId: randomUUID(),\n }\n const { result, logEntry } = await resolveDocumentsCommandBus(ctx).execute<\n DocumentCreateCommandInput,\n { id: string; updatedAt: string }\n >('documents.document.create', {\n input: commandInput,\n ctx: buildDocumentsCommandRuntimeContext(ctx),\n })\n await runMutationGuardAfterSuccess(ctx, guardResult, {\n resourceKind: DOCUMENTS_ENTITY_IDS.document,\n resourceId: 'new',\n operation: 'create',\n })\n\n const response = NextResponse.json(\n { id: result.id, updatedAt: result.updatedAt },\n { status: 201 },\n )\n return attachDocumentsOperationMetadata(response, logEntry, {\n resourceKind: DOCUMENTS_ENTITY_IDS.document,\n resourceId: result.id,\n })\n } catch (error) {\n return handleDocumentsRouteError(error, 'documents.create')\n }\n}\n\nexport const openApi: OpenApiRouteDoc = withDocumentsContextErrors({\n tag: 'Documents',\n summary: 'Document collection',\n methods: {\n GET: {\n summary: 'List visible documents',\n query: listQuerySchema,\n responses: [{ status: 200, description: 'Visible document metadata', schema: listResponseSchema }],\n errors: [\n { status: 401, description: 'Unauthorized', schema: routeErrorSchema },\n { status: 403, description: 'Forbidden', schema: routeErrorSchema },\n ],\n },\n POST: {\n summary: 'Create document',\n requestBody: { contentType: 'application/json', schema: documentCreateSchema },\n responses: [{ status: 201, description: 'Document created', schema: createResponseSchema }],\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 { GET, POST }\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,kBAAkB;AAG3B,SAAS,qBAAqB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AiB;AAAA,MACvG;AAAA,IACF;AAAA,EACF;AACF,CAAC;AAED,IAAO,gBAAQ,EAAE,KAAK,KAAK;",
6
6
  "names": []
7
7
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/modules/documents/backend/documents/%5Bid%5D/DocumentCanvas.tsx"],
4
- "sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport type { Editor } from '@tiptap/core'\nimport { EditorContent, useEditorState } from '@tiptap/react'\nimport { BubbleMenu } from '@tiptap/react/menus'\nimport { Bold, Italic, Link2, MessageSquare, Underline } from 'lucide-react'\nimport { Alert, AlertDescription } from '@open-mercato/ui/primitives/alert'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { IconButton } from '@open-mercato/ui/primitives/icon-button'\nimport { Input } from '@open-mercato/ui/primitives/input'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { cn } from '@open-mercato/shared/lib/utils'\nimport { OutlinePane } from './OutlinePane'\nimport { captureCommentAnchor, type CommentAnchor } from './CommentAnchorNavigation'\nimport { DOCUMENT_EDITOR_CONTENT_CLASS } from './editorTypes'\nimport { DOCUMENT_PAGINATION_STYLES } from './documentPagination'\nimport { useContentSecurityPolicyNonce } from '@open-mercato/ui/theme/ContentSecurityPolicyProvider'\n\ntype TitleModel = {\n value: string\n setValue: (value: string) => void\n saving: boolean\n commit: () => Promise<void>\n onKeyDown: (event: React.KeyboardEvent<HTMLInputElement>) => void\n}\n\nconst EMPTY_BUBBLE_MENU_STATE = {\n bold: false,\n italic: false,\n underline: false,\n link: false,\n}\n\nexport function DocumentCanvas({\n editor,\n title,\n readOnly,\n outlineOpen,\n notice,\n onOpenLink,\n onComment,\n}: {\n editor: Editor | null\n title: TitleModel\n readOnly: boolean\n outlineOpen: boolean\n notice: string | null\n onOpenLink: () => void\n onComment?: (anchor: CommentAnchor) => void\n}) {\n const t = useT()\n const nonce = useContentSecurityPolicyNonce()\n const editorState = useEditorState({\n editor,\n selector: ({ editor: current }) => current ? {\n bold: current.isActive('bold'),\n italic: current.isActive('italic'),\n underline: current.isActive('underline'),\n link: current.isActive('link'),\n } : EMPTY_BUBBLE_MENU_STATE,\n }) ?? EMPTY_BUBBLE_MENU_STATE\n const keepSelection = React.useCallback((event: React.MouseEvent<HTMLButtonElement>) => event.preventDefault(), [])\n const comment = React.useCallback(() => {\n if (!editor || !onComment) return\n const anchor = captureCommentAnchor(editor)\n if (anchor) onComment(anchor)\n }, [editor, onComment])\n const shouldShow = React.useCallback(\n ({ from, to }: { from: number; to: number }) => from !== to && (!readOnly || Boolean(onComment)),\n [onComment, readOnly],\n )\n\n return (\n <div className=\"om-doc-canvas max-h-[calc(100dvh-var(--topbar-height,0px)-12rem)] min-h-96 overflow-auto bg-muted p-0 sm:px-4 sm:py-8 md:px-8 md:py-10\">\n <style nonce={nonce}>{DOCUMENT_PAGINATION_STYLES}</style>\n {notice ? <Alert status=\"information\" style=\"lighter\" className=\"mx-auto mb-4 max-w-3xl\"><AlertDescription>{notice}</AlertDescription></Alert> : null}\n <div className=\"mx-auto flex w-fit min-w-full flex-col gap-4 lg:flex-row lg:items-start\">\n {outlineOpen ? <OutlinePane editor={editor} /> : null}\n <article className=\"om-doc-paper mx-auto flex-none bg-card sm:rounded-sm sm:shadow-lg\">\n {readOnly ? (\n <h1 className=\"mb-6 text-xl font-semibold leading-tight text-foreground sm:mb-8 sm:text-3xl\">{title.value}</h1>\n ) : (\n <Input\n value={title.value}\n onChange={(event) => title.setValue(event.target.value)}\n onBlur={() => void title.commit()}\n onKeyDown={title.onKeyDown}\n maxLength={512}\n disabled={title.saving}\n aria-label={t('documents.editor.title.ariaLabel')}\n className=\"mb-6 h-auto border-0 bg-transparent px-0 py-0 text-xl font-semibold leading-tight text-foreground shadow-none focus-visible:shadow-focus sm:mb-8 sm:text-3xl\"\n />\n )}\n {editor ? (\n <BubbleMenu editor={editor} shouldShow={shouldShow} className=\"z-popover flex items-center gap-1 rounded-md border border-border bg-card p-1 shadow-md\">\n {!readOnly ? (\n <>\n <IconButton type=\"button\" size=\"sm\" variant={editorState.bold ? 'outline' : 'ghost'} aria-label={t('documents.editor.toolbar.bold')} aria-pressed={editorState.bold} onMouseDown={keepSelection} onClick={() => editor.chain().focus().toggleBold().run()}><Bold /></IconButton>\n <IconButton type=\"button\" size=\"sm\" variant={editorState.italic ? 'outline' : 'ghost'} aria-label={t('documents.editor.toolbar.italic')} aria-pressed={editorState.italic} onMouseDown={keepSelection} onClick={() => editor.chain().focus().toggleItalic().run()}><Italic /></IconButton>\n <IconButton type=\"button\" size=\"sm\" variant={editorState.underline ? 'outline' : 'ghost'} aria-label={t('documents.editor.toolbar.underline')} aria-pressed={editorState.underline} onMouseDown={keepSelection} onClick={() => editor.chain().focus().toggleMark('underline').run()}><Underline /></IconButton>\n <IconButton type=\"button\" size=\"sm\" variant={editorState.link ? 'outline' : 'ghost'} aria-label={t('documents.editor.toolbar.link')} aria-pressed={editorState.link} onMouseDown={keepSelection} onClick={onOpenLink}><Link2 /></IconButton>\n </>\n ) : null}\n {onComment ? <Button type=\"button\" size=\"sm\" variant=\"ghost\" onMouseDown={keepSelection} onClick={comment}><MessageSquare />{t('documents.editor.toolbar.comment')}</Button> : null}\n </BubbleMenu>\n ) : null}\n <EditorContent className={cn(DOCUMENT_EDITOR_CONTENT_CLASS, readOnly && 'select-text')} editor={editor} />\n </article>\n </div>\n </div>\n )\n}\n"],
4
+ "sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport type { Editor } from '@tiptap/core'\nimport { EditorContent, useEditorState } from '@tiptap/react'\nimport { BubbleMenu } from '@tiptap/react/menus'\nimport { Bold, Italic, Link2, MessageSquare, Underline } from 'lucide-react'\nimport { Alert, AlertDescription } from '@open-mercato/ui/primitives/alert'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { IconButton } from '@open-mercato/ui/primitives/icon-button'\nimport { Input } from '@open-mercato/ui/primitives/input'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { cn } from '@open-mercato/shared/lib/utils'\nimport { OutlinePane } from './OutlinePane'\nimport { captureCommentAnchor, type CommentAnchor } from './CommentAnchorNavigation'\nimport { DOCUMENT_EDITOR_CONTENT_CLASS } from './editorTypes'\nimport { DOCUMENT_PAGINATION_STYLES } from './documentPagination'\nimport { useContentSecurityPolicyNonce } from '@open-mercato/ui/theme/ContentSecurityPolicyProvider'\n\ntype TitleModel = {\n value: string\n setValue: (value: string) => void\n saving: boolean\n commit: () => Promise<void>\n onKeyDown: (event: React.KeyboardEvent<HTMLInputElement>) => void\n}\n\nconst EMPTY_BUBBLE_MENU_STATE = {\n bold: false,\n italic: false,\n underline: false,\n link: false,\n}\n\nexport function DocumentCanvas({\n editor,\n title,\n readOnly,\n outlineOpen,\n notice,\n onOpenLink,\n onComment,\n}: {\n editor: Editor | null\n title: TitleModel\n readOnly: boolean\n outlineOpen: boolean\n notice: React.ReactNode\n onOpenLink: () => void\n onComment?: (anchor: CommentAnchor) => void\n}) {\n const t = useT()\n const nonce = useContentSecurityPolicyNonce()\n const editorState = useEditorState({\n editor,\n selector: ({ editor: current }) => current ? {\n bold: current.isActive('bold'),\n italic: current.isActive('italic'),\n underline: current.isActive('underline'),\n link: current.isActive('link'),\n } : EMPTY_BUBBLE_MENU_STATE,\n }) ?? EMPTY_BUBBLE_MENU_STATE\n const keepSelection = React.useCallback((event: React.MouseEvent<HTMLButtonElement>) => event.preventDefault(), [])\n const comment = React.useCallback(() => {\n if (!editor || !onComment) return\n const anchor = captureCommentAnchor(editor)\n if (anchor) onComment(anchor)\n }, [editor, onComment])\n const shouldShow = React.useCallback(\n ({ from, to }: { from: number; to: number }) => from !== to && (!readOnly || Boolean(onComment)),\n [onComment, readOnly],\n )\n\n return (\n <div className=\"om-doc-canvas max-h-[calc(100dvh-var(--topbar-height,0px)-12rem)] min-h-96 overflow-auto bg-muted p-0 sm:px-4 sm:py-8 md:px-8 md:py-10\">\n <style nonce={nonce}>{DOCUMENT_PAGINATION_STYLES}</style>\n {notice ? <Alert status=\"information\" style=\"lighter\" className=\"mx-auto mb-4 max-w-3xl\"><AlertDescription>{notice}</AlertDescription></Alert> : null}\n <div className=\"mx-auto flex w-fit min-w-full flex-col gap-4 lg:flex-row lg:items-start\">\n {outlineOpen ? <OutlinePane editor={editor} /> : null}\n <article className=\"om-doc-paper mx-auto flex-none bg-card sm:rounded-sm sm:shadow-lg\">\n {readOnly ? (\n <h1 className=\"mb-6 text-xl font-semibold leading-tight text-foreground sm:mb-8 sm:text-3xl\">{title.value}</h1>\n ) : (\n <Input\n value={title.value}\n onChange={(event) => title.setValue(event.target.value)}\n onBlur={() => void title.commit()}\n onKeyDown={title.onKeyDown}\n maxLength={512}\n disabled={title.saving}\n aria-label={t('documents.editor.title.ariaLabel')}\n className=\"mb-6 h-auto border-0 bg-transparent px-0 py-0 text-xl font-semibold leading-tight text-foreground shadow-none focus-visible:shadow-focus sm:mb-8 sm:text-3xl\"\n />\n )}\n {editor ? (\n <BubbleMenu editor={editor} shouldShow={shouldShow} className=\"z-popover flex items-center gap-1 rounded-md border border-border bg-card p-1 shadow-md\">\n {!readOnly ? (\n <>\n <IconButton type=\"button\" size=\"sm\" variant={editorState.bold ? 'outline' : 'ghost'} aria-label={t('documents.editor.toolbar.bold')} aria-pressed={editorState.bold} onMouseDown={keepSelection} onClick={() => editor.chain().focus().toggleBold().run()}><Bold /></IconButton>\n <IconButton type=\"button\" size=\"sm\" variant={editorState.italic ? 'outline' : 'ghost'} aria-label={t('documents.editor.toolbar.italic')} aria-pressed={editorState.italic} onMouseDown={keepSelection} onClick={() => editor.chain().focus().toggleItalic().run()}><Italic /></IconButton>\n <IconButton type=\"button\" size=\"sm\" variant={editorState.underline ? 'outline' : 'ghost'} aria-label={t('documents.editor.toolbar.underline')} aria-pressed={editorState.underline} onMouseDown={keepSelection} onClick={() => editor.chain().focus().toggleMark('underline').run()}><Underline /></IconButton>\n <IconButton type=\"button\" size=\"sm\" variant={editorState.link ? 'outline' : 'ghost'} aria-label={t('documents.editor.toolbar.link')} aria-pressed={editorState.link} onMouseDown={keepSelection} onClick={onOpenLink}><Link2 /></IconButton>\n </>\n ) : null}\n {onComment ? <Button type=\"button\" size=\"sm\" variant=\"ghost\" onMouseDown={keepSelection} onClick={comment}><MessageSquare />{t('documents.editor.toolbar.comment')}</Button> : null}\n </BubbleMenu>\n ) : null}\n <EditorContent className={cn(DOCUMENT_EDITOR_CONTENT_CLASS, readOnly && 'select-text')} editor={editor} />\n </article>\n </div>\n </div>\n )\n}\n"],
5
5
  "mappings": ";AA2EM,SAsBU,UAtBV,KAsBU,YAtBV;AAzEN,YAAY,WAAW;AAEvB,SAAS,eAAe,sBAAsB;AAC9C,SAAS,kBAAkB;AAC3B,SAAS,MAAM,QAAQ,OAAO,eAAe,iBAAiB;AAC9D,SAAS,OAAO,wBAAwB;AACxC,SAAS,cAAc;AACvB,SAAS,kBAAkB;AAC3B,SAAS,aAAa;AACtB,SAAS,YAAY;AACrB,SAAS,UAAU;AACnB,SAAS,mBAAmB;AAC5B,SAAS,4BAAgD;AACzD,SAAS,qCAAqC;AAC9C,SAAS,kCAAkC;AAC3C,SAAS,qCAAqC;AAU9C,MAAM,0BAA0B;AAAA,EAC9B,MAAM;AAAA,EACN,QAAQ;AAAA,EACR,WAAW;AAAA,EACX,MAAM;AACR;AAEO,SAAS,eAAe;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAQG;AACD,QAAM,IAAI,KAAK;AACf,QAAM,QAAQ,8BAA8B;AAC5C,QAAM,cAAc,eAAe;AAAA,IACjC;AAAA,IACA,UAAU,CAAC,EAAE,QAAQ,QAAQ,MAAM,UAAU;AAAA,MAC3C,MAAM,QAAQ,SAAS,MAAM;AAAA,MAC7B,QAAQ,QAAQ,SAAS,QAAQ;AAAA,MACjC,WAAW,QAAQ,SAAS,WAAW;AAAA,MACvC,MAAM,QAAQ,SAAS,MAAM;AAA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AAY,EAAE,+BAA+B,GAAG,gBAAc,YAAY,MAAM,aAAa,eAAe,SAAS,MAAM,OAAO,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,IAAI,GAAG,8BAAC,QAAK,GAAE;AAAA,YACnQ,oBAAC,cAAW,MAAK,UAAS,MAAK,MAAK,SAAS,YAAY,SAAS,YAAY,SAAS,cAAY,EAAE,iCAAiC,GAAG,gBAAc,YAAY,QAAQ,aAAa,eAAe,SAAS,MAAM,OAAO,MAAM,EAAE,MAAM,EAAE,aAAa,EAAE,IAAI,GAAG,8BAAC,UAAO,GAAE;AAAA,YAC7Q,oBAAC,cAAW,MAAK,UAAS,MAAK,MAAK,SAAS,YAAY,YAAY,YAAY,SAAS,cAAY,EAAE,oCAAoC,GAAG,gBAAc,YAAY,WAAW,aAAa,eAAe,SAAS,MAAM,OAAO,MAAM,EAAE,MAAM,EAAE,WAAW,WAAW,EAAE,IAAI,GAAG,8BAAC,aAAU,GAAE;AAAA,YAClS,oBAAC,cAAW,MAAK,UAAS,MAAK,MAAK,SAAS,YAAY,OAAO,YAAY,SAAS,cAAY,EAAE,+BAA+B,GAAG,gBAAc,YAAY,MAAM,aAAa,eAAe,SAAS,YAAY,8BAAC,SAAM,GAAE;AAAA,aACjO,IACE;AAAA,UACH,YAAY,qBAAC,UAAO,MAAK,UAAS,MAAK,MAAK,SAAQ,SAAQ,aAAa,eAAe,SAAS,SAAS;AAAA,gCAAC,iBAAc;AAAA,YAAG,EAAE,kCAAkC;AAAA,aAAE,IAAY;AAAA,WACjL,IACE;AAAA,QACJ,oBAAC,iBAAc,WAAW,GAAG,+BAA+B,YAAY,aAAa,GAAG,QAAgB;AAAA,SAC1G;AAAA,OACF;AAAA,KACF;AAEJ;",
6
6
  "names": []
7
7
  }
@@ -1,13 +1,15 @@
1
1
  "use client";
2
- import { jsx, jsxs } from "react/jsx-runtime";
2
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
3
3
  import * as React from "react";
4
4
  import { useContentSecurityPolicyNonce } from "@open-mercato/ui/theme/ContentSecurityPolicyProvider";
5
5
  import { Link2, Unlink } from "lucide-react";
6
6
  import { Button } from "@open-mercato/ui/primitives/button";
7
7
  import { Input } from "@open-mercato/ui/primitives/input";
8
8
  import { Label } from "@open-mercato/ui/primitives/label";
9
+ import { LinkButton } from "@open-mercato/ui/primitives/link-button";
9
10
  import { useT } from "@open-mercato/shared/lib/i18n/context";
10
11
  import { cn } from "@open-mercato/shared/lib/utils";
12
+ import { DOCUMENTS_REALTIME_SETUP_GUIDE_URL } from "@open-mercato/documents/modules/documents/lib/constants";
11
13
  import { EntityPicker } from "../components/EntityPicker.js";
12
14
  import { DocumentCanvas } from "./DocumentCanvas.js";
13
15
  import { EditorStatusPresence } from "./EditorStatusPresence.js";
@@ -76,6 +78,14 @@ function DocumentEditorSurface(input) {
76
78
  }, [effectiveReadOnly, insertions.setPickerOpen, suggestionRange]);
77
79
  const status = input.transport === "fallback" ? "offline" : input.connectionStatus;
78
80
  const notice = input.transport === "fallback" ? t(input.readOnly ? "documents.editor.realtime.readOnlyFallback" : "documents.editor.realtime.singleUserFallback") : input.readOnly ? t("documents.editor.readOnly") : input.mode === "preview" ? t("documents.editor.mode.previewNotice") : null;
81
+ const availabilityNotice = status === "offline" ? /* @__PURE__ */ jsxs(Fragment, { children: [
82
+ /* @__PURE__ */ jsx("p", { children: notice ?? t("documents.editor.realtime.offline") }),
83
+ /* @__PURE__ */ jsxs("p", { className: "mt-2", children: [
84
+ t("documents.editor.realtime.setupHint"),
85
+ " ",
86
+ /* @__PURE__ */ jsx(LinkButton, { asChild: true, underline: "always", children: /* @__PURE__ */ jsx("a", { href: DOCUMENTS_REALTIME_SETUP_GUIDE_URL, target: "_blank", rel: "noopener noreferrer", children: t("documents.editor.realtime.setupGuide") }) })
87
+ ] })
88
+ ] }) : notice;
79
89
  const selectionCommentHandler = canCreateSelectionComment({
80
90
  permissionReadOnly: input.readOnly,
81
91
  mode: input.mode,
@@ -154,7 +164,7 @@ function DocumentEditorSurface(input) {
154
164
  /* @__PURE__ */ jsx(Button, { type: "button", variant: "ghost", onClick: () => insertions.setLinkOpen(false), children: t("documents.actions.cancel") })
155
165
  ] }) : null
156
166
  ] }),
157
- /* @__PURE__ */ jsx(DocumentCanvas, { editor: editorModel.editor, title, readOnly: effectiveReadOnly, outlineOpen, notice, onOpenLink: insertions.openLink, onComment: selectionCommentHandler })
167
+ /* @__PURE__ */ jsx(DocumentCanvas, { editor: editorModel.editor, title, readOnly: effectiveReadOnly, outlineOpen, notice: availabilityNotice, onOpenLink: insertions.openLink, onComment: selectionCommentHandler })
158
168
  ] }),
159
169
  /* @__PURE__ */ jsx(EntityPicker, { open: insertions.entityPickerOpen, onOpenChange: insertions.setPickerOpen, onPick: (pick) => {
160
170
  void insertions.handleEntityPick(pick);
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/modules/documents/backend/documents/%5Bid%5D/DocumentEditorSurface.tsx"],
4
- "sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { useContentSecurityPolicyNonce } from '@open-mercato/ui/theme/ContentSecurityPolicyProvider'\nimport { Link2, Unlink } from 'lucide-react'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { Input } from '@open-mercato/ui/primitives/input'\nimport { Label } from '@open-mercato/ui/primitives/label'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { cn } from '@open-mercato/shared/lib/utils'\nimport { EntityPicker } from '../components/EntityPicker'\nimport { DocumentCanvas } from './DocumentCanvas'\nimport { EditorStatusPresence } from './EditorStatusPresence'\nimport { EditorToolbar } from './EditorToolbar'\nimport { RecordFieldsDialog } from './RecordFieldsDialog'\nimport { EDITOR_PRESENCE_STYLES } from './editorPresenceStyles'\nimport { canCreateSelectionComment, type CollabResources, type ConnectionStatus, type DocumentEditorIslandProps, type EditorMode, type PresenceUser } from './editorTypes'\nimport { useDocumentEditor } from './useDocumentEditor'\nimport { useFallbackContentPersistence } from './useFallbackContentPersistence'\nimport { useDocumentTitle } from './useDocumentTitle'\nimport { useEditorInsertions } from './useEditorInsertions'\nimport { saveCollaborativeContent } from './saveCollaborativeContent'\n\ntype Props = DocumentEditorIslandProps & {\n transport: 'collab' | 'fallback'\n collabResources?: CollabResources\n connectionStatus: ConnectionStatus\n presenceUsers: PresenceUser[]\n mode: EditorMode\n onModeChange: (mode: EditorMode) => void\n}\n\nexport function DocumentEditorSurface(input: Props) {\n const t = useT()\n const nonce = useContentSecurityPolicyNonce()\n const [outlineOpen, setOutlineOpen] = React.useState(false)\n const [suggestionRange, setSuggestionRange] = React.useState<{ from: number; to: number } | null>(null)\n const modeChangeInFlightRef = React.useRef(false)\n const effectiveReadOnly = input.readOnly || input.mode === 'preview'\n const openSuggestion = React.useCallback((range: { from: number; to: number }) => setSuggestionRange(range), [])\n const closeSuggestion = React.useCallback(() => setSuggestionRange(null), [])\n const fallbackPersistence = useFallbackContentPersistence({\n documentId: input.documentId,\n initialUpdatedAt: input.contentUpdatedAt ?? null,\n enabled: input.transport === 'fallback' && !input.readOnly,\n onConflictRefresh: input.onContentConflict,\n })\n const editorModel = useDocumentEditor({\n documentId: input.documentId,\n initialContentHtml: input.initialContentHtml,\n editorMode: input.transport,\n collabResources: input.collabResources,\n readOnly: effectiveReadOnly,\n onEditorReady: input.onEditorReady,\n onUpdate: fallbackPersistence.onEditorUpdate,\n onEntitySuggestion: openSuggestion,\n onSuggestionClose: closeSuggestion,\n })\n const title = useDocumentTitle({\n documentId: input.documentId,\n title: input.title,\n updatedAt: input.documentUpdatedAt ?? null,\n readOnly: effectiveReadOnly,\n onTitleChange: input.onTitleChange,\n })\n React.useEffect(() => {\n const controller = new AbortController()\n input.onSaveReady?.(async () => {\n if (controller.signal.aborted || input.readOnly || !editorModel.editorRef.current) return false\n return input.transport === 'fallback'\n ? fallbackPersistence.saveNow()\n : input.collabResources\n ? saveCollaborativeContent(input.collabResources, controller.signal)\n : false\n })\n return () => {\n controller.abort()\n input.onSaveReady?.(null)\n }\n }, [editorModel.editorRef, fallbackPersistence.saveNow, input.collabResources, input.onSaveReady, input.readOnly, input.transport])\n const insertions = useEditorInsertions({\n documentId: input.documentId,\n editorRef: editorModel.editorRef,\n disabled: effectiveReadOnly,\n suggestionRange,\n setSuggestionRange,\n })\n React.useEffect(() => {\n if (suggestionRange && !effectiveReadOnly) insertions.setPickerOpen(true)\n }, [effectiveReadOnly, insertions.setPickerOpen, suggestionRange])\n\n const status = input.transport === 'fallback' ? 'offline' : input.connectionStatus\n const notice = input.transport === 'fallback'\n ? t(input.readOnly ? 'documents.editor.realtime.readOnlyFallback' : 'documents.editor.realtime.singleUserFallback')\n : input.readOnly\n ? t('documents.editor.readOnly')\n : input.mode === 'preview'\n ? t('documents.editor.mode.previewNotice')\n : null\n const selectionCommentHandler = canCreateSelectionComment({\n permissionReadOnly: input.readOnly,\n mode: input.mode,\n transport: input.transport,\n hasCommentHandler: Boolean(input.onComment),\n }) ? input.onComment : undefined\n const handleModeChange = React.useCallback(async (nextMode: EditorMode) => {\n if (nextMode === input.mode || modeChangeInFlightRef.current) return\n if (input.transport !== 'fallback' || nextMode !== 'preview') {\n input.onModeChange(nextMode)\n return\n }\n\n modeChangeInFlightRef.current = true\n try {\n if (await fallbackPersistence.saveNow()) input.onModeChange(nextMode)\n } finally {\n modeChangeInFlightRef.current = false\n }\n }, [fallbackPersistence.saveNow, input.mode, input.onModeChange, input.transport])\n\n return (\n <div className={cn('space-y-3', input.transport === 'collab' && 'om-doc-collab', input.mode === 'preview' && 'om-doc-preview')}>\n <style nonce={nonce}>{EDITOR_PRESENCE_STYLES}</style>\n <div className=\"overflow-hidden rounded-lg border border-border bg-muted shadow-sm\">\n <div className=\"sticky top-0 z-sticky border-b border-border bg-card/95\">\n <div className=\"flex flex-wrap items-center justify-between gap-2 px-3 py-2\">\n <EditorStatusPresence\n status={status}\n users={input.presenceUsers}\n counts={editorModel.counts}\n mode={input.mode}\n canEdit={!input.readOnly}\n onModeChange={(nextMode) => { void handleModeChange(nextMode) }}\n fallbackSave={input.transport === 'fallback' && !input.readOnly ? {\n status: fallbackPersistence.status,\n onSave: fallbackPersistence.saveNow,\n } : undefined}\n />\n </div>\n {input.mode === 'edit' ? (\n <EditorToolbar\n editor={editorModel.editor}\n disabled={effectiveReadOnly || !editorModel.editor}\n outlineOpen={outlineOpen}\n uploading={insertions.uploading}\n onToggleOutline={() => setOutlineOpen((value) => !value)}\n onOpenEntityPicker={insertions.openEntityPicker}\n onOpenLink={insertions.openLink}\n onImage={() => insertions.fileInputRef.current?.click()}\n />\n ) : null}\n {insertions.linkOpen && !effectiveReadOnly ? (\n <div className=\"flex flex-col gap-3 border-t border-border bg-muted/30 p-3 md:flex-row md:items-end\" onKeyDown={(event) => {\n if ((event.metaKey || event.ctrlKey) && event.key === 'Enter') { event.preventDefault(); insertions.applyLink() }\n if (event.key === 'Escape') { event.preventDefault(); insertions.setLinkOpen(false) }\n }}>\n <div className=\"min-w-0 flex-1 space-y-2\">\n <Label htmlFor={`document-link-${input.documentId}`}>{t('documents.editor.link.url')}</Label>\n <Input id={`document-link-${input.documentId}`} type=\"url\" value={insertions.linkHref} onChange={(event) => insertions.setLinkHref(event.target.value)} placeholder={t('documents.editor.link.placeholder')} />\n </div>\n <Button type=\"button\" onClick={insertions.applyLink}><Link2 />{t('documents.editor.link.apply')}</Button>\n <Button type=\"button\" variant=\"outline\" onClick={insertions.removeLink}><Unlink />{t('documents.editor.link.remove')}</Button>\n <Button type=\"button\" variant=\"ghost\" onClick={() => insertions.setLinkOpen(false)}>{t('documents.actions.cancel')}</Button>\n </div>\n ) : null}\n </div>\n <DocumentCanvas editor={editorModel.editor} title={title} readOnly={effectiveReadOnly} outlineOpen={outlineOpen} notice={notice} onOpenLink={insertions.openLink} onComment={selectionCommentHandler} />\n </div>\n <EntityPicker open={insertions.entityPickerOpen} onOpenChange={insertions.setPickerOpen} onPick={(pick) => { void insertions.handleEntityPick(pick) }} />\n <RecordFieldsDialog\n documentId={input.documentId}\n linkId={insertions.recordFieldsLinkId}\n editor={editorModel.editor}\n canInsert={!effectiveReadOnly && Boolean(editorModel.editor)}\n onOpenChange={(open) => { if (!open) insertions.closeRecordFields() }}\n />\n <input ref={insertions.fileInputRef} type=\"file\" accept=\"image/*\" className=\"hidden\" aria-label={t('documents.editor.imageInput')} onChange={(event) => { void insertions.handleFiles(event.target.files) }} />\n </div>\n )\n}\n"],
5
- "mappings": ";AA0HM,cAkCQ,YAlCR;AAxHN,YAAY,WAAW;AACvB,SAAS,qCAAqC;AAC9C,SAAS,OAAO,cAAc;AAC9B,SAAS,cAAc;AACvB,SAAS,aAAa;AACtB,SAAS,aAAa;AACtB,SAAS,YAAY;AACrB,SAAS,UAAU;AACnB,SAAS,oBAAoB;AAC7B,SAAS,sBAAsB;AAC/B,SAAS,4BAA4B;AACrC,SAAS,qBAAqB;AAC9B,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACvC,SAAS,iCAAkJ;AAC3J,SAAS,yBAAyB;AAClC,SAAS,qCAAqC;AAC9C,SAAS,wBAAwB;AACjC,SAAS,2BAA2B;AACpC,SAAS,gCAAgC;AAWlC,SAAS,sBAAsB,OAAc;AAClD,QAAM,IAAI,KAAK;AACf,QAAM,QAAQ,8BAA8B;AAC5C,QAAM,CAAC,aAAa,cAAc,IAAI,MAAM,SAAS,KAAK;AAC1D,QAAM,CAAC,iBAAiB,kBAAkB,IAAI,MAAM,SAA8C,IAAI;AACtG,QAAM,wBAAwB,MAAM,OAAO,KAAK;AAChD,QAAM,oBAAoB,MAAM,YAAY,MAAM,SAAS;AAC3D,QAAM,iBAAiB,MAAM,YAAY,CAAC,UAAwC,mBAAmB,KAAK,GAAG,CAAC,CAAC;AAC/G,QAAM,kBAAkB,MAAM,YAAY,MAAM,mBAAmB,IAAI,GAAG,CAAC,CAAC;AAC5E,QAAM,sBAAsB,8BAA8B;AAAA,IACxD,YAAY,MAAM;AAAA,IAClB,kBAAkB,MAAM,oBAAoB;AAAA,IAC5C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AAA,YAAG,EAAE,8BAA8B;AAAA,aAAE;AAAA,UACrH,oBAAC,UAAO,MAAK,UAAS,SAAQ,SAAQ,SAAS,MAAM,WAAW,YAAY,KAAK,GAAI,YAAE,0BAA0B,GAAE;AAAA,WACrH,IACE;AAAA,SACN;AAAA,MACA,oBAAC,kBAAe,QAAQ,YAAY,QAAQ,OAAc,UAAU,mBAAmB,aAA0B,QAAgB,YAAY,WAAW,UAAU,WAAW,yBAAyB;AAAA,OACxM;AAAA,IACA,oBAAC,gBAAa,MAAM,WAAW,kBAAkB,cAAc,WAAW,eAAe,QAAQ,CAAC,SAAS;AAAE,WAAK,WAAW,iBAAiB,IAAI;AAAA,IAAE,GAAG;AAAA,IACvJ;AAAA,MAAC;AAAA;AAAA,QACC,YAAY,MAAM;AAAA,QAClB,QAAQ,WAAW;AAAA,QACnB,QAAQ,YAAY;AAAA,QACpB,WAAW,CAAC,qBAAqB,QAAQ,YAAY,MAAM;AAAA,QAC3D,cAAc,CAAC,SAAS;AAAE,cAAI,CAAC,KAAM,YAAW,kBAAkB;AAAA,QAAE;AAAA;AAAA,IACtE;AAAA,IACA,oBAAC,WAAM,KAAK,WAAW,cAAc,MAAK,QAAO,QAAO,WAAU,WAAU,UAAS,cAAY,EAAE,6BAA6B,GAAG,UAAU,CAAC,UAAU;AAAE,WAAK,WAAW,YAAY,MAAM,OAAO,KAAK;AAAA,IAAE,GAAG;AAAA,KAC/M;AAEJ;",
4
+ "sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { useContentSecurityPolicyNonce } from '@open-mercato/ui/theme/ContentSecurityPolicyProvider'\nimport { Link2, Unlink } from 'lucide-react'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { Input } from '@open-mercato/ui/primitives/input'\nimport { Label } from '@open-mercato/ui/primitives/label'\nimport { LinkButton } from '@open-mercato/ui/primitives/link-button'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { cn } from '@open-mercato/shared/lib/utils'\nimport { DOCUMENTS_REALTIME_SETUP_GUIDE_URL } from '@open-mercato/documents/modules/documents/lib/constants'\nimport { EntityPicker } from '../components/EntityPicker'\nimport { DocumentCanvas } from './DocumentCanvas'\nimport { EditorStatusPresence } from './EditorStatusPresence'\nimport { EditorToolbar } from './EditorToolbar'\nimport { RecordFieldsDialog } from './RecordFieldsDialog'\nimport { EDITOR_PRESENCE_STYLES } from './editorPresenceStyles'\nimport { canCreateSelectionComment, type CollabResources, type ConnectionStatus, type DocumentEditorIslandProps, type EditorMode, type PresenceUser } from './editorTypes'\nimport { useDocumentEditor } from './useDocumentEditor'\nimport { useFallbackContentPersistence } from './useFallbackContentPersistence'\nimport { useDocumentTitle } from './useDocumentTitle'\nimport { useEditorInsertions } from './useEditorInsertions'\nimport { saveCollaborativeContent } from './saveCollaborativeContent'\n\ntype Props = DocumentEditorIslandProps & {\n transport: 'collab' | 'fallback'\n collabResources?: CollabResources\n connectionStatus: ConnectionStatus\n presenceUsers: PresenceUser[]\n mode: EditorMode\n onModeChange: (mode: EditorMode) => void\n}\n\nexport function DocumentEditorSurface(input: Props) {\n const t = useT()\n const nonce = useContentSecurityPolicyNonce()\n const [outlineOpen, setOutlineOpen] = React.useState(false)\n const [suggestionRange, setSuggestionRange] = React.useState<{ from: number; to: number } | null>(null)\n const modeChangeInFlightRef = React.useRef(false)\n const effectiveReadOnly = input.readOnly || input.mode === 'preview'\n const openSuggestion = React.useCallback((range: { from: number; to: number }) => setSuggestionRange(range), [])\n const closeSuggestion = React.useCallback(() => setSuggestionRange(null), [])\n const fallbackPersistence = useFallbackContentPersistence({\n documentId: input.documentId,\n initialUpdatedAt: input.contentUpdatedAt ?? null,\n enabled: input.transport === 'fallback' && !input.readOnly,\n onConflictRefresh: input.onContentConflict,\n })\n const editorModel = useDocumentEditor({\n documentId: input.documentId,\n initialContentHtml: input.initialContentHtml,\n editorMode: input.transport,\n collabResources: input.collabResources,\n readOnly: effectiveReadOnly,\n onEditorReady: input.onEditorReady,\n onUpdate: fallbackPersistence.onEditorUpdate,\n onEntitySuggestion: openSuggestion,\n onSuggestionClose: closeSuggestion,\n })\n const title = useDocumentTitle({\n documentId: input.documentId,\n title: input.title,\n updatedAt: input.documentUpdatedAt ?? null,\n readOnly: effectiveReadOnly,\n onTitleChange: input.onTitleChange,\n })\n React.useEffect(() => {\n const controller = new AbortController()\n input.onSaveReady?.(async () => {\n if (controller.signal.aborted || input.readOnly || !editorModel.editorRef.current) return false\n return input.transport === 'fallback'\n ? fallbackPersistence.saveNow()\n : input.collabResources\n ? saveCollaborativeContent(input.collabResources, controller.signal)\n : false\n })\n return () => {\n controller.abort()\n input.onSaveReady?.(null)\n }\n }, [editorModel.editorRef, fallbackPersistence.saveNow, input.collabResources, input.onSaveReady, input.readOnly, input.transport])\n const insertions = useEditorInsertions({\n documentId: input.documentId,\n editorRef: editorModel.editorRef,\n disabled: effectiveReadOnly,\n suggestionRange,\n setSuggestionRange,\n })\n React.useEffect(() => {\n if (suggestionRange && !effectiveReadOnly) insertions.setPickerOpen(true)\n }, [effectiveReadOnly, insertions.setPickerOpen, suggestionRange])\n\n const status = input.transport === 'fallback' ? 'offline' : input.connectionStatus\n const notice = input.transport === 'fallback'\n ? t(input.readOnly ? 'documents.editor.realtime.readOnlyFallback' : 'documents.editor.realtime.singleUserFallback')\n : input.readOnly\n ? t('documents.editor.readOnly')\n : input.mode === 'preview'\n ? t('documents.editor.mode.previewNotice')\n : null\n const availabilityNotice = status === 'offline' ? (\n <>\n <p>{notice ?? t('documents.editor.realtime.offline')}</p>\n <p className=\"mt-2\">\n {t('documents.editor.realtime.setupHint')}{' '}\n <LinkButton asChild underline=\"always\">\n <a href={DOCUMENTS_REALTIME_SETUP_GUIDE_URL} target=\"_blank\" rel=\"noopener noreferrer\">\n {t('documents.editor.realtime.setupGuide')}\n </a>\n </LinkButton>\n </p>\n </>\n ) : notice\n const selectionCommentHandler = canCreateSelectionComment({\n permissionReadOnly: input.readOnly,\n mode: input.mode,\n transport: input.transport,\n hasCommentHandler: Boolean(input.onComment),\n }) ? input.onComment : undefined\n const handleModeChange = React.useCallback(async (nextMode: EditorMode) => {\n if (nextMode === input.mode || modeChangeInFlightRef.current) return\n if (input.transport !== 'fallback' || nextMode !== 'preview') {\n input.onModeChange(nextMode)\n return\n }\n\n modeChangeInFlightRef.current = true\n try {\n if (await fallbackPersistence.saveNow()) input.onModeChange(nextMode)\n } finally {\n modeChangeInFlightRef.current = false\n }\n }, [fallbackPersistence.saveNow, input.mode, input.onModeChange, input.transport])\n\n return (\n <div className={cn('space-y-3', input.transport === 'collab' && 'om-doc-collab', input.mode === 'preview' && 'om-doc-preview')}>\n <style nonce={nonce}>{EDITOR_PRESENCE_STYLES}</style>\n <div className=\"overflow-hidden rounded-lg border border-border bg-muted shadow-sm\">\n <div className=\"sticky top-0 z-sticky border-b border-border bg-card/95\">\n <div className=\"flex flex-wrap items-center justify-between gap-2 px-3 py-2\">\n <EditorStatusPresence\n status={status}\n users={input.presenceUsers}\n counts={editorModel.counts}\n mode={input.mode}\n canEdit={!input.readOnly}\n onModeChange={(nextMode) => { void handleModeChange(nextMode) }}\n fallbackSave={input.transport === 'fallback' && !input.readOnly ? {\n status: fallbackPersistence.status,\n onSave: fallbackPersistence.saveNow,\n } : undefined}\n />\n </div>\n {input.mode === 'edit' ? (\n <EditorToolbar\n editor={editorModel.editor}\n disabled={effectiveReadOnly || !editorModel.editor}\n outlineOpen={outlineOpen}\n uploading={insertions.uploading}\n onToggleOutline={() => setOutlineOpen((value) => !value)}\n onOpenEntityPicker={insertions.openEntityPicker}\n onOpenLink={insertions.openLink}\n onImage={() => insertions.fileInputRef.current?.click()}\n />\n ) : null}\n {insertions.linkOpen && !effectiveReadOnly ? (\n <div className=\"flex flex-col gap-3 border-t border-border bg-muted/30 p-3 md:flex-row md:items-end\" onKeyDown={(event) => {\n if ((event.metaKey || event.ctrlKey) && event.key === 'Enter') { event.preventDefault(); insertions.applyLink() }\n if (event.key === 'Escape') { event.preventDefault(); insertions.setLinkOpen(false) }\n }}>\n <div className=\"min-w-0 flex-1 space-y-2\">\n <Label htmlFor={`document-link-${input.documentId}`}>{t('documents.editor.link.url')}</Label>\n <Input id={`document-link-${input.documentId}`} type=\"url\" value={insertions.linkHref} onChange={(event) => insertions.setLinkHref(event.target.value)} placeholder={t('documents.editor.link.placeholder')} />\n </div>\n <Button type=\"button\" onClick={insertions.applyLink}><Link2 />{t('documents.editor.link.apply')}</Button>\n <Button type=\"button\" variant=\"outline\" onClick={insertions.removeLink}><Unlink />{t('documents.editor.link.remove')}</Button>\n <Button type=\"button\" variant=\"ghost\" onClick={() => insertions.setLinkOpen(false)}>{t('documents.actions.cancel')}</Button>\n </div>\n ) : null}\n </div>\n <DocumentCanvas editor={editorModel.editor} title={title} readOnly={effectiveReadOnly} outlineOpen={outlineOpen} notice={availabilityNotice} onOpenLink={insertions.openLink} onComment={selectionCommentHandler} />\n </div>\n <EntityPicker open={insertions.entityPickerOpen} onOpenChange={insertions.setPickerOpen} onPick={(pick) => { void insertions.handleEntityPick(pick) }} />\n <RecordFieldsDialog\n documentId={input.documentId}\n linkId={insertions.recordFieldsLinkId}\n editor={editorModel.editor}\n canInsert={!effectiveReadOnly && Boolean(editorModel.editor)}\n onOpenChange={(open) => { if (!open) insertions.closeRecordFields() }}\n />\n <input ref={insertions.fileInputRef} type=\"file\" accept=\"image/*\" className=\"hidden\" aria-label={t('documents.editor.imageInput')} onChange={(event) => { void insertions.handleFiles(event.target.files) }} />\n </div>\n )\n}\n"],
5
+ "mappings": ";AAsGI,mBACE,KACA,YAFF;AApGJ,YAAY,WAAW;AACvB,SAAS,qCAAqC;AAC9C,SAAS,OAAO,cAAc;AAC9B,SAAS,cAAc;AACvB,SAAS,aAAa;AACtB,SAAS,aAAa;AACtB,SAAS,kBAAkB;AAC3B,SAAS,YAAY;AACrB,SAAS,UAAU;AACnB,SAAS,0CAA0C;AACnD,SAAS,oBAAoB;AAC7B,SAAS,sBAAsB;AAC/B,SAAS,4BAA4B;AACrC,SAA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Y,QAAQ,OAAc,UAAU,mBAAmB,aAA0B,QAAQ,oBAAoB,YAAY,WAAW,UAAU,WAAW,yBAAyB;AAAA,OACpN;AAAA,IACA,oBAAC,gBAAa,MAAM,WAAW,kBAAkB,cAAc,WAAW,eAAe,QAAQ,CAAC,SAAS;AAAE,WAAK,WAAW,iBAAiB,IAAI;AAAA,IAAE,GAAG;AAAA,IACvJ;AAAA,MAAC;AAAA;AAAA,QACC,YAAY,MAAM;AAAA,QAClB,QAAQ,WAAW;AAAA,QACnB,QAAQ,YAAY;AAAA,QACpB,WAAW,CAAC,qBAAqB,QAAQ,YAAY,MAAM;AAAA,QAC3D,cAAc,CAAC,SAAS;AAAE,cAAI,CAAC,KAAM,YAAW,kBAAkB;AAAA,QAAE;AAAA;AAAA,IACtE;AAAA,IACA,oBAAC,WAAM,KAAK,WAAW,cAAc,MAAK,QAAO,QAAO,WAAU,WAAU,UAAS,cAAY,EAAE,6BAA6B,GAAG,UAAU,CAAC,UAAU;AAAE,WAAK,WAAW,YAAY,MAAM,OAAO,KAAK;AAAA,IAAE,GAAG;AAAA,KAC/M;AAEJ;",
6
6
  "names": []
7
7
  }
@@ -15,11 +15,13 @@ const DOCUMENTS_MAX_FOLDER_DEPTH = 64;
15
15
  const DOCUMENTS_MAX_FOLDERS_PER_ORGANIZATION = 2e3;
16
16
  const DOCUMENTS_MAX_LISTED_FOLDERS = 5e3;
17
17
  const DOCUMENTS_MAX_LISTED_SHARES = 500;
18
+ const DOCUMENTS_REALTIME_SETUP_GUIDE_URL = "https://github.com/open-mercato/open-mercato/blob/main/packages/documents/README.md#realtime-collaboration-sidecar-m2";
18
19
  export {
19
20
  DOCUMENTS_ENTITY_IDS,
20
21
  DOCUMENTS_MAX_FOLDERS_PER_ORGANIZATION,
21
22
  DOCUMENTS_MAX_FOLDER_DEPTH,
22
23
  DOCUMENTS_MAX_LISTED_FOLDERS,
23
- DOCUMENTS_MAX_LISTED_SHARES
24
+ DOCUMENTS_MAX_LISTED_SHARES,
25
+ DOCUMENTS_REALTIME_SETUP_GUIDE_URL
24
26
  };
25
27
  //# sourceMappingURL=constants.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/documents/lib/constants.ts"],
4
- "sourcesContent": ["export const DOCUMENTS_ENTITY_IDS = {\n document: 'documents:document',\n documentContent: 'documents:document_content',\n documentFolder: 'documents:document_folder',\n documentShare: 'documents:document_share',\n documentComment: 'documents:document_comment',\n documentFavorite: 'documents:document_favorite',\n documentWatcher: 'documents:document_watcher',\n documentVersion: 'documents:document_version',\n documentAttachment: 'documents:document_attachment',\n documentTemplate: 'documents:document_template',\n documentEntityLink: 'documents:document_entity_link',\n} as const\n\n/** Maximum number of folder nodes from a root through its deepest descendant. */\nexport const DOCUMENTS_MAX_FOLDER_DEPTH = 64\n\n/**\n * Maximum active folders one organization may hold. A navigable folder tree\n * stays in the tens or low hundreds, so this only stops runaway automated\n * creation while bounding the manager-override listing that decrypts every\n * folder in scope.\n */\nexport const DOCUMENTS_MAX_FOLDERS_PER_ORGANIZATION = 2_000\n\n/**\n * Upper bound for one manager-override folder listing. Kept far above the\n * creation cap so an organization that predates that cap still lists a\n * coherent tree it can prune, instead of losing folder navigation entirely.\n */\nexport const DOCUMENTS_MAX_LISTED_FOLDERS = 5_000\n\n/**\n * Upper bound for one document's share listing. Explicit sharing stays in the\n * tens, and the mention path can only add one share per distinct mentioned\n * user, so this sits at the comment cap and keeps the listing (plus its\n * principal-label fan-out) bounded the way the comment and version lists are.\n */\nexport const DOCUMENTS_MAX_LISTED_SHARES = 500\n"],
5
- "mappings": "AAAO,MAAM,uBAAuB;AAAA,EAClC,UAAU;AAAA,EACV,iBAAiB;AAAA,EACjB,gBAAgB;AAAA,EAChB,eAAe;AAAA,EACf,iBAAiB;AAAA,EACjB,kBAAkB;AAAA,EAClB,iBAAiB;AAAA,EACjB,iBAAiB;AAAA,EACjB,oBAAoB;AAAA,EACpB,kBAAkB;AAAA,EAClB,oBAAoB;AACtB;AAGO,MAAM,6BAA6B;AAQnC,MAAM,yCAAyC;AAO/C,MAAM,+BAA+B;AAQrC,MAAM,8BAA8B;",
4
+ "sourcesContent": ["export const DOCUMENTS_ENTITY_IDS = {\n document: 'documents:document',\n documentContent: 'documents:document_content',\n documentFolder: 'documents:document_folder',\n documentShare: 'documents:document_share',\n documentComment: 'documents:document_comment',\n documentFavorite: 'documents:document_favorite',\n documentWatcher: 'documents:document_watcher',\n documentVersion: 'documents:document_version',\n documentAttachment: 'documents:document_attachment',\n documentTemplate: 'documents:document_template',\n documentEntityLink: 'documents:document_entity_link',\n} as const\n\n/** Maximum number of folder nodes from a root through its deepest descendant. */\nexport const DOCUMENTS_MAX_FOLDER_DEPTH = 64\n\n/**\n * Maximum active folders one organization may hold. A navigable folder tree\n * stays in the tens or low hundreds, so this only stops runaway automated\n * creation while bounding the manager-override listing that decrypts every\n * folder in scope.\n */\nexport const DOCUMENTS_MAX_FOLDERS_PER_ORGANIZATION = 2_000\n\n/**\n * Upper bound for one manager-override folder listing. Kept far above the\n * creation cap so an organization that predates that cap still lists a\n * coherent tree it can prune, instead of losing folder navigation entirely.\n */\nexport const DOCUMENTS_MAX_LISTED_FOLDERS = 5_000\n\n/**\n * Upper bound for one document's share listing. Explicit sharing stays in the\n * tens, and the mention path can only add one share per distinct mentioned\n * user, so this sits at the comment cap and keeps the listing (plus its\n * principal-label fan-out) bounded the way the comment and version lists are.\n */\nexport const DOCUMENTS_MAX_LISTED_SHARES = 500\n\nexport const DOCUMENTS_REALTIME_SETUP_GUIDE_URL = 'https://github.com/open-mercato/open-mercato/blob/main/packages/documents/README.md#realtime-collaboration-sidecar-m2'\n"],
5
+ "mappings": "AAAO,MAAM,uBAAuB;AAAA,EAClC,UAAU;AAAA,EACV,iBAAiB;AAAA,EACjB,gBAAgB;AAAA,EAChB,eAAe;AAAA,EACf,iBAAiB;AAAA,EACjB,kBAAkB;AAAA,EAClB,iBAAiB;AAAA,EACjB,iBAAiB;AAAA,EACjB,oBAAoB;AAAA,EACpB,kBAAkB;AAAA,EAClB,oBAAoB;AACtB;AAGO,MAAM,6BAA6B;AAQnC,MAAM,yCAAyC;AAO/C,MAAM,+BAA+B;AAQrC,MAAM,8BAA8B;AAEpC,MAAM,qCAAqC;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/documents",
3
- "version": "0.11.1-develop.8983.1.8f477e3f83",
3
+ "version": "0.11.1-develop.9003.1.ce86c31a07",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -75,8 +75,8 @@
75
75
  "@hocuspocus/server": "^4.4.0",
76
76
  "@hocuspocus/transformer": "^4.3.0",
77
77
  "@mikro-orm/core": "^7.1.14",
78
- "@open-mercato/events": "0.11.1-develop.8983.1.8f477e3f83",
79
- "@open-mercato/ui": "0.11.1-develop.8983.1.8f477e3f83",
78
+ "@open-mercato/events": "0.11.1-develop.9003.1.ce86c31a07",
79
+ "@open-mercato/ui": "0.11.1-develop.9003.1.ce86c31a07",
80
80
  "@tiptap/core": "3.32.0",
81
81
  "@tiptap/extension-bubble-menu": "3.32.0",
82
82
  "@tiptap/extension-collaboration": "3.32.0",
@@ -112,14 +112,14 @@
112
112
  },
113
113
  "peerDependencies": {
114
114
  "@mikro-orm/postgresql": "^7.0.14",
115
- "@open-mercato/shared": "0.11.1-develop.8983.1.8f477e3f83",
115
+ "@open-mercato/shared": "0.11.1-develop.9003.1.ce86c31a07",
116
116
  "react": "^19.0.0",
117
117
  "react-dom": "^19.0.0",
118
118
  "react-is": ">=18.0.0"
119
119
  },
120
120
  "devDependencies": {
121
- "@open-mercato/core": "0.11.1-develop.8983.1.8f477e3f83",
122
- "@open-mercato/shared": "0.11.1-develop.8983.1.8f477e3f83",
121
+ "@open-mercato/core": "0.11.1-develop.9003.1.ce86c31a07",
122
+ "@open-mercato/shared": "0.11.1-develop.9003.1.ce86c31a07",
123
123
  "@types/jest": "^30.0.0",
124
124
  "@types/pg": "^8.23.1",
125
125
  "@types/react": "^19.2.18",
@@ -15,6 +15,7 @@ import { loadDocumentFavoriteIds } from '../lib/favorites'
15
15
  import { getEntityRegistryEntry } from '../lib/entityRegistry'
16
16
  import { verifyEntityRegistryTargetAccess } from '../lib/entityRegistry.server'
17
17
  import { isDocumentEntityRegistryModuleEnabled } from '../lib/entityRegistryAvailability.server'
18
+ import { assertTier } from '../lib/permissions'
18
19
  import {
19
20
  handleDocumentsRouteError,
20
21
  hasDocumentsFeature,
@@ -166,13 +167,19 @@ export async function GET(request: Request): Promise<Response> {
166
167
  ) {
167
168
  throw new CrudHttpError(403, { error: 'api.errors.forbidden' })
168
169
  }
169
- const verifiedTarget = await verifyEntityRegistryTargetAccess(request, {
170
- entityType: query.entityType,
171
- entityId: query.entityId,
172
- })
170
+ let entityId = query.entityId
171
+ if (query.entityType === 'document') {
172
+ await assertTier(ctx.em, entityId, ctx.auth, 'viewer')
173
+ } else {
174
+ const verifiedTarget = await verifyEntityRegistryTargetAccess(request, {
175
+ entityType: query.entityType,
176
+ entityId,
177
+ })
178
+ entityId = verifiedTarget.id
179
+ }
173
180
  relationFilter = {
174
181
  entityType: query.entityType,
175
- entityId: verifiedTarget.id,
182
+ entityId,
176
183
  }
177
184
  }
178
185
 
@@ -45,7 +45,7 @@ export function DocumentCanvas({
45
45
  title: TitleModel
46
46
  readOnly: boolean
47
47
  outlineOpen: boolean
48
- notice: string | null
48
+ notice: React.ReactNode
49
49
  onOpenLink: () => void
50
50
  onComment?: (anchor: CommentAnchor) => void
51
51
  }) {
@@ -6,8 +6,10 @@ import { Link2, Unlink } from 'lucide-react'
6
6
  import { Button } from '@open-mercato/ui/primitives/button'
7
7
  import { Input } from '@open-mercato/ui/primitives/input'
8
8
  import { Label } from '@open-mercato/ui/primitives/label'
9
+ import { LinkButton } from '@open-mercato/ui/primitives/link-button'
9
10
  import { useT } from '@open-mercato/shared/lib/i18n/context'
10
11
  import { cn } from '@open-mercato/shared/lib/utils'
12
+ import { DOCUMENTS_REALTIME_SETUP_GUIDE_URL } from '@open-mercato/documents/modules/documents/lib/constants'
11
13
  import { EntityPicker } from '../components/EntityPicker'
12
14
  import { DocumentCanvas } from './DocumentCanvas'
13
15
  import { EditorStatusPresence } from './EditorStatusPresence'
@@ -97,6 +99,19 @@ export function DocumentEditorSurface(input: Props) {
97
99
  : input.mode === 'preview'
98
100
  ? t('documents.editor.mode.previewNotice')
99
101
  : null
102
+ const availabilityNotice = status === 'offline' ? (
103
+ <>
104
+ <p>{notice ?? t('documents.editor.realtime.offline')}</p>
105
+ <p className="mt-2">
106
+ {t('documents.editor.realtime.setupHint')}{' '}
107
+ <LinkButton asChild underline="always">
108
+ <a href={DOCUMENTS_REALTIME_SETUP_GUIDE_URL} target="_blank" rel="noopener noreferrer">
109
+ {t('documents.editor.realtime.setupGuide')}
110
+ </a>
111
+ </LinkButton>
112
+ </p>
113
+ </>
114
+ ) : notice
100
115
  const selectionCommentHandler = canCreateSelectionComment({
101
116
  permissionReadOnly: input.readOnly,
102
117
  mode: input.mode,
@@ -164,7 +179,7 @@ export function DocumentEditorSurface(input: Props) {
164
179
  </div>
165
180
  ) : null}
166
181
  </div>
167
- <DocumentCanvas editor={editorModel.editor} title={title} readOnly={effectiveReadOnly} outlineOpen={outlineOpen} notice={notice} onOpenLink={insertions.openLink} onComment={selectionCommentHandler} />
182
+ <DocumentCanvas editor={editorModel.editor} title={title} readOnly={effectiveReadOnly} outlineOpen={outlineOpen} notice={availabilityNotice} onOpenLink={insertions.openLink} onComment={selectionCommentHandler} />
168
183
  </div>
169
184
  <EntityPicker open={insertions.entityPickerOpen} onOpenChange={insertions.setPickerOpen} onPick={(pick) => { void insertions.handleEntityPick(pick) }} />
170
185
  <RecordFieldsDialog
@@ -151,6 +151,8 @@
151
151
  "documents.editor.realtime.presenceLabel": "Bearbeiten gerade",
152
152
  "documents.editor.realtime.readOnlyFallback": "Echtzeit ist nicht verfügbar — die zuletzt gespeicherte Version wird schreibgeschützt angezeigt.",
153
153
  "documents.editor.realtime.reconnecting": "Verbindung wird wiederhergestellt…",
154
+ "documents.editor.realtime.setupGuide": "Einrichtung der Echtzeit-Zusammenarbeit",
155
+ "documents.editor.realtime.setupHint": "Die Echtzeit-Zusammenarbeit benötigt einen laufenden Zusammenarbeitsdienst und eine funktionierende Verbindung. Bitten Sie Ihren Administrator, die Einrichtung zu prüfen.",
154
156
  "documents.editor.realtime.singleUserFallback": "Echtzeit ist nicht verfügbar — Änderungen werden im Einzelbenutzermodus gespeichert.",
155
157
  "documents.editor.status.error": "Speichern fehlgeschlagen",
156
158
  "documents.editor.status.saved": "Gespeichert",
@@ -151,6 +151,8 @@
151
151
  "documents.editor.realtime.presenceLabel": "Editing now",
152
152
  "documents.editor.realtime.readOnlyFallback": "Realtime is unavailable — showing the last saved version (read-only).",
153
153
  "documents.editor.realtime.reconnecting": "Reconnecting…",
154
+ "documents.editor.realtime.setupGuide": "Realtime setup guide",
155
+ "documents.editor.realtime.setupHint": "Realtime collaboration needs a running collaboration service and a working connection. Ask your administrator to check the setup.",
154
156
  "documents.editor.realtime.singleUserFallback": "Realtime is unavailable — changes are saved in single-user mode.",
155
157
  "documents.editor.status.error": "Save failed",
156
158
  "documents.editor.status.saved": "Saved",
@@ -151,6 +151,8 @@
151
151
  "documents.editor.realtime.presenceLabel": "Editando ahora",
152
152
  "documents.editor.realtime.readOnlyFallback": "El tiempo real no está disponible — se muestra la última versión guardada (solo lectura).",
153
153
  "documents.editor.realtime.reconnecting": "Reconectando…",
154
+ "documents.editor.realtime.setupGuide": "Guía de configuración de la colaboración en tiempo real",
155
+ "documents.editor.realtime.setupHint": "La colaboración en tiempo real necesita un servicio de colaboración en ejecución y una conexión que funcione. Pide a tu administrador que revise la configuración.",
154
156
  "documents.editor.realtime.singleUserFallback": "El tiempo real no está disponible — los cambios se guardan en modo de un solo usuario.",
155
157
  "documents.editor.status.error": "Error al guardar",
156
158
  "documents.editor.status.saved": "Guardado",
@@ -151,6 +151,8 @@
151
151
  "documents.editor.realtime.presenceLabel": "편집 중",
152
152
  "documents.editor.realtime.readOnlyFallback": "실시간 연결을 사용할 수 없어 마지막으로 저장된 버전을 표시합니다(읽기 전용).",
153
153
  "documents.editor.realtime.reconnecting": "다시 연결하는 중…",
154
+ "documents.editor.realtime.setupGuide": "실시간 공동 작업 설정 가이드",
155
+ "documents.editor.realtime.setupHint": "실시간 공동 작업을 사용하려면 공동 작업 서비스가 실행 중이고 연결이 정상적으로 작동해야 합니다. 관리자에게 설정을 확인해 달라고 요청하세요.",
154
156
  "documents.editor.realtime.singleUserFallback": "실시간 연결을 사용할 수 없어 단독 편집 모드로 변경 사항을 저장합니다.",
155
157
  "documents.editor.status.error": "저장 실패",
156
158
  "documents.editor.status.saved": "저장됨",
@@ -151,6 +151,8 @@
151
151
  "documents.editor.realtime.presenceLabel": "Edytują teraz",
152
152
  "documents.editor.realtime.readOnlyFallback": "Edycja w czasie rzeczywistym jest niedostępna — wyświetlana jest ostatnia zapisana wersja (tylko do odczytu).",
153
153
  "documents.editor.realtime.reconnecting": "Ponowne łączenie…",
154
+ "documents.editor.realtime.setupGuide": "Instrukcja konfiguracji współpracy na żywo",
155
+ "documents.editor.realtime.setupHint": "Współpraca na żywo wymaga uruchomionej usługi współpracy i działającego połączenia. Poproś administratora o sprawdzenie konfiguracji.",
154
156
  "documents.editor.realtime.singleUserFallback": "Edycja w czasie rzeczywistym jest niedostępna — zmiany są zapisywane w trybie jednego użytkownika.",
155
157
  "documents.editor.status.error": "Zapisywanie nie powiodło się",
156
158
  "documents.editor.status.saved": "Zapisano",
@@ -37,3 +37,5 @@ export const DOCUMENTS_MAX_LISTED_FOLDERS = 5_000
37
37
  * principal-label fan-out) bounded the way the comment and version lists are.
38
38
  */
39
39
  export const DOCUMENTS_MAX_LISTED_SHARES = 500
40
+
41
+ export const DOCUMENTS_REALTIME_SETUP_GUIDE_URL = 'https://github.com/open-mercato/open-mercato/blob/main/packages/documents/README.md#realtime-collaboration-sidecar-m2'