← Files Flows by plugin.spaceARCHIVED FILE

lib/comments.mjs

6.25 KB · Nov 30, 2026 · 00:17 UTC

↓ Download file

import { randomUUID } from 'node:crypto';
import { mkdir, open, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { defaultLibraryRoot } from './library.mjs';

export const MAX_COMMENTS = 1000;
export const commentError = (message, status = 422) => Object.assign(new Error(message), { status });
export function commentText(value) {
  if (typeof value !== 'string' || !value.trim() || value.length > 4000) throw commentError('Write a comment of 1–4000 characters.');
  return value.trim();
}
export function commentMetadata(value) {
  if (value == null) return null;
  if (typeof value !== 'object' || Array.isArray(value) || !value.position ||
    !['x', 'y'].every(key => typeof value.position[key] === 'number' && Number.isFinite(value.position[key]) && Math.abs(value.position[key]) <= 1e7) ||
    !['flow', 'patches'].includes(value.view) ||
    !['nodeIds', 'edgeIds'].every(key => Array.isArray(value[key]) && value[key].length <= 100 && value[key].every(id => typeof id === 'string' && id.length > 0 && id.length <= 200))) throw commentError('Invalid whiteboard comment position or references.');
  return { position: { x: value.position.x, y: value.position.y }, nodeIds: [...new Set(value.nodeIds)], edgeIds: [...new Set(value.edgeIds)], view: value.view };
}
export function commentAction(value) {
  if (!value || typeof value !== 'object' || Array.isArray(value)) throw commentError('Send a comment object.');
  if (value.action === 'resolve') {
    if (typeof value.id !== 'string' || typeof value.resolved !== 'boolean') throw commentError('Choose a thread and its status.');
    return { action: 'resolve', id: value.id, resolved: value.resolved };
  }
  const body = commentText(value.body);
  for (const field of ['parentId', 'nodeId']) if (value[field] != null && (typeof value[field] !== 'string' || !value[field] || value[field].length > 200)) throw commentError('Invalid comment anchor.');
  const metadata = value.parentId ? null : commentMetadata(value.metadata);
  return { action: 'create', body, parentId: value.parentId || null, nodeId: metadata ? metadata.nodeIds[0] || null : value.nodeId || null, metadata };
}

// Separate from the flow document so screenshot captures and graph edits never overwrite discussions.
export function createCommentsStore(root = defaultLibraryRoot()) {
  function path(id) { if (!/^[a-f0-9]{24}$/.test(id)) throw commentError('Unknown flow.', 404); return join(root, 'comments', `${id}.json`); }
  async function list(id) {
    try { const value = JSON.parse(await readFile(path(id), 'utf8')); if (!Array.isArray(value)) throw new Error('Invalid comment store.'); return value; }
    catch (error) { if (error.code === 'ENOENT') return []; throw error; }
  }
  async function mutate(id, change) {
    await mkdir(join(root, 'comments'), { recursive: true, mode: 0o700 });
    const file = path(id), lockPath = `${file}.lock`, temporary = `${file}.${randomUUID()}.tmp`;
    let lock;
    for (let attempt = 0; attempt < 100; attempt++) {
      try { lock = await open(lockPath, 'wx', 0o600); await lock.writeFile(String(process.pid)); break; }
      catch (error) {
        if (error.code !== 'EEXIST') throw error;
        try {
          const before = await stat(lockPath), pid = Number(await readFile(lockPath, 'utf8'));
          let dead = !Number.isInteger(pid) || pid <= 0;
          if (!dead) { try { process.kill(pid, 0); } catch (failure) { dead = failure.code === 'ESRCH'; } }
          if (dead && Date.now() - before.mtimeMs > 1000 && (await stat(lockPath)).ino === before.ino) await rm(lockPath, { force: true });
        } catch { /* Another writer released the lock. */ }
        await new Promise(resolve => setTimeout(resolve, 20));
      }
    }
    if (!lock) throw commentError('Comments are busy. Try again.', 409);
    try { const next = change(await list(id)); await writeFile(temporary, JSON.stringify(next), { flag: 'wx', mode: 0o600 }); await rename(temporary, file); return next; }
    finally { await rm(temporary, { force: true }); await lock.close(); await rm(lockPath, { force: true }); }
  }
  return {
    list,
    async clear(id) { await mutate(id, () => []); },
    async create(id, value, document) {
      const input = commentAction(value);
      const nextId = randomUUID();
      await mutate(id, comments => {
        if (comments.length >= MAX_COMMENTS) throw commentError('This flow has reached the 1000-comment limit.', 409);
        const parent = input.parentId && comments.find(comment => comment.id === input.parentId && !comment.parentId);
        if (input.parentId && !parent) throw commentError('Thread not found. Refresh comments.', 404);
        if (!parent && input.nodeId && !document.nodes.some(node => node.id === input.nodeId)) throw commentError('Step not found.', 404);
        if (!parent && input.metadata && (input.metadata.nodeIds.some(id => !document.nodes.some(node => node.id === id)) || input.metadata.edgeIds.some(id => !document.edges.some(edge => edge.id === id)))) throw commentError('Comment references are absent from this flow. Refresh the flow before commenting.', 404);
        const name = typeof value.authorName === 'string' ? value.authorName.trim().slice(0, 80) : '';
        return [...comments, { id: nextId, parentId: parent?.id || null, nodeId: parent ? parent.nodeId : input.nodeId, metadata: parent ? parent.metadata || null : input.metadata, body: input.body, author: { id: 'local', name: name || 'You' }, createdAt: new Date().toISOString(), resolved: false }];
      });
      return { id: nextId };
    },
    async resolve(id, value) {
      const action = commentAction(value);
      await mutate(id, comments => {
        const thread = comments.find(comment => comment.id === action.id && !comment.parentId);
        if (!thread) throw commentError('Thread not found.', 404);
        return comments.map(comment => comment.id === action.id ? { ...comment, resolved: action.resolved } : comment);
      });
      return { updated: true };
    },
    async remove(id, commentId) {
      await mutate(id, comments => {
        if (!comments.some(comment => comment.id === commentId)) throw commentError('Comment not found.', 404);
        return comments.filter(comment => comment.id !== commentId && comment.parentId !== commentId);
      });
      return { deleted: true };
    },
  };
}

SHA-256: 70bcdf8e4abe190a80ccbd9a816c01d97e1e82d1bb6509838230df1bc5c98dde