import { execFileSync } from 'node:child_process'; import { mkdtemp, mkdir, readFile, rm, unlink, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; type PackResult = { filename: string; }; type PackageJson = { exports: Record; }; type ExportCheck = { phase: 'core' | 'optional'; runtime: string[]; types: string[]; }; const scriptDir = dirname(fileURLToPath(import.meta.url)); const rootDir = resolve(scriptDir, '..'); function getExportSpecifier(exportKey: string): string { return exportKey === '.' ? '@statelyai/graph' : `@statelyai/graph/${exportKey.slice(2)}`; } function buildRuntimeCheckScript( exportKeys: string[], exportChecks: Record, ): string { const importLines = exportKeys.map( (key, index) => `const m${index + 1} = await import(${JSON.stringify(getExportSpecifier(key))});`, ); const assertionBlocks = exportKeys.map((key, index) => [ '{', ...exportChecks[key].runtime.map((line) => line.replaceAll('$MOD', `m${index + 1}`), ), '}', ].join('\n'), ); return ` import assert from 'node:assert/strict'; const m0 = await import('@statelyai/graph'); ${importLines.join('\n')} ${assertionBlocks.join('\n\n')} `.trimStart(); } function buildTypeCheckScript( exportKeys: string[], exportChecks: Record, ): string { const importLines = exportKeys.map( (key, index) => `import * as m${index + 1} from ${JSON.stringify(getExportSpecifier(key))};`, ); const assertionBlocks = exportKeys.map((key, index) => [ '{', ...exportChecks[key].types.map((line) => line.replaceAll('$MOD', `m${index + 1}`), ), '}', ].join('\n'), ); return ` import * as m0 from '@statelyai/graph'; ${importLines.join('\n')} ${assertionBlocks.join('\n\n')} `.trimStart(); } async function main(): Promise { const packageJson = JSON.parse( await readFile(join(rootDir, 'package.json'), 'utf8'), ) as PackageJson; const publishedExportKeys = Object.keys(packageJson.exports).filter( (key) => key !== './package.json', ); const exportChecks: Record = { '.': { phase: 'core', runtime: [ `assert.equal(typeof $MOD.createGraph, 'function');`, `assert.equal(typeof $MOD.createVisualGraph, 'function');`, `assert.equal(typeof $MOD.genBFS, 'function');`, `assert.equal(typeof $MOD.updateGraphWithPatches, 'function');`, `assert.equal(typeof $MOD.getFlattenedGraph, 'function');`, `assert.equal(typeof $MOD.genWalkSteps, 'function');`, `const graph = $MOD.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }, { id: 'c' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }, { id: 'e2', sourceId: 'b', targetId: 'c' }] });`, `const visualGraph = $MOD.createVisualGraph(graph);`, `assert.deepEqual([graph.id, visualGraph.nodes.length], ['', 3]);`, `assert.deepEqual([ $MOD.getShortestPath(graph, { from: 'a', to: 'c' })?.source.id, ...($MOD.getShortestPath(graph, { from: 'a', to: 'c' })?.steps.map((step) => step.node.id) ?? []) ], ['a', 'b', 'c']);`, ], types: [ `const graph: m0.Graph = $MOD.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }] });`, `const nodes = [...$MOD.genBFS(graph, 'a')];`, `$MOD.updateGraphWithPatches(graph, []);`, `$MOD.getFlattenedGraph(graph);`, `[...$MOD.genWalkSteps($MOD.genRandomWalk(graph, { from: 'a' }), 1)];`, `nodes[0]?.id;`, `graph.nodes[0]?.id;`, ], }, './algorithms': { phase: 'core', runtime: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }, { id: 'c' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }, { id: 'e2', sourceId: 'b', targetId: 'c' }] });`, `assert.equal(typeof $MOD.genBFS, 'function');`, `assert.equal(typeof $MOD.genDFS, 'function');`, `assert.equal(typeof $MOD.getJoinedPath, 'function');`, `assert.equal(typeof $MOD.getTopologicalSort, 'function');`, `assert.equal(typeof $MOD.getConnectedComponents, 'function');`, ], types: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }] });`, `const visited = [...$MOD.genBFS(graph, 'a')];`, `const topo = $MOD.getTopologicalSort(graph);`, `visited[0]?.id;`, `topo?.[0]?.id;`, ], }, './format-support': { phase: 'core', runtime: [ `assert.equal($MOD.getFormatSupportEntry('dot')?.features.roundTrip, 'partial');`, ], types: [ `const support = $MOD.getFormatSupportEntry('graphml');`, `support?.features.ports;`, ], }, './adjacency-list': { phase: 'core', runtime: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }, { id: 'c' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }, { id: 'e2', sourceId: 'b', targetId: 'c' }] });`, `assert.deepEqual($MOD.toAdjacencyList(graph), { a: ['b'], b: ['c'], c: [] });`, `assert.equal($MOD.fromAdjacencyList($MOD.toAdjacencyList(graph)).edges.length, 2);`, ], types: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }] });`, `const adjacency = $MOD.toAdjacencyList(graph);`, `adjacency.a?.[0];`, ], }, './converter': { phase: 'core', runtime: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }, { id: 'c' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }, { id: 'e2', sourceId: 'b', targetId: 'c' }] });`, `assert.deepEqual($MOD.adjacencyListConverter.to(graph), { a: ['b'], b: ['c'], c: [] });`, `assert.deepEqual($MOD.edgeListConverter.to(graph), [['a', 'b'], ['b', 'c']]);`, ], types: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }] });`, `const edgeList = $MOD.edgeListConverter.to(graph);`, `edgeList[0]?.[0];`, ], }, './document': { phase: 'core', runtime: [ `const converter = $MOD.createGraphDocumentConverter({ format: 'smoke', codec: { from: () => m0.createGraph({ nodes: [{ id: 'a', label: 'A' }] }), to: () => 'regenerated' } });`, `const source = '# retained comment\\nopaque source\\n';`, `const document = converter.from(source);`, `assert.equal(converter.to(JSON.parse(JSON.stringify(document))), source);`, `document.graph.nodes[0].label = 'Edited';`, `assert.equal($MOD.getGraphDocumentUpdate(document, converter).ok, false);`, `assert.throws(() => converter.to(document), /unsupported-edit/);`, ], types: [ `const converter = $MOD.createGraphDocumentConverter({ format: 'visual-smoke', codec: { from: (_source: string) => m0.createVisualGraph({ nodes: [{ id: 'a', width: 3 }] }), to: (_graph: m0.VisualGraph) => 'visual' } });`, `const document: $MOD.GraphDocument = converter.from('visual');`, `const width: number = document.graph!.nodes[0].width;`, `const result = $MOD.getGraphDocumentUpdate(document, converter);`, `if (result.ok) result.source.toUpperCase();`, `width.toFixed();`, ], }, './adjacency-matrix': { phase: 'core', runtime: [ `const graph = m0.createGraph({ nodes: [{ id: 'a', label: 'A' }, { id: 'b', label: 'B' }], edges: [{ id: 'e', sourceId: 'a', targetId: 'b', weight: 1 }] });`, `assert.equal($MOD.fromAdjacencyMatrix($MOD.toAdjacencyMatrix(graph)).edges.length, 1);`, ], types: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e', sourceId: 'a', targetId: 'b', weight: 1 }] });`, `const native = $MOD.toAdjacencyMatrix(graph);`, `native.matrix[0]?.[0];`, ], }, './matrix-market': { phase: 'core', runtime: [ `const graph = m0.createGraph({ nodes: [{ id: 'a', label: 'A' }, { id: 'b', label: 'B' }], edges: [{ id: 'e', sourceId: 'a', targetId: 'b', weight: 1 }] });`, `assert.equal($MOD.fromMatrixMarket($MOD.toMatrixMarket(graph)).edges.length, 1);`, ], types: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e', sourceId: 'a', targetId: 'b', weight: 1 }] });`, `const native = $MOD.toMatrixMarket(graph);`, `native.toUpperCase();`, ], }, './graphviz-json': { phase: 'core', runtime: [ `const graph = m0.createGraph({ nodes: [{ id: 'a', label: 'A' }, { id: 'b', label: 'B' }], edges: [{ id: 'e', sourceId: 'a', targetId: 'b', weight: 1 }] });`, `assert.equal($MOD.fromGraphvizJSON($MOD.toGraphvizJSON(graph, { regenerate: true })).edges.length, 1);`, ], types: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e', sourceId: 'a', targetId: 'b', weight: 1 }] });`, `const native = $MOD.toGraphvizJSON(graph, { regenerate: true });`, `native.objects?.[0]?.name;`, ], }, './drawio': { phase: 'optional', runtime: [ `const graph = m0.createGraph({ nodes: [{ id: 'a', label: 'A' }, { id: 'b', label: 'B' }], edges: [{ id: 'e', sourceId: 'a', targetId: 'b', weight: 1 }] });`, `assert.equal($MOD.fromDrawio($MOD.toDrawio(graph)).edges.length, 1);`, ], types: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e', sourceId: 'a', targetId: 'b', weight: 1 }] });`, `const native = $MOD.toDrawio(graph);`, `native.toUpperCase();`, ], }, './pajek': { phase: 'core', runtime: [ `const graph = m0.createGraph({ nodes: [{ id: 'a', label: 'A' }, { id: 'b', label: 'B' }], edges: [{ id: 'e', sourceId: 'a', targetId: 'b', weight: 1 }] });`, `assert.equal($MOD.fromPajek($MOD.toPajek(graph)).edges.length, 1);`, ], types: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e', sourceId: 'a', targetId: 'b', weight: 1 }] });`, `const native = $MOD.toPajek(graph);`, `native.toUpperCase();`, ], }, './plantuml': { phase: 'core', runtime: [ `const graph = m0.createGraph({ nodes: [{ id: 'a', label: 'A' }, { id: 'b', label: 'B' }], edges: [{ id: 'e', sourceId: 'a', targetId: 'b', weight: 1 }] });`, `assert.equal($MOD.fromPlantUML($MOD.toPlantUML(graph)).edges.length, 1);`, ], types: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e', sourceId: 'a', targetId: 'b', weight: 1 }] });`, `const native = $MOD.toPlantUML(graph);`, `native.toUpperCase();`, ], }, './csv': { phase: 'core', runtime: [ `const graph = m0.createGraph({ nodes: [{ id: 'a', label: 'A' }, { id: 'b' }], edges: [{ id: 'e', sourceId: 'a', targetId: 'b' }] });`, `assert.equal($MOD.fromCSV($MOD.toCSV(graph)).edges.length, 1);`, `assert.equal($MOD.fromTSV($MOD.toTSV(graph)).nodes.length, 2);`, ], types: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e', sourceId: 'a', targetId: 'b' }] });`, `const native = $MOD.toCSV(graph);`, `native.nodes.toUpperCase();`, ], }, './graphlib': { phase: 'core', runtime: [ `const graph = m0.createGraph({ nodes: [{ id: 'a', label: 'A' }, { id: 'b' }], edges: [{ id: 'e', sourceId: 'a', targetId: 'b' }] });`, `assert.equal($MOD.fromGraphlibJSON($MOD.toGraphlibJSON(graph)).edges.length, 1);`, ], types: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e', sourceId: 'a', targetId: 'b' }] });`, `const native = $MOD.toGraphlibJSON(graph);`, `native.nodes[0]?.v;`, ], }, './graphology': { phase: 'core', runtime: [ `const graph = m0.createGraph({ nodes: [{ id: 'a', label: 'A' }, { id: 'b' }], edges: [{ id: 'e', sourceId: 'a', targetId: 'b' }] });`, `assert.equal($MOD.fromGraphologyJSON($MOD.toGraphologyJSON(graph)).edges.length, 1);`, ], types: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e', sourceId: 'a', targetId: 'b' }] });`, `const native = $MOD.toGraphologyJSON(graph);`, `native.nodes[0]?.key;`, ], }, './networkx': { phase: 'core', runtime: [ `const graph = m0.createGraph({ nodes: [{ id: 'a', label: 'A' }, { id: 'b' }], edges: [{ id: 'e', sourceId: 'a', targetId: 'b' }] });`, `assert.equal($MOD.fromNetworkXNodeLink($MOD.toNetworkXNodeLink(graph)).edges.length, 1);`, ], types: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e', sourceId: 'a', targetId: 'b' }] });`, `const native = $MOD.toNetworkXNodeLink(graph);`, `native.nodes[0]?.id;`, ], }, './cytoscape': { phase: 'core', runtime: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }] });`, `assert.equal($MOD.fromCytoscapeJSON($MOD.toCytoscapeJSON(graph)).edges.length, 1);`, ], types: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }] });`, `const cyto = $MOD.toCytoscapeJSON(graph);`, `cyto.elements.nodes[0]?.data.id;`, ], }, './d3': { phase: 'core', runtime: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }] });`, `assert.equal($MOD.fromD3Graph($MOD.toD3Graph(graph)).edges.length, 1);`, ], types: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }] });`, `const d3 = $MOD.toD3Graph(graph);`, `d3.links[0]?.source;`, ], }, './d2': { phase: 'core', runtime: [ `const graph = $MOD.fromD2('a -> b: hello');`, `assert.equal(graph.edges[0]?.label, 'hello');`, `assert.equal($MOD.fromD2($MOD.toD2(graph)).edges.length, 1);`, ], types: [ `const graph = $MOD.fromD2('a -> b');`, `const d2 = $MOD.toD2(graph);`, `d2.toUpperCase();`, ], }, './dot': { phase: 'optional', runtime: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e1', sourceId: 'a', sourcePort: 'out', targetId: 'b', targetPort: 'in' }] });`, `assert.equal($MOD.fromDOT($MOD.toDOT(graph)).edges[0]?.sourcePort, 'out');`, ], types: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }] });`, `const dot = $MOD.toDOT(graph);`, `dot.toUpperCase();`, ], }, './edge-list': { phase: 'core', runtime: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }, { id: 'c' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }, { id: 'e2', sourceId: 'b', targetId: 'c' }] });`, `assert.deepEqual($MOD.toEdgeList(graph), [['a', 'b'], ['b', 'c']]);`, `assert.equal($MOD.fromEdgeList($MOD.toEdgeList(graph)).edges.length, 2);`, ], types: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }] });`, `const edgeList = $MOD.toEdgeList(graph);`, `edgeList[0]?.[1];`, ], }, './elk': { phase: 'core', runtime: [ `const graph = m0.createVisualGraph({ nodes: [{ id: 'a', x: 0, y: 0, width: 10, height: 10 }, { id: 'b', x: 20, y: 0, width: 10, height: 10 }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b', width: 0, height: 0 }] });`, `assert.equal($MOD.fromELK($MOD.toELK(graph)).edges.length, 1);`, ], types: [ `const graph = m0.createVisualGraph({ nodes: [{ id: 'a', x: 0, y: 0, width: 10, height: 10 }, { id: 'b', x: 20, y: 0, width: 10, height: 10 }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b', width: 0, height: 0 }] });`, `const elkGraph = $MOD.toELK(graph);`, `elkGraph.children?.[0]?.id;`, ], }, './layout': { phase: 'core', runtime: [ `const graph = m0.createGraph({ nodes: [{ id: 'a', x: 0, y: 0, width: 10, height: 10 }], edges: [] });`, `assert.equal($MOD.getLayoutBounds(graph).width, 10);`, `$MOD.applyLayoutFrame(graph, { positions: { a: { x: 5, y: 5 } }, alpha: 0 });`, `assert.equal(graph.nodes[0].x, 5);`, ], types: [ `const opts: $MOD.LayoutOptions = { direction: 'down', seed: 1 };`, `opts.direction;`, ], }, './layout/elk': { phase: 'optional', runtime: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }] });`, `const laidOut = await $MOD.getElkLayout(graph);`, `assert.equal(laidOut.nodes.length, 2);`, `assert.ok(laidOut.edges[0].points && laidOut.edges[0].points.length >= 2);`, ], types: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }], edges: [] });`, `const pending: Promise = $MOD.getElkLayout(graph);`, `void pending;`, ], }, './layout/dagre': { phase: 'optional', runtime: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }] });`, `const laidOut = $MOD.getDagreLayout(graph);`, `assert.ok(laidOut.nodes[1].y > laidOut.nodes[0].y);`, ], types: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }], edges: [] });`, `const laidOut: m0.VisualGraph = $MOD.getDagreLayout(graph, { direction: 'right' });`, `void laidOut;`, ], }, './layout/d3-force': { phase: 'optional', runtime: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }] });`, `const laidOut = $MOD.getForceLayout(graph, { seed: 1, iterations: 10 });`, `assert.equal(laidOut.nodes.length, 2);`, ], types: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }], edges: [] });`, `const frames: Generator = $MOD.genForceLayout(graph);`, `void frames;`, ], }, './layout/graphviz': { phase: 'optional', runtime: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }] });`, `const laidOut = await $MOD.getGraphvizLayout(graph);`, `assert.equal(laidOut.nodes.length, 2);`, `assert.equal(laidOut.edges[0].routing, 'splines');`, ], types: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }], edges: [] });`, `const pending: Promise = $MOD.getGraphvizLayout(graph, { engine: 'dot' });`, `void pending;`, ], }, './layout/forceatlas2': { phase: 'optional', runtime: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }] });`, `const laidOut = $MOD.getForceAtlas2Layout(graph, { seed: 1, iterations: 10 });`, `assert.equal(laidOut.nodes.length, 2);`, ], types: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }], edges: [] });`, `const laidOut: m0.VisualGraph = $MOD.getForceAtlas2Layout(graph);`, `void laidOut;`, ], }, './layout/d3-hierarchy': { phase: 'optional', runtime: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }] });`, `const laidOut = $MOD.getTidyTreeLayout(graph);`, `assert.ok(laidOut.nodes[1].y > laidOut.nodes[0].y);`, ], types: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }], edges: [] });`, `const laidOut: m0.VisualGraph = $MOD.getTidyTreeLayout(graph, { rootId: 'a' });`, `void laidOut;`, ], }, './layout/webcola': { phase: 'optional', runtime: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }] });`, `const laidOut = $MOD.getColaLayout(graph, { seed: 1 });`, `assert.equal(laidOut.nodes.length, 2);`, ], types: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }], edges: [] });`, `const laidOut: m0.VisualGraph = $MOD.getColaLayout(graph, { linkDistance: 100 });`, `void laidOut;`, ], }, './layout/cytoscape': { phase: 'optional', runtime: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }] });`, `const laidOut = await $MOD.getCytoscapeLayout(graph, { name: 'grid' });`, `assert.equal(laidOut.nodes.length, 2);`, ], types: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }], edges: [] });`, `const pending: Promise = $MOD.getCytoscapeLayout(graph);`, `void pending;`, ], }, './gexf': { phase: 'optional', runtime: [ `const graph = m0.createGraph({ id: 'g', initialNodeId: 'a', direction: 'right', data: { ok: true }, nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }] });`, `const parsed = $MOD.fromGEXF($MOD.toGEXF(graph));`, `assert.equal(parsed.initialNodeId, 'a');`, `assert.deepEqual(parsed.data, { ok: true });`, ], types: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }] });`, `const xml = $MOD.toGEXF(graph);`, `xml.toUpperCase();`, ], }, './gml': { phase: 'core', runtime: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b', parentId: 'a' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }] });`, `assert.equal($MOD.fromGML($MOD.toGML(graph)).nodes[1]?.parentId, 'a');`, ], types: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b', parentId: 'a' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }] });`, `const gml = $MOD.toGML(graph);`, `gml.toUpperCase();`, ], }, './graphml': { phase: 'optional', runtime: [ `const graph = m0.createGraph({ nodes: [{ id: 'a', ports: [{ name: 'out' }] }, { id: 'b', ports: [{ name: 'in' }] }], edges: [{ id: 'e1', sourceId: 'a', sourcePort: 'out', targetId: 'b', targetPort: 'in' }] });`, `assert.equal($MOD.fromGraphML($MOD.toGraphML(graph)).edges[0]?.targetPort, 'in');`, ], types: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }] });`, `const xml = $MOD.toGraphML(graph);`, `xml.toUpperCase();`, ], }, './jgf': { phase: 'core', runtime: [ `const graph = m0.createGraph({ initialNodeId: 'a', nodes: [{ id: 'a' }, { id: 'b', parentId: 'a' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }] });`, `assert.equal($MOD.fromJGF($MOD.toJGF(graph)).nodes[1]?.parentId, 'a');`, ], types: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }] });`, `const jgf = $MOD.toJGF(graph);`, `jgf.graph.nodes[0]?.id;`, ], }, './mermaid': { phase: 'core', runtime: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }] });`, `assert.match($MOD.toMermaidFlowchart(graph), /flowchart/i);`, ], types: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }] });`, `const flowchart = $MOD.toMermaidFlowchart(graph);`, `flowchart.toUpperCase();`, ], }, './tgf': { phase: 'core', runtime: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }] });`, `assert.equal($MOD.fromTGF($MOD.toTGF(graph)).edges.length, 1);`, ], types: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }] });`, `const tgf = $MOD.toTGF(graph);`, `tgf.toUpperCase();`, ], }, './xyflow': { phase: 'core', runtime: [ `const graph = m0.createVisualGraph({ nodes: [{ id: 'a', x: 0, y: 0, width: 10, height: 10 }, { id: 'b', x: 20, y: 0, width: 10, height: 10 }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b', width: 0, height: 0 }] });`, `assert.equal($MOD.fromXYFlow($MOD.toXYFlow(graph)).edges.length, 1);`, ], types: [ `const graph = m0.createVisualGraph({ nodes: [{ id: 'a', x: 0, y: 0, width: 10, height: 10 }, { id: 'b', x: 20, y: 0, width: 10, height: 10 }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b', width: 0, height: 0 }] });`, `const flow = $MOD.toXYFlow(graph);`, `flow.nodes[0]?.id;`, ], }, './xstate': { phase: 'optional', runtime: [ `const { createMachine } = await import('xstate');`, `const graph = $MOD.createGraphFromMachine(createMachine({ initial: 'a', states: { a: { on: { NEXT: 'b' } }, b: {} } }));`, `assert.equal(graph.nodes.length, 2);`, `assert.equal(graph.edges[0].data.eventType, 'NEXT');`, ], types: [ `const graph: $MOD.MachineGraph = $MOD.createGraphFromMachine({} as any);`, `graph.nodes[0]?.data.stateIds;`, ], }, './queries': { phase: 'core', runtime: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }] });`, `assert.equal($MOD.getNeighbors(graph, 'a')[0]?.id, 'b');`, ], types: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }] });`, `const neighbors = $MOD.getNeighbors(graph, 'a');`, `neighbors[0]?.id;`, ], }, './kernel': { phase: 'core', runtime: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }] });`, `const csr = $MOD.getCSR(graph);`, `assert.equal(csr.ids.length, 2);`, `const memo = $MOD.memoizeByGraph((g) => g.nodes.length);`, `assert.equal(memo(graph), 2);`, `assert.equal(memo(graph), 2);`, ], types: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }] });`, `const index: $MOD.GraphIndex = $MOD.getIndex(graph);`, `index.version.toFixed();`, `const csr: $MOD.GraphCSR = $MOD.getCSR(graph);`, `csr.ids.length.toFixed();`, ], }, './schemas': { phase: 'optional', runtime: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }] });`, `assert.equal($MOD.GraphSchema.safeParse(graph).success, true);`, `assert.equal($MOD.isGraph(graph), true);`, `assert.deepEqual($MOD.getGraphIssues(graph), []);`, ], types: [ `const graph = m0.createGraph({ nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'e1', sourceId: 'a', targetId: 'b' }] });`, `const issues: $MOD.GraphValidationIssue[] = $MOD.getGraphIssues(graph);`, `issues[0]?.message;`, ], }, }; Object.assign(exportChecks, { "./graphson": { phase: "core", runtime: [ `const graph = m0.createGraph({ nodes:[{id:'a',label:'A'},{id:'b',label:'B'}], edges:[{id:'e',sourceId:'a',targetId:'b'}] });`, `const source = $MOD.toGraphSON(graph); assert.equal(source['@type'],'tinker:graph'); assert.equal($MOD.fromGraphSON(source).edges[0].id,'e');`, ], types: [ `const source: $MOD.GraphSONGraph = $MOD.toGraphSON(m0.createGraph({})); $MOD.graphsonConverter.from(source);`, ], }, "./cx2": { phase: "core", runtime: [ `const source = $MOD.toCX2(m0.createGraph({nodes:[{id:'0',label:'A'},{id:'1',label:'B'}],edges:[{id:'2',sourceId:'0',targetId:'1',label:'Go'}]})); assert.equal($MOD.fromCX2(source).edges[0].id,'2');`, ], types: [ `const source: $MOD.CX2JSON = $MOD.toCX2(m0.createGraph({})); $MOD.cx2Converter.from(source);`, ], }, "./dgml": { phase: "optional", runtime: [ `const source = $MOD.toDGML(m0.createGraph({nodes:[{id:'a',label:'A'},{id:'b',label:'B'}],edges:[{id:'dgml_link_0',sourceId:'a',targetId:'b',label:'Go'}]})); assert.equal($MOD.fromDGML(source).edges[0].id,'dgml_link_0');`, ], types: [ `const source: string = $MOD.toDGML(m0.createGraph({})); const graph: $MOD.DGMLGraph = $MOD.fromDGML(source); void graph;`, ], }, "./rdf": { phase: "core", runtime: [ `const source = {version:'1.1',quads:[{subject:{termType:'NamedNode',value:'urn:a'},predicate:{termType:'NamedNode',value:'urn:p'},object:{termType:'NamedNode',value:'urn:b'},graph:{termType:'DefaultGraph',value:''}}]}; assert.deepEqual($MOD.toRDFDataset($MOD.fromRDFDataset(source)),source);`, `assert.equal(typeof $MOD.getRDFTermId($MOD.getRDFTerm(source.quads[0].subject)),'string'); assert.equal(typeof $MOD.getRDFQuadId(source.quads[0]),'string');`, ], types: [ `const source: $MOD.RDFDataset = {version:'1.1',quads:[]}; const term: $MOD.RDFTerm = $MOD.getRDFTerm({termType:'NamedNode',value:'urn:a'}); $MOD.getRDFTermId(term); $MOD.rdfDatasetConverter.from(source);`, ], }, "./rdf/syntax": { phase: "optional", runtime: [ `const text = ' .'; const graph = $MOD.fromRDF(text,{format:'N-Triples'}); assert.equal(graph.edges.length,1); assert.ok($MOD.toRDF(graph,{format:'N-Triples'}).includes('urn:p')); const codec = $MOD.createRDFDocumentConverter({format:'N-Triples'}); assert.equal(codec.to(JSON.parse(JSON.stringify(codec.from(text)))),text);`, ], types: [ `const options: $MOD.RDFSyntaxOptions = {format:'N-Triples'}; const graph = $MOD.fromRDF(' .',options); $MOD.toRDF(graph,{format:'N-Triples'}); $MOD.createRDFDocumentConverter(options);`, ], }, } satisfies Record); const documentExports: Array<[string, string, string]> = [ [ "./graphson", "graphsonDocumentConverter", '({"@type": "tinker:graph", "@value": {"vertices": [{"@type": "g:Vertex", "@value": {"id": "a", "label": "A"}}], "edges": []}})', ], [ "./cx2", "cx2DocumentConverter", '([{"CXVersion": "2.0", "hasFragments": false}, {"nodes": [{"id": 0}]}, {"edges": []}, {"status": [{"success": true}]}])', ], [ "./rdf", "rdfDatasetDocumentConverter", '({"version": "1.1", "quads": []})', ], [ "./dgml", "dgmlDocumentConverter", '""', ], ['./adjacency-list', 'adjacencyListDocumentConverter', '({a:["b"]})'], ['./adjacency-matrix', 'adjacencyMatrixDocumentConverter', '({matrix:[[0,1],[0,0]],nodeIds:["a","b"],mode:"directed"})'], ['./matrix-market', 'matrixMarketDocumentConverter', '"%%MatrixMarket matrix coordinate real general\\n2 2 1\\n1 2 1\\n"'], ['./graphviz-json', 'graphvizJSONDocumentConverter', '({name:"g",directed:true,strict:false,_subgraph_cnt:0,objects:[{_gvid:0,name:"a"}],edges:[]})'], ['./drawio', 'drawioDocumentConverter', '\'\''], ['./pajek', 'pajekDocumentConverter', '\'*Vertices 1\\n1 "A"\\n*Arcs\\n\''], ['./plantuml', 'plantumlDocumentConverter', '\'@startuml\\ncomponent "A" as a\\n@enduml\''], ['./csv', 'csvDocumentConverter', '({nodes:"id\\r\\na\\r\\n",edges:"id,sourceId,targetId\\r\\n"})'], ['./csv', 'tsvDocumentConverter', '({nodes:"id\\na\\n",edges:"id\\tsourceId\\ttargetId\\n"})'], ['./graphlib', 'graphlibDocumentConverter', '({options:{directed:true,multigraph:false,compound:false},nodes:[{v:"a"}],edges:[]})'], ['./graphology', 'graphologyDocumentConverter', '({options:{type:"directed",multi:false,allowSelfLoops:true},attributes:{},nodes:[{key:"a"}],edges:[]})'], ['./networkx', 'networkxDocumentConverter', '({directed:true,multigraph:false,graph:{},nodes:[{id:"a"}],edges:[]})'], ['./cytoscape', 'cytoscapeDocumentConverter', '({elements:{nodes:[{data:{id:"a"}}],edges:[]}})'], ['./d2', 'd2DocumentConverter', '"# comment\\na: Before\\n"'], ['./d3', 'd3DocumentConverter', '({nodes:[{id:"a"}],links:[]})'], ['./dot', 'dotDocumentConverter', '"// comment\\ndigraph { a [label=\\\"Before\\\"]; }"'], ['./edge-list', 'edgeListDocumentConverter', '([["a","b"]])'], ['./elk', 'elkDocumentConverter', '({id:"root",children:[{id:"a"}],edges:[]})'], ['./gexf', 'gexfDocumentConverter', '\'\''], ['./gml', 'gmlDocumentConverter', '\'graph [ node [ id 0 label "Before" ] ]\''], ['./graphml', 'graphMLDocumentConverter', '\'\''], ['./jgf', 'jgfDocumentConverter', '({graph:{id:"g",nodes:[{id:"a"}],edges:[]}})'], ['./tgf', 'tgfDocumentConverter', '"a Before\\r\\n#\\r\\n"'], ['./xyflow', 'xyflowDocumentConverter', '({nodes:[{id:"a",position:{x:0,y:0},data:{label:"Before"}}],edges:[]})'], ...[ ['Flowchart', 'flowchart TD\\nA[Before]'], ['Sequence', 'sequenceDiagram\\nA->>B: Before'], ['State', 'stateDiagram-v2\\nA --> B'], ['Class', 'classDiagram\\nclass A'], ['ER', 'erDiagram\\nA'], ['Block', 'block-beta\\nA[Before]'], ['Architecture', 'architecture-beta\\nservice a(server)[Before]'], ['Requirement', 'requirementDiagram\\nrequirement a {\\ntext: Before\\n}'], ['Sankey', 'sankey-beta\\nA,B,1'], ['GitGraph', 'gitGraph\\ncommit id: "a"'], ['C4', 'C4Context\\nPerson(a, "A")'], ['UseCase', 'usecase-beta\\nactor A("A")'], ['Mindmap', 'mindmap\\n root((Before))'], ['Ishikawa', 'ishikawa-beta\\n Before'], ].map(([name, source]) => ['./mermaid', `mermaid${name}DocumentConverter`, JSON.stringify(source).replace(/\\\\n/g, '\\n')] as [string, string, string]), ]; for (const [key, symbol, source] of documentExports) { exportChecks[key].runtime.push(`{ const nativeSource = ${source}; const nativeDocument = $MOD.${symbol}.from(nativeSource); assert.notEqual(nativeDocument.graph, null, ${JSON.stringify(`${key}:${symbol}`)}); assert.deepEqual($MOD.${symbol}.to(JSON.parse(JSON.stringify(nativeDocument))), nativeSource); }`); exportChecks[key].types.push(`{ const nativeDocument = $MOD.${symbol}.from(${source}); const nativeSource = $MOD.${symbol}.to(nativeDocument); void nativeSource; }`); } const missingChecks = publishedExportKeys.filter((key) => !(key in exportChecks)); const staleChecks = Object.keys(exportChecks).filter( (key) => !publishedExportKeys.includes(key), ); if (missingChecks.length > 0 || staleChecks.length > 0) { throw new Error( [ missingChecks.length > 0 ? `Missing smoke-package coverage for exports: ${missingChecks.join(', ')}` : '', staleChecks.length > 0 ? `Stale smoke-package coverage for non-exported subpaths: ${staleChecks.join(', ')}` : '', ] .filter(Boolean) .join('\n'), ); } const coreExportKeys = publishedExportKeys.filter( (key) => exportChecks[key].phase === 'core', ); const optionalExportKeys = publishedExportKeys.filter( (key) => exportChecks[key].phase === 'optional', ); const packOutput = execFileSync('npm', ['pack', '--json', '--ignore-scripts'], { cwd: rootDir, encoding: 'utf8', }); const jsonStart = packOutput.indexOf('[\n {'); const jsonEnd = packOutput.lastIndexOf('\n]'); if (jsonStart < 0 || jsonEnd < 0) { throw new Error(`Unable to parse npm pack output as JSON:\n${packOutput}`); } const parsedOutput = JSON.parse( packOutput.slice(jsonStart, jsonEnd + 2), ) as PackResult[]; const [{ filename }] = parsedOutput; const tarballPath = join(rootDir, filename); const tempDir = await mkdtemp(join(tmpdir(), 'statelyai-graph-smoke-')); const consumerDir = join(tempDir, 'consumer'); const coreCheckPath = join(consumerDir, 'check-core.mjs'); const coreTypesPath = join(consumerDir, 'check-core.ts'); const optionalCheckPath = join(consumerDir, 'check-optional.mjs'); const optionalTypesPath = join(consumerDir, 'check-optional.ts'); try { await mkdir(consumerDir, { recursive: true }); await writeFile( join(consumerDir, 'package.json'), JSON.stringify( { name: 'graph-smoke-consumer', private: true, type: 'module', }, null, 2, ) + '\n', ); execFileSync('pnpm', ['add', '--ignore-workspace', tarballPath], { cwd: consumerDir, stdio: 'inherit', }); execFileSync('pnpm', ['add', '--ignore-workspace', '--save-dev', 'typescript'], { cwd: consumerDir, stdio: 'inherit', }); await writeFile( coreCheckPath, buildRuntimeCheckScript(coreExportKeys, exportChecks), ); execFileSync('node', [coreCheckPath], { cwd: consumerDir, stdio: 'inherit', }); await writeFile( coreTypesPath, buildTypeCheckScript(coreExportKeys, exportChecks), ); execFileSync( 'pnpm', [ 'exec', 'tsc', '--noEmit', '--moduleResolution', 'bundler', '--module', 'preserve', '--target', 'esnext', '--strict', '--skipLibCheck', coreTypesPath, ], { cwd: consumerDir, stdio: 'inherit', }, ); execFileSync( 'pnpm', [ 'add', '--ignore-workspace', 'dotparser', 'fast-xml-parser', 'n3', 'fflate', 'zod', // Layout adapter optional peers 'elkjs', '@dagrejs/dagre', 'd3-force', '@hpcc-js/wasm-graphviz', 'graphology', 'graphology-layout-forceatlas2', 'd3-hierarchy', 'webcola', 'cytoscape', // XState adapter optional peer 'xstate', ], { cwd: consumerDir, stdio: 'inherit', }, ); await writeFile( optionalCheckPath, buildRuntimeCheckScript(optionalExportKeys, exportChecks), ); execFileSync('node', [optionalCheckPath], { cwd: consumerDir, stdio: 'inherit', }); const installedPackageDir = join( consumerDir, 'node_modules', '@statelyai', 'graph', ); const schemaFiles = ['graph.schema.json', 'node.schema.json', 'edge.schema.json']; for (const schemaFile of schemaFiles) { const schemaText = await readFile( join(installedPackageDir, 'schemas', schemaFile), 'utf8', ); JSON.parse(schemaText); } await writeFile( optionalTypesPath, buildTypeCheckScript(optionalExportKeys, exportChecks), ); execFileSync( 'pnpm', [ 'exec', 'tsc', '--noEmit', '--moduleResolution', 'bundler', '--module', 'preserve', '--target', 'esnext', '--strict', '--skipLibCheck', optionalTypesPath, ], { cwd: consumerDir, stdio: 'inherit', }, ); console.log('Package smoke test passed'); } finally { await unlink(tarballPath).catch(() => undefined); await rm(tempDir, { recursive: true, force: true }); } } await main();