SPB Git

Repository Public MIT

objects.ts 25.9 KB 558 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : VQuant8 * File             : server/next/objects.ts9 * Module           : server10 * Repository       : https://git.spboucher.ai/vquant11 * Project Website  : https://vquant.spboucher.ai12 * Created          : 2026-11-2013 * Last Modified    : 2026-11-2014 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development      : dev@spboucher.ai24 * Support          : support@spboucher.ai25 * Security/Admin   : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * SPDX Identifier  : MIT34 * License          : MIT License35 * License File     : LICENSE36 *37 * Do not embed credentials, private keys, access tokens,38 * certificates or confidential personal information.39 *40 * =============================================================================41 * END OF SP BOUCHER SOURCE HEADER42 * =============================================================================43 */4445/**46 * Object store of VQuant Next (contract §1.1, §1.2): the person's watchlists, portfolios, workspaces, charts,47 * projects, notes, reviews and preferences, synchronised between the web app and the native clients.48 *49 * Every write is one SQLite transaction: it checks the base revision, bumps `rev`, takes the next value of the50 * owner's change counter (`seq`), archives the revision it replaces (versioned kinds) and only then tells the51 * owner's other devices (sync bus). Nothing here ever reads or writes a row of another owner: `owner` is part of52 * every statement's WHERE clause and of the primary key.53 *54 * Internal API for the other server modules: getObject, listObjects, putObject, deleteObject, and writeObject55 * for server-authored changes (no base revision: the mutation is applied to whatever is stored, atomically).56 */57import type { Express, NextFunction, Request, Response } from "express";58import type Database from "better-sqlite3";59import { z } from "zod";60import { isSqlite, pool } from "../db";61import { logger } from "../utils/logger";62import { audit, requestDevice } from "./audit";63import { publishChange } from "./sync";6465export const KINDS = ["watchlist", "portfolio", "workspace", "chart", "project", "note", "review", "preference"] as const;66export type Kind = (typeof KINDS)[number];6768/** Kinds whose replaced revisions are kept (the last VERSIONS_KEPT of each object). */69const VERSIONED: ReadonlySet<string> = new Set(["project", "note", "chart", "workspace", "portfolio"]);70const VERSIONS_KEPT = 30;71/** Kinds a client may read and delete but never write: the server authors them. */72const SERVER_ONLY: ReadonlySet<string> = new Set(["review"]);73export const MAX_DATA_BYTES = 256 * 1024;74export const ID_RE = /^[A-Za-z0-9_-]{1,64}$/;7576export interface Envelope<T = Record<string, unknown>> {77  kind: Kind;78  id: string;79  rev: number;80  seq: number;81  createdAt: number;82  updatedAt: number;83  deleted: boolean;84  device: string | null;85  data: T;86}8788/** A refused write. `status` is the HTTP status; a conflict carries the stored envelope. */89export class ObjectError extends Error {90  constructor(91    public status: number,92    message: string,93    public current?: Envelope,94  ) {95    super(message);96  }97}9899// ─── Validation (unknown keys are kept: a newer client may store fields this server does not know yet) ────────100const text = (max: number) => z.string().max(max);101const opt = <T extends z.ZodTypeAny>(t: T) => t.nullish();102const symbol = z.string().trim().min(1).max(24);103104const layoutNode: z.ZodType<unknown> = z.lazy(() =>105  z.union([106    z.object({ type: z.literal("split"), direction: z.enum(["row", "column"]), sizes: z.array(z.number().finite()).max(32), children: z.array(layoutNode).max(32) }).passthrough(),107    z.object({ type: z.literal("panel"), panelId: z.string().min(1).max(64) }).passthrough(),108  ]),109);110const PANEL_TYPES = ["chart", "watchlist", "quote", "statements", "news", "chat", "notebook", "quant", "portfolio", "options", "macro", "risk", "note", "table"] as const;111const PROJECT_ITEM_TYPES = ["conversation", "quant_job", "note", "chart", "report", "notebook", "dataset", "review", "portfolio", "watchlist"] as const;112113const SCHEMAS: Record<Kind, z.ZodTypeAny> = {114  watchlist: z.object({ name: text(120).min(1), symbols: z.array(symbol).max(200), note: opt(text(4000)) }).passthrough(),115  portfolio: z116    .object({117      name: text(120).min(1),118      baseCurrency: text(8).min(3),119      benchmark: opt(symbol),120      cash: opt(z.array(z.object({ currency: text(8).min(3), amount: z.number().finite() }).passthrough()).max(50)),121      positions: z122        .array(123          z124            .object({125              symbol,126              quantity: z.number().finite(),127              costBasis: opt(z.number().finite()),128              currency: opt(text(8)),129              note: opt(text(300)),130              openedAt: opt(z.union([z.number().finite(), text(40)])),131            })132            .passthrough(),133        )134        .max(2000),135    })136    .passthrough(),137  workspace: z138    .object({139      name: text(120).min(1),140      icon: opt(text(64)),141      layout: layoutNode,142      panels: z.record(z.string().max(64), z.object({ type: z.enum(PANEL_TYPES), title: opt(text(200)), config: opt(z.record(z.unknown())) }).passthrough()),143    })144    .passthrough(),145  chart: z146    .object({147      symbol,148      interval: opt(text(12)),149      range: opt(z.unknown()),150      chartType: opt(z.enum(["candles", "ohlc", "line", "area"])),151      logScale: opt(z.boolean()),152      adjust: opt(z.union([z.boolean(), text(20)])),153      indicators: opt(z.array(z.object({ id: text(64), type: text(64), params: opt(z.record(z.unknown())), pane: opt(z.union([z.number(), text(32)])) }).passthrough()).max(60)),154      compare: opt(z.array(symbol).max(20)),155      drawings: opt(156        z157          .array(158            z159              .object({ id: text(64), type: text(40), points: z.array(z.object({ t: z.number().finite(), p: z.number().finite() }).passthrough()).max(200), style: opt(z.record(z.unknown())), text: opt(text(2000)) })160              .passthrough(),161          )162          .max(500),163      ),164      events: opt(z.boolean()),165    })166    .passthrough(),167  project: z168    .object({169      title: text(200).min(1),170      question: opt(text(4000)),171      hypotheses: opt(z.array(z.object({ id: text(64), text: text(2000), status: opt(z.enum(["open", "supported", "rejected", "inconclusive"])) }).passthrough()).max(100)),172      status: opt(z.enum(["active", "paused", "done", "archived"])),173      dataSources: opt(z.array(z.object({ id: text(64), provider: opt(text(80)), description: opt(text(1000)) }).passthrough()).max(100)),174      items: z175        .array(z.object({ id: text(64).min(1), type: z.enum(PROJECT_ITEM_TYPES), ref: text(200).min(1), title: opt(text(300)), addedAt: opt(z.number().finite()) }).passthrough())176        .max(1000),177      summary: opt(text(20000)),178    })179    .passthrough(),180  note: z.object({ title: text(300).min(1), body: z.string(), projectId: opt(z.string().regex(ID_RE)) }).passthrough(),181  review: z.object({}).passthrough(),182  preference: z183    .object({184      theme: opt(text(40)),185      accent: opt(text(40)),186      density: opt(text(40)),187      numberFormat: opt(text(40)),188      upDownColors: opt(z.enum(["classic", "cvd"])),189      reduceMotion: opt(z.boolean()),190      defaultModel: opt(text(120)),191      defaultMode: opt(text(20)),192      routing: opt(z.object({ strategy: opt(z.enum(["quality", "balanced", "economy"])), providers: opt(z.array(text(40)).max(20)) }).passthrough()),193      budget: opt(z.object({ maxCostUsd: opt(z.number().finite().min(0)), maxMinutes: opt(z.number().finite().min(0)) }).passthrough()),194      memory: opt(z.object({ enabled: opt(z.boolean()), retentionDays: opt(z.number().int().min(1).max(3650)) }).passthrough()),195      recentSearches: opt(z.array(text(200)).max(50)),196      homeWorkspaceId: opt(z.string().regex(ID_RE)),197    })198    .passthrough(),199};200201export function isKind(k: unknown): k is Kind {202  return typeof k === "string" && (KINDS as readonly string[]).includes(k);203}204205/** Checks `data` against its kind and the size limit; returns the JSON text that is stored. */206function validate(kind: Kind, id: string, data: unknown): { json: string; data: Record<string, unknown> } {207  if (!ID_RE.test(id)) throw new ObjectError(400, "Invalid id: 1 to 64 characters among A-Z a-z 0-9 _ -");208  if (kind === "preference" && id !== "default") throw new ObjectError(400, 'The preference object has the id "default".');209  if (typeof data !== "object" || data === null || Array.isArray(data)) throw new ObjectError(400, "data must be a JSON object");210  let json: string;211  try {212    json = JSON.stringify(data);213  } catch {214    throw new ObjectError(400, "data must be JSON");215  }216  if (Buffer.byteLength(json, "utf8") > MAX_DATA_BYTES) throw new ObjectError(413, `data is larger than ${MAX_DATA_BYTES / 1024} KB`);217  const parsed = SCHEMAS[kind].safeParse(data);218  if (!parsed.success) {219    const issue = parsed.error.issues[0];220    throw new ObjectError(400, `Invalid ${kind}: ${issue.path.length ? `${issue.path.join(".")}: ` : ""}${issue.message}`);221  }222  // The stored value is the client's own JSON (not zod's output): nothing is coerced, reordered or dropped.223  return { json, data: JSON.parse(json) as Record<string, unknown> };224}225226// ─── Storage ─────────────────────────────────────────────────────────────────227interface Row {228  owner: string;229  kind: string;230  id: string;231  rev: number;232  seq: number;233  data: string;234  created_at: number;235  updated_at: number;236  deleted: number;237  device: string | null;238}239240function sqlite(): Database.Database {241  if (!isSqlite) throw new Error("VQuant Next needs the SQLite database");242  return pool as Database.Database;243}244245function envelope(r: Row): Envelope {246  let data: Record<string, unknown> = {};247  try {248    data = JSON.parse(r.data);249  } catch {250    /* a row that does not parse is served empty rather than breaking the whole feed */251  }252  return { kind: r.kind as Kind, id: r.id, rev: r.rev, seq: r.seq, createdAt: r.created_at, updatedAt: r.updated_at, deleted: !!r.deleted, device: r.device, data };253}254255// Work that must happen once before an owner's objects are read (the legacy portfolio bridge registers here).256const firstAccessHooks: Array<(owner: string) => void> = [];257const seenOwners = new Set<string>();258export function onOwnerFirstAccess(fn: (owner: string) => void): void {259  firstAccessHooks.push(fn);260}261function touch(owner: string): void {262  if (seenOwners.has(owner)) return;263  seenOwners.add(owner); // before the hooks: they write objects themselves264  for (const fn of firstAccessHooks) {265    try {266      fn(owner);267    } catch (e) {268      // Not remembered as done: the next access of this person tries again.269      seenOwners.delete(owner);270      logger.error(`[objects] first-access hook failed for ${owner}: ${(e as Error).message}`);271    }272  }273}274275const selectRow = (db: Database.Database, owner: string, kind: string, id: string) =>276  db.prepare("SELECT * FROM vq_objects WHERE owner = ? AND kind = ? AND id = ?").get(owner, kind, id) as Row | undefined;277278function nextSeq(db: Database.Database, owner: string): number {279  const r = db.prepare("INSERT INTO vq_sync_seq (owner, seq) VALUES (?, 1) ON CONFLICT(owner) DO UPDATE SET seq = seq + 1 RETURNING seq").get(owner) as { seq: number };280  return r.seq;281}282283/** The single place a row changes. Must run inside a transaction. `json === null` writes a tombstone. */284function commit(db: Database.Database, owner: string, kind: Kind, id: string, previous: Row | undefined, json: string | null, device: string): Envelope {285  const now = Date.now();286  const seq = nextSeq(db, owner);287  const rev = (previous?.rev ?? 0) + 1;288  if (json === null) {289    // A deletion deletes: the content and its archived revisions go, only the marker stays in the feed.290    db.prepare("DELETE FROM vq_object_versions WHERE owner = ? AND kind = ? AND id = ?").run(owner, kind, id);291    db.prepare("UPDATE vq_objects SET rev = ?, seq = ?, data = '{}', updated_at = ?, deleted = 1, device = ? WHERE owner = ? AND kind = ? AND id = ?").run(rev, seq, now, device, owner, kind, id);292  } else {293    if (previous && !previous.deleted && VERSIONED.has(kind)) {294      db.prepare("INSERT OR REPLACE INTO vq_object_versions (owner, kind, id, rev, data, updated_at, device) VALUES (?, ?, ?, ?, ?, ?, ?)").run(owner, kind, id, previous.rev, previous.data, previous.updated_at, previous.device);295      db.prepare(296        "DELETE FROM vq_object_versions WHERE owner = ? AND kind = ? AND id = ? AND rev NOT IN (SELECT rev FROM vq_object_versions WHERE owner = ? AND kind = ? AND id = ? ORDER BY rev DESC LIMIT ?)",297      ).run(owner, kind, id, owner, kind, id, VERSIONS_KEPT);298    }299    // A re-created object (after a tombstone) starts a new life: new creation time, the revision keeps counting.300    const createdAt = previous && !previous.deleted ? previous.created_at : now;301    db.prepare(302      "INSERT INTO vq_objects (owner, kind, id, rev, seq, data, created_at, updated_at, deleted, device) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, ?) " +303        "ON CONFLICT(owner, kind, id) DO UPDATE SET rev = excluded.rev, seq = excluded.seq, data = excluded.data, created_at = excluded.created_at, updated_at = excluded.updated_at, deleted = 0, device = excluded.device",304    ).run(owner, kind, id, rev, seq, json, createdAt, now, device);305  }306  return envelope(selectRow(db, owner, kind, id)!);307}308309// ─── Internal API ────────────────────────────────────────────────────────────310export function getObject<T = Record<string, unknown>>(owner: string, kind: Kind, id: string, opts: { includeDeleted?: boolean } = {}): Envelope<T> | null {311  touch(owner);312  const r = selectRow(sqlite(), owner, kind, id);313  if (!r || (r.deleted && !opts.includeDeleted)) return null;314  return envelope(r) as unknown as Envelope<T>;315}316317/** Live objects of a kind, most recently changed first. */318export function listObjects<T = Record<string, unknown>>(owner: string, kind: Kind): Envelope<T>[] {319  touch(owner);320  const rows = sqlite().prepare("SELECT * FROM vq_objects WHERE owner = ? AND kind = ? AND deleted = 0 ORDER BY updated_at DESC, seq DESC LIMIT 2000").all(owner, kind) as Row[];321  return rows.map(envelope) as unknown as Envelope<T>[];322}323324/**325 * A client write. `baseRev` 0 creates (409 when a live object has this id); otherwise the write is accepted only326 * when `baseRev` is the stored revision. A tombstone is only written over with `baseRev` 0.327 */328export function putObject(owner: string, kind: Kind, id: string, data: unknown, baseRev: number, device: string): Envelope {329  touch(owner);330  const v = validate(kind, id, data);331  if (!Number.isInteger(baseRev) || baseRev < 0) throw new ObjectError(400, "baseRev must be a non-negative integer");332  const db = sqlite();333  const saved = db334    .transaction(() => {335      const row = selectRow(db, owner, kind, id);336      if (baseRev === 0) {337        if (row && !row.deleted) throw new ObjectError(409, "conflict", envelope(row));338      } else {339        if (!row) throw new ObjectError(404, "Object not found");340        if (row.deleted || row.rev !== baseRev) throw new ObjectError(409, "conflict", envelope(row));341      }342      return commit(db, owner, kind, id, row, v.json, device);343    })344    .immediate();345  publishChange(owner, saved);346  return saved;347}348349/** Tombstones an object. `baseRev` null deletes whatever is stored (server-side callers only). */350export function deleteObject(owner: string, kind: Kind, id: string, baseRev: number | null, device: string): Envelope {351  touch(owner);352  if (!ID_RE.test(id)) throw new ObjectError(400, "Invalid id");353  if (baseRev !== null && (!Number.isInteger(baseRev) || baseRev < 1)) throw new ObjectError(400, "baseRev must be the revision you are deleting");354  const db = sqlite();355  const saved = db356    .transaction(() => {357      const row = selectRow(db, owner, kind, id);358      if (!row || row.deleted) throw new ObjectError(404, "Object not found");359      if (baseRev !== null && row.rev !== baseRev) throw new ObjectError(409, "conflict", envelope(row));360      return commit(db, owner, kind, id, row, null, device);361    })362    .immediate();363  publishChange(owner, saved);364  return saved;365}366367/**368 * Server-authored write: `mutate` receives the stored data (null when the object does not exist or is deleted)369 * and returns the new data, or null to leave everything as it is. Read, mutation and write are one transaction,370 * so it cannot lose a concurrent client write; revision, change counter and notification are the normal ones.371 */372export function writeObject<T extends Record<string, unknown> = Record<string, unknown>>(owner: string, kind: Kind, id: string, mutate: (current: T | null) => T | null, device = "server"): Envelope<T> | null {373  touch(owner);374  const db = sqlite();375  let changed = false;376  const saved = db377    .transaction(() => {378      const row = selectRow(db, owner, kind, id);379      const current = row && !row.deleted ? (envelope(row).data as T) : null;380      const next = mutate(current);381      if (next === null) return row && !row.deleted ? envelope(row) : null;382      const v = validate(kind, id, next);383      changed = true;384      return commit(db, owner, kind, id, row, v.json, device);385    })386    .immediate();387  if (changed && saved) publishChange(owner, saved);388  return saved as Envelope<T> | null;389}390391/** The owner's latest change number (0 when nothing was ever written). */392export function currentSeq(owner: string): number {393  touch(owner);394  return (sqlite().prepare("SELECT seq FROM vq_sync_seq WHERE owner = ?").get(owner) as { seq: number } | undefined)?.seq ?? 0;395}396397/** Change feed: everything written after `since`, oldest first, tombstones included. */398export function listChanges(owner: string, since: number, kinds: Kind[] | null, limit: number): { changes: Envelope[]; seq: number; more: boolean } {399  touch(owner);400  const db = sqlite();401  const n = Math.min(1000, Math.max(1, Math.floor(limit) || 500));402  const filter = kinds && kinds.length > 0 ? ` AND kind IN (${kinds.map(() => "?").join(",")})` : "";403  const rows = db.prepare(`SELECT * FROM vq_objects WHERE owner = ? AND seq > ?${filter} ORDER BY seq ASC LIMIT ?`).all(owner, Math.max(0, Math.floor(since) || 0), ...(kinds ?? []), n + 1) as Row[];404  const more = rows.length > n;405  return { changes: rows.slice(0, n).map(envelope), seq: currentSeq(owner), more };406}407408export function listVersions(owner: string, kind: Kind, id: string): Array<{ rev: number; updatedAt: number; device: string | null }> {409  return sqlite().prepare("SELECT rev, updated_at AS updatedAt, device FROM vq_object_versions WHERE owner = ? AND kind = ? AND id = ? ORDER BY rev DESC").all(owner, kind, id) as Array<{ rev: number; updatedAt: number; device: string | null }>;410}411412/** An archived revision as an envelope (`seq` is the live object's: an old revision has no place in the feed). */413export function getVersion(owner: string, kind: Kind, id: string, rev: number): Envelope | null {414  const live = getObject(owner, kind, id);415  if (!live) return null;416  if (live.rev === rev) return live;417  const r = sqlite().prepare("SELECT rev, data, updated_at, device FROM vq_object_versions WHERE owner = ? AND kind = ? AND id = ? AND rev = ?").get(owner, kind, id, rev) as Pick<Row, "rev" | "data" | "updated_at" | "device"> | undefined;418  if (!r) return null;419  return envelope({ owner, kind, id, rev: r.rev, seq: live.seq, data: r.data, created_at: live.createdAt, updated_at: r.updated_at, deleted: 0, device: r.device });420}421422// ─── Rate limit of /api/v2 writes (per person) ───────────────────────────────423// A token bucket: bursts of an interactive client (drag a panel, reorder a list) pass, a runaway loop does not.424const limit = { capacity: 240, refillPerSec: 4 };425const buckets = new Map<string, { tokens: number; at: number }>();426/** Tests shrink the bucket; production keeps the default. */427export function configureWriteLimit(capacity: number, refillPerSec: number): void {428  limit.capacity = capacity;429  limit.refillPerSec = refillPerSec;430  buckets.clear();431}432/** True when this person may write now (and takes one token). */433export function allowWrite(owner: string): boolean {434  const now = Date.now();435  if (buckets.size > 5000) buckets.clear();436  const b = buckets.get(owner) ?? { tokens: limit.capacity, at: now };437  b.tokens = Math.min(limit.capacity, b.tokens + ((now - b.at) / 1000) * limit.refillPerSec);438  b.at = now;439  const ok = b.tokens >= 1;440  if (ok) b.tokens -= 1;441  buckets.set(owner, b);442  return ok;443}444445const ownerId = (req: Request): string => {446  const user = (req as Request & { vqUser?: { id: string } }).vqUser;447  if (!user) throw new Error("Request reached a handler without passing the access gate");448  return user.id;449};450451/** Sends the error of a refused write, or a 500 for anything unexpected. */452export function sendObjectError(res: Response, e: unknown, what: string): void {453  if (e instanceof ObjectError) {454    res.status(e.status).json(e.current ? { error: e.message, current: e.current } : { error: e.message });455    return;456  }457  logger.error(`[objects] ${what}: ${(e as Error).message}`);458  if (!res.headersSent) res.status(500).json({ error: "Object store error" });459}460461export function registerObjectRoutes(app: Express): void {462  // Registered first among the /api/v2 modules, so it covers every write of the surface.463  app.use("/api/v2", (req: Request, res: Response, next: NextFunction) => {464    if (req.method === "GET" || req.method === "HEAD" || req.method === "OPTIONS") return next();465    if (!allowWrite(ownerId(req))) {466      res.set("Retry-After", "5");467      return res.status(429).json({ error: "Too many changes in a short time. Try again in a few seconds." });468    }469    next();470  });471472  /** Resolves :kind (and checks :id); answers 400/404 itself when they are not usable. */473  const kindOf = (req: Request, res: Response): Kind | null => {474    if (!isKind(req.params.kind)) {475      res.status(404).json({ error: "Unknown kind" });476      return null;477    }478    if (req.params.id !== undefined && !ID_RE.test(req.params.id)) {479      res.status(400).json({ error: "Invalid id: 1 to 64 characters among A-Z a-z 0-9 _ -" });480      return null;481    }482    return req.params.kind;483  };484485  app.get("/api/v2/objects/:kind", (req: Request, res: Response) => {486    const kind = kindOf(req, res);487    if (!kind) return;488    try {489      res.set("Cache-Control", "private, no-store").json({ objects: listObjects(ownerId(req), kind) });490    } catch (e) {491      sendObjectError(res, e, "list");492    }493  });494495  app.get("/api/v2/objects/:kind/:id", (req: Request, res: Response) => {496    const kind = kindOf(req, res);497    if (!kind) return;498    try {499      const object = getObject(ownerId(req), kind, req.params.id);500      if (!object) return res.status(404).json({ error: "Object not found" });501      res.set("Cache-Control", "private, no-store").json({ object });502    } catch (e) {503      sendObjectError(res, e, "get");504    }505  });506507  app.put("/api/v2/objects/:kind/:id", (req: Request, res: Response) => {508    const kind = kindOf(req, res);509    if (!kind) return;510    if (SERVER_ONLY.has(kind)) return res.status(403).json({ error: `A ${kind} is written by the server only.` });511    const body = z.object({ data: z.unknown(), baseRev: z.number().int().min(0) }).safeParse(req.body);512    if (!body.success) return res.status(400).json({ error: "Body must be { data, baseRev } with baseRev a non-negative integer" });513    try {514      res.json({ object: putObject(ownerId(req), kind, req.params.id, body.data.data, body.data.baseRev, requestDevice(req)) });515    } catch (e) {516      sendObjectError(res, e, "put");517    }518  });519520  app.delete("/api/v2/objects/:kind/:id", (req: Request, res: Response) => {521    const kind = kindOf(req, res);522    if (!kind) return;523    const raw = String(req.query.baseRev ?? "");524    if (!/^\d{1,12}$/.test(raw) || Number(raw) < 1) return res.status(400).json({ error: "baseRev (the revision you are deleting) is required" });525    try {526      const object = deleteObject(ownerId(req), kind, req.params.id, Number(raw), requestDevice(req));527      audit(req, "object.delete", `${kind}/${req.params.id}`, { rev: object.rev });528      res.json({ object });529    } catch (e) {530      sendObjectError(res, e, "delete");531    }532  });533534  app.get("/api/v2/objects/:kind/:id/versions", (req: Request, res: Response) => {535    const kind = kindOf(req, res);536    if (!kind) return;537    try {538      if (!getObject(ownerId(req), kind, req.params.id)) return res.status(404).json({ error: "Object not found" });539      res.set("Cache-Control", "private, no-store").json({ versions: listVersions(ownerId(req), kind, req.params.id) });540    } catch (e) {541      sendObjectError(res, e, "versions");542    }543  });544545  app.get("/api/v2/objects/:kind/:id/versions/:rev", (req: Request, res: Response) => {546    const kind = kindOf(req, res);547    if (!kind) return;548    if (!/^\d{1,12}$/.test(req.params.rev)) return res.status(400).json({ error: "Invalid revision" });549    try {550      const object = getVersion(ownerId(req), kind, req.params.id, Number(req.params.rev));551      if (!object) return res.status(404).json({ error: "Revision not found" });552      res.set("Cache-Control", "private, no-store").json({ object });553    } catch (e) {554      sendObjectError(res, e, "version");555    }556  });557}558
Files main
Menu

Theme