@siglo/ide-analysis 1.2.1 → 1.2.3

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.
@@ -5,18 +5,27 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.analyzeWorkflowsInSourceFile = analyzeWorkflowsInSourceFile;
7
7
  exports.runDiagnostics = runDiagnostics;
8
+ const fs_1 = __importDefault(require("fs"));
9
+ const path_1 = __importDefault(require("path"));
8
10
  const typescript_1 = __importDefault(require("typescript"));
9
11
  const mapper_1 = require("../mapper");
10
12
  const step_detector_1 = require("./step-detector");
13
+ const module_resolver_1 = require("./module-resolver");
14
+ const MAX_RESOLVE_DEPTH = 10;
15
+ const FLOW_CHAIN_METHODS = new Set(['then', 'parallel', 'branch', 'fallback', 'compensate']);
16
+ const FLOW_CONFIG_METHODS = new Set(['timeout', 'version', 'networkPolicy', 'monitor', 'durable', 'saga']);
11
17
  function analyzeWorkflowsInSourceFile(sourceFile, uri, documentVersion = 1) {
12
- const ctx = {
13
- sourceFile,
14
- uri,
15
- documentVersion,
16
- stepDefinitions: new Map(),
17
- flowDefinitions: new Map(),
18
+ const filePath = (0, mapper_1.toFilePath)(uri);
19
+ const session = {
20
+ fileContexts: new Map(),
21
+ resolvingKeys: new Set(),
22
+ depth: 0,
18
23
  };
19
- // Phase 1: Collect top-level step variable declarations
24
+ const ctx = createWorkflowContext(sourceFile, uri, filePath, documentVersion, session);
25
+ if (filePath) {
26
+ session.fileContexts.set(path_1.default.resolve(filePath), ctx);
27
+ }
28
+ // Phase 1: Collect step variable declarations
20
29
  collectStepDefinitions(sourceFile, ctx);
21
30
  // Phase 2: Find workflow declarations and chains
22
31
  const workflows = [];
@@ -38,6 +47,7 @@ function analyzeWorkflowsInSourceFile(sourceFile, uri, documentVersion = 1) {
38
47
  uri,
39
48
  documentVersion,
40
49
  workflowName: 'defaultWorkflow',
50
+ ...(nodes[0]?.location ? { location: nodes[0].location } : {}),
41
51
  nodes,
42
52
  edges,
43
53
  unresolved: [],
@@ -46,6 +56,47 @@ function analyzeWorkflowsInSourceFile(sourceFile, uri, documentVersion = 1) {
46
56
  }
47
57
  return workflows;
48
58
  }
59
+ function createWorkflowContext(sourceFile, uri, filePath, documentVersion, session) {
60
+ return {
61
+ sourceFile,
62
+ uri,
63
+ filePath,
64
+ documentVersion,
65
+ stepDefinitions: new Map(),
66
+ flowDefinitions: new Map(),
67
+ metadata: (0, module_resolver_1.collectModuleMetadata)(sourceFile),
68
+ session,
69
+ };
70
+ }
71
+ function getScriptKindForFile(filePath) {
72
+ const ext = path_1.default.extname(filePath).toLowerCase();
73
+ if (ext === '.tsx')
74
+ return typescript_1.default.ScriptKind.TSX;
75
+ if (ext === '.jsx')
76
+ return typescript_1.default.ScriptKind.JSX;
77
+ if (ext === '.js' || ext === '.mjs' || ext === '.cjs')
78
+ return typescript_1.default.ScriptKind.JS;
79
+ return typescript_1.default.ScriptKind.TS;
80
+ }
81
+ function getOrLoadFileContext(filePath, session) {
82
+ const resolved = path_1.default.resolve(filePath);
83
+ const cached = session.fileContexts.get(resolved);
84
+ if (cached)
85
+ return cached;
86
+ let content;
87
+ try {
88
+ content = fs_1.default.readFileSync(resolved, 'utf-8');
89
+ }
90
+ catch {
91
+ return null;
92
+ }
93
+ const sourceFile = typescript_1.default.createSourceFile(resolved, content, typescript_1.default.ScriptTarget.Latest, true, getScriptKindForFile(resolved));
94
+ const ctx = createWorkflowContext(sourceFile, (0, mapper_1.normalizeUri)(resolved), resolved, 1, session);
95
+ session.fileContexts.set(resolved, ctx);
96
+ collectStepDefinitions(sourceFile, ctx);
97
+ walkForWorkflows(sourceFile, ctx, []);
98
+ return ctx;
99
+ }
49
100
  function collectStepDefinitions(sourceFile, ctx) {
50
101
  function visit(node) {
51
102
  if (typescript_1.default.isVariableDeclaration(node) && node.initializer) {
@@ -209,6 +260,135 @@ function findRootFlowCall(callExpr, sourceFile) {
209
260
  }
210
261
  return null;
211
262
  }
263
+ function unwrapTransparent(expr) {
264
+ let curr = expr;
265
+ while (typescript_1.default.isParenthesizedExpression(curr) ||
266
+ typescript_1.default.isAsExpression(curr) ||
267
+ typescript_1.default.isTypeAssertionExpression(curr) ||
268
+ typescript_1.default.isNonNullExpression(curr) ||
269
+ typescript_1.default.isSatisfiesExpression(curr)) {
270
+ curr = curr.expression;
271
+ }
272
+ return curr;
273
+ }
274
+ function resolveFunctionLikeFromDecl(node) {
275
+ if (typescript_1.default.isFunctionDeclaration(node))
276
+ return node;
277
+ const expr = typescript_1.default.isVariableDeclaration(node) ? node.initializer : node;
278
+ if (!expr)
279
+ return null;
280
+ const unwrapped = unwrapTransparent(expr);
281
+ if (typescript_1.default.isArrowFunction(unwrapped) || typescript_1.default.isFunctionExpression(unwrapped)) {
282
+ return unwrapped;
283
+ }
284
+ return null;
285
+ }
286
+ function resolveExportTarget(targetCtx, exportName, session, visitedExports = new Set()) {
287
+ const key = `${targetCtx.filePath}::${exportName}`;
288
+ if (visitedExports.has(key))
289
+ return null;
290
+ visitedExports.add(key);
291
+ const direct = targetCtx.metadata.exports.get(exportName);
292
+ if (direct) {
293
+ if (direct.kind === 'local') {
294
+ const decl = targetCtx.metadata.declarations.get(direct.localName);
295
+ return decl ? { ctx: targetCtx, target: { kind: 'declaration', node: decl } } : null;
296
+ }
297
+ if (direct.kind === 'reexport') {
298
+ const nextPath = (0, module_resolver_1.resolveRelativeImportPath)(targetCtx.filePath, direct.specifier);
299
+ const nextCtx = nextPath ? getOrLoadFileContext(nextPath, session) : null;
300
+ return nextCtx ? resolveExportTarget(nextCtx, direct.importedName, session, visitedExports) : null;
301
+ }
302
+ return { ctx: targetCtx, target: direct };
303
+ }
304
+ for (const specifier of targetCtx.metadata.starExports) {
305
+ const nextPath = (0, module_resolver_1.resolveRelativeImportPath)(targetCtx.filePath, specifier);
306
+ const nextCtx = nextPath ? getOrLoadFileContext(nextPath, session) : null;
307
+ if (nextCtx) {
308
+ const found = resolveExportTarget(nextCtx, exportName, session, visitedExports);
309
+ if (found)
310
+ return found;
311
+ }
312
+ }
313
+ return null;
314
+ }
315
+ function remapSubflowToCallSite(subflow, callSiteRange, targetCtx, callerCtx) {
316
+ if (targetCtx.filePath === callerCtx.filePath) {
317
+ return subflow;
318
+ }
319
+ const relPath = path_1.default.relative(path_1.default.dirname(callerCtx.filePath), targetCtx.filePath).replace(/\\/g, '/') ||
320
+ path_1.default.basename(targetCtx.filePath);
321
+ const idMap = new Map();
322
+ const usedIds = new Set();
323
+ const nextUniqueId = (baseId) => {
324
+ let candidate = baseId;
325
+ let counter = 2;
326
+ while (usedIds.has(candidate)) {
327
+ candidate = `${baseId}_${counter++}`;
328
+ }
329
+ usedIds.add(candidate);
330
+ return candidate;
331
+ };
332
+ const nodes = subflow.nodes.map(node => {
333
+ const baseId = (0, mapper_1.generateDeterministicNodeId)(node.name, callSiteRange);
334
+ const newId = nextUniqueId(baseId);
335
+ idMap.set(node.id, newId);
336
+ return {
337
+ ...node,
338
+ id: newId,
339
+ location: callSiteRange,
340
+ declarationRange: callSiteRange,
341
+ sourceUri: node.sourceUri || targetCtx.uri,
342
+ sourceLocation: node.sourceLocation || node.location,
343
+ properties: {
344
+ ...node.properties,
345
+ importedFrom: node.properties?.importedFrom || `${relPath}:${node.location.start.line + 1}`,
346
+ },
347
+ };
348
+ });
349
+ const unresolved = (subflow.unresolved || []).map(un => {
350
+ const baseId = `unresolved_L${callSiteRange.start.line + 1}_C${callSiteRange.start.character + 1}`;
351
+ const newId = nextUniqueId(baseId);
352
+ idMap.set(un.id, newId);
353
+ return {
354
+ ...un,
355
+ id: newId,
356
+ location: callSiteRange,
357
+ };
358
+ });
359
+ const edges = subflow.edges.map(edge => ({
360
+ ...edge,
361
+ from: idMap.get(edge.from) || edge.from,
362
+ to: idMap.get(edge.to) || edge.to,
363
+ }));
364
+ return {
365
+ nodes,
366
+ edges,
367
+ ...(unresolved.length ? { unresolved } : {}),
368
+ };
369
+ }
370
+ function resolveSubflowEntryAndExitIds(subflow) {
371
+ const allIds = [...subflow.nodes.map(n => n.id), ...(subflow.unresolved || []).map(u => u.id)];
372
+ if (allIds.length === 0)
373
+ return { entryIds: [], exitIds: [] };
374
+ const idSet = new Set(allIds);
375
+ const hasIncoming = new Set();
376
+ const hasOutgoing = new Set();
377
+ for (const edge of subflow.edges) {
378
+ if (edge.type === 'compensation')
379
+ continue;
380
+ if (idSet.has(edge.from) && idSet.has(edge.to)) {
381
+ hasIncoming.add(edge.to);
382
+ hasOutgoing.add(edge.from);
383
+ }
384
+ }
385
+ const entryIds = allIds.filter(id => !hasIncoming.has(id));
386
+ const exitIds = allIds.filter(id => !hasOutgoing.has(id));
387
+ return {
388
+ entryIds: entryIds.length > 0 ? entryIds : [allIds[0]],
389
+ exitIds: exitIds.length > 0 ? exitIds : [allIds[allIds.length - 1]],
390
+ };
391
+ }
212
392
  function parseWorkflowChain(outerCall, rootFlow, ctx) {
213
393
  // Collect the chain of calls from inner rootFlow to outerCall
214
394
  const chain = [];
@@ -234,28 +414,58 @@ function parseWorkflowChain(outerCall, rootFlow, ctx) {
234
414
  break;
235
415
  }
236
416
  }
237
- const properties = {};
238
- const nodes = [];
239
- const edges = [];
240
- const unresolved = [];
241
- let currentHeadIds = [];
242
- function addNode(detected) {
417
+ return buildWorkflowDocument(rootFlow.name, Array.from(rootFlow.call.arguments).filter(arg => !typescript_1.default.isStringLiteral(arg) &&
418
+ !typescript_1.default.isNoSubstitutionTemplateLiteral(arg) &&
419
+ !typescript_1.default.isObjectLiteralExpression(arg)), chain, ctx, undefined, (0, mapper_1.getSourceRange)(ctx.sourceFile, outerCall));
420
+ }
421
+ function buildWorkflowDocument(workflowName, initialExpressions, chain, ctx, seedSubflow, workflowLocation) {
422
+ const properties = { ...(seedSubflow?.properties || {}) };
423
+ const nodes = [...(seedSubflow?.nodes || [])];
424
+ const edges = [...(seedSubflow?.edges || [])];
425
+ const unresolved = [...(seedSubflow?.unresolved || [])];
426
+ const stepInvocations = [];
427
+ let currentHeadIds = seedSubflow ? resolveSubflowEntryAndExitIds(seedSubflow).exitIds : [];
428
+ function addNode(detected, usageNode) {
243
429
  if (detected.kind === 'node') {
244
430
  let nodeToAdd = detected.node;
245
- // If referencing a known definition, merge definition range
246
- if (detected.variableName && ctx.stepDefinitions.has(detected.variableName)) {
247
- const def = ctx.stepDefinitions.get(detected.variableName);
248
- nodeToAdd = {
249
- ...nodeToAdd,
250
- name: def.name,
251
- stepKind: def.stepKind,
252
- location: def.location,
253
- declarationRange: def.declarationRange,
254
- executionConfig: { ...def.executionConfig, ...nodeToAdd.executionConfig },
255
- properties: { ...def.properties, ...nodeToAdd.properties },
256
- specs: [...(def.specs || []), ...(nodeToAdd.specs || [])],
257
- };
431
+ // If referencing a known definition, merge definition range (preferring lexical scope)
432
+ if (detected.variableName) {
433
+ let def;
434
+ if (usageNode) {
435
+ const lexical = (0, module_resolver_1.findLexicalDeclaration)(detected.variableName, usageNode, ctx.metadata.declarations);
436
+ if (lexical && typescript_1.default.isVariableDeclaration(lexical) && lexical.initializer) {
437
+ const enclosingRange = (0, mapper_1.getSourceRange)(ctx.sourceFile, lexical);
438
+ const lexicalDetected = (0, step_detector_1.detectStepFromExpression)(lexical.initializer, ctx.sourceFile, enclosingRange);
439
+ if (lexicalDetected?.kind === 'node') {
440
+ def = { ...lexicalDetected.node, declarationRange: enclosingRange };
441
+ }
442
+ }
443
+ }
444
+ if (!def) {
445
+ def = ctx.stepDefinitions.get(detected.variableName);
446
+ }
447
+ if (def) {
448
+ nodeToAdd = {
449
+ ...nodeToAdd,
450
+ id: def.id,
451
+ name: def.name,
452
+ stepKind: def.stepKind,
453
+ location: def.location,
454
+ declarationRange: def.declarationRange,
455
+ executionConfig: { ...def.executionConfig, ...nodeToAdd.executionConfig },
456
+ properties: { ...def.properties, ...nodeToAdd.properties },
457
+ specs: [...(def.specs || []), ...(nodeToAdd.specs || [])],
458
+ ecosystemConfig: def.ecosystemConfig || nodeToAdd.ecosystemConfig,
459
+ };
460
+ }
258
461
  }
462
+ const usageLoc = usageNode ? (0, mapper_1.getSourceRange)(ctx.sourceFile, usageNode) : undefined;
463
+ stepInvocations.push({
464
+ id: nodeToAdd.id,
465
+ name: nodeToAdd.name,
466
+ location: nodeToAdd.location,
467
+ usageLocation: usageLoc,
468
+ });
259
469
  // Check if already in nodes
260
470
  const existing = nodes.find(n => n.id === nodeToAdd.id);
261
471
  if (!existing) {
@@ -269,29 +479,41 @@ function parseWorkflowChain(outerCall, rootFlow, ctx) {
269
479
  }
270
480
  }
271
481
  function appendSubflow(subflow) {
272
- if (subflow.nodes.length === 0)
482
+ const subUnresolved = subflow.unresolved || [];
483
+ if (subflow.nodes.length === 0 && subUnresolved.length === 0)
273
484
  return;
274
485
  for (const n of subflow.nodes) {
486
+ stepInvocations.push({
487
+ id: n.id,
488
+ name: n.name,
489
+ location: n.location,
490
+ });
275
491
  if (!nodes.some(existing => existing.id === n.id)) {
276
492
  nodes.push(n);
277
493
  }
278
494
  }
495
+ for (const u of subUnresolved) {
496
+ if (!unresolved.some(existing => existing.id === u.id)) {
497
+ unresolved.push(u);
498
+ }
499
+ }
279
500
  for (const e of subflow.edges) {
280
501
  if (!edges.some(existing => existing.id === e.id)) {
281
502
  edges.push(e);
282
503
  }
283
504
  }
284
- const entryId = subflow.nodes[0].id;
285
- const exitId = subflow.nodes[subflow.nodes.length - 1].id;
505
+ const { entryIds, exitIds } = resolveSubflowEntryAndExitIds(subflow);
286
506
  for (const headId of currentHeadIds) {
287
- edges.push({
288
- id: `edge_${headId}_to_${entryId}_${edges.length}`,
289
- from: headId,
290
- to: entryId,
291
- type: 'sequential',
292
- });
507
+ for (const entryId of entryIds) {
508
+ edges.push({
509
+ id: `edge_${headId}_to_${entryId}_${edges.length}`,
510
+ from: headId,
511
+ to: entryId,
512
+ type: 'sequential',
513
+ });
514
+ }
293
515
  }
294
- currentHeadIds = [exitId];
516
+ currentHeadIds = exitIds;
295
517
  }
296
518
  function connect(from, to, type = 'sequential', label) {
297
519
  for (const id of new Set(from))
@@ -311,9 +533,23 @@ function parseWorkflowChain(outerCall, rootFlow, ctx) {
311
533
  }
312
534
  // Expand combinators before step detection: their arguments are graph fragments,
313
535
  // and options objects are metadata rather than executable steps.
314
- function appendExpression(expr, resolving = new Set()) {
315
- if (typescript_1.default.isParenthesizedExpression(expr))
316
- return appendExpression(expr.expression, resolving);
536
+ function appendExpression(rawExpr, resolving = new Set()) {
537
+ const expr = unwrapTransparent(rawExpr);
538
+ const exprRange = (0, mapper_1.getSourceRange)(ctx.sourceFile, rawExpr);
539
+ if (typescript_1.default.isSpreadElement(expr)) {
540
+ const subflow = resolveExpandableExpression(expr.expression, ctx, exprRange, resolving, false);
541
+ if (subflow) {
542
+ appendSubflow(subflow);
543
+ return;
544
+ }
545
+ }
546
+ if (typescript_1.default.isPropertyAccessExpression(expr) && expr.name.text === 'steps') {
547
+ const subflow = resolveExpandableExpression(expr.expression, ctx, exprRange, resolving, false);
548
+ if (subflow) {
549
+ appendSubflow(subflow);
550
+ return;
551
+ }
552
+ }
317
553
  if (typescript_1.default.isIdentifier(expr)) {
318
554
  const definition = findCombinatorDefinition(expr.text);
319
555
  if (definition && !resolving.has(expr.text)) {
@@ -324,6 +560,11 @@ function parseWorkflowChain(outerCall, rootFlow, ctx) {
324
560
  appendSubflow(ctx.flowDefinitions.get(expr.text));
325
561
  return;
326
562
  }
563
+ const subflow = resolveExpandableExpression(expr, ctx, exprRange, resolving, false);
564
+ if (subflow) {
565
+ appendSubflow(subflow);
566
+ return;
567
+ }
327
568
  }
328
569
  if (typescript_1.default.isArrayLiteralExpression(expr)) {
329
570
  for (const child of expr.elements)
@@ -352,6 +593,25 @@ function parseWorkflowChain(outerCall, rootFlow, ctx) {
352
593
  connect(currentHeadIds, fork);
353
594
  const exits = [];
354
595
  const alternatives = [];
596
+ const pushParallelChild = (child) => {
597
+ const unwrappedChild = unwrapTransparent(child);
598
+ if (typescript_1.default.isSpreadElement(unwrappedChild)) {
599
+ const spreadSubflow = resolveExpandableExpression(unwrappedChild.expression, ctx, (0, mapper_1.getSourceRange)(ctx.sourceFile, unwrappedChild), resolving, false);
600
+ if (spreadSubflow) {
601
+ const onlySequential = spreadSubflow.edges.every(e => e.type === 'sequential');
602
+ if (onlySequential && spreadSubflow.nodes.length > 0 && !spreadSubflow.unresolved?.length) {
603
+ for (const stepNode of spreadSubflow.nodes) {
604
+ alternatives.push({ subflow: { nodes: [stepNode], edges: [] } });
605
+ }
606
+ }
607
+ else {
608
+ alternatives.push({ subflow: spreadSubflow });
609
+ }
610
+ return;
611
+ }
612
+ }
613
+ alternatives.push({ expression: child });
614
+ };
355
615
  if (kind === 'branch') {
356
616
  const mapIndex = expr.arguments[0] && typescript_1.default.isObjectLiteralExpression(expr.arguments[0]) ? 0 : 1;
357
617
  const map = expr.arguments[mapIndex];
@@ -387,13 +647,18 @@ function parseWorkflowChain(outerCall, rootFlow, ctx) {
387
647
  if (typescript_1.default.isObjectLiteralExpression(arg))
388
648
  continue;
389
649
  for (const child of typescript_1.default.isArrayLiteralExpression(arg) ? arg.elements : [arg])
390
- alternatives.push({ expression: child });
650
+ pushParallelChild(child);
391
651
  }
392
652
  }
393
653
  for (const alternative of alternatives) {
394
654
  currentHeadIds = [fork];
395
655
  const edgeStart = edges.length;
396
- appendExpression(alternative.expression, resolving);
656
+ if (alternative.subflow) {
657
+ appendSubflow(alternative.subflow);
658
+ }
659
+ else if (alternative.expression) {
660
+ appendExpression(alternative.expression, resolving);
661
+ }
397
662
  for (const edge of edges.slice(edgeStart))
398
663
  if (edge.from === fork) {
399
664
  edge.type = kind === 'branch' || kind === 'when' ? 'branch' : 'parallel';
@@ -413,10 +678,22 @@ function parseWorkflowChain(outerCall, rootFlow, ctx) {
413
678
  }
414
679
  return;
415
680
  }
681
+ const resolvedCall = resolveExpandableExpression(expr, ctx, exprRange, resolving, false);
682
+ if (resolvedCall) {
683
+ appendSubflow(resolvedCall);
684
+ return;
685
+ }
686
+ }
687
+ if (typescript_1.default.isPropertyAccessExpression(expr)) {
688
+ const resolvedProp = resolveExpandableExpression(expr, ctx, exprRange, resolving, false);
689
+ if (resolvedProp) {
690
+ appendSubflow(resolvedProp);
691
+ return;
692
+ }
416
693
  }
417
694
  const detected = (0, step_detector_1.detectStepFromExpression)(expr, ctx.sourceFile);
418
695
  if (detected) {
419
- const id = addNode(detected);
696
+ const id = addNode(detected, expr);
420
697
  connect(currentHeadIds, id);
421
698
  currentHeadIds = [id];
422
699
  }
@@ -440,9 +717,8 @@ function parseWorkflowChain(outerCall, rootFlow, ctx) {
440
717
  visit(ctx.sourceFile);
441
718
  return result;
442
719
  }
443
- for (const arg of rootFlow.call.arguments) {
444
- if (!typescript_1.default.isStringLiteral(arg) && !typescript_1.default.isNoSubstitutionTemplateLiteral(arg) && !typescript_1.default.isObjectLiteralExpression(arg))
445
- appendExpression(arg);
720
+ for (const arg of initialExpressions) {
721
+ appendExpression(arg);
446
722
  }
447
723
  // 2. Process chained methods (.then, .parallel, .branch, .fallback, .compensate)
448
724
  for (const item of chain) {
@@ -468,23 +744,24 @@ function parseWorkflowChain(outerCall, rootFlow, ctx) {
468
744
  if (!edges.some(existing => existing.id === e.id))
469
745
  edges.push(e);
470
746
  }
471
- const entryId = sub.nodes[0].id;
472
- const exitId = sub.nodes[sub.nodes.length - 1].id;
747
+ const { entryIds, exitIds } = resolveSubflowEntryAndExitIds(sub);
473
748
  for (const headId of currentHeadIds) {
474
- edges.push({
475
- id: `edge_${headId}_to_${entryId}_parallel`,
476
- from: headId,
477
- to: entryId,
478
- type: 'parallel',
479
- });
749
+ for (const entryId of entryIds) {
750
+ edges.push({
751
+ id: `edge_${headId}_to_${entryId}_parallel`,
752
+ from: headId,
753
+ to: entryId,
754
+ type: 'parallel',
755
+ });
756
+ }
480
757
  }
481
- nextHeadIds.push(exitId);
758
+ nextHeadIds.push(...exitIds);
482
759
  }
483
760
  continue;
484
761
  }
485
762
  const detected = (0, step_detector_1.detectStepFromExpression)(el, ctx.sourceFile);
486
763
  if (detected) {
487
- const nextId = addNode(detected);
764
+ const nextId = addNode(detected, el);
488
765
  nextHeadIds.push(nextId);
489
766
  for (const headId of currentHeadIds) {
490
767
  edges.push({
@@ -510,7 +787,7 @@ function parseWorkflowChain(outerCall, rootFlow, ctx) {
510
787
  if (trueArg) {
511
788
  const detected = (0, step_detector_1.detectStepFromExpression)(trueArg, ctx.sourceFile);
512
789
  if (detected) {
513
- const trueId = addNode(detected);
790
+ const trueId = addNode(detected, trueArg);
514
791
  nextHeadIds.push(trueId);
515
792
  for (const headId of currentHeadIds) {
516
793
  edges.push({
@@ -526,7 +803,7 @@ function parseWorkflowChain(outerCall, rootFlow, ctx) {
526
803
  if (falseArg) {
527
804
  const detected = (0, step_detector_1.detectStepFromExpression)(falseArg, ctx.sourceFile);
528
805
  if (detected) {
529
- const falseId = addNode(detected);
806
+ const falseId = addNode(detected, falseArg);
530
807
  nextHeadIds.push(falseId);
531
808
  for (const headId of currentHeadIds) {
532
809
  edges.push({
@@ -548,7 +825,7 @@ function parseWorkflowChain(outerCall, rootFlow, ctx) {
548
825
  if (arg) {
549
826
  const detected = (0, step_detector_1.detectStepFromExpression)(arg, ctx.sourceFile);
550
827
  if (detected) {
551
- const fallbackId = addNode(detected);
828
+ const fallbackId = addNode(detected, arg);
552
829
  for (const headId of currentHeadIds) {
553
830
  edges.push({
554
831
  id: `edge_${headId}_to_${fallbackId}_fallback`,
@@ -566,7 +843,7 @@ function parseWorkflowChain(outerCall, rootFlow, ctx) {
566
843
  if (arg) {
567
844
  const detected = (0, step_detector_1.detectStepFromExpression)(arg, ctx.sourceFile);
568
845
  if (detected) {
569
- const compId = addNode(detected);
846
+ const compId = addNode(detected, arg);
570
847
  for (const headId of currentHeadIds) {
571
848
  edges.push({
572
849
  id: `edge_${headId}_to_${compId}_comp`,
@@ -579,6 +856,30 @@ function parseWorkflowChain(outerCall, rootFlow, ctx) {
579
856
  }
580
857
  }
581
858
  }
859
+ // Process step-level compensations (e.g. step.compensate(stepRefund))
860
+ for (const node of [...nodes]) {
861
+ if (node.executionConfig?.hasCompensation && node.properties?.compensationStep) {
862
+ const compTargetName = node.properties.compensationStep;
863
+ const hasEdge = edges.some(e => e.from === node.id && e.type === 'compensation');
864
+ if (!hasEdge) {
865
+ let compNode = nodes.find(n => n.name === compTargetName || n.id === compTargetName);
866
+ if (!compNode && ctx.stepDefinitions.has(compTargetName)) {
867
+ compNode = ctx.stepDefinitions.get(compTargetName);
868
+ if (compNode && !nodes.some(n => n.id === compNode.id)) {
869
+ nodes.push(compNode);
870
+ }
871
+ }
872
+ if (compNode) {
873
+ edges.push({
874
+ id: `edge_${node.id}_to_${compNode.id}_comp`,
875
+ from: node.id,
876
+ to: compNode.id,
877
+ type: 'compensation',
878
+ });
879
+ }
880
+ }
881
+ }
882
+ }
582
883
  const routeEdges = new Map();
583
884
  const normalizedEdges = [];
584
885
  for (const edge of edges) {
@@ -597,11 +898,12 @@ function parseWorkflowChain(outerCall, rootFlow, ctx) {
597
898
  normalizedEdges.push(normalized);
598
899
  }
599
900
  }
600
- const diagnostics = runDiagnostics(nodes, normalizedEdges);
901
+ const diagnostics = runDiagnostics(nodes, normalizedEdges, workflowName, properties);
601
902
  return {
602
903
  uri: ctx.uri,
603
904
  documentVersion: ctx.documentVersion,
604
- workflowName: rootFlow.name,
905
+ workflowName,
906
+ ...(workflowLocation ? { location: workflowLocation } : {}),
605
907
  properties,
606
908
  nodes,
607
909
  edges: normalizedEdges,
@@ -609,21 +911,252 @@ function parseWorkflowChain(outerCall, rootFlow, ctx) {
609
911
  diagnostics,
610
912
  };
611
913
  }
612
- function runDiagnostics(nodes, edges) {
914
+ function resolveExpressionToSingleStep(expr, ctx) {
915
+ const detected = (0, step_detector_1.detectStepFromExpression)(expr, ctx.sourceFile);
916
+ if (detected?.kind === 'node') {
917
+ return { nodes: [detected.node], edges: [] };
918
+ }
919
+ return null;
920
+ }
921
+ function resolveExportedTargetToSubflow(targetCtx, target, callSiteRange, callerCtx, resolving) {
922
+ if (target.kind === 'expression') {
923
+ const subflow = resolveExpandableExpression(target.expr, targetCtx, (0, mapper_1.getSourceRange)(targetCtx.sourceFile, target.expr), resolving, true);
924
+ return subflow ? remapSubflowToCallSite(subflow, callSiteRange, targetCtx, callerCtx) : null;
925
+ }
926
+ if (target.kind === 'declaration') {
927
+ if (typescript_1.default.isVariableDeclaration(target.node) && target.node.initializer) {
928
+ const subflow = resolveExpandableExpression(target.node.initializer, targetCtx, (0, mapper_1.getSourceRange)(targetCtx.sourceFile, target.node.initializer), resolving, true);
929
+ return subflow ? remapSubflowToCallSite(subflow, callSiteRange, targetCtx, callerCtx) : null;
930
+ }
931
+ }
932
+ return null;
933
+ }
934
+ function resolveFunctionCallToSubflow(fn, targetCtx, callSiteRange, callerCtx) {
935
+ const { session } = callerCtx;
936
+ if (session.depth >= MAX_RESOLVE_DEPTH)
937
+ return null;
938
+ const key = `fn:${targetCtx.filePath}:${fn.pos}`;
939
+ if (session.resolvingKeys.has(key))
940
+ return null;
941
+ session.resolvingKeys.add(key);
942
+ session.depth += 1;
943
+ try {
944
+ const returns = (0, module_resolver_1.extractFunctionReturnExpressions)(fn);
945
+ for (let i = returns.length - 1; i >= 0; i--) {
946
+ const retExpr = returns[i];
947
+ const retRange = (0, mapper_1.getSourceRange)(targetCtx.sourceFile, retExpr);
948
+ const subflow = resolveExpandableExpression(retExpr, targetCtx, retRange, new Set(), true);
949
+ if (subflow && (subflow.nodes.length > 0 || (subflow.unresolved?.length ?? 0) > 0)) {
950
+ return remapSubflowToCallSite(subflow, callSiteRange, targetCtx, callerCtx);
951
+ }
952
+ }
953
+ return null;
954
+ }
955
+ finally {
956
+ session.depth -= 1;
957
+ session.resolvingKeys.delete(key);
958
+ }
959
+ }
960
+ function resolveExpandableExpression(rawExpr, ctx, callSiteRange, resolving, allowSingleStep = false) {
961
+ const expr = unwrapTransparent(rawExpr);
962
+ if (typescript_1.default.isPropertyAccessExpression(expr) && expr.name.text === 'steps') {
963
+ return resolveExpandableExpression(expr.expression, ctx, callSiteRange, resolving, allowSingleStep);
964
+ }
965
+ if (typescript_1.default.isArrayLiteralExpression(expr)) {
966
+ const doc = buildWorkflowDocument('array', Array.from(expr.elements), [], ctx);
967
+ return doc.nodes.length > 0 || doc.unresolved.length > 0
968
+ ? { nodes: doc.nodes, edges: doc.edges, unresolved: doc.unresolved }
969
+ : null;
970
+ }
971
+ if (typescript_1.default.isIdentifier(expr)) {
972
+ if (ctx.flowDefinitions.has(expr.text)) {
973
+ return ctx.flowDefinitions.get(expr.text);
974
+ }
975
+ const localDecl = (0, module_resolver_1.findLexicalDeclaration)(expr.text, expr, ctx.metadata.declarations);
976
+ if (localDecl) {
977
+ if (typescript_1.default.isVariableDeclaration(localDecl) && localDecl.initializer) {
978
+ const key = `var:${ctx.filePath}:${localDecl.pos}`;
979
+ if (resolving.has(key))
980
+ return null;
981
+ if (!allowSingleStep &&
982
+ (0, step_detector_1.detectStepFromExpression)(localDecl.initializer, ctx.sourceFile)?.kind === 'node') {
983
+ return null;
984
+ }
985
+ const nextResolving = new Set(resolving);
986
+ nextResolving.add(key);
987
+ return resolveExpandableExpression(localDecl.initializer, ctx, callSiteRange, nextResolving, allowSingleStep);
988
+ }
989
+ return null;
990
+ }
991
+ const binding = ctx.metadata.imports.get(expr.text);
992
+ if (binding && !binding.isNamespace && ctx.session.depth < MAX_RESOLVE_DEPTH) {
993
+ const importPath = (0, module_resolver_1.resolveRelativeImportPath)(ctx.filePath, binding.specifier);
994
+ const targetCtx = importPath ? getOrLoadFileContext(importPath, ctx.session) : null;
995
+ if (targetCtx) {
996
+ const resolved = resolveExportTarget(targetCtx, binding.importedName, ctx.session);
997
+ if (resolved) {
998
+ ctx.session.depth += 1;
999
+ try {
1000
+ return resolveExportedTargetToSubflow(resolved.ctx, resolved.target, callSiteRange, ctx, new Set());
1001
+ }
1002
+ finally {
1003
+ ctx.session.depth -= 1;
1004
+ }
1005
+ }
1006
+ }
1007
+ }
1008
+ return allowSingleStep ? resolveExpressionToSingleStep(expr, ctx) : null;
1009
+ }
1010
+ if (typescript_1.default.isPropertyAccessExpression(expr)) {
1011
+ const base = unwrapTransparent(expr.expression);
1012
+ if (typescript_1.default.isIdentifier(base)) {
1013
+ const binding = ctx.metadata.imports.get(base.text);
1014
+ if (binding?.isNamespace && ctx.session.depth < MAX_RESOLVE_DEPTH) {
1015
+ const importPath = (0, module_resolver_1.resolveRelativeImportPath)(ctx.filePath, binding.specifier);
1016
+ const targetCtx = importPath ? getOrLoadFileContext(importPath, ctx.session) : null;
1017
+ if (targetCtx) {
1018
+ const resolved = resolveExportTarget(targetCtx, expr.name.text, ctx.session);
1019
+ if (resolved) {
1020
+ ctx.session.depth += 1;
1021
+ try {
1022
+ return resolveExportedTargetToSubflow(resolved.ctx, resolved.target, callSiteRange, ctx, new Set());
1023
+ }
1024
+ finally {
1025
+ ctx.session.depth -= 1;
1026
+ }
1027
+ }
1028
+ }
1029
+ }
1030
+ }
1031
+ return null;
1032
+ }
1033
+ if (typescript_1.default.isCallExpression(expr)) {
1034
+ const rootFlow = findRootFlowCall(expr, ctx.sourceFile);
1035
+ if (rootFlow) {
1036
+ const doc = parseWorkflowChain(expr, rootFlow, ctx);
1037
+ return doc ? { nodes: doc.nodes, edges: doc.edges, unresolved: doc.unresolved } : null;
1038
+ }
1039
+ // Unwrap chained flow configuration or composition calls onto a resolved base flow.
1040
+ if (typescript_1.default.isPropertyAccessExpression(expr.expression)) {
1041
+ const methodChain = [];
1042
+ let receiver = expr;
1043
+ while (typescript_1.default.isCallExpression(receiver) && typescript_1.default.isPropertyAccessExpression(receiver.expression)) {
1044
+ const methodName = receiver.expression.name.text;
1045
+ if (!FLOW_CHAIN_METHODS.has(methodName) && !FLOW_CONFIG_METHODS.has(methodName)) {
1046
+ break;
1047
+ }
1048
+ methodChain.unshift({
1049
+ methodName,
1050
+ args: Array.from(receiver.arguments),
1051
+ callExpr: receiver,
1052
+ });
1053
+ receiver = receiver.expression.expression;
1054
+ }
1055
+ if (methodChain.length > 0 && receiver !== expr) {
1056
+ const baseSubflow = resolveExpandableExpression(receiver, ctx, callSiteRange, resolving, allowSingleStep);
1057
+ if (baseSubflow) {
1058
+ const hasWorkflowChain = methodChain.some(m => FLOW_CHAIN_METHODS.has(m.methodName));
1059
+ if (!hasWorkflowChain)
1060
+ return baseSubflow;
1061
+ const doc = buildWorkflowDocument('subflow', [], methodChain, ctx, baseSubflow);
1062
+ return { nodes: doc.nodes, edges: doc.edges, unresolved: doc.unresolved };
1063
+ }
1064
+ }
1065
+ }
1066
+ const callee = unwrapTransparent(expr.expression);
1067
+ const calleeKind = typescript_1.default.isIdentifier(callee)
1068
+ ? callee.text
1069
+ : typescript_1.default.isPropertyAccessExpression(callee) &&
1070
+ ['Step', 'Func', 'Chain'].includes(callee.expression.getText(ctx.sourceFile))
1071
+ ? callee.name.text
1072
+ : '';
1073
+ if (['parallel', 'all', 'race', 'allSettled', 'branch', 'when', 'map'].includes(calleeKind)) {
1074
+ const doc = buildWorkflowDocument(calleeKind, [expr], [], ctx);
1075
+ return { nodes: doc.nodes, edges: doc.edges, unresolved: doc.unresolved };
1076
+ }
1077
+ // Resolve call to a local or imported factory function.
1078
+ if (typescript_1.default.isIdentifier(callee)) {
1079
+ const localDecl = (0, module_resolver_1.findLexicalDeclaration)(callee.text, expr, ctx.metadata.declarations);
1080
+ if (localDecl) {
1081
+ const fn = resolveFunctionLikeFromDecl(localDecl);
1082
+ if (fn) {
1083
+ return resolveFunctionCallToSubflow(fn, ctx, callSiteRange, ctx);
1084
+ }
1085
+ }
1086
+ const binding = ctx.metadata.imports.get(callee.text);
1087
+ if (binding && !binding.isNamespace && ctx.session.depth < MAX_RESOLVE_DEPTH) {
1088
+ const importPath = (0, module_resolver_1.resolveRelativeImportPath)(ctx.filePath, binding.specifier);
1089
+ const targetCtx = importPath ? getOrLoadFileContext(importPath, ctx.session) : null;
1090
+ if (targetCtx) {
1091
+ const resolved = resolveExportTarget(targetCtx, binding.importedName, ctx.session);
1092
+ if (resolved) {
1093
+ const fn = resolved.target.kind === 'declaration'
1094
+ ? resolveFunctionLikeFromDecl(resolved.target.node)
1095
+ : resolved.target.kind === 'expression'
1096
+ ? resolveFunctionLikeFromDecl(resolved.target.expr)
1097
+ : null;
1098
+ if (fn) {
1099
+ return resolveFunctionCallToSubflow(fn, resolved.ctx, callSiteRange, ctx);
1100
+ }
1101
+ }
1102
+ }
1103
+ }
1104
+ }
1105
+ else if (typescript_1.default.isPropertyAccessExpression(callee)) {
1106
+ const obj = unwrapTransparent(callee.expression);
1107
+ if (typescript_1.default.isIdentifier(obj)) {
1108
+ const binding = ctx.metadata.imports.get(obj.text);
1109
+ if (binding?.isNamespace && ctx.session.depth < MAX_RESOLVE_DEPTH) {
1110
+ const importPath = (0, module_resolver_1.resolveRelativeImportPath)(ctx.filePath, binding.specifier);
1111
+ const targetCtx = importPath ? getOrLoadFileContext(importPath, ctx.session) : null;
1112
+ if (targetCtx) {
1113
+ const resolved = resolveExportTarget(targetCtx, callee.name.text, ctx.session);
1114
+ if (resolved) {
1115
+ const fn = resolved.target.kind === 'declaration'
1116
+ ? resolveFunctionLikeFromDecl(resolved.target.node)
1117
+ : resolved.target.kind === 'expression'
1118
+ ? resolveFunctionLikeFromDecl(resolved.target.expr)
1119
+ : null;
1120
+ if (fn) {
1121
+ return resolveFunctionCallToSubflow(fn, resolved.ctx, callSiteRange, ctx);
1122
+ }
1123
+ }
1124
+ }
1125
+ }
1126
+ }
1127
+ }
1128
+ }
1129
+ return allowSingleStep ? resolveExpressionToSingleStep(expr, ctx) : null;
1130
+ }
1131
+ function runDiagnostics(nodes, edges, workflowName, properties) {
613
1132
  const diagnostics = [];
614
- // 1. Detect duplicate node IDs
615
- const idCounts = new Map();
616
- for (const node of nodes) {
617
- idCounts.set(node.id, (idCounts.get(node.id) || 0) + 1);
1133
+ // Helper to identify synthetic combinator hubs
1134
+ function isSyntheticNode(node) {
1135
+ return (node.name.endsWith(' fork') ||
1136
+ node.name.endsWith(' join') ||
1137
+ node.name === 'inline action' ||
1138
+ node.id.includes('_fork_') ||
1139
+ node.id.includes('_join_') ||
1140
+ ['parallel', 'all', 'race', 'allSettled', 'branch', 'when', 'map'].includes(node.name));
618
1141
  }
619
- for (const node of nodes) {
620
- if ((idCounts.get(node.id) || 0) > 1) {
621
- diagnostics.push({
622
- code: 'SIGLO_DUPLICATE_STEP_ID',
623
- message: `Duplicate step ID detected: "${node.id}"`,
624
- severity: 'error',
625
- range: node.location,
626
- });
1142
+ // 1. Detect duplicate step IDs
1143
+ const userNodes = nodes.filter(n => !isSyntheticNode(n));
1144
+ const nameToNodes = new Map();
1145
+ for (const node of userNodes) {
1146
+ if (!nameToNodes.has(node.name))
1147
+ nameToNodes.set(node.name, []);
1148
+ nameToNodes.get(node.name).push(node);
1149
+ }
1150
+ for (const [name, matchedNodes] of nameToNodes.entries()) {
1151
+ if (matchedNodes.length > 1) {
1152
+ for (const node of matchedNodes) {
1153
+ diagnostics.push({
1154
+ code: 'SIGLO_DUPLICATE_STEP_ID',
1155
+ message: `Duplicate step ID detected: "${name}"`,
1156
+ severity: 'error',
1157
+ range: node.location,
1158
+ });
1159
+ }
627
1160
  }
628
1161
  }
629
1162
  // 2. Detect cycles in graph edges
@@ -662,7 +1195,7 @@ function runDiagnostics(nodes, edges) {
662
1195
  diagnostics.push({
663
1196
  code: 'SIGLO_STATIC_CYCLE',
664
1197
  message: `Cyclic workflow dependency detected involving step "${node.name}"`,
665
- severity: 'error',
1198
+ severity: 'warning',
666
1199
  range: node.location,
667
1200
  });
668
1201
  }
@@ -670,9 +1203,13 @@ function runDiagnostics(nodes, edges) {
670
1203
  }
671
1204
  // 3. Detect side-effect steps lacking compensation in sagas
672
1205
  const hasAnyCompensationEdge = edges.some(e => e.type === 'compensation');
673
- if (hasAnyCompensationEdge) {
1206
+ const isSaga = hasAnyCompensationEdge || properties?.isSaga === 'true' || properties?.saga === 'true';
1207
+ if (isSaga) {
674
1208
  for (const node of nodes) {
675
- if ((node.stepKind === 'http' || node.stepKind === 'crypto') && !node.executionConfig?.hasCompensation) {
1209
+ const isSideEffect = node.stepKind === 'http' ||
1210
+ node.stepKind === 'crypto' ||
1211
+ (node.stepKind === 'notification' && node.properties?.autoCompensate !== 'true');
1212
+ if (isSideEffect && !node.executionConfig?.hasCompensation) {
676
1213
  const hasOutCompensation = edges.some(e => e.from === node.id && e.type === 'compensation');
677
1214
  if (!hasOutCompensation) {
678
1215
  diagnostics.push({
@@ -686,6 +1223,45 @@ function runDiagnostics(nodes, edges) {
686
1223
  }
687
1224
  }
688
1225
  }
1226
+ // 4. Detect unhandled error branches in durable workflows
1227
+ const durableNodes = nodes.filter(n => n.name.startsWith('wait:') ||
1228
+ n.name.startsWith('waitForEvent:') ||
1229
+ n.properties?.operation === 'wait' ||
1230
+ n.properties?.operation === 'waitForEvent' ||
1231
+ n.properties?.operation === 'Step.wait' ||
1232
+ n.properties?.operation === 'Step.waitForEvent' ||
1233
+ n.properties?.operation?.toLowerCase().includes('wait'));
1234
+ const isDurableWorkflow = durableNodes.length > 0 || properties?.durable === 'true';
1235
+ if (isDurableWorkflow) {
1236
+ // Check for branch forks lacking a default or fallback route
1237
+ const branchForks = nodes.filter(n => n.name === 'branch fork' || n.properties?.operation === 'branch');
1238
+ for (const fork of branchForks) {
1239
+ const outEdges = edges.filter(e => e.from === fork.id);
1240
+ const hasDefault = outEdges.some(e => e.label === 'default' || e.label?.includes('default') || e.type === 'fallback');
1241
+ if (!hasDefault) {
1242
+ diagnostics.push({
1243
+ code: 'SIGLO_UNHANDLED_ERROR_BRANCH',
1244
+ message: `Durable workflow branch "${fork.name}" has unhandled error/default branch`,
1245
+ severity: 'warning',
1246
+ range: fork.location,
1247
+ });
1248
+ }
1249
+ }
1250
+ // Check for when forks lacking an else / fallback route
1251
+ const whenForks = nodes.filter(n => n.name === 'when fork' || n.properties?.operation === 'when');
1252
+ for (const fork of whenForks) {
1253
+ const outEdges = edges.filter(e => e.from === fork.id);
1254
+ const hasElse = outEdges.some(e => e.label === 'else' || e.label?.includes('else') || e.type === 'fallback');
1255
+ if (!hasElse) {
1256
+ diagnostics.push({
1257
+ code: 'SIGLO_UNHANDLED_ERROR_BRANCH',
1258
+ message: `Durable workflow conditional "${fork.name}" has unhandled alternate/error branch`,
1259
+ severity: 'warning',
1260
+ range: fork.location,
1261
+ });
1262
+ }
1263
+ }
1264
+ }
689
1265
  return diagnostics;
690
1266
  }
691
1267
  function applyFlowProperty(properties, method, args, sourceFile) {
@@ -703,6 +1279,10 @@ function applyFlowProperty(properties, method, args, sourceFile) {
703
1279
  properties.workflowVersion = value;
704
1280
  else if (method === 'monitor')
705
1281
  properties.monitor = value;
1282
+ else if (method === 'durable')
1283
+ properties.durable = 'true';
1284
+ else if (method === 'saga')
1285
+ properties.isSaga = 'true';
706
1286
  else if (method === 'networkPolicy') {
707
1287
  for (const key of Object.keys(properties))
708
1288
  if (key.startsWith('network.'))