/** * @module branch-helper * * B2tFS Branch Helper functions: dedicated branch spaces (`b2s~...`), branch creation, * and branch timeline tracking. */ import { extractErrorMsg, getUUID } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs'; import { UUID_REGEXP } from '@ibgib/helper-gib/dist/constants.mjs'; import { ROOT } from '@ibgib/ts-gib/dist/V1/constants.mjs'; import { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs'; import { Factory_V1 } from '@ibgib/ts-gib/dist/V1/factory.mjs'; import { rel8 } from '@ibgib/ts-gib/dist/V1/transforms/rel8.mjs'; import { mut8 } from '@ibgib/ts-gib/dist/V1/transforms/mut8.mjs'; import { Ib, } from '@ibgib/ts-gib/dist/types.mjs'; import { GLOBAL_LOG_A_LOT } from '../../../core-constants.mjs'; import { MetaspaceService } from '../../../witness/space/metaspace/metaspace-types.mjs'; import { IbGibSpaceAny } from '../../../witness/space/space-base-v1.mjs'; import { persistTransformResult, registerNewIbGib, parseSpaceIb } from '../../../witness/space/space-helper.mjs'; import { B2tFSBranchIbGib_V1, B2tFSBranchData_V1, B2tFSBranchRel8ns_V1, B2tFSBranchIb_V1, BranchInfo, CompositeBranchNode, } from './branch-types.mjs'; import { B2tFSItemIbGib_V1 } from '../item/item-types.mjs'; import { B2TFS_BRANCH_ATOM, B2TFS_BRANCH_DEFAULT_NAME, B2TFS_BRANCH_SPACE_PREFIX, B2TFS_BRANCH_SPACE_DELIMITER } from './branch-constants.mjs'; import { getSpaceIdFromIb } from '../../../witness/space/metaspace/metaspace-innerspace/metaspace-innerspace-helper.mjs'; import { B2tFSGalaxyIbGib_V1 } from '../b2tfs-galaxy/b2tfs-galaxy-types.mjs'; import { GalaxyIbGib_V1 } from '../../galaxy/galaxy-types.mjs'; import { SpaceQualifiedAddrInfo, SpaceQualifiedIbGibAddr } from '../../../common/other/ibgib-types.mjs'; import { getIbGibFromSpace, parseSpaceQualifiedIbGibAddr, getSpaceQualifiedIbGibAddr, } from '../../../common/other/ibgib-helper.mjs'; const lcFile = `[branch-helper]`; const logalot = GLOBAL_LOG_A_LOT; /** * Regular expression validating allowed branch names. * Allows letters, numbers, hyphens, underscores, and dots. * Must start and end with an alphanumeric character. */ export const BRANCH_NAME_REGEXP = /^[a-zA-Z0-9](?:[a-zA-Z0-9._-]*[a-zA-Z0-9])?$/; /** * Validates a proposed branch name. * - Non-empty, max 64 chars * - Allowed chars: alphanumerics, hyphens (-), underscores (_), and dots (.) * - Must start and end with an alphanumeric char * - Cannot contain tildes (~), spaces, or consecutive dots (..) */ export function validateBranchName(name?: string): { isValid: boolean; error?: string } { if (!name || !name.trim()) { return { isValid: false, error: 'Branch name cannot be empty.' }; } const trimmed = name.trim(); if (trimmed.length > 64) { return { isValid: false, error: 'Branch name cannot exceed 64 characters.' }; } if (trimmed.includes('~')) { return { isValid: false, error: 'Branch name cannot contain tildes (~).' }; } if (trimmed.includes('..')) { return { isValid: false, error: 'Branch name cannot contain consecutive dots (..).' }; } if (trimmed.includes(' ')) { return { isValid: false, error: 'Branch name cannot contain spaces.' }; } if (!BRANCH_NAME_REGEXP.test(trimmed)) { return { isValid: false, error: 'Branch name can only contain letters, numbers, hyphens (-), underscores (_), and dots (.), and must start and end with a letter or number.', }; } return { isValid: true }; } export function isValidBranchName(name?: string): boolean { return validateBranchName(name).isValid; } /** * Generates a dedicated branch space name. * Follows the cosmology delimiter convention: * Example: ('main', 'code-1') -> 'b2s~code-1~main' * Example: ('main', 'code-1', 'cosmos-1') -> 'b2s~cosmos-1~code-1~main' */ export function getB2tFSBranchSpaceName(branchName: string, galaxyName?: string, cosmosName?: string): string { const safeBranch = branchName.replace(/[^a-zA-Z0-9_\-]/g, '_'); const safeCosmos = (cosmosName || 'cosmos').replace(/[^a-zA-Z0-9_\-]/g, '_'); if (galaxyName) { return `b2s${B2TFS_BRANCH_SPACE_DELIMITER}${safeCosmos}${B2TFS_BRANCH_SPACE_DELIMITER}${galaxyName}${B2TFS_BRANCH_SPACE_DELIMITER}${safeBranch}`; } return `b2s${B2TFS_BRANCH_SPACE_DELIMITER}${safeCosmos}${B2TFS_BRANCH_SPACE_DELIMITER}${safeBranch}`; } export function getBranchIb({ branchName, uuid }: { branchName: string, uuid: string }): Ib { if (!branchName) { throw new Error(`branchName falsy (E: 61f048e02ea84a2276b3cd6d731fa826)`); } if (!uuid) { throw new Error(`uuid falsy (E: 3e54a910bb1815433822c78a9c48b826)`); } if (!UUID_REGEXP.test(uuid)) { throw new Error(`uuid (${uuid}) does not match UUID_REGEXP (${UUID_REGEXP.source}) (E: 64794844e948435c38f58a8891b6e126)`); } return `${B2TFS_BRANCH_ATOM} ${branchName} v1 ${uuid}`; } export function parseBranchIb({ ib }: { ib: Ib }): B2tFSBranchIb_V1 { const lc = `[${parseBranchIb.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: cbd009f57961884dd3024c18f7b01926)`); } const [atom, branchName, version, uuid] = ib.split(' '); if (!atom) { throw new Error(`atom falsy (E: 68fb989be1ebaeb6220570618ee53826)`); } if (atom !== B2TFS_BRANCH_ATOM) { throw new Error(`atom !== ${B2TFS_BRANCH_ATOM} (b2tfs branch atom) (E: 389d481f8ca86472f81eaa61c55fdc26)`); } if (!branchName) { throw new Error(`branchName falsy (E: d698cb6dc8b8b307485305e1527f5826)`); } if (!version) { throw new Error(`version falsy (E: 37ccf82d9718c38678c3f271e675c826)`); } if (version !== 'v1') { throw new Error(`version (${version}) !== 'v1' (E: 1122d86884d8231dcb7fddd889c9e626)`); } if (!uuid) { throw new Error(`uuid falsy (E: 9edca4d919a8d44188d002b807aab826)`); } if (!UUID_REGEXP.test(uuid)) { throw new Error(`uuid (${uuid}) does not match UUID_REGEXP (${UUID_REGEXP.source}) (E: b60587540c5ddf17482eb47804909426)`); } return { atom, branchName, version, uuid, } } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * Creates a new B2tFSBranchIbGib pointing to a root folder item. */ export async function createB2tFSBranchIbGib(opts: { branchName: string; rootItem: B2tFSItemIbGib_V1; space: IbGibSpaceAny; metaspace: MetaspaceService; parentBranchSqAddr?: SpaceQualifiedIbGibAddr; parentBranchName?: string; scopedItemPath?: string; uuid?: string; }): Promise { const lc = `${lcFile}[${createB2tFSBranchIbGib.name}]`; const { branchName, rootItem, space, metaspace, parentBranchSqAddr, parentBranchName, scopedItemPath, uuid: optUuid, } = opts; if (!branchName || !rootItem) { throw new Error(`branchName and rootItem required (E: c67bb2a61e6d4270d8056f0afb01d426)`); } if (optUuid && !UUID_REGEXP.test(optUuid)) { throw new Error(`uuid (${optUuid}) does not match UUID_REGEXP (${UUID_REGEXP.source}) (E: d2384a91c8414b2e91240c5b3671a926)`); } const uuid = optUuid || await getUUID(); const rootAddr = getIbGibAddr({ ibGib: rootItem }); const data: B2tFSBranchData_V1 = { name: branchName, uuid, classname: 'B2tFSBranchIbGib_V1', ...(parentBranchSqAddr ? { parentBranchSqAddr } : {}), ...(parentBranchName ? { parentBranchName } : {}), ...(scopedItemPath ? { scopedItemPath } : {}), '$@branch': [], }; const rel8ns: B2tFSBranchRel8ns_V1 = { b2tfs_item: [rootAddr], }; const res = await Factory_V1.firstGen({ parentIbGib: ROOT, ib: getBranchIb({ branchName, uuid }), data, rel8ns, tjp: { timestamp: true }, dna: true, nCounter: true, }); const branchIbGib = res.newIbGib as B2tFSBranchIbGib_V1; await persistTransformResult({ resTransform: res, space }); await registerNewIbGib({ ibGib: branchIbGib, space }); if (logalot) { console.log(`${lc} Created branch IbGib: ${branchIbGib.ib}`); } return branchIbGib; } /** * Evolves a B2tFSBranchIbGib pointing to a new root item. */ export async function evolveB2tFSBranchIbGib(opts: { existingBranch: B2tFSBranchIbGib_V1; rootItem: B2tFSItemIbGib_V1; space: IbGibSpaceAny; metaspace: MetaspaceService; commentAddr?: string; }): Promise { const lc = `${lcFile}[${evolveB2tFSBranchIbGib.name}]`; const { existingBranch, rootItem, space, metaspace, commentAddr } = opts; const rootAddr = getIbGibAddr({ ibGib: rootItem }); const rel8nsToAddByAddr: Record = { b2tfs_item: [rootAddr], }; if (commentAddr) { rel8nsToAddByAddr.comment = [commentAddr]; } const resRel8 = await rel8({ src: existingBranch, rel8nsToAddByAddr, dna: true, nCounter: true, }); const newBranch = resRel8.newIbGib as B2tFSBranchIbGib_V1; await metaspace.persistTransformResult({ resTransform: resRel8, space }); await metaspace.registerNewIbGib({ ibGib: newBranch, space }); if (logalot) { console.log(`${lc} Evolved branch IbGib: ${newBranch.ib}`); } return newBranch; } /** * Registers a new child sub-branch on an existing parent branch stone by evolving * the parent branch to append the child's space-qualified address to its `$@branch` list. */ export async function registerSubBranchOnParent({ parentBranchIbGib, childBranchSqAddr, space, metaspace, }: { parentBranchIbGib: B2tFSBranchIbGib_V1; childBranchSqAddr: SpaceQualifiedIbGibAddr; space: IbGibSpaceAny; metaspace: MetaspaceService; }): Promise { const lc = `${lcFile}[${registerSubBranchOnParent.name}]`; try { if (!parentBranchIbGib) throw new Error(`parentBranchIbGib required (E: a1b2c3d4e5f64718890123456789abcd)`); if (!childBranchSqAddr) throw new Error(`childBranchSqAddr required (E: b2c3d4e5f6a14718890123456789abcd)`); if (!space) throw new Error(`space required (E: c3d4e5f6a1b24718890123456789abcd)`); if (!metaspace) throw new Error(`metaspace required (E: d4e5f6a1b2c34718890123456789abcd)`); const existingChildren = parentBranchIbGib.data['$@branch'] || []; if (existingChildren.includes(childBranchSqAddr)) { if (logalot) { console.warn(`${lc} childBranchSqAddr already registered on parent: ${childBranchSqAddr}`); } return parentBranchIbGib; } const updatedChildren = [...existingChildren, childBranchSqAddr]; const resTransform = await mut8({ src: parentBranchIbGib, dataToRemove: parentBranchIbGib.data['$@branch'] ? { '$@branch': '' as any } : undefined, dataToAddOrPatch: { '$@branch': updatedChildren, }, dna: true, nCounter: true, }); const evolvedParent = resTransform.newIbGib as B2tFSBranchIbGib_V1; await metaspace.persistTransformResult({ resTransform, space }); await metaspace.registerNewIbGib({ ibGib: evolvedParent, space }); if (logalot) { console.log(`${lc} Registered sub-branch ${childBranchSqAddr} on parent ${parentBranchIbGib.data.name} (newAddr: ${getIbGibAddr({ ibGib: evolvedParent })})`); } return evolvedParent; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } } /** * Resolves the contextual branch name given the target directory and repository root. * If targetDir is physically located inside a secondary branch worktree (`b2tfsGalaxyRoot/b/`), * that worktree's branchName is returned. Otherwise, the galaxy's activeBranch (defaulting to 'main') is returned. */ export function resolveContextualBranchName({ targetDir, b2tfsGalaxyRoot, galaxyIbGib, }: { targetDir?: string; b2tfsGalaxyRoot?: string; galaxyIbGib: B2tFSGalaxyIbGib_V1; }): string { if (!galaxyIbGib) { throw new Error(`(UNEXPECTED) galaxyIbGib falsy when resolving contextual branch name (E: 83a04bc612984ea7c89f5d134b280826)`); } if (!b2tfsGalaxyRoot) { return galaxyIbGib.data.policy?.defaultBranch || B2TFS_BRANCH_DEFAULT_NAME; } const normTarget = (targetDir || b2tfsGalaxyRoot).replace(/\\/g, '/').replace(/\/+$/, ''); const normRoot = b2tfsGalaxyRoot.replace(/\\/g, '/').replace(/\/+$/, ''); if (normTarget.startsWith(normRoot)) { const rel = normTarget.slice(normRoot.length).replace(/^\/+/, ''); if (rel.startsWith('b/') || rel === 'b') { const parts = rel.split('/').filter(Boolean); if (parts.length >= 2 && parts[0] === 'b') { const candidateBranch = parts[1]; if (candidateBranch) { return candidateBranch; } } } } return galaxyIbGib.data.policy?.defaultBranch || B2TFS_BRANCH_DEFAULT_NAME; } export interface GetOrCreateBranchSpaceOpts { metaspace: MetaspaceService; branchName: string; galaxyName?: string; cosmosName?: string; spaceId?: string; } export interface GetOrCreateBranchSpaceResult { space: IbGibSpaceAny; spaceId: string; spaceName: string; } /** * Gets an existing branch space or creates and registers a new dedicated NodeFilesystemSpace_V1 in metaspace. */ export async function getOrCreateBranchSpace({ metaspace, branchName, galaxyName, cosmosName, spaceId, }: GetOrCreateBranchSpaceOpts): Promise { const lc = `${lcFile}[${getOrCreateBranchSpace.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 237cfd38398851a997e0f399dc148826)`); } if (!metaspace || !branchName) { throw new Error(`metaspace and branchName are required (E: d223dc50b376e9b2d84c712fbb497826)`); } if (spaceId && !UUID_REGEXP.test(spaceId)) { throw new Error(`spaceId (${spaceId}) does not match UUID_REGEXP (${UUID_REGEXP.source}) (E: 885fa29571eb405aa50fbfa9a1286926)`); } const spaceName = getB2tFSBranchSpaceName(branchName, galaxyName, cosmosName); const localSpaces = await metaspace.getLocalUserSpaces({ lock: false }); let existingBranchSpace: IbGibSpaceAny | undefined; if (spaceId) { existingBranchSpace = localSpaces.find(s => { const sId = (s.data as any)?.spaceId || (s.data as any)?.uuid || (s.ib ? getSpaceIdFromIb(s.ib) : undefined); return sId === spaceId; }); } if (!existingBranchSpace) { existingBranchSpace = localSpaces.find(s => { if (s.data?.name === spaceName) { return true; } try { return parseSpaceIb({ spaceIb: s.ib }).spaceName === spaceName; } catch (parseErr) { if (logalot) { console.log(`${lc} space.ib (${s.ib}) not parseable as spaceIb: ${extractErrorMsg(parseErr)} (I: c7a9e142385149a4a755de89f41b9c26)`); } return false; } }); } if (existingBranchSpace) { const existingBranchSpaceId = getSpaceIdFromIb(existingBranchSpace.ib); if (spaceId && existingBranchSpaceId !== spaceId) { throw new Error(`existingBranchSpaceId (${existingBranchSpaceId}) does not match expected spaceId (${spaceId}) for branchName ${branchName} (E: 3a3b7c89d0e14a2bb34f6879e1e2d326)`); } if (logalot) { console.log(`${lc} Found existing branch space (name: ${spaceName}, space.ib: ${existingBranchSpace.ib}) (I: 58ef28a2eda5f501e78497381d596326)`); } return { space: existingBranchSpace, spaceId: existingBranchSpaceId, spaceName: existingBranchSpace.data?.name || spaceName, }; } else { // no existing space found, so create it const newBranchSpace = await metaspace.createLocalSpaceAndUpdateBootstrap({ zeroSpace: metaspace.zeroSpace, allowCancel: false, createBootstrap: false, spaceName, spaceId, }); // #region sanity if (!newBranchSpace) { throw new Error(`(UNEXPECTED) newBranchSpace falsy? we just called the create function, so we could not create a local space and update bootstrap? But it didn't throw an exception? (E: 4b8be9dd6a182090680b60c8653f2826)`); } if (!newBranchSpace.data) { throw new Error(`(UNEXPECTED) newBranchSpace.data falsy? (E: dc3e78b7a3782e7dd80f4fb8609f8a26)`); } // #endregion sanity const newBranchSpaceId = getSpaceIdFromIb(newBranchSpace.ib); if (logalot) { console.log(`${lc} Using branchName (${branchName}), created new branch space (ib: ${newBranchSpace.ib}) (I: fc08086f6cc73caa383bc72c662ee826)`); } return { space: newBranchSpace, spaceId: newBranchSpaceId, spaceName, }; } } catch (error) { console.error(`${lc} ${extractErrorMsg(error)} (E: 091a2820de9a3eca833107883524c626)`); throw error; } finally { if (logalot) { console.log(`${lc} complete. (I: 8452386b1247d58618905a28cf692126)`); } } } export interface InitBranchSpaceOpts { metaspace: MetaspaceService; branchName: string; galaxyName?: string; cosmosName?: string; spaceId?: string; } export interface EnsureBranchSpaceOpts { metaspace: MetaspaceService; branchName: string; galaxyName?: string; cosmosName?: string; spaceId?: string; } /** * Initializes a new dedicated branch space in metaspace. * Fails fast (throws) if the branch space already exists. */ export async function initBranchSpace(opts: InitBranchSpaceOpts): Promise { const lc = `${lcFile}[${initBranchSpace.name}]`; const { metaspace, branchName, galaxyName, cosmosName, spaceId } = opts; if (!metaspace || !branchName) { throw new Error(`metaspace and branchName are required (E: 96f89a2f8b28ca410e4caa41f8734aa2)`); } if (spaceId && !UUID_REGEXP.test(spaceId)) { throw new Error(`spaceId (${spaceId}) does not match UUID_REGEXP (${UUID_REGEXP.source}) (E: 2aae2600100812dec6d4c95dcee3f7b7)`); } const spaceName = getB2tFSBranchSpaceName(branchName, galaxyName, cosmosName); const localSpaces = await metaspace.getLocalUserSpaces({ lock: false }); const existingBranchSpace = localSpaces.find(s => { if (spaceId) { const sId = (s.data as any)?.spaceId || (s.data as any)?.uuid || (s.ib ? getSpaceIdFromIb(s.ib) : undefined); if (sId === spaceId) return true; } if (s.data?.name === spaceName) return true; try { return parseSpaceIb({ spaceIb: s.ib }).spaceName === spaceName; } catch (parseErr) { if (logalot) { console.log(`${lc} space.ib (${s.ib}) not parseable as spaceIb: ${extractErrorMsg(parseErr)} (I: c8b1f234567849a4a755de89f41b9c26)`); } return false; } }); if (existingBranchSpace) { throw new Error(`Branch space "${spaceName}" already exists in metaspace (spaceId: ${getSpaceIdFromIb(existingBranchSpace.ib)}). Expected not to exist for initBranchSpace. (E: 383e755e32d96090b44e4849488d8306)`); } const newBranchSpace = await metaspace.createLocalSpaceAndUpdateBootstrap({ zeroSpace: metaspace.zeroSpace, allowCancel: false, createBootstrap: false, spaceName, spaceId, }); if (!newBranchSpace || !newBranchSpace.data) { throw new Error(`Failed to create new branch space "${spaceName}" in metaspace. (E: 30386af366cd3e9a08632983fa612cf4)`); } const newBranchSpaceId = getSpaceIdFromIb(newBranchSpace.ib); return { space: newBranchSpace, spaceId: newBranchSpaceId, spaceName, }; } /** * Ensures an existing dedicated branch space in metaspace. * Fails fast (throws) if the branch space does not exist. Never creates. */ export async function ensureBranchSpace(opts: EnsureBranchSpaceOpts): Promise { const lc = `${lcFile}[${ensureBranchSpace.name}]`; const { metaspace, branchName, galaxyName, cosmosName, spaceId } = opts; if (!metaspace || !branchName) { throw new Error(`metaspace and branchName are required (E: f49860120959221b79e2b535f5ebf92c)`); } if (spaceId && !UUID_REGEXP.test(spaceId)) { throw new Error(`spaceId (${spaceId}) does not match UUID_REGEXP (${UUID_REGEXP.source}) (E: 7b6d839a89b5c0f851564813aeeec460)`); } const spaceName = getB2tFSBranchSpaceName(branchName, galaxyName, cosmosName); const localSpaces = await metaspace.getLocalUserSpaces({ lock: false }); let existingBranchSpace: IbGibSpaceAny | undefined; if (spaceId) { existingBranchSpace = localSpaces.find(s => { const sId = (s.data as any)?.spaceId || (s.data as any)?.uuid || (s.ib ? getSpaceIdFromIb(s.ib) : undefined); return sId === spaceId; }); } if (!existingBranchSpace) { existingBranchSpace = localSpaces.find(s => { if (s.data?.name === spaceName) return true; try { return parseSpaceIb({ spaceIb: s.ib }).spaceName === spaceName; } catch (parseErr) { if (logalot) { console.log(`${lc} space.ib (${s.ib}) not parseable as spaceIb: ${extractErrorMsg(parseErr)} (I: a9c2e345678949a4a755de89f41b9c26)`); } return false; } }); } if (!existingBranchSpace) { throw new Error(`Branch space "${spaceName}" (spaceId: ${spaceId || 'any'}) not found in metaspace. Expected existing branch space. (E: 98079416cc2935a0d9e7f709c1b7d630)`); } const existingBranchSpaceId = getSpaceIdFromIb(existingBranchSpace.ib); if (spaceId && existingBranchSpaceId !== spaceId) { throw new Error(`existingBranchSpaceId (${existingBranchSpaceId}) does not match expected spaceId (${spaceId}) for branchName "${branchName}". (E: 6234862a840fd9d9a4ab0760a25d698a)`); } return { space: existingBranchSpace, spaceId: existingBranchSpaceId, spaceName: existingBranchSpace.data?.name || spaceName, }; } /** * Helper to recursively search a CompositeBranchNode tree for a specific branchName. */ export function findNodeInTree(node: CompositeBranchNode, branchName: string): CompositeBranchNode | undefined { if (node.branchInfo.branchName === branchName) return node; for (const child of node.children) { const found = findNodeInTree(child, branchName); if (found) return found; } return undefined; } /** * Helper to prune a CompositeBranchNode tree to a maximum depth. */ export function pruneTreeDepth(node: CompositeBranchNode, maxDepth: number, currentDepth: number = 0): CompositeBranchNode { if (maxDepth <= 0) { return { ...node, depth: currentDepth, children: [] }; } return { ...node, depth: currentDepth, children: node.children.map(child => pruneTreeDepth(child, maxDepth - 1, currentDepth + 1)), }; } /** * Flattens all CompositeBranchNode nodes into a flat array of BranchInfo[]. */ export function flattenCompositeBranchTree(rootNode: CompositeBranchNode): BranchInfo[] { const result: BranchInfo[] = []; const queue: CompositeBranchNode[] = [rootNode]; const seen = new Set(); while (queue.length > 0) { const current = queue.shift()!; if (!seen.has(current.branchInfo.branchName)) { seen.add(current.branchInfo.branchName); result.push(current.branchInfo); for (const child of current.children) { queue.push(child); } } } return result; } export interface GetCompositeBranchTreeFromBranchOpts { branchIbGib?: B2tFSBranchIbGib_V1; branchSqAddr?: SpaceQualifiedIbGibAddr; branchSpace?: IbGibSpaceAny; metaspace: MetaspaceService; /** * Maximum depth to traverse. * 0 = current branch only (no children). * 1 = current branch + immediate children. * undefined = full recursion. */ depth?: number; currentDepth?: number; } /** * Recursively traverses the composite tree of branches starting from a specific branch stone. */ export async function getCompositeBranchTreeFromBranch( opts: GetCompositeBranchTreeFromBranchOpts ): Promise { const lc = `${lcFile}[${getCompositeBranchTreeFromBranch.name}]`; const { metaspace, depth, currentDepth = 0 } = opts; let { branchIbGib, branchSqAddr, branchSpace } = opts; if (!metaspace) { throw new Error(`metaspace required (E: e5f6a1b2c3d44718890123456789abcd)`); } // 1. Resolve branchSqAddr if only branchIbGib provided if (!branchSqAddr && branchIbGib && branchSpace) { const spaceId = getSpaceIdFromIb(branchSpace.ib); branchSqAddr = getSpaceQualifiedIbGibAddr({ spaceId, ibGibAddr: getIbGibAddr({ ibGib: branchIbGib }), }); } if (!branchSqAddr && !branchIbGib) { throw new Error(`branchSqAddr or branchIbGib required (E: f6a1b2c3d4e54718890123456789abcd)`); } const sqAddrInfo = parseSpaceQualifiedIbGibAddr({ sqAddr: branchSqAddr! }); const { spaceId } = sqAddrInfo; // 2. Resolve branchSpace if not provided or if provided branchSpace does not match spaceId if (!branchSpace) { branchSpace = await metaspace.getLocalUserSpace({ localSpaceId: spaceId, lock: false, }); if (!branchSpace) { throw new Error(`branchSpace not found for spaceId: ${spaceId} (E: a1b2c3d4e5f64718890123456789abce)`); } } else if (spaceId) { const currentSpaceId = (branchSpace.data as any)?.spaceId || (branchSpace.ib ? getSpaceIdFromIb(branchSpace.ib) : undefined); if (currentSpaceId && currentSpaceId !== spaceId) { branchSpace = await metaspace.getLocalUserSpace({ localSpaceId: spaceId, lock: false, }); if (!branchSpace) { throw new Error(`branchSpace not found for spaceId: ${spaceId} (E: a1b2c3d4e5f64718890123456789abce)`); } } } // 3. Resolve latest branchIbGib in space const latestAddr = await metaspace.getLatestAddr({ addr: sqAddrInfo.ibGibAddr, space: branchSpace }) || sqAddrInfo.ibGibAddr; branchIbGib = await getIbGibFromSpace({ addr: latestAddr, space: branchSpace, }); if (!branchIbGib) { throw new Error(`branchIbGib not found at addr ${latestAddr} in space ${branchSpace.ib} (E: b2c3d4e5f6a14718890123456789abce)`); } const branchIbInfo = parseBranchIb({ ib: branchIbGib.ib }); const branchInfo: BranchInfo = { branchName: branchIbGib.data.name || branchIbInfo.branchName, branchId: branchIbGib.data.uuid || branchIbInfo.uuid, branchIbInfo, branchAddr: latestAddr, branchSqAddr: branchSqAddr!, branchSqAddrInfo: sqAddrInfo, }; const node: CompositeBranchNode = { branchInfo, branchIbGib, parentBranchName: branchIbGib.data.parentBranchName, parentBranchSqAddr: branchIbGib.data.parentBranchSqAddr, scopedItemPath: branchIbGib.data.scopedItemPath, depth: currentDepth, children: [], }; // If depth limit reached, return without recursing into children if (depth !== undefined && depth <= 0) { return node; } // 4. Recurse into child branches via $@branch const childSqAddrs = branchIbGib.data['$@branch'] || []; for (const childSqAddr of childSqAddrs) { try { const childNode = await getCompositeBranchTreeFromBranch({ branchSqAddr: childSqAddr, metaspace, depth: depth !== undefined ? depth - 1 : undefined, currentDepth: currentDepth + 1, }); node.children.push(childNode); } catch (childErr) { console.error(`${lc} Failed to traverse child branch ${childSqAddr}: ${extractErrorMsg(childErr)}`); } } return node; } export interface GetCompositeBranchTreeFromGalaxyOpts { galaxyIbGib: B2tFSGalaxyIbGib_V1 | GalaxyIbGib_V1; metaspace: MetaspaceService; startBranchName?: string; depth?: number; } /** * Retrieves the composite branch tree for a galaxy starting from the canonical trunk ('main') * or a specified starting branch name. */ export async function getCompositeBranchTreeFromGalaxy( opts: GetCompositeBranchTreeFromGalaxyOpts ): Promise { const lc = `${lcFile}[${getCompositeBranchTreeFromGalaxy.name}]`; const { galaxyIbGib, metaspace, startBranchName, depth } = opts; if (!galaxyIbGib) throw new Error(`galaxyIbGib required (E: c3d4e5f6a1b24718890123456789abcf)`); if (!metaspace) throw new Error(`metaspace required (E: d4e5f6a1b2c34718890123456789abcf)`); // 1. Resolve starting branch space-qualified address const b2tfsGalaxy = galaxyIbGib as B2tFSGalaxyIbGib_V1; let trunkSqAddr: SpaceQualifiedIbGibAddr | undefined = b2tfsGalaxy.data?.trunkBranchSqAddr; // Fallback: look at first branch in $@branch if (!trunkSqAddr) { const sqBranchAddrs = b2tfsGalaxy.data?.['$@branch'] || []; if (sqBranchAddrs.length > 0) { trunkSqAddr = sqBranchAddrs[0]; } } if (!trunkSqAddr) { const galaxyName = (galaxyIbGib as any).data?.galaxyName; if (!galaxyName) { throw new Error(`galaxyIbGib.data.galaxyName required. (E: f3a8d11c4b7245ef8a69e710b1928026)`); } throw new Error(`Galaxy [${galaxyName}] has no trunk branch registered. (E: e5f6a1b2c3d44718890123456789abcf)`); } // 2. If startBranchName is specified and is NOT the trunk branch, traverse from trunk to find start branch if (startBranchName) { const trunkTree = await getCompositeBranchTreeFromBranch({ branchSqAddr: trunkSqAddr, metaspace, depth: undefined, }); const targetNode = findNodeInTree(trunkTree, startBranchName); if (!targetNode) { throw new Error(`Branch [${startBranchName}] not found in galaxy composite tree. (E: f6a1b2c3d4e54718890123456789abcf)`); } if (depth !== undefined) { return pruneTreeDepth(targetNode, depth); } return targetNode; } // Default: start from trunk branch return getCompositeBranchTreeFromBranch({ branchSqAddr: trunkSqAddr, metaspace, depth, }); } /** * Retrieves all BranchInfo instances across the galaxy's composite branch hierarchy. */ export async function getAllBranchInfosFromGalaxy({ galaxyIbGib, metaspace, depth, }: { galaxyIbGib: B2tFSGalaxyIbGib_V1 | GalaxyIbGib_V1; metaspace?: MetaspaceService; depth?: number; }): Promise { const lc = `[${getAllBranchInfosFromGalaxy.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 86f07281948470f89ae72308e1e92826)`); } if (!galaxyIbGib) { throw new Error(`(UNEXPECTED) galaxyIbGib falsy? (E: 52242814ae88f24442f0dc289505b826)`); } // If metaspace is provided, use composite tree traversal with fallback to $@branch if (metaspace) { try { const rootNode = await getCompositeBranchTreeFromGalaxy({ galaxyIbGib, metaspace, depth, }); const treeInfos = flattenCompositeBranchTree(rootNode); if (treeInfos.length > 0) return treeInfos; } catch (treeErr) { if (logalot) { console.warn(`${lc} getCompositeBranchTreeFromGalaxy failed, falling back to static $@branch: ${extractErrorMsg(treeErr)}`); } } } // Fast fallback when metaspace is not provided (e.g. initial static check) const sqBranchAddrs = (galaxyIbGib as B2tFSGalaxyIbGib_V1).data?.['$@branch'] || []; const allInfos: BranchInfo[] = []; for (const sqBranchAddr of sqBranchAddrs) { const thatSqAddrInfo = parseSpaceQualifiedIbGibAddr({ sqAddr: sqBranchAddr }); const thatBranchIbInfo = parseBranchIb({ ib: thatSqAddrInfo.ib }); allInfos.push({ branchName: thatBranchIbInfo.branchName, branchId: thatBranchIbInfo.uuid, branchIbInfo: thatBranchIbInfo, branchAddr: thatSqAddrInfo.ibGibAddr, branchSqAddr: sqBranchAddr, branchSqAddrInfo: thatSqAddrInfo, }); } return allInfos; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } export async function getBranchInfoFromGalaxy({ galaxyIbGib, branchName, metaspace, }: { galaxyIbGib: B2tFSGalaxyIbGib_V1 | GalaxyIbGib_V1; branchName: string; metaspace?: MetaspaceService; }): Promise { const lc = `[${getBranchInfoFromGalaxy.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: d63138d40debdb1a8b398b6135875326)`); } // 1. Fast check on trunk/galaxy $@branch const sqBranchAddrs = (galaxyIbGib as B2tFSGalaxyIbGib_V1).data?.['$@branch'] || []; for (const sqBranchAddr of sqBranchAddrs) { const thatSqAddrInfo = parseSpaceQualifiedIbGibAddr({ sqAddr: sqBranchAddr }); const thatBranchIbInfo = parseBranchIb({ ib: thatSqAddrInfo.ib }); if (thatBranchIbInfo.branchName === branchName) { return { branchName, branchId: thatBranchIbInfo.uuid, branchIbInfo: thatBranchIbInfo, branchAddr: thatSqAddrInfo.ibGibAddr, branchSqAddr: sqBranchAddr, branchSqAddrInfo: thatSqAddrInfo, }; } } // 2. If metaspace provided, check full composite tree if (metaspace) { const allInfos = await getAllBranchInfosFromGalaxy({ galaxyIbGib, metaspace }); const found = allInfos.find(info => info.branchName === branchName); if (found) { return found; } } throw new Error(`branchName (${branchName}) not found in galaxyIbGib ${getIbGibAddr({ ibGib: galaxyIbGib })} (E: 8c9cf891f118afafe853049883248826)`); } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * Retrieves all registered B2tFSBranchIbGib_V1 instances across the galaxy's composite branch hierarchy. */ export async function getAllBranchIbGibsFromGalaxy({ galaxyIbGib, metaspace, }: { galaxyIbGib: B2tFSGalaxyIbGib_V1 | GalaxyIbGib_V1; metaspace: MetaspaceService; }): Promise { const lc = `[${getAllBranchIbGibsFromGalaxy.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 1b14785116888c37a8b3a03189811826)`); } if (!galaxyIbGib) { throw new Error(`(UNEXPECTED) galaxyIbGib falsy? (E: 52242814ae88f24442f0dc289505b826)`); } if (!metaspace) { throw new Error(`(UNEXPECTED) metaspace falsy? (E: 1a7dc1b555bd5ee98a826da857a5c826)`); } const rootNode = await getCompositeBranchTreeFromGalaxy({ galaxyIbGib, metaspace }); const branchIbGibs: B2tFSBranchIbGib_V1[] = []; const queue: CompositeBranchNode[] = [rootNode]; const seen = new Set(); while (queue.length > 0) { const current = queue.shift()!; if (!seen.has(current.branchInfo.branchName)) { seen.add(current.branchInfo.branchName); branchIbGibs.push(current.branchIbGib); for (const child of current.children) { queue.push(child); } } } return branchIbGibs; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } }