Skip to content

⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.

5.2 KB
Raw Blame
// Shared helpers for the planner API (projects, issues, and their dependent
// entities). Each feature folder under modules/ holds a service.ts (Drizzle data
// access) and an index.ts (Elysia routes) that exposes it over HTTP.

// An error carrying an HTTP status. Services and routes throw it. The planner
// plugin's onError maps it to a { error } JSON response with that status.
//
// `code` names the failure for a caller that has to branch on it rather than show
// the message — an agent moving issues without a human watching. Most failures
// leave it unset: the status and the message are enough to render.
export class HttpError extends Error {
  constructor(
    public status: number,
    message: string,
    public code?: string,
  ) {
    super(message);
  }
}

// A timestamptz column comes back from Drizzle as a JS Date; callers return it
// as an ISO string. `date` columns come back as raw 'YYYY-MM-DD' strings
// (Drizzle's default mode for date), so no timezone is ever applied to them.
export const iso = (value: Date): string => value.toISOString();

// Whether a share link with this expiry still works: no expiry, or one still ahead.
// Issues, views, documents and the share module all read a link's state through it.
export const shareLive = (expiresAt: Date | null): boolean =>
  expiresAt === null || expiresAt.getTime() > Date.now();

// A timestamp from a query string. Empty means not set: a tool-calling model fills
// optional fields with "".
export function instantParam(name: string, value: string | undefined): Date | undefined {
  if (!value) return undefined;
  const at = new Date(value);
  if (Number.isNaN(at.getTime())) throw new HttpError(400, `${name} is not a valid ISO timestamp`);
  return at;
}

// numeric columns come back as strings; coerce to a JS number.
export const num = (value: unknown): number => (value == null ? 0 : Number(value));

// The same coercion for a nullable numeric column, where null is a value.
export const numOrNull = (value: string | null): number | null =>
  value == null ? null : Number(value);

// Escapes the five characters that are significant in HTML/XML text, so a value
// (an issue title, a user name) is safe to interpolate into an HTML email body or a
// Telegram HTML message.
export function escapeHtml(s: string): string {
  return s
    .replace(/&/g, '&')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');
}

// The ILIKE pattern for the term. The wildcards a member types are escaped, so a query
// with a % in it looks for that character.
export function likePattern(term: string): string {
  return `%${term.replace(/([\\%_])/g, '\\$1')}%`;
}

// The Postgres SQLSTATE of a driver error. Drizzle wraps the driver error in a
// DrizzleQueryError with the original as `.cause`, so the code may be one level
// down; unwrap the cause chain to find it.
export function pgErrorCode(err: unknown): string | undefined {
  let current: unknown = err;
  for (let depth = 0; current && typeof current === 'object' && depth < 5; depth++) {
    const code = (current as { code?: unknown }).code;
    if (typeof code === 'string') return code;
    current = (current as { cause?: unknown }).cause;
  }
  return undefined;
}

// Maps a Postgres unique_violation (a duplicate name on a UNIQUE constraint) to
// a clean 409, so the UI shows "already exists" instead of an opaque 500. Any
// other error is rethrown unchanged.
export function rethrowDuplicate(err: unknown, what: string): never {
  if (pgErrorCode(err) === '23505') {
    const article = /^[aeiou]/i.test(what) ? 'An' : 'A';
    throw new HttpError(409, `${article} ${what} with this name already exists.`);
  }
  throw err;
}

// The status and the { error } body the planner answers an error with. `code` is the
// one Elysia hands to onError.
export function errorAnswer(
  code: unknown,
  error: unknown,
): { status: number; body: { error: string; code?: string } } {
  if (error instanceof HttpError) {
    const body = error.code ? { error: error.message, code: error.code } : { error: error.message };
    return { status: error.status, body };
  }
  if (code === 'VALIDATION') {
    // The validator's first message is enough for the UI; the full report is
    // large JSON that the client would just show verbatim.
    const first = (error as { all?: { summary?: string }[] }).all?.[0]?.summary;
    return { status: 400, body: { error: first ?? 'Invalid request body' } };
  }
  if (code === 'NOT_FOUND') return { status: 404, body: { error: 'Not found' } };
  if (pgErrorCode(error) === '23505') {
    return { status: 409, body: { error: 'A record with this name already exists.' } };
  }
  // drizzle puts the failed statement and its parameters in the message, and the public
  // routes would hand that to anyone.
  return { status: 500, body: { error: 'Internal server error' } };
}

// Reads a positive integer from an environment variable, falling back to the default
// when unset, empty, or not a positive finite number.
export function intEnv(name: string, fallback: number): number {
  const raw = process.env[name];
  if (raw == null || raw === '') return fallback;
  const n = Number(raw);
  return Number.isFinite(n) && n > 0 ? n : fallback;
}