Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : ORIX App Universe8 * File : src/lib/catalog.ts9 * Module : lib10 * Repository : https://git.spboucher.ai/orix-spboucher-ai11 * Project Website : https://www.orixlab.dev12 * Created : 2026-11-2113 * Last Modified : 2026-11-2114 *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: support@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 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243import { db, now } from "./database/db";44import { AppDoc, publishProblems } from "@/models/app";45import { ApiError } from "./security/http";4647export type Publish = "draft" | "published" | "archived";48export type AppRow = { slug: string; publish: Publish; app: AppDoc; hasDraft: boolean; updatedAt: string; publishedAt: string | null };49type Raw = { slug: string; publish: Publish; data: string; draft: string | null; updated_at: string; published_at: string | null };5051const toRow = (r: Raw, preview: boolean): AppRow => ({52 slug: r.slug, publish: r.publish, hasDraft: r.draft !== null, updatedAt: r.updated_at, publishedAt: r.published_at,53 app: JSON.parse(preview && r.draft ? r.draft : r.data) as AppDoc,54});5556/** Public catalog: published applications only, in editorial order. */57export function listApps(opts: { all?: boolean; preview?: boolean } = {}): AppRow[] {58 const rows = db().prepare(`SELECT * FROM apps ${opts.all ? "" : "WHERE publish = 'published'"} ORDER BY sort, slug`).all() as unknown as Raw[];59 return rows.map((r) => toRow(r, !!opts.preview));60}6162export function getApp(slug: string, opts: { all?: boolean; preview?: boolean } = {}): AppRow | null {63 const r = db().prepare("SELECT * FROM apps WHERE slug = ?").get(slug) as Raw | undefined;64 if (!r || (!opts.all && r.publish !== "published")) return null;65 return toRow(r, !!opts.preview);66}6768/** Creates or replaces an application from seed content. `overwrite: false` keeps anything edited in the CMS. */69export function upsertSeed(doc: unknown, opts: { overwrite?: boolean } = {}): "created" | "updated" | "kept" {70 const app = AppDoc.parse(doc);71 const cur = db().prepare("SELECT slug FROM apps WHERE slug = ?").get(app.slug);72 if (cur && !opts.overwrite) return "kept";73 db().prepare(`INSERT INTO apps (slug, publish, data, draft, sort, updated_at, published_at) VALUES (?, 'published', ?, NULL, ?, ?, ?)74 ON CONFLICT (slug) DO UPDATE SET data = excluded.data, draft = NULL, sort = excluded.sort, updated_at = excluded.updated_at`)75 .run(app.slug, JSON.stringify(app), app.order, now(), now());76 return cur ? "updated" : "created";77}7879/** Saves edits as a draft: nothing public changes until `publishApp`. */80export function saveDraft(slug: string, doc: unknown): AppDoc {81 const parsed = AppDoc.safeParse(doc);82 if (!parsed.success) throw new ApiError(422, "invalid_app", "The application document is invalid", { issues: parsed.error.issues.slice(0, 20).map((i) => `${i.path.join(".")}: ${i.message}`) });83 if (parsed.data.slug !== slug) throw new ApiError(422, "invalid_app", "The slug cannot be changed");84 const r = db().prepare("UPDATE apps SET draft = ?, updated_at = ? WHERE slug = ?").run(JSON.stringify(parsed.data), now(), slug);85 if (r.changes !== 1) throw new ApiError(404, "not_found", "Unknown application");86 return parsed.data;87}8889export function createApp(slug: string, name: string): AppDoc {90 const e = { en: "", fr: "" };91 const doc: AppDoc = AppDoc.parse({92 slug, name, order: 99, category: "utilities", platforms: ["ios"], status: "coming-soon", accent: null, icon: null,93 repo: { name: null, visibility: "none" }, bundleId: null, version: null, build: null, minOS: {}, architectures: [], downloadSize: null,94 tagline: e, summary: e, description: e, features: [], deepDives: [], specs: { offline: e, permissions: [], languages: [] },95 privacy: { summary: e, points: [] }, faq: [], screenshots: [], distribution: [], verification: { testedOnDevice: false, notes: e }, releases: [],96 });97 if (db().prepare("SELECT 1 FROM apps WHERE slug = ?").get(slug)) throw new ApiError(409, "exists", "This slug already exists");98 db().prepare("INSERT INTO apps (slug, publish, data, draft, sort, updated_at) VALUES (?, 'draft', ?, NULL, 99, ?)").run(slug, JSON.stringify(doc), now());99 return doc;100}101102/** Publishes the pending draft (or the current document). Required fields are validated first. */103export function publishApp(slug: string): AppDoc {104 const r = db().prepare("SELECT * FROM apps WHERE slug = ?").get(slug) as Raw | undefined;105 if (!r) throw new ApiError(404, "not_found", "Unknown application");106 const app = AppDoc.parse(JSON.parse(r.draft ?? r.data));107 const problems = publishProblems(app);108 if (problems.length) throw new ApiError(422, "not_publishable", "Required fields are missing", { issues: problems });109 db().prepare("UPDATE apps SET data = ?, draft = NULL, publish = 'published', sort = ?, updated_at = ?, published_at = ? WHERE slug = ?").run(JSON.stringify(app), app.order, now(), now(), slug);110 return app;111}112113export function setPublish(slug: string, publish: Publish): void {114 const r = db().prepare("UPDATE apps SET publish = ?, updated_at = ? WHERE slug = ?").run(publish, now(), slug);115 if (r.changes !== 1) throw new ApiError(404, "not_found", "Unknown application");116}117export function discardDraft(slug: string): void { db().prepare("UPDATE apps SET draft = NULL WHERE slug = ?").run(slug); }118119