SPB Git

Repository Public Research preview

format.mjs 9.0 KB 155 lines javascript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : LLM API toolkits8 * File             : scholarly/mcp/lib/format.mjs9 * Module           : scholarly10 * Repository       : https://git.spboucher.ai/llm-api-toolkits11 * Created          : 2026-11-1012 * Last Modified    : 2026-11-1013 *14 * Author           : Simon-Pierre Boucher15 * Position         : Professor of Finance16 * Institution      : Université du Québec en Outaouais (UQO)17 * Organization     : SP Boucher18 * Website          : https://spboucher.ai19 * Git              : https://git.spboucher.ai20 *21 * Preferred Contact: dev@spboucher.ai22 * Development      : dev@spboucher.ai23 * Support          : support@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142import { foldText } from "./normalize.mjs";4344/**45 * Citation formatters. They format the metadata as registered: titles are not re-cased and46 * journal names are not abbreviated, because doing either silently is how references drift.47 * Plain text only: italics required by a style are not marked.48 */49export const STYLES = ["apa", "chicago", "mla", "bibtex", "ris", "csl-json"];50const PARTICLES = /^(van|von|der|den|de|del|della|di|da|dos|du|la|le|ter|ten|bin|ibn|al)$/i;5152export function nameParts(a) {53  if (!a) return { family: "", given: "" };54  if (a.family) return { family: a.family, given: a.given ?? "" };55  const s = String(a.name ?? "").trim();56  if (!s) return { family: "", given: "" };57  if (s.includes(",")) { const [f, ...g] = s.split(","); return { family: f.trim(), given: g.join(" ").trim() }; }58  const w = s.split(/\s+/);59  if (w.length === 1) return { family: w[0], given: "" };60  let i = w.length - 1;61  while (i > 0 && PARTICLES.test(w[i - 1])) i--;62  return { family: w.slice(i).join(" "), given: w.slice(0, i).join(" ") };63}64const initials = (given) => given.split(/[\s]+/).filter(Boolean).map((p) => p.split("-").map((q) => `${q[0].toUpperCase()}.`).join("-")).join(" ");65const dash = (p) => (p ? String(p).replace(/\s*[-–—]+\s*/, "–") : p);66const doiUrl = (w) => (w.doi ? `https://doi.org/${w.doi}` : w.url ?? null);67const end = (s) => (/[.?!]$/.test(s) ? s : `${s}.`);68const join = (list, last) => (list.length <= 1 ? list.join("") : list.length === 2 ? `${list[0]}${last === "&" ? " & " : " and "}${list[1]}` : `${list.slice(0, -1).join(", ")}, ${last} ${list.at(-1)}`);6970export function formatApa(w) {71  const ps = (w.authors ?? []).map(nameParts).filter((p) => p.family).map((p) => (p.given ? `${p.family}, ${initials(p.given)}` : p.family));72  const authors = ps.length > 20 ? `${ps.slice(0, 19).join(", ")}, … ${ps.at(-1)}` : join(ps, "&");73  let s = `${authors ? `${end(authors)} ` : ""}(${w.year ?? "n.d."}). ${end(w.title ?? "[No title]")}`;74  if (w.venue) s += ` ${w.venue}${w.volume ? `, ${w.volume}${w.issue ? `(${w.issue})` : ""}` : ""}${w.pages ? `, ${dash(w.pages)}` : ""}.`;75  else if (w.publisher) s += ` ${end(w.publisher)}`;76  const u = doiUrl(w);77  return u ? `${s} ${u}` : s;78}7980export function formatChicago(w) {81  const ps = (w.authors ?? []).map(nameParts).filter((p) => p.family);82  const names = ps.map((p, i) => (i === 0 ? (p.given ? `${p.family}, ${p.given}` : p.family) : [p.given, p.family].filter(Boolean).join(" ")));83  const authors = names.length > 10 ? `${names.slice(0, 7).join(", ")}, et al` : join(names, "and");84  let s = `${authors ? `${end(authors)} ` : ""}${w.year ?? "n.d."}. “${end(w.title ?? "[No title]")}”`;85  if (w.venue) s += ` ${w.venue}${w.volume ? ` ${w.volume}` : ""}${w.issue ? ` (${w.issue})` : ""}${w.pages ? `: ${dash(w.pages)}` : ""}.`;86  else if (w.publisher) s += ` ${end(w.publisher)}`;87  const u = doiUrl(w);88  return u ? `${s} ${u}.` : s;89}9091export function formatMla(w) {92  const ps = (w.authors ?? []).map(nameParts).filter((p) => p.family);93  const firstA = ps[0] ? (ps[0].given ? `${ps[0].family}, ${ps[0].given}` : ps[0].family) : "";94  const authors = ps.length === 0 ? "" : ps.length === 1 ? firstA : ps.length === 2 ? `${firstA}, and ${[ps[1].given, ps[1].family].filter(Boolean).join(" ")}` : `${firstA}, et al`;95  const bits = [w.venue, w.volume ? `vol. ${w.volume}` : null, w.issue ? `no. ${w.issue}` : null, w.year ?? null, w.pages ? `${/[-–]/.test(w.pages) ? "pp." : "p."} ${dash(w.pages)}` : null].filter(Boolean);96  let s = `${authors ? `${end(authors)} ` : ""}“${end(w.title ?? "[No title]")}”${bits.length ? ` ${bits.join(", ")}.` : w.publisher ? ` ${w.publisher}.` : ""}`;97  const u = doiUrl(w);98  return u ? `${s} ${u}.` : s;99}100101const BIB_TYPE = { "journal-article": "article", article: "article", "proceedings-article": "inproceedings", "book-chapter": "incollection", book: "book", monograph: "book", "edited-book": "book", "posted-content": "misc", preprint: "misc", dissertation: "phdthesis", report: "techreport", dataset: "misc" };102const bibEscape = (s) => String(s).replace(/([&%#_$])/g, "\\$1");103const SKIP = new Set(["a", "an", "the", "on", "of", "in", "le", "la", "les", "un", "une", "der", "die", "das"]);104105export function bibtexKey(w) {106  const fam = foldText(nameParts(w.authors?.[0]).family).replace(/[^a-z]/g, "") || "anon";107  const word = foldText(w.title ?? "").replace(/[^a-z0-9 ]/g, " ").split(/\s+/).find((t) => t && !SKIP.has(t)) ?? "";108  return `${fam}${w.year ?? ""}${word}`;109}110111export function formatBibtex(w, { key } = {}) {112  const type = BIB_TYPE[w.type] ?? "misc", f = [];113  const add = (k, v) => { if (v != null && v !== "") f.push(`  ${k} = {${bibEscape(v)}}`); };114  add("author", (w.authors ?? []).map(nameParts).filter((p) => p.family).map((p) => (p.given ? `${p.family}, ${p.given}` : `{${p.family}}`)).join(" and "));115  add("title", w.title);116  if (type === "article") add("journal", w.venue); else if (type === "inproceedings" || type === "incollection") add("booktitle", w.venue);117  add("year", w.year); add("volume", w.volume); add("number", w.issue);118  add("pages", w.pages ? String(w.pages).replace(/\s*[-–—]+\s*/, "--") : null);119  if (type !== "article") add("publisher", w.publisher);120  if (w.ids?.arxiv) { add("eprint", w.ids.arxiv); add("archivePrefix", "arXiv"); }121  if (w.doi) f.push(`  doi = {${w.doi}}`);122  else if (w.url) f.push(`  url = {${w.url}}`);123  return `@${type}{${key ?? bibtexKey(w)},\n${f.join(",\n")}\n}`;124}125126const RIS_TYPE = { "journal-article": "JOUR", article: "JOUR", "proceedings-article": "CONF", "book-chapter": "CHAP", book: "BOOK", monograph: "BOOK", "posted-content": "UNPB", preprint: "UNPB", dissertation: "THES", report: "RPRT", dataset: "DATA" };127export function formatRis(w) {128  const l = [`TY  - ${RIS_TYPE[w.type] ?? "GEN"}`];129  for (const p of (w.authors ?? []).map(nameParts)) if (p.family) l.push(`AU  - ${p.given ? `${p.family}, ${p.given}` : p.family}`);130  const add = (k, v) => { if (v != null && v !== "") l.push(`${k}  - ${v}`); };131  add("TI", w.title); add("JO", w.venue); add("PY", w.year); add("VL", w.volume); add("IS", w.issue);132  if (w.pages) { const [sp, ep] = String(w.pages).split(/\s*[-–—]+\s*/); add("SP", sp); add("EP", ep); }133  add("PB", w.publisher); add("DO", w.doi); add("UR", doiUrl(w));134  l.push("ER  - ");135  return l.join("\n");136}137138export function toCslJson(w) {139  const type = { "journal-article": "article-journal", article: "article-journal", "proceedings-article": "paper-conference", "book-chapter": "chapter", book: "book", dissertation: "thesis", report: "report", dataset: "dataset" }[w.type] ?? "article";140  const o = { id: bibtexKey(w), type, title: w.title ?? undefined, author: (w.authors ?? []).map(nameParts).filter((p) => p.family).map((p) => ({ family: p.family, ...(p.given ? { given: p.given } : {}) })), issued: w.year ? { "date-parts": [[w.year]] } : undefined, "container-title": w.venue ?? undefined, volume: w.volume ?? undefined, issue: w.issue ?? undefined, page: w.pages ?? undefined, publisher: w.publisher ?? undefined, DOI: w.doi ?? undefined, URL: doiUrl(w) ?? undefined };141  return JSON.parse(JSON.stringify(o));142}143144export function formatWork(w, style = "apa", opts = {}) {145  switch (style) {146    case "apa": return formatApa(w);147    case "chicago": return formatChicago(w);148    case "mla": return formatMla(w);149    case "bibtex": return formatBibtex(w, opts);150    case "ris": return formatRis(w);151    case "csl-json": return toCslJson(w);152    default: throw new Error(`Unknown style "${style}". Use one of: ${STYLES.join(", ")}.`);153  }154}155
Files main
Menu

Theme