/** * @module cosmology/package-galaxy/commands/core-package-cmds * * Pure isomorphic core commands for Package Galaxies across the ibgib cosmology. * Decoupled from CLI stdin/stdout so both CLI tools and HTTP servers (serve-gib) * can execute package operations identically without duplicate logic. */ import { extractErrorMsg } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs'; import { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs'; import { getGalaxiesFromCosmos } from '../../cosmos/cosmos-helpers.mjs'; import { CosmosIbGib_V1 } from '../../cosmos/cosmos-types.mjs'; import { GalaxyPresetType } from '../../galaxy/galaxy-configs.mjs'; import { MetaspaceService } from '../../../witness/space/metaspace/metaspace-types.mjs'; import { IbGibSpaceAny } from '../../../witness/space/space-base-v1.mjs'; import { getIbGibFromSpace, getIbGibsFromSpace, resolveLatestIbGibInSpace, isSpaceQualifiedAddr, parseSpaceQualifiedIbGibAddr, } from '../../../common/other/ibgib-helper.mjs'; import { getProjectedItemFilename } from '../../branching/item/item-helpers.mjs'; import { getOrCreateBranchSpace } from '../../branching/branch/branch-helpers.mjs'; import { B2tFSItemIbGib_V1, B2TFS_CHILD_ITEM_REL8N_NAME } from '../../branching/item/item-types.mjs'; import { B2tFSBranchIbGib_V1 } from '../../branching/branch/branch-types.mjs'; import { B2tFSSnapshotIbGib_V1 } from '../../branching/snapshot/snapshot-types.mjs'; import { BinIbGib_V1 } from '../../../common/bin/bin-types.mjs'; import { getPackageVersionFrame } from '../package-timeline-helpers.mjs'; import { tryResolvePackageVersion, comparePackageVersions } from '../version-parser/version-parser-resolver.mjs'; import { PackageGalaxyIbGib_V1 } from '../package-galaxy-types.mjs'; import { B2tFSGalaxyIbGib_V1 } from '../../branching/b2tfs-galaxy/b2tfs-galaxy-types.mjs'; import { GLOBAL_LOG_A_LOT } from '../../../core-constants.mjs'; const lcFile = `[core-package-cmds]`; const logalot = GLOBAL_LOG_A_LOT; export interface CorePackageGetOpts { metaspace: MetaspaceService; space: IbGibSpaceAny; cosmos: CosmosIbGib_V1; galaxyName?: string; packageName: string; version?: string; branchName?: string; } export interface CorePackageGetResult { packageName: string; version: string; filename: string; binHash: string; binAddr: string; itemAddr: string; packageItem: B2tFSItemIbGib_V1; frameItem: B2tFSItemIbGib_V1; binStone: BinIbGib_V1; } export interface CorePackageInfo { packageName: string; latestVersion: string; releasesCount: number; filename: string; fileHash: string; itemAddr: string; binAddr?: string; } export interface CorePackageListOpts { metaspace: MetaspaceService; space: IbGibSpaceAny; cosmos: CosmosIbGib_V1; galaxyName?: string; branchName?: string; } export interface CorePackageListResult { galaxyName: string; packages: CorePackageInfo[]; } /** * Resolves the target package galaxy entry from a Cosmos. */ export function resolvePackageGalaxyEntry(cosmos: CosmosIbGib_V1, galaxyName?: string) { const galaxies = getGalaxiesFromCosmos(cosmos); if (galaxyName) { const found = galaxies.find(g => g.galaxyName === galaxyName); if (!found) { throw new Error(`fatal: galaxy "${galaxyName}" not found in cosmos "${cosmos.data.cosmosName}" (E: galaxy_not_found)`); } return found; } const pkgGalaxies = galaxies.filter( g => g.discriminator === GalaxyPresetType.package || g.discriminator === 'package' ); if (pkgGalaxies.length === 0) { throw new Error( `fatal: No package galaxy found in cosmos "${cosmos.data.cosmosName}". (E: no_pkg_galaxy)` ); } if (pkgGalaxies.length > 1) { const names = pkgGalaxies.map(g => g.galaxyName).join(', '); throw new Error( `fatal: Multiple package galaxies found in cosmos "${cosmos.data.cosmosName}" (${names}). Please specify --galaxy / galaxyName explicitly. (E: ambiguous_pkg_galaxy)` ); } return pkgGalaxies[0]; } /** * Unwraps a potentially space-qualified address into a raw address string. */ function unwrapAddr(addr?: string): string | undefined { if (!addr) { return undefined; } if (isSpaceQualifiedAddr(addr)) { return parseSpaceQualifiedIbGibAddr({ sqAddr: addr }).ibGibAddr; } return addr; } /** * Retrieves the snapshot and package items map for a package galaxy. */ export async function getPackageItemsMap({ metaspace, space, cosmos, galaxyName, branchName, }: { metaspace?: MetaspaceService; space: IbGibSpaceAny; cosmos: CosmosIbGib_V1; galaxyName?: string; branchName?: string; }): Promise<{ galaxyName: string; snapshot?: B2tFSSnapshotIbGib_V1; packageItems: Map; branchStone?: B2tFSBranchIbGib_V1; targetSpace: IbGibSpaceAny; }> { const pkgGalaxyEntry = resolvePackageGalaxyEntry(cosmos, galaxyName); const resolvedGalaxyName = pkgGalaxyEntry.galaxyName; let targetSpace = space; if (metaspace) { const effectiveBranch = branchName || pkgGalaxyEntry.policy?.defaultBranch; if (effectiveBranch) { try { const { space: branchSpace } = await getOrCreateBranchSpace({ metaspace, cosmosName: cosmos.data.cosmosName, galaxyName: resolvedGalaxyName, branchName: effectiveBranch, }); if (branchSpace) { targetSpace = branchSpace; } } catch (branchSpaceErr) { if (logalot) { console.log(`[core-package-cmds] Dedicated branch space lookup note: ${extractErrorMsg(branchSpaceErr)} (I: c8194db47a2542a19b348d601248a026)`); } } } } const rawGalaxyAddr = unwrapAddr(pkgGalaxyEntry.sqGalaxyAddr || pkgGalaxyEntry.galaxyAddr); if (!rawGalaxyAddr) { throw new Error(`fatal: galaxy "${resolvedGalaxyName}" has no address recorded in cosmos (E: galaxy_addr_missing)`); } let galaxyIbGib = await getIbGibFromSpace({ addr: rawGalaxyAddr, space, }); if (!galaxyIbGib && targetSpace !== space) { galaxyIbGib = await getIbGibFromSpace({ addr: rawGalaxyAddr, space: targetSpace, }); } if (!galaxyIbGib) { throw new Error(`fatal: failed to load galaxy ibgib for address: ${rawGalaxyAddr} (E: galaxy_load_failed)`); } const branchSq = galaxyIbGib.data?.trunkBranchSqAddr || galaxyIbGib.data?.['$@branch']?.[0]; const rawBranchAddr = unwrapAddr(branchSq); if (!rawBranchAddr) { throw new Error(`fatal: galaxy "${resolvedGalaxyName}" has no branch address recorded (E: branch_addr_missing)`); } let initialBranchStone = rawBranchAddr ? await getIbGibFromSpace({ addr: rawBranchAddr, space: targetSpace, }).catch(() => undefined) : undefined; if (!initialBranchStone && rawBranchAddr && targetSpace !== space) { initialBranchStone = await getIbGibFromSpace({ addr: rawBranchAddr, space, }).catch(() => undefined); } const activeBranchStone = initialBranchStone ? await resolveLatestIbGibInSpace({ ibGib: initialBranchStone, space: targetSpace, }).catch(() => initialBranchStone) : undefined; const snapshotAddrs = activeBranchStone?.data?.['@snapshot'] || []; const latestSnapshotAddr = snapshotAddrs.at(-1); const packageItems = new Map(); let snapshot: B2tFSSnapshotIbGib_V1 | undefined; if (latestSnapshotAddr) { snapshot = await getIbGibFromSpace({ addr: latestSnapshotAddr, space: targetSpace, }).catch(() => undefined); if (!snapshot && targetSpace !== space) { snapshot = await getIbGibFromSpace({ addr: latestSnapshotAddr, space, }).catch(() => undefined); } } if (!snapshot && typeof (targetSpace as any).loadSnapshot === 'function') { snapshot = await (targetSpace as any).loadSnapshot().catch(() => undefined); } if (!snapshot && targetSpace !== space && typeof (space as any).loadSnapshot === 'function') { snapshot = await (space as any).loadSnapshot().catch(() => undefined); } let items: B2tFSItemIbGib_V1[] = []; if (snapshot?.data?.items) { const itemAddrs = Object.entries(snapshot.data.items) .filter(([relPath]) => relPath !== '' && relPath !== '.') .map(([, [itemAddr]]) => itemAddr) .filter(Boolean); if (itemAddrs.length > 0) { items = await getIbGibsFromSpace({ addrs: itemAddrs, space: targetSpace, }).catch(() => []); if (items.length === 0 && targetSpace !== space) { items = await getIbGibsFromSpace({ addrs: itemAddrs, space, }).catch(() => []); } } } else if (activeBranchStone) { const rootAddr = activeBranchStone.rel8ns?.['b2tfs_item']?.at(-1); if (rootAddr) { const rootItem = await getIbGibFromSpace({ addr: rootAddr, space: targetSpace, }).catch(() => undefined); const childAddrs = rootItem?.rel8ns?.[B2TFS_CHILD_ITEM_REL8N_NAME] || []; if (childAddrs.length > 0) { items = await getIbGibsFromSpace({ addrs: childAddrs, space: targetSpace, }).catch(() => []); } } } else if (!initialBranchStone && !snapshot) { throw new Error(`fatal: branch stone not found for address: ${rawBranchAddr} (E: branch_stone_missing)`); } const groupedByPkg = new Map(); for (const item of items) { if (!item?.data || item.data.fsType === 'folder') { continue; } const filename = item.data.packageInfo?.filename || item.data.filename || getProjectedItemFilename(item); const parsed = item.data.packageInfo ? { packageName: item.data.packageInfo.packageName, version: item.data.packageInfo.version, rawFilename: filename, scope: item.data.packageInfo.scope, schema: item.data.packageInfo.schema, } : tryResolvePackageVersion({ filename }); if (parsed) { const list = groupedByPkg.get(parsed.packageName) || []; list.push(item); groupedByPkg.set(parsed.packageName, list); } else { const key = filename || item.data.name; if (key) { packageItems.set(key, item); } } } for (const [pkgName, group] of groupedByPkg.entries()) { group.sort((a, b) => { const fnA = a.data?.packageInfo?.filename || a.data?.filename || getProjectedItemFilename(a); const fnB = b.data?.packageInfo?.filename || b.data?.filename || getProjectedItemFilename(b); const vA = a.data?.packageInfo?.version || tryResolvePackageVersion({ filename: fnA })?.version || '0.0.0'; const vB = b.data?.packageInfo?.version || tryResolvePackageVersion({ filename: fnB })?.version || '0.0.0'; return comparePackageVersions(vA, vB); }); const latestItem = group[group.length - 1]; if (group.length > 1) { (latestItem as any).__groupedVersionItems = group; } const latestFilename = latestItem.data?.packageInfo?.filename || latestItem.data?.filename || getProjectedItemFilename(latestItem); packageItems.set(pkgName, latestItem); if (latestFilename && !packageItems.has(latestFilename)) { packageItems.set(latestFilename, latestItem); } } return { galaxyName: resolvedGalaxyName, snapshot, packageItems, branchStone: activeBranchStone, targetSpace, }; } /** * Pure core function to resolve and retrieve a package binary from space. */ export async function executeCorePackageGet(opts: CorePackageGetOpts): Promise { const lc = `${lcFile}[${executeCorePackageGet.name}]`; try { const { packageName, version } = opts; const { packageItems, targetSpace } = await getPackageItemsMap(opts); let item = packageItems.get(packageName); if (!item && packageName.includes('.')) { const base = packageName.slice(0, packageName.lastIndexOf('.')); item = packageItems.get(base); } if (!item && !packageName.includes('.')) { item = packageItems.get(`${packageName}.exe`) || packageItems.get(`${packageName}.mjs`) || packageItems.get(`${packageName}.json`); } if (!item) { throw new Error(`fatal: package "${packageName}" not found in package galaxy (E: not_found)`); } let frameItem: B2tFSItemIbGib_V1 = item; if (version) { const foundFrame = await getPackageVersionFrame({ packageItem: item, version, space: targetSpace, }); if (!foundFrame) { throw new Error(`fatal: version "${version}" not found for package "${packageName}" (E: version_not_found)`); } frameItem = foundFrame; } const filename = getProjectedItemFilename(frameItem); const resolvedVersion = frameItem.data?.packageInfo?.version || tryResolvePackageVersion({ filename })?.version || 'latest'; const binAddr = frameItem.rel8ns?.bin?.at(-1); if (!binAddr) { throw new Error(`fatal: package item stone missing binary stone relation (E: bin_missing)`); } let binStone = await getIbGibFromSpace({ addr: binAddr, space: targetSpace, }); if (!binStone && targetSpace !== opts.space) { binStone = await getIbGibFromSpace({ addr: binAddr, space: opts.space, }); } if (!binStone) { throw new Error(`fatal: failed to retrieve binary data stone for address: ${binAddr} (E: bin_load_failed)`); } const binHash = frameItem.data?.fileHash || (binStone as any).data?.hash || ''; const itemAddr = getIbGibAddr({ ibGib: frameItem }); return { packageName, version: resolvedVersion, filename, binHash, binAddr, itemAddr, packageItem: item, frameItem, binStone, }; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } } /** * Pure core function to list packages registered in a package galaxy. */ export async function executeCorePackageList(opts: CorePackageListOpts): Promise { const lc = `${lcFile}[${executeCorePackageList.name}]`; try { const { galaxyName, packageItems } = await getPackageItemsMap(opts); const packages: CorePackageInfo[] = []; const seenItemAddrs = new Set(); for (const [pkgName, item] of packageItems.entries()) { const itemAddr = getIbGibAddr({ ibGib: item }); if (seenItemAddrs.has(itemAddr)) { continue; } seenItemAddrs.add(itemAddr); const filename = getProjectedItemFilename(item); const parsed = item.data?.packageInfo || tryResolvePackageVersion({ filename }); const canonicalName = parsed?.packageName || item.data?.name || pkgName; const latestVersion = parsed?.version || 'latest'; const groupedCount = Array.isArray((item as any).__groupedVersionItems) ? (item as any).__groupedVersionItems.length : 0; const releasesCount = Math.max((item.rel8ns?.past?.length || 0) + 1, groupedCount); const fileHash = item.data?.fileHash || ''; const binAddr = item.rel8ns?.bin?.at(-1); packages.push({ packageName: canonicalName, latestVersion, releasesCount, filename, fileHash, itemAddr, binAddr, }); } return { galaxyName, packages, }; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } }