@layerzerolabs/dfs 0.0.43 → 0.0.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -11,8 +11,8 @@
11
11
  CJS Build start
12
12
  ESM Build start
13
13
  CJS dist/index.cjs 3.43 KB
14
- CJS dist/index.cjs.map 11.76 KB
15
- CJS ⚡️ Build success in 166ms
14
+ CJS dist/index.cjs.map 11.79 KB
15
+ CJS ⚡️ Build success in 96ms
16
16
  ESM dist/index.js 3.42 KB
17
- ESM dist/index.js.map 11.75 KB
18
- ESM ⚡️ Build success in 165ms
17
+ ESM dist/index.js.map 11.78 KB
18
+ ESM ⚡️ Build success in 96ms
@@ -5,11 +5,11 @@
5
5
 
6
6
   RUN  v3.2.3 /home/runner/work/monorepo-internal/monorepo-internal/packages/framework/dfs
7
7
 
8
- ✓ test/dfs.test.ts (7 tests) 551ms
9
- ✓ DI Depth-first-search > The handlers for each of a node's dependencies should be completed before that node  302ms
8
+ ✓ test/dfs.test.ts (7 tests) 589ms
9
+ ✓ DI Depth-first-search > The handlers for each of a node's dependencies should be completed before that node  305ms
10
10
 
11
11
   Test Files  1 passed (1)
12
12
   Tests  7 passed (7)
13
-  Start at  22:31:10
14
-  Duration  996ms (transform 92ms, setup 0ms, collect 90ms, tests 551ms, environment 0ms, prepare 119ms)
13
+  Start at  16:11:13
14
+  Duration  1.12s (transform 90ms, setup 0ms, collect 92ms, tests 589ms, environment 0ms, prepare 94ms)
15
15
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"names":["mergeAncestorDistances","parentDistances","childDistances","ancestor","parentDist","candidate","current","get","Infinity","set","Math","min","buildAncestryDistanceIndex","node","prehandler","ancestryDistanceIndex","Map","inDegreeByNodeName","initializeMaps","cur","name","dep","Object","values","dependencies","handledDep","inDegree","has","handled","queue","length","curNode","shift","currentMinimalDistances","push","nodeName","Error","dfs","handler","_returns","nodeResolverPromises","resolveNode","prehandledNode","childrenPromises","d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AQC,IAAIH,gBAAAA,CAAAA;AAGlB,IAAA,MAAMI,gBAAAA,GAAmBhC,qBAAAA,CAAsBR,GAAAA,CAAImC,cAAAA,CAAetB,IAAI,CAAA;AACtE,IAAA,MAAM4B,kBAAkBC,KAAAA,CAAMC,IAAAA,CAAKH,gBAAAA,CAAiBI,OAAAA,EAAO,CAAA,CAAIC,IAAAA,CAAK,CAACC,CAAAA,EAAGC,MAAMD,CAAAA,CAAE,CAAA,CAAA,GAAKC,CAAAA,CAAE,CAAA,CAAE,CAAA;AACzF,IAAA,MAAMC,MAAAA,GAAS,MAAMjB,OAAAA,CACjBI,cAAAA,EACAM,eAAAA,CAAgBQ,GAAAA,CAAI,CAAC,CAAC3C,KAAAA,EAAM4C,CAAAA,CAAAA,KAAO5C,KAAAA,CAAAA,CAAAA;AAEvC,IAAA,IAAI0C,MAAAA,EAAQ;AACP,MAAA,CAAChB,QAAAA,CAAiBgB,OAAOG,GAAG,CAAA,KAAM,EAAC,EAAGhB,cAAAA,CAAetB,IAAI,CAAA,GAAImC,MAAAA,CAAOI,KAAAA;AACzE,IAAA;EACJ,CAAA,EAvBoB,aAAA,CAAA;AAyBpB,EAAA,OAAO,YAAA;AACH,IAAA,MAAMlB,YAAY5B,IAAAA,CAAAA;AAClB,IAAA,OAAO0B,QAAAA;AACX,EAAA,CAAA;AACJ,CAAA,EAvCmB,KAAA","file":"index.cjs","sourcesContent":["import type { DependencyNode } from '@layerzerolabs/dependency-graph';\n\n/**\n * A registrar is a simple interface for an object that provides the ability to traverse the dependency graph.\n * It is implicit in this definition that the registrar should also *register* values adhering to the schemata\n * of the graph.\n */\nexport interface Registrar<ReturnType> {\n traverseDependencies: (rootNode: DependencyNode) => Promise<ReturnType>;\n}\nexport type NodeHandlerFunction = (\n node: DependencyNode,\n ancestry: DependencyNode[],\n) => Promise<{ key: string; value: any }>;\nexport type NodePreHandlerFunction = (node: DependencyNode) => DependencyNode;\n\n// Map of ancestor node -> minimal hop distance\ntype AncestorDistanceByNode = Map<DependencyNode, number>;\n// Index from node name -> its ancestor distance map\ntype AncestryDistanceIndex = Map<string, AncestorDistanceByNode>;\n\n/**\n * In-place merge of minimal ancestry distances.\n *\n * childDistances holds minimal distances from the child to each ancestor (keyed by DependencyNode).\n * For every entry in parentDistances, we update the child's map with (parentDist + 1),\n * keeping the minimal value if the ancestor already exists.\n */\nconst mergeAncestorDistances = (\n parentDistances: AncestorDistanceByNode,\n childDistances: AncestorDistanceByNode,\n) => {\n for (const [ancestor, parentDist] of parentDistances) {\n const candidate = parentDist + 1;\n const current = childDistances.get(ancestor) || Infinity;\n childDistances.set(ancestor, Math.min(current, candidate));\n }\n};\n\n/**\n * Builds a minimal ancestry distance index for all nodes reachable from the root.\n *\n * Returns a Map: node.name -> Map<DependencyNode, distance> where distance is the minimal hop count\n * from the node to that ancestor. We perform a Kahn-style BFS over the DAG, and for each edge\n * curNode -> dep we merge curNode's minimal distances into the dependency with +1 hop and take the minimum.\n */\nconst buildAncestryDistanceIndex = (\n node: DependencyNode,\n prehandler: NodePreHandlerFunction,\n): AncestryDistanceIndex => {\n const ancestryDistanceIndex: AncestryDistanceIndex = new Map();\n const inDegreeByNodeName = new Map<string, number>();\n\n // If A depends on B and C, B depends on C, we initialize with:\n // ancestryDistanceIndex: { A: Map(), B: Map(), C: Map() }\n // inDegreeByNodeName: { B: 1, C: 2 }\n const initializeMaps = (cur: DependencyNode) => {\n ancestryDistanceIndex.set(cur.name, new Map());\n for (const dep of Object.values(cur.dependencies)) {\n const handledDep = prehandler(dep);\n const inDegree = inDegreeByNodeName.get(handledDep.name) || 0;\n inDegreeByNodeName.set(handledDep.name, inDegree + 1);\n if (!ancestryDistanceIndex.has(handledDep.name)) initializeMaps(handledDep);\n }\n };\n\n const handled = prehandler(node);\n\n initializeMaps(handled);\n\n // Kahn-style topological BFS accumulating minimal distance ancestors\n let queue = [handled];\n while (queue.length > 0) {\n const curNode = queue.shift()!;\n // Include self with distance 0, then extend with the already known minimal distances\n const currentMinimalDistances: AncestorDistanceByNode = new Map([\n [curNode, 0],\n ...ancestryDistanceIndex.get(curNode.name)!,\n ]);\n // Add the new processable dependencies to the queue, update their state.\n for (const dep of Object.values(curNode.dependencies)) {\n const handledDep = prehandler(dep);\n const inDegree = inDegreeByNodeName.get(handledDep.name)!;\n // We are the last edge missing in the graph for this dependency -> we can process it after us.\n if (inDegree === 1) {\n queue.push(handledDep);\n }\n // Reduce the in-degree of the dependency -> it basically means that this edge got removed from the graph.\n inDegreeByNodeName.set(handledDep.name, inDegree - 1);\n\n // Merge curNode's minimal distances (+1 hop) into the dependency's minimal distances\n const childDistances = ancestryDistanceIndex.get(handledDep.name)!;\n mergeAncestorDistances(currentMinimalDistances, childDistances);\n }\n }\n\n for (const [nodeName, inDegree] of inDegreeByNodeName) {\n if (inDegree !== 0) {\n throw new Error(\n `node ${nodeName} has in-degree ${inDegree}, this indicates a cycle in the graph containing the node`,\n );\n }\n }\n\n return ancestryDistanceIndex;\n};\n\n/**\n * Performs a depth-first-search on a tree of dependency nodes, and returns a function\n * that will call the handler for each node in the tree, ordered s.t. the handler of N\n * will be called only after the handlers of dependencies(N) have been called.\n * The node's ancestors are sorted by non-decreasing minimal distance.\n * The resolver function will only call the handler once for each unique definition node.\n * The resolver function returns an object whose keys are the keys defined\n * by each of the handlers, and whose values are objects whose keys are the names\n * of the nodes resolved and whose values are the values defined by the handlers.\n * @param node the root node of the tree\n * @param handler a function that accepts a node and registers it\n * @param prehandler a function that accepts a node and returns a node. Will be used to pre-process the graph\n * @returns a resolver function\n */\nexport const dfs = <ReturnTypes>(\n node: DependencyNode,\n handler: NodeHandlerFunction,\n prehandler: NodePreHandlerFunction = (node) => node,\n _returns: ReturnTypes = {} as any,\n): (() => Promise<ReturnTypes>) => {\n const ancestryDistanceIndex = buildAncestryDistanceIndex(node, prehandler);\n\n // Maintains Map<node.name, Promise<void>> -> the promise to resolve the node, for all nodes.\n const nodeResolverPromises = new Map<string, Promise<void>>();\n const resolveNode = async (node: DependencyNode) => {\n const prehandledNode = prehandler(node);\n // first wait for all its children\n const childrenPromises = [];\n for (const dependencyValue of Object.values(prehandledNode.dependencies)) {\n // Grab the cached promise or create it, we want to have only 1 handler promise for each node.\n if (!nodeResolverPromises.has(dependencyValue.name)) {\n nodeResolverPromises.set(dependencyValue.name, resolveNode(dependencyValue));\n }\n childrenPromises.push(nodeResolverPromises.get(dependencyValue.name)!);\n }\n await Promise.all(childrenPromises);\n\n // Then, you can process yourself. Build ancestry sorted by non-decreasing minimal distance.\n const minimalDistances = ancestryDistanceIndex.get(prehandledNode.name)!;\n const sortedAncestors = Array.from(minimalDistances.entries()).sort((a, b) => a[1] - b[1]);\n const regRes = await handler(\n prehandledNode,\n sortedAncestors.map(([node, _]) => node),\n );\n if (regRes) {\n ((_returns as any)[regRes.key] ??= {})[prehandledNode.name] = regRes.value;\n }\n };\n\n return async () => {\n await resolveNode(node);\n return _returns;\n };\n};\n"]}
1
+ {"version":3,"sources":["../src/index.ts"],"names":["mergeAncestorDistances","parentDistances","childDistances","ancestor","parentDist","candidate","current","get","Infinity","set","Math","min","buildAncestryDistanceIndex","node","prehandler","ancestryDistanceIndex","Map","inDegreeByNodeName","initializeMaps","cur","name","dep","Object","values","dependencies","handledDep","inDegree","has","handled","queue","length","curNode","shift","currentMinimalDistances","push","nodeName","Error","dfs","handler","_returns","nodeResolverPromises","resolveNode","prehandledNode","childrenPromises","dependencyValue","Promise","all","minimalDistances","sortedAncestors","Array","from","entries","sort","a","b","regRes","map","_","key","value"],"mappings":";;;;;;AA6BA,IAAMA,sBAAAA,mBAAyB,MAAA,CAAA,CAC3BC,eAAAA,EACAC,cAAAA,KAAAA;AAEA,EAAA,KAAA,MAAW,CAACC,QAAAA,EAAUC,UAAAA,CAAAA,IAAeH,eAAAA,EAAiB;AAClD,IAAA,MAAMI,YAAYD,UAAAA,GAAa,CAAA;AAC/B,IAAA,MAAME,OAAAA,GAAUJ,cAAAA,CAAeK,GAAAA,CAAIJ,QAAAA,CAAAA,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AAMjB,OAAAA,CACjBI,cAAAA,EACAM,eAAAA,CAAgBQ,GAAAA,CAAI,CAAC,CAAC3C,KAAAA,EAAM4C,CAAAA,CAAAA,KAAO5C,KAAAA,CAAAA,CAAAA;AAEvC,IAAA,IAAI0C,MAAAA,EAAQ;AACP,MAAA,CAAChB,QAAAA,CAAiBgB,OAAOG,GAAG,CAAA,KAAM,EAAC,EAAGhB,cAAAA,CAAetB,IAAI,CAAA,GAAImC,MAAAA,CAAOI,KAAAA;AACzE,IAAA;EACJ,CAAA,EAvBoB,aAAA,CAAA;AAyBpB,EAAA,OAAO,YAAA;AACH,IAAA,MAAMlB,YAAY5B,IAAAA,CAAAA;AAClB,IAAA,OAAO0B,QAAAA;AACX,EAAA,CAAA;AACJ,CAAA,EAvCmB,KAAA","file":"index.cjs","sourcesContent":["import type { DependencyNode } from '@layerzerolabs/dependency-graph';\n\n/**\n * <!-- anchor:Registrar -->\n * A registrar is a simple interface for an object that provides the ability to traverse the dependency graph.\n * It is implicit in this definition that the registrar should also *register* values adhering to the schemata\n * of the graph.\n */\nexport interface Registrar<ReturnType> {\n traverseDependencies: (rootNode: DependencyNode) => Promise<ReturnType>;\n}\nexport type NodeHandlerFunction = (\n node: DependencyNode,\n ancestry: DependencyNode[],\n) => Promise<{ key: string; value: any }>;\nexport type NodePreHandlerFunction = (node: DependencyNode) => DependencyNode;\n\n// Map of ancestor node -> minimal hop distance\ntype AncestorDistanceByNode = Map<DependencyNode, number>;\n// Index from node name -> its ancestor distance map\ntype AncestryDistanceIndex = Map<string, AncestorDistanceByNode>;\n\n/**\n * In-place merge of minimal ancestry distances.\n *\n * childDistances holds minimal distances from the child to each ancestor (keyed by DependencyNode).\n * For every entry in parentDistances, we update the child's map with (parentDist + 1),\n * keeping the minimal value if the ancestor already exists.\n */\nconst mergeAncestorDistances = (\n parentDistances: AncestorDistanceByNode,\n childDistances: AncestorDistanceByNode,\n) => {\n for (const [ancestor, parentDist] of parentDistances) {\n const candidate = parentDist + 1;\n const current = childDistances.get(ancestor) || Infinity;\n childDistances.set(ancestor, Math.min(current, candidate));\n }\n};\n\n/**\n * Builds a minimal ancestry distance index for all nodes reachable from the root.\n *\n * Returns a Map: node.name -> Map<DependencyNode, distance> where distance is the minimal hop count\n * from the node to that ancestor. We perform a Kahn-style BFS over the DAG, and for each edge\n * curNode -> dep we merge curNode's minimal distances into the dependency with +1 hop and take the minimum.\n */\nconst buildAncestryDistanceIndex = (\n node: DependencyNode,\n prehandler: NodePreHandlerFunction,\n): AncestryDistanceIndex => {\n const ancestryDistanceIndex: AncestryDistanceIndex = new Map();\n const inDegreeByNodeName = new Map<string, number>();\n\n // If A depends on B and C, B depends on C, we initialize with:\n // ancestryDistanceIndex: { A: Map(), B: Map(), C: Map() }\n // inDegreeByNodeName: { B: 1, C: 2 }\n const initializeMaps = (cur: DependencyNode) => {\n ancestryDistanceIndex.set(cur.name, new Map());\n for (const dep of Object.values(cur.dependencies)) {\n const handledDep = prehandler(dep);\n const inDegree = inDegreeByNodeName.get(handledDep.name) || 0;\n inDegreeByNodeName.set(handledDep.name, inDegree + 1);\n if (!ancestryDistanceIndex.has(handledDep.name)) initializeMaps(handledDep);\n }\n };\n\n const handled = prehandler(node);\n\n initializeMaps(handled);\n\n // Kahn-style topological BFS accumulating minimal distance ancestors\n let queue = [handled];\n while (queue.length > 0) {\n const curNode = queue.shift()!;\n // Include self with distance 0, then extend with the already known minimal distances\n const currentMinimalDistances: AncestorDistanceByNode = new Map([\n [curNode, 0],\n ...ancestryDistanceIndex.get(curNode.name)!,\n ]);\n // Add the new processable dependencies to the queue, update their state.\n for (const dep of Object.values(curNode.dependencies)) {\n const handledDep = prehandler(dep);\n const inDegree = inDegreeByNodeName.get(handledDep.name)!;\n // We are the last edge missing in the graph for this dependency -> we can process it after us.\n if (inDegree === 1) {\n queue.push(handledDep);\n }\n // Reduce the in-degree of the dependency -> it basically means that this edge got removed from the graph.\n inDegreeByNodeName.set(handledDep.name, inDegree - 1);\n\n // Merge curNode's minimal distances (+1 hop) into the dependency's minimal distances\n const childDistances = ancestryDistanceIndex.get(handledDep.name)!;\n mergeAncestorDistances(currentMinimalDistances, childDistances);\n }\n }\n\n for (const [nodeName, inDegree] of inDegreeByNodeName) {\n if (inDegree !== 0) {\n throw new Error(\n `node ${nodeName} has in-degree ${inDegree}, this indicates a cycle in the graph containing the node`,\n );\n }\n }\n\n return ancestryDistanceIndex;\n};\n\n/**\n * Performs a depth-first-search on a tree of dependency nodes, and returns a function\n * that will call the handler for each node in the tree, ordered s.t. the handler of N\n * will be called only after the handlers of dependencies(N) have been called.\n * The node's ancestors are sorted by non-decreasing minimal distance.\n * The resolver function will only call the handler once for each unique definition node.\n * The resolver function returns an object whose keys are the keys defined\n * by each of the handlers, and whose values are objects whose keys are the names\n * of the nodes resolved and whose values are the values defined by the handlers.\n * @param node the root node of the tree\n * @param handler a function that accepts a node and registers it\n * @param prehandler a function that accepts a node and returns a node. Will be used to pre-process the graph\n * @returns a resolver function\n */\nexport const dfs = <ReturnTypes>(\n node: DependencyNode,\n handler: NodeHandlerFunction,\n prehandler: NodePreHandlerFunction = (node) => node,\n _returns: ReturnTypes = {} as any,\n): (() => Promise<ReturnTypes>) => {\n const ancestryDistanceIndex = buildAncestryDistanceIndex(node, prehandler);\n\n // Maintains Map<node.name, Promise<void>> -> the promise to resolve the node, for all nodes.\n const nodeResolverPromises = new Map<string, Promise<void>>();\n const resolveNode = async (node: DependencyNode) => {\n const prehandledNode = prehandler(node);\n // first wait for all its children\n const childrenPromises = [];\n for (const dependencyValue of Object.values(prehandledNode.dependencies)) {\n // Grab the cached promise or create it, we want to have only 1 handler promise for each node.\n if (!nodeResolverPromises.has(dependencyValue.name)) {\n nodeResolverPromises.set(dependencyValue.name, resolveNode(dependencyValue));\n }\n childrenPromises.push(nodeResolverPromises.get(dependencyValue.name)!);\n }\n await Promise.all(childrenPromises);\n\n // Then, you can process yourself. Build ancestry sorted by non-decreasing minimal distance.\n const minimalDistances = ancestryDistanceIndex.get(prehandledNode.name)!;\n const sortedAncestors = Array.from(minimalDistances.entries()).sort((a, b) => a[1] - b[1]);\n const regRes = await handler(\n prehandledNode,\n sortedAncestors.map(([node, _]) => node),\n );\n if (regRes) {\n ((_returns as any)[regRes.key] ??= {})[prehandledNode.name] = regRes.value;\n }\n };\n\n return async () => {\n await resolveNode(node);\n return _returns;\n };\n};\n"]}
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { DependencyNode } from '@layerzerolabs/dependency-graph';
2
2
  /**
3
+ * <!-- anchor:Registrar -->
3
4
  * A registrar is a simple interface for an object that provides the ability to traverse the dependency graph.
4
5
  * It is implicit in this definition that the registrar should also *register* values adhering to the schemata
5
6
  * of the graph.
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AAEtE;;;;GAIG;AACH,MAAM,WAAW,SAAS,CAAC,UAAU;IACjC,oBAAoB,EAAE,CAAC,QAAQ,EAAE,cAAc,KAAK,OAAO,CAAC,UAAU,CAAC,CAAC;CAC3E;AACD,MAAM,MAAM,mBAAmB,GAAG,CAC9B,IAAI,EAAE,cAAc,EACpB,QAAQ,EAAE,cAAc,EAAE,KACzB,OAAO,CAAC;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,GAAG,CAAA;CAAE,CAAC,CAAC;AAC1C,MAAM,MAAM,sBAAsB,GAAG,CAAC,IAAI,EAAE,cAAc,KAAK,cAAc,CAAC;AA6F9E;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,GAAG,GAAI,WAAW,EAC3B,MAAM,cAAc,EACpB,SAAS,mBAAmB,EAC5B,aAAY,sBAAuC,EACnD,WAAU,WAAuB,KAClC,CAAC,MAAM,OAAO,CAAC,WAAW,CAAC,CAkC7B,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AAEtE;;;;;GAKG;AACH,MAAM,WAAW,SAAS,CAAC,UAAU;IACjC,oBAAoB,EAAE,CAAC,QAAQ,EAAE,cAAc,KAAK,OAAO,CAAC,UAAU,CAAC,CAAC;CAC3E;AACD,MAAM,MAAM,mBAAmB,GAAG,CAC9B,IAAI,EAAE,cAAc,EACpB,QAAQ,EAAE,cAAc,EAAE,KACzB,OAAO,CAAC;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,GAAG,CAAA;CAAE,CAAC,CAAC;AAC1C,MAAM,MAAM,sBAAsB,GAAG,CAAC,IAAI,EAAE,cAAc,KAAK,cAAc,CAAC;AA6F9E;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,GAAG,GAAI,WAAW,EAC3B,MAAM,cAAc,EACpB,SAAS,mBAAmB,EAC5B,aAAY,sBAAuC,EACnD,WAAU,WAAuB,KAClC,CAAC,MAAM,OAAO,CAAC,WAAW,CAAC,CAkC7B,CAAC"}
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"names":["mergeAncestorDistances","parentDistances","childDistances","ancestor","parentDist","candidate","current","get","Infinity","set","Math","min","buildAncestryDistanceIndex","node","prehandler","ancestryDistanceIndex","Map","inDegreeByNodeName","initializeMaps","cur","name","dep","Object","values","dependencies","handledDep","inDegree","has","handled","queue","length","curNode","shift","currentMinimalDistances","push","nodeName","Error","dfs","handler","_returns","nodeResolverPromises","resolveNode","prehandledNode","childrenPromises","dependencyValue","Promise","all","minimalDistances","sortedAncestors","Array","from","entries","sort","a","b","regRes","map","_","key","value"],"mappings":";;;;AA4BA,IAAMA,sBAAAA,mBAAyB,MAAA,CAAA,CAC3BC,eAAAA,EACAC,cAAAA,KAAAA;AAEA,EAAA,KAAA,MAAW,CAACC,QAAAA,EAAUC,UAAAA,CAAAA,IAAeH,eAAA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AA,CAAK,CAACC,CAAAA,EAAGC,MAAMD,CAAAA,CAAE,CAAA,CAAA,GAAKC,CAAAA,CAAE,CAAA,CAAE,CAAA;AACzF,IAAA,MAAMC,MAAAA,GAAS,MAAMjB,OAAAA,CACjBI,cAAAA,EACAM,eAAAA,CAAgBQ,GAAAA,CAAI,CAAC,CAAC3C,KAAAA,EAAM4C,CAAAA,CAAAA,KAAO5C,KAAAA,CAAAA,CAAAA;AAEvC,IAAA,IAAI0C,MAAAA,EAAQ;AACP,MAAA,CAAChB,QAAAA,CAAiBgB,OAAOG,GAAG,CAAA,KAAM,EAAC,EAAGhB,cAAAA,CAAetB,IAAI,CAAA,GAAImC,MAAAA,CAAOI,KAAAA;AACzE,IAAA;EACJ,CAAA,EAvBoB,aAAA,CAAA;AAyBpB,EAAA,OAAO,YAAA;AACH,IAAA,MAAMlB,YAAY5B,IAAAA,CAAAA;AAClB,IAAA,OAAO0B,QAAAA;AACX,EAAA,CAAA;AACJ,CAAA,EAvCmB,KAAA","file":"index.js","sourcesContent":["import type { DependencyNode } from '@layerzerolabs/dependency-graph';\n\n/**\n * A registrar is a simple interface for an object that provides the ability to traverse the dependency graph.\n * It is implicit in this definition that the registrar should also *register* values adhering to the schemata\n * of the graph.\n */\nexport interface Registrar<ReturnType> {\n traverseDependencies: (rootNode: DependencyNode) => Promise<ReturnType>;\n}\nexport type NodeHandlerFunction = (\n node: DependencyNode,\n ancestry: DependencyNode[],\n) => Promise<{ key: string; value: any }>;\nexport type NodePreHandlerFunction = (node: DependencyNode) => DependencyNode;\n\n// Map of ancestor node -> minimal hop distance\ntype AncestorDistanceByNode = Map<DependencyNode, number>;\n// Index from node name -> its ancestor distance map\ntype AncestryDistanceIndex = Map<string, AncestorDistanceByNode>;\n\n/**\n * In-place merge of minimal ancestry distances.\n *\n * childDistances holds minimal distances from the child to each ancestor (keyed by DependencyNode).\n * For every entry in parentDistances, we update the child's map with (parentDist + 1),\n * keeping the minimal value if the ancestor already exists.\n */\nconst mergeAncestorDistances = (\n parentDistances: AncestorDistanceByNode,\n childDistances: AncestorDistanceByNode,\n) => {\n for (const [ancestor, parentDist] of parentDistances) {\n const candidate = parentDist + 1;\n const current = childDistances.get(ancestor) || Infinity;\n childDistances.set(ancestor, Math.min(current, candidate));\n }\n};\n\n/**\n * Builds a minimal ancestry distance index for all nodes reachable from the root.\n *\n * Returns a Map: node.name -> Map<DependencyNode, distance> where distance is the minimal hop count\n * from the node to that ancestor. We perform a Kahn-style BFS over the DAG, and for each edge\n * curNode -> dep we merge curNode's minimal distances into the dependency with +1 hop and take the minimum.\n */\nconst buildAncestryDistanceIndex = (\n node: DependencyNode,\n prehandler: NodePreHandlerFunction,\n): AncestryDistanceIndex => {\n const ancestryDistanceIndex: AncestryDistanceIndex = new Map();\n const inDegreeByNodeName = new Map<string, number>();\n\n // If A depends on B and C, B depends on C, we initialize with:\n // ancestryDistanceIndex: { A: Map(), B: Map(), C: Map() }\n // inDegreeByNodeName: { B: 1, C: 2 }\n const initializeMaps = (cur: DependencyNode) => {\n ancestryDistanceIndex.set(cur.name, new Map());\n for (const dep of Object.values(cur.dependencies)) {\n const handledDep = prehandler(dep);\n const inDegree = inDegreeByNodeName.get(handledDep.name) || 0;\n inDegreeByNodeName.set(handledDep.name, inDegree + 1);\n if (!ancestryDistanceIndex.has(handledDep.name)) initializeMaps(handledDep);\n }\n };\n\n const handled = prehandler(node);\n\n initializeMaps(handled);\n\n // Kahn-style topological BFS accumulating minimal distance ancestors\n let queue = [handled];\n while (queue.length > 0) {\n const curNode = queue.shift()!;\n // Include self with distance 0, then extend with the already known minimal distances\n const currentMinimalDistances: AncestorDistanceByNode = new Map([\n [curNode, 0],\n ...ancestryDistanceIndex.get(curNode.name)!,\n ]);\n // Add the new processable dependencies to the queue, update their state.\n for (const dep of Object.values(curNode.dependencies)) {\n const handledDep = prehandler(dep);\n const inDegree = inDegreeByNodeName.get(handledDep.name)!;\n // We are the last edge missing in the graph for this dependency -> we can process it after us.\n if (inDegree === 1) {\n queue.push(handledDep);\n }\n // Reduce the in-degree of the dependency -> it basically means that this edge got removed from the graph.\n inDegreeByNodeName.set(handledDep.name, inDegree - 1);\n\n // Merge curNode's minimal distances (+1 hop) into the dependency's minimal distances\n const childDistances = ancestryDistanceIndex.get(handledDep.name)!;\n mergeAncestorDistances(currentMinimalDistances, childDistances);\n }\n }\n\n for (const [nodeName, inDegree] of inDegreeByNodeName) {\n if (inDegree !== 0) {\n throw new Error(\n `node ${nodeName} has in-degree ${inDegree}, this indicates a cycle in the graph containing the node`,\n );\n }\n }\n\n return ancestryDistanceIndex;\n};\n\n/**\n * Performs a depth-first-search on a tree of dependency nodes, and returns a function\n * that will call the handler for each node in the tree, ordered s.t. the handler of N\n * will be called only after the handlers of dependencies(N) have been called.\n * The node's ancestors are sorted by non-decreasing minimal distance.\n * The resolver function will only call the handler once for each unique definition node.\n * The resolver function returns an object whose keys are the keys defined\n * by each of the handlers, and whose values are objects whose keys are the names\n * of the nodes resolved and whose values are the values defined by the handlers.\n * @param node the root node of the tree\n * @param handler a function that accepts a node and registers it\n * @param prehandler a function that accepts a node and returns a node. Will be used to pre-process the graph\n * @returns a resolver function\n */\nexport const dfs = <ReturnTypes>(\n node: DependencyNode,\n handler: NodeHandlerFunction,\n prehandler: NodePreHandlerFunction = (node) => node,\n _returns: ReturnTypes = {} as any,\n): (() => Promise<ReturnTypes>) => {\n const ancestryDistanceIndex = buildAncestryDistanceIndex(node, prehandler);\n\n // Maintains Map<node.name, Promise<void>> -> the promise to resolve the node, for all nodes.\n const nodeResolverPromises = new Map<string, Promise<void>>();\n const resolveNode = async (node: DependencyNode) => {\n const prehandledNode = prehandler(node);\n // first wait for all its children\n const childrenPromises = [];\n for (const dependencyValue of Object.values(prehandledNode.dependencies)) {\n // Grab the cached promise or create it, we want to have only 1 handler promise for each node.\n if (!nodeResolverPromises.has(dependencyValue.name)) {\n nodeResolverPromises.set(dependencyValue.name, resolveNode(dependencyValue));\n }\n childrenPromises.push(nodeResolverPromises.get(dependencyValue.name)!);\n }\n await Promise.all(childrenPromises);\n\n // Then, you can process yourself. Build ancestry sorted by non-decreasing minimal distance.\n const minimalDistances = ancestryDistanceIndex.get(prehandledNode.name)!;\n const sortedAncestors = Array.from(minimalDistances.entries()).sort((a, b) => a[1] - b[1]);\n const regRes = await handler(\n prehandledNode,\n sortedAncestors.map(([node, _]) => node),\n );\n if (regRes) {\n ((_returns as any)[regRes.key] ??= {})[prehandledNode.name] = regRes.value;\n }\n };\n\n return async () => {\n await resolveNode(node);\n return _returns;\n };\n};\n"]}
1
+ {"version":3,"sources":["../src/index.ts"],"names":["mergeAncestorDistances","parentDistances","childDistances","ancestor","parentDist","candidate","current","get","Infinity","set","Math","min","buildAncestryDistanceIndex","node","prehandler","ancestryDistanceIndex","Map","inDegreeByNodeName","initializeMaps","cur","name","dep","Object","values","dependencies","handledDep","inDegree","has","handled","queue","length","curNode","shift","currentMinimalDistances","push","nodeName","Error","dfs","handler","_returns","nodeResolverPromises","resolveNode","prehandledNode","childrenPromises","dependencyValue","Promise","all","minimalDistances","sortedAncestors","Array","from","entries","sort","a","b","regRes","map","_","key","value"],"mappings":";;;;AA6BA,IAAMA,sBAAAA,mBAAyB,MAAA,CAAA,CAC3BC,eAAAA,EACAC,cAAAA,KAAAA;AAEA,EAAA,KAAA,MAAW,CAACC,QAAAA,EAAUC,UAAAA,CAAAA,IAAeH,eAAAA,EAAiB;AAClD,IAAA,MAAMI,YAAYD,UAAAA,GAAa,CAAA;AAC/B,IAAA,MAAME,OAAAA,GAAUJ,cAAAA,CAAeK,GAAAA,CAAIJ,QAAAA,CAAAA,IAAaK,QAAAA;AAChDN,IAAAA,cAAAA,CAAeO,IAAIN,QAAAA,EAAUO,IAAAA,CAAKC,GAAAA,CAAIL,OAAAA,EAASD,SAAAA,CAAAA,CAAAA;AACnD,EAAA;AACJ,CAAA,EAT+B,wBAAA,CAAA;AAkB/B,IAAMO,0BAAAA,mBAA6B,MAAA,CAAA,CAC/BC,IAAAA,E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,EAAC,EAAGhB,cAAAA,CAAetB,IAAI,CAAA,GAAImC,MAAAA,CAAOI,KAAAA;AACzE,IAAA;EACJ,CAAA,EAvBoB,aAAA,CAAA;AAyBpB,EAAA,OAAO,YAAA;AACH,IAAA,MAAMlB,YAAY5B,IAAAA,CAAAA;AAClB,IAAA,OAAO0B,QAAAA;AACX,EAAA,CAAA;AACJ,CAAA,EAvCmB,KAAA","file":"index.js","sourcesContent":["import type { DependencyNode } from '@layerzerolabs/dependency-graph';\n\n/**\n * <!-- anchor:Registrar -->\n * A registrar is a simple interface for an object that provides the ability to traverse the dependency graph.\n * It is implicit in this definition that the registrar should also *register* values adhering to the schemata\n * of the graph.\n */\nexport interface Registrar<ReturnType> {\n traverseDependencies: (rootNode: DependencyNode) => Promise<ReturnType>;\n}\nexport type NodeHandlerFunction = (\n node: DependencyNode,\n ancestry: DependencyNode[],\n) => Promise<{ key: string; value: any }>;\nexport type NodePreHandlerFunction = (node: DependencyNode) => DependencyNode;\n\n// Map of ancestor node -> minimal hop distance\ntype AncestorDistanceByNode = Map<DependencyNode, number>;\n// Index from node name -> its ancestor distance map\ntype AncestryDistanceIndex = Map<string, AncestorDistanceByNode>;\n\n/**\n * In-place merge of minimal ancestry distances.\n *\n * childDistances holds minimal distances from the child to each ancestor (keyed by DependencyNode).\n * For every entry in parentDistances, we update the child's map with (parentDist + 1),\n * keeping the minimal value if the ancestor already exists.\n */\nconst mergeAncestorDistances = (\n parentDistances: AncestorDistanceByNode,\n childDistances: AncestorDistanceByNode,\n) => {\n for (const [ancestor, parentDist] of parentDistances) {\n const candidate = parentDist + 1;\n const current = childDistances.get(ancestor) || Infinity;\n childDistances.set(ancestor, Math.min(current, candidate));\n }\n};\n\n/**\n * Builds a minimal ancestry distance index for all nodes reachable from the root.\n *\n * Returns a Map: node.name -> Map<DependencyNode, distance> where distance is the minimal hop count\n * from the node to that ancestor. We perform a Kahn-style BFS over the DAG, and for each edge\n * curNode -> dep we merge curNode's minimal distances into the dependency with +1 hop and take the minimum.\n */\nconst buildAncestryDistanceIndex = (\n node: DependencyNode,\n prehandler: NodePreHandlerFunction,\n): AncestryDistanceIndex => {\n const ancestryDistanceIndex: AncestryDistanceIndex = new Map();\n const inDegreeByNodeName = new Map<string, number>();\n\n // If A depends on B and C, B depends on C, we initialize with:\n // ancestryDistanceIndex: { A: Map(), B: Map(), C: Map() }\n // inDegreeByNodeName: { B: 1, C: 2 }\n const initializeMaps = (cur: DependencyNode) => {\n ancestryDistanceIndex.set(cur.name, new Map());\n for (const dep of Object.values(cur.dependencies)) {\n const handledDep = prehandler(dep);\n const inDegree = inDegreeByNodeName.get(handledDep.name) || 0;\n inDegreeByNodeName.set(handledDep.name, inDegree + 1);\n if (!ancestryDistanceIndex.has(handledDep.name)) initializeMaps(handledDep);\n }\n };\n\n const handled = prehandler(node);\n\n initializeMaps(handled);\n\n // Kahn-style topological BFS accumulating minimal distance ancestors\n let queue = [handled];\n while (queue.length > 0) {\n const curNode = queue.shift()!;\n // Include self with distance 0, then extend with the already known minimal distances\n const currentMinimalDistances: AncestorDistanceByNode = new Map([\n [curNode, 0],\n ...ancestryDistanceIndex.get(curNode.name)!,\n ]);\n // Add the new processable dependencies to the queue, update their state.\n for (const dep of Object.values(curNode.dependencies)) {\n const handledDep = prehandler(dep);\n const inDegree = inDegreeByNodeName.get(handledDep.name)!;\n // We are the last edge missing in the graph for this dependency -> we can process it after us.\n if (inDegree === 1) {\n queue.push(handledDep);\n }\n // Reduce the in-degree of the dependency -> it basically means that this edge got removed from the graph.\n inDegreeByNodeName.set(handledDep.name, inDegree - 1);\n\n // Merge curNode's minimal distances (+1 hop) into the dependency's minimal distances\n const childDistances = ancestryDistanceIndex.get(handledDep.name)!;\n mergeAncestorDistances(currentMinimalDistances, childDistances);\n }\n }\n\n for (const [nodeName, inDegree] of inDegreeByNodeName) {\n if (inDegree !== 0) {\n throw new Error(\n `node ${nodeName} has in-degree ${inDegree}, this indicates a cycle in the graph containing the node`,\n );\n }\n }\n\n return ancestryDistanceIndex;\n};\n\n/**\n * Performs a depth-first-search on a tree of dependency nodes, and returns a function\n * that will call the handler for each node in the tree, ordered s.t. the handler of N\n * will be called only after the handlers of dependencies(N) have been called.\n * The node's ancestors are sorted by non-decreasing minimal distance.\n * The resolver function will only call the handler once for each unique definition node.\n * The resolver function returns an object whose keys are the keys defined\n * by each of the handlers, and whose values are objects whose keys are the names\n * of the nodes resolved and whose values are the values defined by the handlers.\n * @param node the root node of the tree\n * @param handler a function that accepts a node and registers it\n * @param prehandler a function that accepts a node and returns a node. Will be used to pre-process the graph\n * @returns a resolver function\n */\nexport const dfs = <ReturnTypes>(\n node: DependencyNode,\n handler: NodeHandlerFunction,\n prehandler: NodePreHandlerFunction = (node) => node,\n _returns: ReturnTypes = {} as any,\n): (() => Promise<ReturnTypes>) => {\n const ancestryDistanceIndex = buildAncestryDistanceIndex(node, prehandler);\n\n // Maintains Map<node.name, Promise<void>> -> the promise to resolve the node, for all nodes.\n const nodeResolverPromises = new Map<string, Promise<void>>();\n const resolveNode = async (node: DependencyNode) => {\n const prehandledNode = prehandler(node);\n // first wait for all its children\n const childrenPromises = [];\n for (const dependencyValue of Object.values(prehandledNode.dependencies)) {\n // Grab the cached promise or create it, we want to have only 1 handler promise for each node.\n if (!nodeResolverPromises.has(dependencyValue.name)) {\n nodeResolverPromises.set(dependencyValue.name, resolveNode(dependencyValue));\n }\n childrenPromises.push(nodeResolverPromises.get(dependencyValue.name)!);\n }\n await Promise.all(childrenPromises);\n\n // Then, you can process yourself. Build ancestry sorted by non-decreasing minimal distance.\n const minimalDistances = ancestryDistanceIndex.get(prehandledNode.name)!;\n const sortedAncestors = Array.from(minimalDistances.entries()).sort((a, b) => a[1] - b[1]);\n const regRes = await handler(\n prehandledNode,\n sortedAncestors.map(([node, _]) => node),\n );\n if (regRes) {\n ((_returns as any)[regRes.key] ??= {})[prehandledNode.name] = regRes.value;\n }\n };\n\n return async () => {\n await resolveNode(node);\n return _returns;\n };\n};\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@layerzerolabs/dfs",
3
- "version": "0.0.43",
3
+ "version": "0.0.44",
4
4
  "private": false,
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -14,13 +14,13 @@
14
14
  "module": "./dist/index.js",
15
15
  "types": "./dist/index.d.ts",
16
16
  "dependencies": {
17
- "@layerzerolabs/dependency-graph": "0.0.43"
17
+ "@layerzerolabs/dependency-graph": "0.0.44"
18
18
  },
19
19
  "devDependencies": {
20
20
  "tsup": "^8.4.0",
21
21
  "vitest": "^3.2.3",
22
- "@layerzerolabs/typescript-configuration": "0.0.43",
23
- "@layerzerolabs/tsup-configuration": "0.0.43"
22
+ "@layerzerolabs/typescript-configuration": "0.0.44",
23
+ "@layerzerolabs/tsup-configuration": "0.0.44"
24
24
  },
25
25
  "publishConfig": {
26
26
  "access": "restricted",
package/src/index.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { DependencyNode } from '@layerzerolabs/dependency-graph';
2
2
 
3
3
  /**
4
+ * <!-- anchor:Registrar -->
4
5
  * A registrar is a simple interface for an object that provides the ability to traverse the dependency graph.
5
6
  * It is implicit in this definition that the registrar should also *register* values adhering to the schemata
6
7
  * of the graph.