import { delay, extractErrorMsg, pretty, unique } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs'; import { IbGibAddr, TjpIbGibAddr, } from '@ibgib/ts-gib/dist/types.mjs'; import { getIbAndGib, getIbGibAddr, } from '@ibgib/ts-gib/dist/helper.mjs'; import { validateIbGibAddr } from '@ibgib/ts-gib/dist/V1/validate-helper.mjs'; import { GIB, IbGib_V1, isPrimitive, IBGIB_DELIMITER, } from '@ibgib/ts-gib/dist/V1/index.mjs'; import { GLOBAL_LOG_A_LOT } from '../../core-constants.mjs'; import { getFromSpace, getLatestAddrs, persistTransformResult, registerNewIbGib } from '../../witness/space/space-helper.mjs'; import { rel8 } from '@ibgib/ts-gib/dist/V1/transforms/rel8.mjs'; import { getIbGibFromSpace, getTimelinesGroupedByTjp, toDto } from './ibgib-helper.mjs'; import { IbGibSpaceAny } from '../../witness/space/space-base-v1.mjs'; import { MetaspaceService } from '../../witness/space/metaspace/metaspace-types.mjs'; import { FlatIbGibGraph } from './graph-types.mjs'; const logalot = GLOBAL_LOG_A_LOT; /** * Options when getting dependency graph for ibGib(s). * * Note that this is used both in local and outer space contexts. * When you want to default to the local user space in the local context, * i.e. in `IbgibsService` atow, pass in `null` for {@link space}. */ export interface GetGraphOptions { /** * source ibGib to grab dependencies of. * * caller can pass in `ibGib` or `ibGibs` or `ibGibAddr` or `ibGibAddrs`. */ ibGib?: IbGib_V1, /** * source ibGibs to grab dependencies of. * * caller can pass in `ibGib` or `ibGibs` or `ibGibAddr` or `ibGibAddrs`. */ ibGibs?: IbGib_V1[], /** * source ibGib address to grab dependencies of. * * caller can pass in `ibGib` or `ibGibs` or `ibGibAddr` or `ibGibAddrs`. */ ibGibAddr?: IbGibAddr, /** * source ibGib addresses to grab dependencies of. * * caller can pass in `ibGib` or `ibGibs` or `ibGibAddr` or `ibGibAddrs`. */ ibGibAddrs?: IbGibAddr[], /** * If true, for each timeline in each "frozen" ibgib graph we will get the * latest address in the timeline and recheck rel8d ibgibs for newly * added timeline branches. * * If false, this will only look in the past for each rel8d ibgib. * * ## notes * * Say you have a source ibgib with a comment "child" (relative to our * source ibgib). Now say you add an ibgib to that child comment. The rel8d * addr in the source ibgib will still point to the child comment's initial * addr - before it was changed by adding its own "child" ("grandchild" to * the source). So if you get a live dependency graph on the parent, it will * come across the child's timeline and get the latest for that timeline * (and associated ibgibs like the child's dna transforms that add the * grandchild). This will include the grandchild. If it's not a live graph, * then the parent will only have the child and will exclude the grandchild. */ live?: boolean, /** * object that will be populated through recursive calls to this function. * * First caller of this function should not provide this and I'm not atow * coding a separate implementation function to ensure this. * * @see {@link skipAddrs} */ gotten?: { [addr: string]: IbGib_V1 }, /** * used when doing {@link live} dependency graph gets. Same use as * {@link gotten}, but with regards to timelines. */ tjpAddrsAlreadyAnalyzed?: TjpIbGibAddr[], /** * List of ibgib addresses to skip not retrive in the dependency graph. * * This will also skip any ibgib addresses that would have occurred in the * past of these ibgibs, as when skipping an ibgib, you are also skipping * its dependencies implicitly as well (unless those others are related via * another ibgib that is not skipped of course). * * ## driving use case * * We don't want to get ibgibs that we already have, and this is cleaner * than pre-populating the `gotten` parameter for double-duty. That property * should be strictly used within this call recursively. * * @see {@link gotten} */ skipAddrs?: IbGibAddr[] | Set, /** * Skip these particular rel8n names. * * ## driving intent * * I'm adding this to be able to skip getting dna ibgibs. * * ## see also * * @see {@link onlyRel8nNames} for whitelist of rel8n names for traversal */ skipRel8nNames?: string[], /** * whitelist of rel8nNames to traverse. * * ## see also * * @see {@link skipRel8nNames} for a blacklist of rel8n names for traversal */ onlyRel8nNames?: string[], /** * If not found when getting dependency graph, do we retry? This is the * max number of retries. */ maxRetries?: number, /** * If provided and {@link maxRetries} is non-zero, the next retry will be * delayed this amount of time if one or more addrs are not found. */ msBetweenRetries?: number, /** * Space within which we should be looking for ibGibs. * Mutually exclusive with {@link spaces}. */ space?: IbGibSpaceAny | null, /** * Spaces within which we should be looking for ibGibs. * Mutually exclusive with {@link space}. */ spaces?: IbGibSpaceAny[], /** * If supplied, will make intermittent calls to console.timeLog using this name. */ timeLogName?: string, /** * When getting the live dependency graph, this is used so we don't * duplicate work in recursive calls. * * IOW, in the first run of{@link getGraphProjection_Live}, we call * getLatestAddrs which maps some addrs to the latest addrs in the space. So * we now have a reference to the latest and if we need to call the function * {@link getGraphProjection_Live} recursively, then we can provide this * info to reduce unnecessary computation. */ mapTjpAddrToLatestAddrsInSpace?: { [tjpAddr: string]: IbGibAddr } } export type GetGraphResult = FlatIbGibGraph; export interface GetGraphProjectionOptions extends GetGraphOptions { // /** // * max depth away from source ibgibs to traverse // */ // depth?: number; } export interface GetDependencyGraphOptions extends GetGraphProjectionOptions { // depth?: undefined; } /** * * @returns dependency graph, live or non-live depending on {@link GetDependencyGraphOptions} * * Getting a `live` dependency graph means that we will be looking in the given * @see {@link GetDependencyGraphOptions.space} for updates to ibGibs' timelines * (those ibGibs that have timelines/tjps). This is more costly computationally * in the short-term, but often cheaper in the long-term. */ export async function getDependencyGraph({ ibGib, ibGibs, ibGibAddr, ibGibAddrs, live, gotten, tjpAddrsAlreadyAnalyzed, skipAddrs, skipRel8nNames, onlyRel8nNames, maxRetries, msBetweenRetries, space, spaces, timeLogName, mapTjpAddrToLatestAddrsInSpace, }: GetGraphProjectionOptions): Promise { const lc = `[${getDependencyGraph.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: c2a4426c22e849611ca0cedabe683a22)`); } const graph = await getGraphProjection({ ibGib, ibGibs, ibGibAddr, ibGibAddrs, live, gotten, tjpAddrsAlreadyAnalyzed, skipAddrs, skipRel8nNames, onlyRel8nNames, maxRetries, msBetweenRetries, space, spaces, timeLogName, mapTjpAddrToLatestAddrsInSpace, }); if (logalot) { Object.values(graph).filter(ibGib => ibGib.ib.startsWith('comment ')).forEach(ibGib => { console.table(ibGib); }); } if (logalot) { console.log(`${lc} graph size: ${Object.keys(graph).length} (I: c6cb5e7e1e2611d35b9006fac6503d22)`); const ibs = Object.values(graph).filter(ibGib => ibGib.ib.startsWith('comment ') || ibGib.ib.startsWith('pic ')) .map(ibGib => ibGib.ib); unique(ibs).forEach(ib => console.log(ib)); } return graph; } catch (error) { console.error(`${lc} ${error.message}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } // #region getGraphProjection async function getGraphProjection_initializeOpts({ ibGib, ibGibs, ibGibAddr, ibGibAddrs, live, gotten, tjpAddrsAlreadyAnalyzed, skipAddrs, skipRel8nNames, onlyRel8nNames, maxRetries, msBetweenRetries, space, spaces, timeLogName, mapTjpAddrToLatestAddrsInSpace, }: GetDependencyGraphOptions): Promise { const lc = `[${getGraphProjection_initializeOpts.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: bd6807477f679345df9dddefe0b4e922)`); } if (space && (spaces ?? []).length > 0) { throw new Error("space and spaces parameters are mutually exclusive. Pass either space or spaces, not both. (E: 994a5323e4214f4e95d5bb2b89f89090)"); } const resolvedSpaces: IbGibSpaceAny[] = space ? [space] : (spaces ?? []).filter(s => !!s); if (resolvedSpaces.length === 0) { throw new Error("space or spaces required. (E: 9f38166ab70340cb919174f8d26af909)"); } if (!ibGib && !ibGibAddr && (ibGibs ?? []).length === 0 && (ibGibAddrs ?? []).length === 0) { throw new Error(`either ibGib/s or ibGibAddr/s required. (E: b6d08699651f455697f0d05a41edb039)`); } const skipAddrsSet: Set = skipAddrs instanceof Set ? skipAddrs : new Set(skipAddrs || []); skipRel8nNames = skipRel8nNames || []; // do NOT initialize onlyRel8nNames because we do logic based on falsy value gotten = gotten || {}; tjpAddrsAlreadyAnalyzed = tjpAddrsAlreadyAnalyzed || []; // convert single args (ibGib, ibGibAddr) into the array args, filtering // out primitives that we don't want. The `filter` function creates the // copy here, so we won't mutate the incoming arrays. (The ibgibs and // addrs themselves are immutable). ibGibAddrs = (ibGibAddrs ?? []) .filter(x => !isPrimitive({ gib: getIbAndGib({ ibGibAddr: x }).gib })) // no primitives .filter(x => !skipAddrsSet.has(x)); ibGibs = (ibGibs ?? []) .filter(x => !isPrimitive({ ibGib: x })) // no primitives .filter(x => !skipAddrsSet.has(getIbGibAddr({ ibGib: x }))); // if we're passed in a single ibGib, add it to the ibGibs array because // we're going to work off of that. if (ibGib && !isPrimitive({ ibGib }) && !ibGibs.some(x => x.gib === ibGib.gib) && !skipAddrsSet.has(getIbGibAddr({ ibGib })) ) { ibGibs.push(ibGib); } // if we're passed in a single ibGibAddr, add it to the ibGibAddrs array because // we're going to work off of that. if (ibGibAddr && !isPrimitive({ gib: getIbAndGib({ ibGibAddr }).gib }) && !ibGibAddrs.includes(ibGibAddr) && !skipAddrsSet.has(ibGibAddr) ) { ibGibAddrs.push(ibGibAddr); } return { ibGib, ibGibs, ibGibAddr, ibGibAddrs, live, gotten, tjpAddrsAlreadyAnalyzed, skipAddrs: skipAddrsSet, skipRel8nNames, onlyRel8nNames, maxRetries, msBetweenRetries, space: undefined, spaces: resolvedSpaces, timeLogName, mapTjpAddrToLatestAddrsInSpace, }; } catch (error) { console.error(`${lc} ${error.message}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } async function getGraphProjection_getIbGibsInIbGibAddrs({ ibGibs, ibGibAddrs, gotten, skipAddrs, maxRetries, msBetweenRetries, timeLogName, space, spaces, }: GetGraphProjectionOptions & { spaces?: IbGibSpaceAny[] }): Promise { const lc = `[${getGraphProjection_getIbGibsInIbGibAddrs.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 67b2be37ff24393fff56e229304da122)`); } const resolvedSpaces: IbGibSpaceAny[] = spaces ?? (space ? [space] : []); if (resolvedSpaces.length === 0) { throw new Error(`(UNEXPECTED) spaces empty? (E: aa9f657695717034b3581066932d7d23)`); } /** * ibgibs that we'll return */ const resIbGibs: IbGib_V1[] = []; ibGibs ??= []; ibGibAddrs ??= []; const skipAddrsSet: Set = skipAddrs instanceof Set ? skipAddrs : new Set(skipAddrs || []); gotten ??= {}; const localGotten = gotten; const addrsToGetFromSpace: IbGibAddr[] = []; const incomingIbGibAddrsSet = new Set(ibGibs.map(x => getIbGibAddr({ ibGib: x }))); for (let i = 0; i < ibGibAddrs.length; i++) { const addr = ibGibAddrs[i]; if (skipAddrsSet.has(addr) || incomingIbGibAddrsSet.has(addr)) { continue; } else if (localGotten[addr]) { resIbGibs.push(localGotten[addr]); } else { addrsToGetFromSpace.push(addr); } } if (logalot) { console.log(`${lc}[analyze debugging] addrsToGetFromSpace (${addrsToGetFromSpace.length}):\n${addrsToGetFromSpace.join('\n')} (I: b45a2614184b48b694becfd377c789f5)`); } if (addrsToGetFromSpace.length > 0) { let addrsToGet = addrsToGetFromSpace.concat(); let retryCount = 0; maxRetries = maxRetries ?? 0; while (retryCount <= maxRetries && addrsToGet.length > 0) { if (timeLogName && retryCount === 0) { console.timeLog(timeLogName, `${lc} FIRST try starting...`) } if (timeLogName && retryCount > 0) { console.timeLog(timeLogName, `${lc} RETRY starting...`) } if (retryCount > 0 && msBetweenRetries) { if (timeLogName) { console.timeLog(timeLogName, `${lc} delaying ${msBetweenRetries}ms for retry`); } if (logalot) { console.log(`${lc} retrying. addrsToGet (${addrsToGet.length}): ${addrsToGet} (I: 8460694cdd5518472680784c3b96a822)`); } await delay(msBetweenRetries); } for (const spaceOfSpaces of resolvedSpaces) { if (addrsToGet.length === 0) { break; } if (timeLogName) { console.timeLog(timeLogName, `${lc} getFromSpace (${addrsToGet.length}) starting...`); } let resGetThese = await getFromSpace({ addrs: addrsToGet, space: spaceOfSpaces }); if (timeLogName) { console.timeLog(timeLogName, `${lc} getFromSpace complete.`); } if (resGetThese.success && (resGetThese.ibGibs?.length ?? 0) > 0) { resGetThese.ibGibs!.forEach(x => resIbGibs.push(x)); const gottenAddrsInTry = new Set(resGetThese.ibGibs!.map(x => getIbGibAddr({ ibGib: x }))); addrsToGet = addrsToGet.filter(x => !gottenAddrsInTry.has(x)); } else { const gottenIbGibs: IbGib_V1[] = (resGetThese.rawResultIbGib as any)?.ibGibs ?? []; if (gottenIbGibs.length > 0) { gottenIbGibs.forEach(x => resIbGibs.push(x)); const gottenAddrsInTry = new Set(gottenIbGibs.map(x => getIbGibAddr({ ibGib: x }))); addrsToGet = addrsToGet.filter(x => !gottenAddrsInTry.has(x)); } } } retryCount++; } if (addrsToGet.length > 0) { const spaceIbs = resolvedSpaces.map(s => s?.ib).join(', '); throw new Error(`unable to retrieve dependency ibgibs from space/s (ib/s: ${spaceIbs}). addrsToGet: ${addrsToGet.join('\n')} (E: 8413594b6c1b447988781cf3f3e1729d)`); } } return resIbGibs; } catch (error) { console.error(`${lc} ${error.message}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } export async function getGraphProjection(opts: GetDependencyGraphOptions): Promise { const lc = `[${getGraphProjection.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 70508d7a5c63eae1f22ae851b32b3d22)`); } if (!opts.ibGib && !opts.ibGibAddr && (opts.ibGibs ?? []).length === 0 && (opts.ibGibAddrs ?? []).length === 0) { // no ibgibs/addrs, return empty - don't throw return {} as GetGraphResult; /* <<<< returns early */ } // ibGib and ibGibAddr get condensed into ibGibs and ibGibAddrs let { /*ibGib,*/ ibGibs, /*ibGibAddr,*/ ibGibAddrs, live, gotten, tjpAddrsAlreadyAnalyzed, skipAddrs, skipRel8nNames, onlyRel8nNames, maxRetries, msBetweenRetries, space, spaces, timeLogName, mapTjpAddrToLatestAddrsInSpace, } = await getGraphProjection_initializeOpts(opts); if (timeLogName) { console.timeLog(timeLogName, `${lc} starting...`) } // retrieve ibgibs listed in incoming ibGibAddrs (if any) and put them // in our incoming ibGibs array if (ibGibAddrs?.length ?? 0 > 0) { const supplementalIbGibs = await getGraphProjection_getIbGibsInIbGibAddrs({ ibGibs, ibGibAddrs, gotten, skipAddrs, maxRetries, msBetweenRetries, timeLogName, space, spaces, }); ibGibs = ibGibs ? [...ibGibs, ...supplementalIbGibs] : [...supplementalIbGibs] } ibGibAddrs = ibGibs!.map(x => getIbGibAddr({ ibGib: x })); // at this point, there are two different strategies for diving deeper, // depending on if we are building a `live` graph or not. let commentIbs = unique(ibGibs!.map(x => x.ib).filter(x => x.startsWith('comment '))); if (logalot) { console.log(`${lc}[analyze debugging] ibGibs commentIbs: ${commentIbs.join('\n')} (I: c89dc951315f746954f9bddbe8941122)`); } if (live) { return getGraphProjection_Live({ ibGibs, ibGibAddrs, gotten, tjpAddrsAlreadyAnalyzed, skipAddrs, skipRel8nNames, onlyRel8nNames, maxRetries, msBetweenRetries, space, spaces, timeLogName, mapTjpAddrToLatestAddrsInSpace, }); } else { return getGraphProjection_NonLive({ ibGibs, ibGibAddrs, gotten, /* tjpAddrsAlreadyAnalyzed not used */ skipAddrs, skipRel8nNames, onlyRel8nNames, maxRetries, msBetweenRetries, space, spaces, timeLogName, }); } } catch (error) { console.error(`${lc} ${error.message}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * Get the dependency graph for {@link ibGibAddr} since {@link latestCommonFrameAddr}. * * if ibGibAddr is A^5 and latestCommonFrameAddr is A^3, then this should * get all dependencies in A^5 dependency graph NOT ALREADY IN the A^3 * graph. * * NOTE: The {@link live} param is for the delta graph itself. The graph * corresponding to {@link latestCommonFrameAddr} is always calculated live === * false. */ export async function getDeltaDependencyGraph({ ibGibAddr, latestCommonFrameAddr, live, skipRel8nNames, space, spaces, }: { ibGibAddr: string; latestCommonFrameAddr: string; live: boolean, skipRel8nNames?: string[]; space?: IbGibSpaceAny; spaces?: IbGibSpaceAny[]; }): Promise { const lc = `[${getDeltaDependencyGraph.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 5d225e56dc11e62cd83c5366ea288826)`); } if (ibGibAddr === latestCommonFrameAddr) { console.warn(`${lc} ibGibAddr === latestCommonFrameAddr. So the delta graph is empty. what are we doing here? (W: e0c8287ae6de8152bf36b6c73ca59a26)`); return {}; } const dependencyGraph_lcf = await getDependencyGraph({ ibGibAddr: latestCommonFrameAddr, live: false, // always get the smaller graph live === false! skipRel8nNames, space, spaces, }); const dependencyGraph_delta = await getDependencyGraph({ ibGibAddr, live, skipAddrs: new Set(Object.keys(dependencyGraph_lcf)), skipRel8nNames, space, spaces, }); return dependencyGraph_delta; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * * live dependency graph searching requires a timeline-centric approach. * for each incoming ibGib, we must first determine if it has a * timeline. if it does, then we get the latest in that timeline and * get all ibgibs in that lineage only. we do NOT YET go through any * rel8d ibgibs that also have timelines * * what we can do is compile our list of ibGib addrs according to each * timeline and then call the nonlive version of the dependency graph. * but we must get the latest in the timeline, then get all associated * timelines and get the latest of those. Then we can call get * dependency graph on the non-live version, passing in all of those * latest ibgibs in the timelines (and everything we've gotten in the * interim so we don't waste time getting more). * * @see {@link getGraphProjection} * @see {@link getDependencyGraph} */ async function getGraphProjection_Live({ ibGibs, ibGibAddrs, gotten, tjpAddrsAlreadyAnalyzed, mapTjpAddrToLatestAddrsInSpace, skipAddrs, skipRel8nNames, onlyRel8nNames, maxRetries, msBetweenRetries, space, spaces, timeLogName, }: GetGraphProjectionOptions & { spaces?: IbGibSpaceAny[] }): Promise { const lc = `[${getGraphProjection_Live.name}]`; try { const resolvedSpaces: IbGibSpaceAny[] = spaces ?? (space ? [space] : []); mapTjpAddrToLatestAddrsInSpace = mapTjpAddrToLatestAddrsInSpace ?? {}; tjpAddrsAlreadyAnalyzed = tjpAddrsAlreadyAnalyzed ?? []; // `ibGibs` contains the ones we explicitly are still working on getting // projections within, `gotten` are the ones we have completed. so we // want to get all of them together so we have a complete (up to this // point) picture of timelines, because we're looking for timelines that // we haven't yet analyzed let allIbGibsSoFar = { ...gotten }; (ibGibs ?? []).forEach(x => allIbGibsSoFar[getIbGibAddr({ ibGib: x })] = x); const allKnownTimelinesAtThisPoint = getTimelinesGroupedByTjp({ ibGibs: Object.values(allIbGibsSoFar), }); if (logalot) { console.log(`${lc}[analyze debugging] timeline tjps(${Object.keys(allKnownTimelinesAtThisPoint).length}): ${Object.keys(allKnownTimelinesAtThisPoint)} (I: 509f04ac15ca08c5a3f0777b48934622)`); } const timelinesNotAnalyzed: { [addr: string]: IbGib_V1[] } = {}; Object.keys(allKnownTimelinesAtThisPoint).forEach(tjpAddr => { if (!tjpAddrsAlreadyAnalyzed!.includes(tjpAddr)) { timelinesNotAnalyzed[tjpAddr] = allKnownTimelinesAtThisPoint[tjpAddr]; } }); if (logalot) { console.log(`${lc}[analyze debugging] timelinesNotAnalyzed: ${pretty(timelinesNotAnalyzed)} (I: a4b67d95fdd6b98d3241c0a7d0a93c22)`); } const mapTjpAddrToLatestIbGibInTimelineThatWeHaventAlreadyAnalyzed: { [tjpAddr: IbGibAddr]: IbGib_V1 } = {}; /** * Convience mapping back from latest addr already gotten back to the tjp addr. * Convenience = not strictly necessary, but makes it easier later. */ const mapLatestAddrAlreadyGottenToTjpAddr: { [latestAddrAlreadyGotten: IbGibAddr]: IbGibAddr } = {}; Object.keys(allKnownTimelinesAtThisPoint) .filter(tjpAddr => !tjpAddrsAlreadyAnalyzed!.includes(tjpAddr)) .forEach(tjpAddr => { const timeline = allKnownTimelinesAtThisPoint[tjpAddr]; // add to the array we'll send below const latestIbGibAlreadyGotten = timeline[timeline.length - 1]; mapTjpAddrToLatestIbGibInTimelineThatWeHaventAlreadyAnalyzed[tjpAddr] = latestIbGibAlreadyGotten; // add to mapping back from addr to tjpaddr for convenience below const latestAddrAlreadyGotten = getIbGibAddr({ ibGib: latestIbGibAlreadyGotten }); mapLatestAddrAlreadyGottenToTjpAddr[latestAddrAlreadyGotten] = tjpAddr; }); let countOfTimelinesNotYetGotten = Object.keys(mapTjpAddrToLatestIbGibInTimelineThatWeHaventAlreadyAnalyzed).length; if (countOfTimelinesNotYetGotten > 0) { // we have more timelines still to do. get the latest ibGib in each timeline, // add it, check for more timelines. But we may have already gotten a latestAddrsMap // in a previous call, so account for this. // query only latest ibgibs that we haven't already gotten AND whose // timelines we've not already analyzed, per // mapTjpAddrToLatestAddrsInSpace. /** * build this map of latest addr given -> latest addr in space (per timeline/tjp). */ let latestAddrsMap: { [addr: string]: IbGibAddr | null } = {}; Object.keys(mapTjpAddrToLatestAddrsInSpace) .filter(tjpAddr => !tjpAddrsAlreadyAnalyzed!.includes(tjpAddr)) .forEach(tjpAddr => { const latestIbGibCorrespondingToTjpAddr = mapTjpAddrToLatestIbGibInTimelineThatWeHaventAlreadyAnalyzed[tjpAddr]; if (latestIbGibCorrespondingToTjpAddr) { const latestAddrCorrespondingToTjpAddr = getIbGibAddr({ ibGib: latestIbGibCorrespondingToTjpAddr }); latestAddrsMap[latestAddrCorrespondingToTjpAddr] = mapTjpAddrToLatestAddrsInSpace![tjpAddr]; } else { console.error(`${lc} latestIbGibCorrespondingToTjpAddr is falsy (E: 8a5d3f2e1c4b90876543210fe89abcdf)`); } }); if (logalot) { console.log(`${lc} latestAddrsMap *before* getLatestAddrs: ${pretty(latestAddrsMap)} (I: 427b4bb78595e9e521ecf2c5e5c80722)`); } /** * these are the ibgibs whose timelines we are aware of but haven't * explicitly queried for the latest in the space. */ const ibGibsToQueryLatestAddrs = Object.values(mapTjpAddrToLatestIbGibInTimelineThatWeHaventAlreadyAnalyzed); /** * this is the result map of ibgibs whose timelines we are aware of * but hadn't explicitly queried for. */ let queriedLatestAddrsMap: { [addr: string]: IbGibAddr | null } = {}; if (ibGibsToQueryLatestAddrs.length > 0) { if (resolvedSpaces.length === 0) { throw new Error(`(UNEXPECTED) space/s falsy? (E: 8e878975e3561df9a8dc4c628b0abc23)`); } for (const currentSpace of resolvedSpaces) { const resLatest = await getLatestAddrs({ ibGibs: ibGibsToQueryLatestAddrs, space: currentSpace, }); if (!resLatest?.data?.latestAddrsMap) { throw new Error(`(UNEXPECTED) getLatestAddrs result latestAddrsMap falsy (E: 088caa1fc95fd3b079108ab63ef33422)`); } const spaceMap = resLatest.data.latestAddrsMap; Object.keys(spaceMap).forEach(addr => { const spaceLatestAddr = spaceMap[addr]; if (spaceLatestAddr) { queriedLatestAddrsMap[addr] = spaceLatestAddr; } else if (!queriedLatestAddrsMap[addr]) { queriedLatestAddrsMap[addr] = null; } }); } ibGibsToQueryLatestAddrs.forEach(ibGib => { const origAddr = getIbGibAddr({ ibGib }); if (!queriedLatestAddrsMap[origAddr]) { queriedLatestAddrsMap[origAddr] = origAddr; } }); if (Object.keys(queriedLatestAddrsMap).length !== countOfTimelinesNotYetGotten) { throw new Error(`(UNEXPECTED) latestAddrsMap is not the same size as the incoming map (E: 666af512bbd44534983bb28ee8d43fed)`); } if (logalot) { console.log(`${lc} queriedLatestAddrsMap: ${pretty(queriedLatestAddrsMap)} (I: 7b39a5f7ce9e9d9fabae4be98ed44522)`); } latestAddrsMap = { ...queriedLatestAddrsMap, ...latestAddrsMap }; } if (logalot) { console.log(`${lc} combined latestAddrsMap: ${pretty(latestAddrsMap)} (I: e3aedea63f29c5b06a79632f691aa522)`); } /** * these addrs are those whose timelines we did not yet have the latest. * this means that we will have to work off of these ibgibs. */ const newerAddrsFound: IbGibAddr[] = []; const newerAddrFoundToTjpAddrMap: { [newerAddrFound: string]: IbGibAddr } = {} Object.values(mapTjpAddrToLatestIbGibInTimelineThatWeHaventAlreadyAnalyzed) .forEach(latestIbGibAlreadyGotten => { const latestAddrAlreadyGotten = getIbGibAddr({ ibGib: latestIbGibAlreadyGotten }); const tjpAddr = mapLatestAddrAlreadyGottenToTjpAddr[latestAddrAlreadyGotten]; const latestAddrInSpace = latestAddrsMap[latestAddrAlreadyGotten]; if (!latestAddrInSpace) { throw new Error(`(UNEXPECTED) latestAddrInSpace not found in latestAddrsMap (E: 095d2b3f88e3e8a2c3e7d3de4c6d5622)`); } if (latestAddrInSpace === latestAddrAlreadyGotten) { // we've already got the latest for this timeline. This // means that we must have already at least queued all // timelines possible, so nothing else to do. if (logalot) { console.log(`${lc} analyzed ${tjpAddr} (I: afb7960900f04b8a87538f4c7bd903b7)`); } tjpAddrsAlreadyAnalyzed!.push(tjpAddr); } else { // there is a newer "latest" in this timeline that we // haven't gotten yet, so add that addr to the newerAddrsFound.push(latestAddrInSpace); newerAddrFoundToTjpAddrMap[latestAddrInSpace] = tjpAddr; } }); const incomingIbGibAddrsSet = new Set((ibGibs ?? []).map(x => getIbGibAddr({ ibGib: x }))); const rel8dAddrsNotYetGottenSet = new Set(); let rel8dAddrsNotYetGotten: IbGibAddr[] = []; for (let i = 0; i < (ibGibs ?? []).length; i++) { const ibGib = ibGibs![i]; const rel8ns = ibGib.rel8ns ?? {}; const rel8nNames = Object.keys(rel8ns) .filter(x => !(skipRel8nNames ?? []).includes(x)) .filter(x => onlyRel8nNames ? onlyRel8nNames.includes(x) : true); rel8nNames.forEach(rel8nName => { const rel8dAddrs = rel8ns[rel8nName] ?? []; rel8dAddrs.forEach(rel8dAddr => { // only add todo if we don't already have the ibgib if (!rel8dAddrsNotYetGottenSet.has(rel8dAddr) && !incomingIbGibAddrsSet.has(rel8dAddr) && !isPrimitive({ gib: getIbAndGib({ ibGibAddr: rel8dAddr }).gib }) ) { rel8dAddrsNotYetGotten.push(rel8dAddr); rel8dAddrsNotYetGottenSet.add(rel8dAddr); } }); }); } ibGibAddrs = unique([...(ibGibAddrs ?? []), ...rel8dAddrsNotYetGotten, ...newerAddrsFound]); return await getGraphProjection({ ibGibs, ibGibAddrs, gotten, tjpAddrsAlreadyAnalyzed, skipAddrs, skipRel8nNames, onlyRel8nNames, maxRetries, msBetweenRetries, space, spaces: resolvedSpaces, timeLogName, live: true, mapTjpAddrToLatestAddrsInSpace, }); } else { // we have no more timelines that we haven't already gotten, so we // can pass off to the non-live version if (!ibGibs) { ibGibs = []; } const currentAddrsSet = new Set(ibGibs.map(x => getIbGibAddr({ ibGib: x }))); Object.values(gotten ?? {}).forEach(x => { const addr = getIbGibAddr({ ibGib: x }); if (!currentAddrsSet.has(addr)) { ibGibs!.push(x); currentAddrsSet.add(addr); } }); return await getGraphProjection({ /* <<<< returns early */ ibGibs, ibGibAddrs, gotten, /* tjpAddrsAlreadyAnalyzed not used */ skipAddrs, skipRel8nNames, onlyRel8nNames, maxRetries, msBetweenRetries, space, spaces: resolvedSpaces, timeLogName, live: false, }); } } catch (error) { const emsg = `${lc} ${error.message}`; console.error(emsg); if (timeLogName) { console.timeLog(timeLogName, `${lc} error: ${emsg}`); } throw error; } finally { if (timeLogName) { console.timeLog(timeLogName, `${lc} complete.`) } } } /** * NOT EXPORTED * * @see {@link getGraphProjection} * @see {@link getDependencyGraph} */ async function getGraphProjection_NonLive({ ibGibs, ibGibAddrs, gotten, /* tjpAddrsAlreadyAnalyzed not used */ skipAddrs, skipRel8nNames, onlyRel8nNames, maxRetries, msBetweenRetries, space, spaces, timeLogName, }: GetGraphProjectionOptions & { spaces?: IbGibSpaceAny[] }): Promise { const lc = `[${getGraphProjection_NonLive.name}]`; try { // next, compile what could be a rather large list of rel8d ibgibAddrs // which must necessarily be in the past of the futuremost incoming // ibGib/ibGibAddr/s as rel8ns only work backwards (whereas tjp's can // refer to future timelines, the DAG substrate only looks backwards) const addrsWeDontHaveAlready_Rel8dAddrs: IbGibAddr[] = []; const addrsWeDontHaveAlready_Rel8dAddrsSet = new Set(); ibGibs ??= []; gotten ??= {}; const localGotten = gotten; const skipAddrsSet: Set = skipAddrs instanceof Set ? skipAddrs : new Set(skipAddrs || []); skipRel8nNames ??= []; const skipRel8nNamesSet = new Set(skipRel8nNames); const onlyRel8nNamesSet = onlyRel8nNames ? new Set(onlyRel8nNames) : undefined; // so, we will iterate through all of our given and loaded ibGibs (not // the ones in gotten map though), look through all of their rel8ns, and // add any that haven't already been gotten if (timeLogName) { console.timeLog(timeLogName, `${lc} analyzing next step starting...`); } for (let i = 0; i < ibGibs.length; i++) { const ibGib = ibGibs[i]; const ibGibAddr = getIbGibAddr({ ibGib }); // do i need this? const { gib } = getIbAndGib({ ibGib }); if (gib === GIB) { throw new Error(`cannot get dependency graph of primitive. (E: 5493b8908d134bdf887e91122a6a57e3)`); } // ? // I believe I have this so we don't try to do this ibgib again on recursive call. // but should I be adding it at this point? hmm... if (!localGotten[ibGibAddr]) { localGotten[ibGibAddr] = ibGib; } // iterate through rel8ns and compile list of ibgib addrs not yet gotten /** map of addr to validation errors array */ const invalidAddrs: { [addr: string]: string[] } = {}; const rel8ns = ibGib.rel8ns || {}; let rel8nNames = (Object.keys(rel8ns) || []).filter(x => !skipRel8nNamesSet.has(x)); if (onlyRel8nNamesSet) { rel8nNames = rel8nNames.filter(x => onlyRel8nNamesSet.has(x)); } for (let i = 0; i < rel8nNames.length; i++) { const rel8nName = rel8nNames[i]; const rel8dAddrs = rel8ns[rel8nName] ?? []; const falsyAddrs = rel8dAddrs.filter(addr => addr === '' || addr === undefined || addr === null || !addr.includes(IBGIB_DELIMITER) ); if (falsyAddrs.length > 0) { console.warn(`${lc} (UNEXPECTED) has falsyAddrs: ${falsyAddrs} (W: da9505cb0a4db68a4aff7f279ad2d322)`); } const rel8dAddrsNotGottenYetThisRel8n = rel8dAddrs .filter(addr => !!addr) .filter(addr => !localGotten[addr]) .filter(addr => !skipAddrsSet.has(addr)) .filter(addr => getIbAndGib({ ibGibAddr: addr }).gib !== GIB) .filter(addr => !addrsWeDontHaveAlready_Rel8dAddrsSet.has(addr)); rel8dAddrsNotGottenYetThisRel8n.forEach(rel8dAddr => { const validationErrors = validateIbGibAddr({ addr: rel8dAddr }); if ((validationErrors || []).length === 0) { // valid addr. add it if we haven't gotten/queued it yet addrsWeDontHaveAlready_Rel8dAddrs.push(rel8dAddr); addrsWeDontHaveAlready_Rel8dAddrsSet.add(rel8dAddr); } else { // invalid address invalidAddrs[rel8dAddr] = validationErrors!; } }); } if (Object.keys(invalidAddrs).length > 0) { throw new Error(`invalid addresses found in dependency graph. Errors (clipped to 1kB): ${JSON.stringify(invalidAddrs).substring(0, 1024)} (E: d2416b9b23fa4d178e6c7104b40ee78c)`); } } if (timeLogName) { console.timeLog(timeLogName, `${lc} analyzing next step complete.`); } if (addrsWeDontHaveAlready_Rel8dAddrs.length > 0) { if (timeLogName) { console.timeLog(timeLogName, `${lc} get addrsWeDontHaveAlready_Rel8dAddrs starting...`); } const newlyGottenIbGibs = await getGraphProjection_getIbGibsInIbGibAddrs({ ibGibAddrs: addrsWeDontHaveAlready_Rel8dAddrs, gotten: localGotten, skipAddrs: skipAddrsSet, maxRetries, msBetweenRetries, timeLogName, space, spaces, }); newlyGottenIbGibs.forEach(x => localGotten[getIbGibAddr({ ibGib: x })] = x); if (timeLogName) { console.timeLog(timeLogName, `${lc} call getGraphProjection recursively starting...`); } const result = await getGraphProjection({ ibGibs: newlyGottenIbGibs, live: false, gotten: localGotten, /* tjpAddrsAlreadyAnalyzed not used */ skipAddrs: skipAddrsSet, skipRel8nNames, onlyRel8nNames, maxRetries, msBetweenRetries, space, spaces, }); if (timeLogName) { console.timeLog(timeLogName, `${lc} call getGraphProjection recursively complete.`); } return result; // <<<< returns early } else { // no other rel8d addrs to get, so our job is done and the `gotten` // map of dependency ibgibs is complete (no need for another // recursive call). return localGotten; } } catch (error) { const emsg = `${lc} ${error.message}`; console.error(`${emsg} (E: 8a42e56616014e7a8848aa6bb6f2722b)`); if (timeLogName) { console.timeLog(timeLogName, `${lc} error: ${emsg}`); } throw new Error(`${emsg} (E: a21b0682121746a480572b83413cf2d0)`); } finally { if (timeLogName) { console.timeLog(timeLogName, `${lc} complete.`) } } } // #endregion getGraphProjection_NonLive /** * Helper function to convert an array of {@link ibGibs} (or undefined) to a * {@link FlatIbGibGraph} ([addr] -> ibGib map). * @returns if ibGibs undefined returns undefined, else flat graph map */ export function toFlatGraph({ ibGibs }: { ibGibs: IbGib_V1[] | undefined }): FlatIbGibGraph | undefined { const lc = `[${toFlatGraph.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 6019a812cff8597f79c12088e45cc226)`); } if (ibGibs) { const resGraph: FlatIbGibGraph = {}; ibGibs.forEach(x => { resGraph[getIbGibAddr({ ibGib: x })] = x; }) return resGraph; } else { return undefined; } } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * compare two graphs for "equivalency". * * The default just checks that sizes and addrs are the same. * * The more thorough check does the json strings of the values (as dtos). */ export function graphsAreEquivalent({ graphA, graphB, slowButThorough, }: { graphA: FlatIbGibGraph, graphB: FlatIbGibGraph, /** * if true, will actually compare the dto strings of each ibgib in the graph */ slowButThorough?: boolean, }): boolean { const lc = `[${graphsAreEquivalent.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: e50a98b659189dece8b4ef581e4ad826)`); } const sameSize = Object.keys(graphA).length === Object.keys(graphB).length; if (!sameSize) { if (logalot) { console.log(`${lc} not the same size. false. (I: e1044e52421dbf7e067e0fe850ac6826)`); } return false; /* <<<< returns early */ } for (const addr of Object.keys(graphA)) { if (!graphB[addr]) { if (logalot) { console.log(`${lc} addr (${addr}) in graphA not found in graphB (I: 264c68408378ce30b8f6a978f8b86926)`); } return false; /* <<<< returns early */ } } if (slowButThorough) { // go back through and check for dto string equality (deep equality) for (const addr of Object.keys(graphA)) { const ibGibA = toDto({ ibGib: graphA[addr] }); const jsonA = JSON.stringify(ibGibA); const ibGibB = toDto({ ibGib: graphB[addr] }); const jsonB = JSON.stringify(ibGibB); if (jsonA !== jsonB) { if (logalot) { console.log(`${lc} jsonA !== jsonB for addr (${addr}) (I: 98ed9f58ac88dabba83f96582f725926)`); } return false; /* <<<< returns early */ } } } return true; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } // #region reifyDependencyGraph export interface ReifyDependencyGraphOpts { /** Either ibGib or ibGibAddr required. NOT BOTH (throws error if both or neither provided). */ ibGib?: IbGib_V1; /** Either ibGib or ibGibAddr required. NOT BOTH (throws error if both or neither provided). */ ibGibAddr?: IbGibAddr; /** * If provided, traverses and reifies ONLY relationships matching these names. * Throws error if provided as an empty array `[]` or if it contains forbidden * intrinsic/lineage rel8ns ('past', 'dna', 'tjp', 'ancestor'). */ onlyRel8nNames?: string[]; /** * Relationship names to explicitly skip during traversal (defaults to skipping * intrinsic/lineage rel8ns like 'past', 'dna', 'tjp', 'ancestor'). */ skipRel8nNames?: string[]; /** Metaspace service instance used for fallback lookups & registrations. */ metaspace: MetaspaceService; /** Target space containing the registered ibgibs and updated timeline tips. */ space: IbGibSpaceAny; } export interface ReifyDependencyGraphResult { /** The root ibgib (either original if unchanged, or newly evolved if any descendants changed). */ reifiedIbGib: IbGib_V1; /** True if one or more nodes in the graph evolved to new tips. */ hasChanges: boolean; /** Map of old address -> new address for every node that evolved in this reification run. */ reifiedAddrsMap: { [oldAddr: string]: string }; /** All newly evolved and persisted intermediate/root ibgibs created during reification. */ evolvedIbGibs: IbGib_V1[]; } const FORBIDDEN_REIFY_REL8N_NAMES = ['past', 'dna', 'tjp', 'ancestor']; /** * Reifies a dependency graph bottom-up (post-order traversal). * * Checks all constituent relationship targets for newer timeline tips in `space`. * Whenever a child timeline has advanced to a newer frame, the parent is evolved * via `rel8` with the updated child address, persisted to `space`, and registered. * This bubbles all descendant updates up through the DAG to produce a newly reified root ibgib. */ export async function reifyDependencyGraph({ ibGib, ibGibAddr, onlyRel8nNames, skipRel8nNames, metaspace, space, }: ReifyDependencyGraphOpts): Promise { const lc = `[${reifyDependencyGraph.name}]`; try { if (logalot) { console.log(`${lc} starting...`); } // 1. Validation & Guards if (!ibGib && !ibGibAddr) { throw new Error(`Either ibGib or ibGibAddr is required (E: 5ab00fed90d2c59638368b38643d5826)`); } if (ibGib && ibGibAddr) { throw new Error(`Cannot provide both ibGib and ibGibAddr (E: f4121894ae389c8f818d8d5657f1ad26)`); } if (!space) { throw new Error(`space is required (E: 8894680a77d8251bf886f3e83820ce26)`); } if (!metaspace) { throw new Error(`metaspace is required (E: a5ac39b725b86a58386bd598be16d826)`); } if (onlyRel8nNames !== undefined) { if (onlyRel8nNames.length === 0) { throw new Error(`onlyRel8nNames cannot be empty (E: ddb968035e2856fb06b8fb283732f826)`); } const forbiddenFound = onlyRel8nNames.filter(r => FORBIDDEN_REIFY_REL8N_NAMES.includes(r)); if (forbiddenFound.length > 0) { throw new Error(`onlyRel8nNames contains forbidden intrinsic relationship names: ${forbiddenFound.join(', ')} (E: 4f828ff5cb4d9daab86eaf787c9ff826)`); } } const effectiveSkipRel8ns = unique([...FORBIDDEN_REIFY_REL8N_NAMES, ...(skipRel8nNames ?? [])]); // 2. Fetch root ibgib if needed let rootNode: IbGib_V1 | undefined = ibGib; if (!rootNode && ibGibAddr) { rootNode = await getIbGibFromSpace({ addr: ibGibAddr, space, metaspace }); if (!rootNode) { throw new Error(`Root ibGib '${ibGibAddr}' not found in space or metaspace (E: 2e36285dfacd5de4383b14085792b826)`); } } if (!rootNode) { throw new Error(`(UNEXPECTED) rootNode falsy (E: 1828aca373bf289d06f6243847d5b526)`); } const reifiedAddrsMap: { [oldAddr: string]: string } = {}; const evolvedIbGibs: IbGib_V1[] = []; const memo = new Map(); const visiting = new Set(); const knownLatestMap = new Map(); async function reifyNode(currentNode: IbGib_V1): Promise<{ reifiedIbGib: IbGib_V1; hasChanges: boolean }> { const currentAddr = getIbGibAddr({ ibGib: currentNode }); if (memo.has(currentAddr)) { return memo.get(currentAddr)!; } if (visiting.has(currentAddr)) { // Cycle guard - return as unchanged return { reifiedIbGib: currentNode, hasChanges: false }; } visiting.add(currentAddr); try { // A. Check if currentNode itself has a newer timeline tip in space let nodeToProcess = currentNode; let selfEvolved = false; const tjpAddr = currentNode.rel8ns?.tjp?.at(0) ?? currentAddr; let latestAddrInSpace: IbGibAddr | null; if (knownLatestMap.has(tjpAddr)) { latestAddrInSpace = knownLatestMap.get(tjpAddr) ?? null; } else { const latestRes = await getLatestAddrs({ addrs: [tjpAddr], space }); latestAddrInSpace = (latestRes?.data as any)?.latestAddrsMap?.[tjpAddr] ?? (latestRes?.data as any)?.latestAddrsMap?.[currentAddr] ?? null; knownLatestMap.set(tjpAddr, latestAddrInSpace); } if (latestAddrInSpace && latestAddrInSpace !== currentAddr) { const fetchedLatest = await getIbGibFromSpaceOrMetaspace({ addr: latestAddrInSpace, space, metaspace }); if (fetchedLatest) { nodeToProcess = fetchedLatest; selfEvolved = true; reifiedAddrsMap[currentAddr] = latestAddrInSpace; } } // B. Examine rel8ns of nodeToProcess let childrenChanged = false; const rel8nsToReplace: { [rel8nName: string]: Array<{ oldAddr: string; newAddr: string }> } = {}; const rel8ns = nodeToProcess.rel8ns ?? {}; let rel8nKeys = Object.keys(rel8ns).filter(k => !effectiveSkipRel8ns.includes(k)); if (onlyRel8nNames) { rel8nKeys = rel8nKeys.filter(k => onlyRel8nNames.includes(k)); } // Batch-prefetch all child IbGibs and their latestAddrs across rel8nKeys const allChildAddrs: IbGibAddr[] = []; for (const rel8nName of rel8nKeys) { for (const childAddr of rel8ns[rel8nName] ?? []) { if (childAddr && !isPrimitive({ gib: getIbAndGib({ ibGibAddr: childAddr }).gib })) { allChildAddrs.push(childAddr); } } } const prefetchedChildren = new Map(); if (allChildAddrs.length > 0) { const uniqueBareAddrs = unique(allChildAddrs.map(a => a.includes('@') ? a.split('@').slice(1).join('@') : a)); const resBatchGet = await getFromSpace({ addrs: uniqueBareAddrs, space }); if (resBatchGet.success && resBatchGet.ibGibs) { for (const child of resBatchGet.ibGibs) { prefetchedChildren.set(getIbGibAddr({ ibGib: child }), child); } } const unqueriedTjpAddrs: IbGibAddr[] = []; for (const child of prefetchedChildren.values()) { const cAddr = getIbGibAddr({ ibGib: child }); const cTjpAddr = child.rel8ns?.tjp?.at(0) ?? cAddr; if (!knownLatestMap.has(cTjpAddr) && !unqueriedTjpAddrs.includes(cTjpAddr)) { unqueriedTjpAddrs.push(cTjpAddr); } } if (unqueriedTjpAddrs.length > 0) { const batchLatestRes = await getLatestAddrs({ addrs: unqueriedTjpAddrs, space }); const batchLatestMap = (batchLatestRes?.data as any)?.latestAddrsMap ?? {}; for (const qTjpAddr of unqueriedTjpAddrs) { knownLatestMap.set(qTjpAddr, batchLatestMap[qTjpAddr] ?? null); } } } for (const rel8nName of rel8nKeys) { const childAddrs = rel8ns[rel8nName] ?? []; for (const childAddr of childAddrs) { if (!childAddr || isPrimitive({ gib: getIbAndGib({ ibGibAddr: childAddr }).gib })) { continue; } const bareChildAddr = childAddr.includes('@') ? childAddr.split('@').slice(1).join('@') : childAddr; const childIbGib = prefetchedChildren.get(bareChildAddr) ?? await getIbGibFromSpaceOrMetaspace({ addr: childAddr, space, metaspace }); if (!childIbGib) { continue; } const childResult = await reifyNode(childIbGib); if (childResult.hasChanges) { const newChildAddr = getIbGibAddr({ ibGib: childResult.reifiedIbGib }); if (newChildAddr !== childAddr) { childrenChanged = true; rel8nsToReplace[rel8nName] ??= []; if (!rel8nsToReplace[rel8nName].some(r => r.oldAddr === childAddr)) { rel8nsToReplace[rel8nName].push({ oldAddr: childAddr, newAddr: newChildAddr }); } } } } } // C. If children changed, evolve nodeToProcess with rel8 if (childrenChanged) { const resRel8 = await rel8({ src: nodeToProcess, rel8nsToReplaceByAddr: rel8nsToReplace, dna: true, nCounter: true, }); await persistTransformResult({ resTransform: resRel8, space }); await registerNewIbGib({ ibGib: resRel8.newIbGib, space }); const evolvedNode = resRel8.newIbGib; const evolvedAddr = getIbGibAddr({ ibGib: evolvedNode }); evolvedIbGibs.push(evolvedNode); reifiedAddrsMap[currentAddr] = evolvedAddr; const res = { reifiedIbGib: evolvedNode, hasChanges: true }; memo.set(currentAddr, res); return res; } else if (selfEvolved) { const res = { reifiedIbGib: nodeToProcess, hasChanges: true }; memo.set(currentAddr, res); return res; } else { const res = { reifiedIbGib: currentNode, hasChanges: false }; memo.set(currentAddr, res); return res; } } finally { visiting.delete(currentAddr); } } const rootResult = await reifyNode(rootNode); return { reifiedIbGib: rootResult.reifiedIbGib, hasChanges: rootResult.hasChanges, reifiedAddrsMap, evolvedIbGibs, }; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)} (E: bcafd7bc234892113c7f2658ac5feb26)`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } async function getIbGibFromSpaceOrMetaspace({ addr, space, metaspace, }: { addr: IbGibAddr; space: IbGibSpaceAny; metaspace?: MetaspaceService; }): Promise { const resSpace = await getFromSpace({ addrs: [addr], space }); if (resSpace.success && resSpace.ibGibs && resSpace.ibGibs.length > 0) { return resSpace.ibGibs[0]; } const rawIbGibs: IbGib_V1[] = (resSpace.rawResultIbGib as any)?.ibGibs ?? []; if (rawIbGibs.length > 0) { return rawIbGibs[0]; } if (metaspace) { const resMeta = await metaspace.get({ addrs: [addr], space }); if (resMeta.success && resMeta.ibGibs && resMeta.ibGibs.length > 0) { return resMeta.ibGibs[0]; } } return undefined; } // #endregion reifyDependencyGraph