Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : ORIX App Universe8 * File : src/lib/maps.ts9 * Module : lib10 * Repository : https://git.spboucher.ai/orix-spboucher-ai11 * Project Website : https://www.orixlab.dev12 * Created : 2026-11-2513 * Last Modified : 2026-11-2514 *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 { readFile, realpath } from "node:fs/promises";44import path from "node:path";4546/**47 * The map regions ORIX Maps can download, read from the distribution the application itself reads48 * (ORIX_MAPS_DIR/v1/catalog.json, then regions/<id>.json for the licences and the components of each region). The root49 * is resolved exactly as in the route that serves the files (src/app/maps/v1/[...path]/route.ts). Nothing is written50 * by hand here: a region appears on the site when the published catalogue lists it. A missing, empty or malformed51 * catalogue is an empty library, never an error.52 */5354export const MAP_CAPABILITIES = ["map", "search", "routing"] as const;55export type MapCapability = (typeof MAP_CAPABILITIES)[number];56export type MapLicence = { source: string; licence: string; attribution: string; url: string | null };57export type MapRegion = {58 id: string; names: { en: string; fr: string }; capabilities: MapCapability[];59 /** Size of the signed package the application downloads, and of the region once installed (null when not stated). */60 downloadBytes: number; installedBytes: number | null;61 /** Date of the map data (ISO 8601) and version of the package. */62 dataDate: string | null; dataVersion: string;63 /** From regions/<id>.json; empty when that document is missing, unreadable or describes another version. */64 licences: MapLicence[]; components: { id: string; bytes: number }[];65};66export type MapLibrary = { regions: MapRegion[]; updated: string | null };6768const ID = /^[a-z0-9-]{1,64}$/, VERSION = /^\d{1,10}(\.\d{1,10}){0,7}$/, MAX_JSON = 8 * 1024 * 1024;6970const root = () => path.join(process.env.ORIX_MAPS_DIR ?? path.join(process.env.HOME ?? "", "apps-data", "orix-maps"), "v1");7172const obj = (v: unknown): Record<string, unknown> | null => (v !== null && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : null);73const str = (v: unknown): string | null => (typeof v === "string" && v.trim() !== "" ? v : null);74const size = (v: unknown): number | null => (typeof v === "number" && Number.isSafeInteger(v) && v > 0 ? v : null);75const stamp = (v: unknown): string | null => (typeof v === "string" && !Number.isNaN(Date.parse(v)) ? v : null);7677/** Reads one JSON document of the distribution; null when it is absent, too large, outside the root or not an object. */78async function read(relative: string): Promise<Record<string, unknown> | null> {79 try {80 const base = await realpath(root()), file = await realpath(path.join(base, relative));81 if (!file.startsWith(base + path.sep)) return null;82 const raw = await readFile(file, "utf8");83 return raw.length > MAX_JSON ? null : obj(JSON.parse(raw));84 } catch { return null; }85}8687function licences(doc: Record<string, unknown> | null): MapLicence[] {88 const list = Array.isArray(doc?.licences) ? doc.licences : [];89 return list.flatMap((l): MapLicence[] => {90 const o = obj(l), source = str(o?.source), attribution = str(o?.attribution), url = str(o?.url);91 if (!source || !attribution) return [];92 return [{ source, attribution, licence: str(o?.licence) ?? "", url: url && /^https:\/\//.test(url) ? url : null }];93 });94}9596function components(doc: Record<string, unknown> | null): { id: string; bytes: number }[] {97 const list = Array.isArray(doc?.components) ? doc.components : [];98 return list.flatMap((c) => { const o = obj(c), id = str(o?.id), bytes = size(o?.length); return id && bytes ? [{ id, bytes }] : []; });99}100101export async function mapLibrary(): Promise<MapLibrary> {102 const catalog = await read("catalog.json");103 const listed = Array.isArray(catalog?.regions) ? catalog.regions : [];104 const seen = new Set<string>();105 const regions = (await Promise.all(listed.map(async (entry): Promise<MapRegion | null> => {106 const r = obj(entry), id = str(r?.id), latest = obj(r?.latest), names = obj(r?.names);107 const downloadBytes = size(latest?.downloadSize), dataVersion = str(latest?.dataVersion), en = str(names?.en) ?? str(names?.fr);108 if (!id || !ID.test(id) || seen.has(id) || !downloadBytes || !dataVersion || !VERSION.test(dataVersion) || !en) return null;109 seen.add(id);110 const detail = await read(`regions/${id}.json`);111 const same = str(obj(obj(detail?.region)?.latest)?.dataVersion) === dataVersion;112 const caps = Array.isArray(r?.capabilities) ? r.capabilities : [];113 return {114 id, names: { en, fr: str(names?.fr) ?? en }, capabilities: MAP_CAPABILITIES.filter((c) => caps.includes(c)),115 downloadBytes, installedBytes: size(latest?.installedSize), dataDate: stamp(latest?.dataTimestamp), dataVersion,116 licences: same ? licences(detail) : [], components: same ? components(detail) : [],117 };118 }))).filter((r): r is MapRegion => r !== null).sort((a, b) => a.downloadBytes - b.downloadBytes || a.id.localeCompare(b.id));119 return { regions, updated: regions.length ? stamp(catalog?.generatedAt) : null };120}121122/** Sizes as the application shows them: decimal units, megabytes below one gigabyte. */123export function mapSize(bytes: number, locale: "en" | "fr"): string {124 const gb = bytes >= 1_000_000_000, v = gb ? bytes / 1_000_000_000 : bytes / 1_000_000;125 const n = new Intl.NumberFormat(locale === "fr" ? "fr-CA" : "en-CA", { minimumFractionDigits: gb ? 1 : 0, maximumFractionDigits: gb ? 1 : 0 }).format(v);126 return `${n} ${gb ? (locale === "fr" ? "Go" : "GB") : locale === "fr" ? "Mo" : "MB"}`;127}128