effect-analyzer 0.1.0 → 0.1.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.
- package/dist/{analyze-a8PswlPG.d.cts → analyze-BXCwo5MU.d.cts} +2 -0
- package/dist/{analyze-a8PswlPG.d.ts → analyze-BXCwo5MU.d.ts} +2 -0
- package/dist/cli.js +76 -76
- package/dist/effect-workflow.cjs +3 -3
- package/dist/effect-workflow.cjs.map +1 -1
- package/dist/effect-workflow.d.cts +2 -2
- package/dist/effect-workflow.d.ts +2 -2
- package/dist/effect-workflow.js +3 -3
- package/dist/effect-workflow.js.map +1 -1
- package/dist/index.cjs +79 -74
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +80 -75
- package/dist/index.js.map +1 -1
- package/dist/lsp/server.js +1367 -1187
- package/package.json +37 -18
package/dist/cli.js
CHANGED
|
@@ -1,62 +1,62 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{resolve as ze,sep as jl,join as Nt,dirname as Sr,extname as Bl}from"path";import{watch as ql,existsSync as zl}from"fs";import*as pe from"fs/promises";import{Project as en}from"ts-morph";import{spawn as _l}from"child_process";import{fileURLToPath as Hl}from"url";import{Effect as k,Console as D,Exit as Ce,Option as tn}from"effect";import{Effect as X,Option as Pt}from"effect";import{Option as B}from"effect";var Se=class extends Error{code;location;constructor(t,r,s){super(r),this.code=t,this.location=s,this.name="AnalysisError"}};var Er=e=>e.type==="unknown";var P=e=>{switch(e.type){case"program":return B.some(e.children);case"generator":return B.some(e.yields.map(t=>t.effect));case"pipe":return B.some([e.initial,...e.transformations]);case"parallel":case"race":return B.some([...e.children]);case"error-handler":return B.some(e.handler?[e.source,e.handler]:[e.source]);case"retry":{let t=e,r=[t.source,t.scheduleNode].filter(s=>s!==void 0);return r.length>0?B.some(r):B.none()}case"timeout":{let t=e.source;return t?B.some([t]):B.none()}case"resource":return B.some(e.use?[e.acquire,e.release,e.use]:[e.acquire,e.release]);case"conditional":return B.some(e.onFalse?[e.onTrue,e.onFalse]:[e.onTrue]);case"loop":return B.some([e.body]);case"cause":return e.children&&e.children.length>0?B.some(e.children):B.none();case"exit":case"schedule":case"match":return B.none();case"transform":return e.source?B.some([e.source]):B.none();case"layer":return B.some([...e.operations]);case"stream":return B.some([e.source]);case"channel":return e.source?B.some([e.source]):B.none();case"sink":return e.source?B.some([e.source]):B.none();case"concurrency-primitive":return e.source?B.some([e.source]):B.none();case"fiber":return e.fiberSource?B.some([e.fiberSource]):B.none();case"interruption":{let t=[];return e.source&&t.push(e.source),e.handler&&t.push(e.handler),t.length>0?B.some(t):B.none()}case"effect":return e.callbackBody&&e.callbackBody.length>0?B.some([...e.callbackBody]):B.none();case"decision":return B.some([...e.onTrue,...e.onFalse??[]]);case"switch":return B.some(e.cases.flatMap(t=>[...t.body]));case"try-catch":return B.some([...e.tryBody,...e.catchBody??[],...e.finallyBody??[]]);case"terminal":return e.value?B.some([...e.value]):B.none();case"opaque":return B.none();default:return B.none()}};import{Effect as Re}from"effect";import{createRequire as Bi}from"module";var rn=null,br=new Map,w=()=>{if(!rn)try{rn=Bi(import.meta.url)("ts-morph")}catch{throw new Error("ts-morph is required but not installed. Please install it as a peer dependency: npm install ts-morph")}return rn},Nr=e=>{let t=e??"__default__",r=br.get(t);if(r)return r;let{Project:s}=w(),n={};e&&(n.tsConfigFilePath=e);let i=new s(n);return br.set(t,i),i};var Cr=(e,t="temp.ts")=>{let{Project:r}=w();return new r({useInMemoryFileSystem:!0,compilerOptions:{strict:!0,esModuleInterop:!0}}).createSourceFile(t,e)};import{Option as vr}from"effect";var qi=/Effect(?:\.Effect)?<([^,]+),\s*([^,]+),\s*([^>]+)>/,zi=/Effect(?:\.Effect)?<([^,>]+),\s*([^,>]+)>/;function on(e){let t=n=>n.replace(/import\([^)]+\)\./g,"").replace(/typeof\s+/g,"").trim().substring(0,200),r=qi.exec(e);if(r)return{successType:t(r[1]),errorType:t(r[2]),requirementsType:t(r[3]),isInferred:!1,typeConfidence:"inferred",rawTypeString:e};let s=zi.exec(e);if(s)return{successType:t(s[1]),errorType:t(s[2]),requirementsType:"never",isInferred:!1,typeConfidence:"inferred",rawTypeString:e}}var Ze=(e,t)=>{let r;try{r=e.getType()}catch{return}if(!Hi(r))return;let s=Ct(r);if(s){let[o,a,d]=s;return{successType:$e(o),errorType:$e(a),requirementsType:$e(d),isInferred:!0,typeConfidence:"declared",rawTypeString:r.getText()}}let n=r.getText(),i=on(n);if(i)return i;let c=_i(e);return c||{successType:"unknown",errorType:"never",requirementsType:"never",isInferred:!1,typeConfidence:"unknown",rawTypeString:n}};function _i(e){try{if(!("getExpression"in e))return;let r=e.getExpression(),n=r.getType().getCallSignatures();if(n.length>0){let c=n[0].getReturnType(),o=Ct(c);if(o){let[l,f,u]=o;return{successType:$e(l),errorType:$e(f),requirementsType:$e(u),isInferred:!0,typeConfidence:"inferred",rawTypeString:c.getText()}}let a=c.getText(),d=on(a);if(d)return d}let i=r.getSymbol();if(!i)return;for(let c of i.getDeclarations()){let o;if("getReturnType"in c)o=c.getReturnType().getText();else if("getType"in c){let d=c.getType().getCallSignatures();if(d.length>0){let l=d[0].getReturnType(),f=Ct(l);if(f){let[u,g,p]=f;return{successType:$e(u),errorType:$e(g),requirementsType:$e(p),isInferred:!0,typeConfidence:"inferred",rawTypeString:l.getText()}}o=l.getText()}}if(o){let a=on(o);if(a)return{...a,typeConfidence:"inferred"}}}}catch{}}var Hi=e=>{let t=e.getSymbol(),r=e.getText();if(t){let n=t.getName();if(n==="Effect"||n.includes("Effect"))return!0}if(r.includes("Effect<")||r.startsWith("Effect."))return!0;let s=e.getAliasSymbol();if(s){let n=s.getName();if(n==="Effect"||n.includes("Effect"))return!0}return!1},Ct=e=>{try{let t=e.getTypeArguments?.();if(!t||t.length<3){let r=e.getAliasTypeArguments?.();return r&&r.length>=3?[r[0],r[1],r[2]]:void 0}return[t[0],t[1],t[2]]}catch{return}},$e=e=>e.getText().replace(/import\([^)]+\)\./g,"").replace(/typeof\s+/g,"").substring(0,200),wt=(e,t)=>{let r=[],s=e.getType(),n=e,i;try{i=typeof s.getTypeArguments=="function"?s.getTypeArguments():void 0}catch{i=void 0}if(!i||i.length<3){let a=e.getParent();if(a?.getKindName()==="VariableDeclaration"){let d=a,l=d.getType();l&&(s=l,n=d)}}let c=Ui(s);if(!c)return r;let o=Gi(c);for(let a of o){let d=n.getSourceFile(),{line:l,column:f}=d.getLineAndColumnAtPos(n.getStart()),u={filePath:d.getFilePath(),line:l,column:f};r.push({serviceId:a.id,serviceType:a.typeName,requiredAt:u})}return r},Ui=e=>{let t=Ct(e);if(t)return t[2]},Gi=e=>{let t=[],r=e.getText(),s=/Context<([^>]+)>/.exec(r);if(s){let n=s[1];t.push({id:wr(n),typeName:n})}if(r.includes("|")){let n=Fe(r);for(let i of n){let c=/Context<([^>]+)>/.exec(i);c&&t.push({id:wr(c[1]),typeName:c[1]})}}return r==="never"||r==="{}"?[]:t},wr=e=>{let t=/Tag<["']([^"']+)["']/.exec(e);return t?t[1]:e.split("<")[0].trim()};function Fe(e){let t=[],r="",s=0,n=null;for(let c=0;c<e.length;c++){let o=e[c];if(n){r+=o,o===n&&e[c-1]!=="\\"&&(n=null);continue}if(o==='"'||o==="'"||o==="`"){n=o,r+=o;continue}if(o==="<"||o==="("){s++,r+=o;continue}if(o===">"||o===")"){s=Math.max(0,s-1),r+=o;continue}if(o==="|"&&s===0){t.push(r.trim()),r="";continue}r+=o}let i=r.trim();return i&&t.push(i),t.filter(Boolean)}var sn=e=>e.replace(/import\([^)]+\)\./g,"").replace(/typeof\s+/g,"").trim().substring(0,200);var Vi=/Layer<([^,]+),\s*([^,]+),\s*([^>]+)>/;function Tr(e){let t=e.getType().getText(),r=Vi.exec(t);if(r)return{providedType:sn(r[1]),errorType:sn(r[2]),requiredType:sn(r[3]),rawTypeString:t}}var an={tsConfigPath:"./tsconfig.json",resolveReferences:!0,maxReferenceDepth:5,includeLocations:!0,assumeImported:!1,enableEffectWorkflow:!1,knownEffectInternalsRoot:void 0,minDiscoveryConfidence:"low",onlyExportedPrograms:!1,enableEffectFlow:!1},Ir=0,Tt=()=>{Ir=0},C=()=>`effect-${++Ir}`,kr=new WeakMap;function kt(e){let t=kr.get(e);return t===void 0&&(t=e.getText(),kr.set(e,t)),t}function $r(e){let t=new Set,r=s=>{for(let n of s){if(n.type==="effect"){let c=n.typeSignature?.errorType?.trim();if(c&&c!=="never")for(let o of Fe(c))t.add(o)}let i=vr.getOrElse(P(n),()=>[]);i.length>0&&r(i)}};return r(e),Array.from(t).sort()}function Fr(e){let t=new Map,r=s=>{for(let n of s){if(n.type==="effect"){let c=n.requiredServices;if(c)for(let o of c)t.has(o.serviceId)||t.set(o.serviceId,{name:o.serviceId,typeSignature:o.serviceType,isLayer:!1});if((n.semanticRole==="environment"||n.semanticRole==="side-effect")&&n.callee){let o=n.callee;/^[A-Z]/.test(o)&&!o.startsWith("Effect.")&&!o.startsWith("Schema.")&&!o.startsWith("Data.")&&!o.startsWith("Config.")&&!o.startsWith("Command.")&&!o.startsWith("Stream.")&&!o.startsWith("Option.")&&!o.startsWith("Either.")&&!o.startsWith("Cause.")&&!o.startsWith("Exit.")&&!t.has(o)&&t.set(o,{name:o,typeSignature:n.typeSignature?.requirementsType,isLayer:!1})}}let i=vr.getOrElse(P(n),()=>[]);i.length>0&&r(i)}};return r(e),Array.from(t.values())}var _=(e,t,r)=>{if(!r)return;let s=e.getSourceFile(),n=e.getStart(),{line:i,column:c}=s.getLineAndColumnAtPos(n),o=e.getEnd(),a=s.getLineAndColumnAtPos(o);return{filePath:t,line:i,column:c,endLine:a.line,endColumn:a.column}},_e=e=>{let t=e.getJsDocs?.();if(t&&t.length>0){let s=t[0];if(!s)return;let n=s.getComment?.();if(n){let o;if(typeof n=="string")o=n;else if(Array.isArray(n))o=n.map(d=>d.text).join(`
|
|
3
|
-
`);else return;let a=o.search(/\n\s*@/);return a!==-1&&(o=o.substring(0,a)),o.trim()||void 0}let i=s.getText(),c=/\/\*\*\s*\n?\s*\*\s*([^@]*?)(?=\n\s*\*\s*@|\*\/)/.exec(i);if(c?.[1])return c[1].replace(/\n\s*\*\s*/g," ").trim()||void 0}let r=e.getLeadingCommentRanges();if(r.length>0){let s=r[r.length-1];if(!s)return;let n=s.getText();if(n.startsWith("/**")){let i=n.replace(/^\/\*\*\s*/,"").replace(/\s*\*\/\s*$/,"").replace(/^\s*\*\s?/gm,"").trim(),c=i.search(/\n@/);return c!==-1?i.substring(0,c).trim()||void 0:i||void 0}}},
|
|
2
|
+
import{resolve as Ve,sep as Zl,join as $t,dirname as kr,extname as Yl}from"path";import{watch as Xl,existsSync as ed}from"fs";import*as ge from"fs/promises";import{Project as dn}from"ts-morph";import{spawn as td}from"child_process";import{fileURLToPath as nd}from"url";import{Effect as v,Console as D,Exit as Te,Option as un}from"effect";import{Effect as te,Option as _t}from"effect";import{Option as j}from"effect";var xe=class extends Error{code;location;constructor(t,r,s){super(r),this.code=t,this.location=s,this.name="AnalysisError"}};var Ir=e=>e.type==="unknown";var P=e=>{switch(e.type){case"program":return j.some(e.children);case"generator":return j.some(e.yields.map(t=>t.effect));case"pipe":return j.some([e.initial,...e.transformations]);case"parallel":case"race":return j.some([...e.children]);case"error-handler":return j.some(e.handler?[e.source,e.handler]:[e.source]);case"retry":{let t=e,r=[t.source,t.scheduleNode].filter(s=>s!==void 0);return r.length>0?j.some(r):j.none()}case"timeout":{let t=e.source;return t?j.some([t]):j.none()}case"resource":return j.some(e.use?[e.acquire,e.release,e.use]:[e.acquire,e.release]);case"conditional":return j.some(e.onFalse?[e.onTrue,e.onFalse]:[e.onTrue]);case"loop":return j.some([e.body]);case"cause":return e.children&&e.children.length>0?j.some(e.children):j.none();case"exit":case"schedule":case"match":return j.none();case"transform":return e.source?j.some([e.source]):j.none();case"layer":return j.some([...e.operations]);case"stream":return j.some([e.source]);case"channel":return e.source?j.some([e.source]):j.none();case"sink":return e.source?j.some([e.source]):j.none();case"concurrency-primitive":return e.source?j.some([e.source]):j.none();case"fiber":return e.fiberSource?j.some([e.fiberSource]):j.none();case"interruption":{let t=[];return e.source&&t.push(e.source),e.handler&&t.push(e.handler),t.length>0?j.some(t):j.none()}case"effect":return e.callbackBody&&e.callbackBody.length>0?j.some([...e.callbackBody]):j.none();case"decision":return j.some([...e.onTrue,...e.onFalse??[]]);case"switch":return j.some(e.cases.flatMap(t=>[...t.body]));case"try-catch":return j.some([...e.tryBody,...e.catchBody??[],...e.finallyBody??[]]);case"terminal":return e.value?j.some([...e.value]):j.none();case"opaque":return j.none();default:return j.none()}};import{Effect as Oe}from"effect";import{createRequire as Ji}from"module";var pn=null,$r=new Map,T=()=>{if(!pn)try{pn=Ji(import.meta.url)("ts-morph")}catch{throw new Error("ts-morph is required but not installed. Please install it as a peer dependency: npm install ts-morph")}return pn},Fr=e=>{let t=e??"__default__",r=$r.get(t);if(r)return r;let{Project:s}=T(),n={};e&&(n.tsConfigFilePath=e);let i=new s(n);return $r.set(t,i),i};var Ar=(e,t="temp.ts")=>{let{Project:r}=T();return new r({useInMemoryFileSystem:!0,compilerOptions:{strict:!0,esModuleInterop:!0}}).createSourceFile(t,e)};import{Option as Qr}from"effect";var Qi=/Effect(?:\.Effect)?<([^,]+),\s*([^,]+),\s*([^>]+)>/,Zi=/Effect(?:\.Effect)?<([^,>]+),\s*([^,>]+)>/;function mn(e){let t=n=>n.replace(/import\([^)]+\)\./g,"").replace(/typeof\s+/g,"").trim().substring(0,200),r=Qi.exec(e);if(r)return{successType:t(r[1]),errorType:t(r[2]),requirementsType:t(r[3]),isInferred:!1,typeConfidence:"inferred",rawTypeString:e};let s=Zi.exec(e);if(s)return{successType:t(s[1]),errorType:t(s[2]),requirementsType:"never",isInferred:!1,typeConfidence:"inferred",rawTypeString:e}}function Rr(e,t){try{let{SyntaxKind:r}=T();if(e.getKind()===r.CallExpression){let s=e,n=s.getExpression();if(n.getKind()===r.PropertyAccessExpression){let c=n;if(c.getName()==="pipe"){let o=c.getExpression();if(o){let a=Be(o,t);if(a&&!/^[A-Z]$/.test(a.errorType))return{errorType:a.errorType}}}}let i=s.getArguments();if(i.length>0)for(let c of i){let o=Be(c,t);if(o&&!/^[A-Z]$/.test(o.errorType))return{errorType:o.errorType}}}}catch{}}var Be=(e,t)=>{let r;try{r=e.getType()}catch{return}if(!Xi(r))return;let s=Ft(r);if(s){let[o,a,d]=s,l=Ce(a);if(/^[A-Z]$/.test(l)){let f=Rr(e,t);if(f)return{successType:Ce(o),errorType:f.errorType,requirementsType:Ce(d),isInferred:!0,typeConfidence:"inferred",rawTypeString:r.getText()}}return{successType:Ce(o),errorType:l,requirementsType:Ce(d),isInferred:!0,typeConfidence:"declared",rawTypeString:r.getText()}}let n=r.getText(),i=mn(n);if(i){let o=i.errorType.trim();if(/^[A-Z]$/.test(o)){let a=Rr(e,t);if(a)return{...i,errorType:a.errorType,isInferred:!0,typeConfidence:"inferred",rawTypeString:r.getText()}}return i}let c=Yi(e);return c||{successType:"unknown",errorType:"never",requirementsType:"never",isInferred:!1,typeConfidence:"unknown",rawTypeString:n}};function Yi(e){try{if(!("getExpression"in e))return;let r=e.getExpression(),n=r.getType().getCallSignatures();if(n.length>0){let c=n[0].getReturnType(),o=Ft(c);if(o){let[l,f,u]=o;return{successType:Ce(l),errorType:Ce(f),requirementsType:Ce(u),isInferred:!0,typeConfidence:"inferred",rawTypeString:c.getText()}}let a=c.getText(),d=mn(a);if(d)return d}let i=r.getSymbol();if(!i)return;for(let c of i.getDeclarations()){let o;if("getReturnType"in c)o=c.getReturnType().getText();else if("getType"in c){let d=c.getType().getCallSignatures();if(d.length>0){let l=d[0].getReturnType(),f=Ft(l);if(f){let[u,g,p]=f;return{successType:Ce(u),errorType:Ce(g),requirementsType:Ce(p),isInferred:!0,typeConfidence:"inferred",rawTypeString:l.getText()}}o=l.getText()}}if(o){let a=mn(o);if(a)return{...a,typeConfidence:"inferred"}}}}catch{}}var Xi=e=>{let t=e.getSymbol(),r=e.getText();if(t){let n=t.getName();if(n==="Effect"||n.includes("Effect"))return!0}if(r.includes("Effect<")||r.startsWith("Effect."))return!0;let s=e.getAliasSymbol();if(s){let n=s.getName();if(n==="Effect"||n.includes("Effect"))return!0}return!1},Ft=e=>{try{let t=e.getTypeArguments?.();if(!t||t.length<3){let r=e.getAliasTypeArguments?.();return r&&r.length>=3?[r[0],r[1],r[2]]:void 0}return[t[0],t[1],t[2]]}catch{return}},Ce=e=>e.getText().replace(/import\([^)]+\)\./g,"").replace(/typeof\s+/g,"").substring(0,200),At=(e,t)=>{let r=[],s=e.getType(),n=e,i;try{i=typeof s.getTypeArguments=="function"?s.getTypeArguments():void 0}catch{i=void 0}if(!i||i.length<3){let a=e.getParent();if(a?.getKindName()==="VariableDeclaration"){let d=a,l=d.getType();l&&(s=l,n=d)}}let c=eo(s);if(!c)return r;let o=to(c);for(let a of o){let d=n.getSourceFile(),{line:l,column:f}=d.getLineAndColumnAtPos(n.getStart()),u={filePath:d.getFilePath(),line:l,column:f};r.push({serviceId:a.id,serviceType:a.typeName,requiredAt:u})}return r},eo=e=>{let t=Ft(e);if(t)return t[2]},to=e=>{let t=[],r=e.getText(),s=/Context<([^>]+)>/.exec(r);if(s){let n=s[1];t.push({id:Dr(n),typeName:n})}if(r.includes("|")){let n=De(r);for(let i of n){let c=/Context<([^>]+)>/.exec(i);c&&t.push({id:Dr(c[1]),typeName:c[1]})}}return r==="never"||r==="{}"?[]:t},Dr=e=>{let t=/Tag<["']([^"']+)["']/.exec(e);return t?t[1]:e.split("<")[0].trim()};function De(e){let t=[],r="",s=0,n=null;for(let c=0;c<e.length;c++){let o=e[c];if(n){r+=o,o===n&&e[c-1]!=="\\"&&(n=null);continue}if(o==='"'||o==="'"||o==="`"){n=o,r+=o;continue}if(o==="<"||o==="("){s++,r+=o;continue}if(o===">"||o===")"){s=Math.max(0,s-1),r+=o;continue}if(o==="|"&&s===0){t.push(r.trim()),r="";continue}r+=o}let i=r.trim();return i&&t.push(i),t.filter(Boolean)}var gn=e=>e.replace(/import\([^)]+\)\./g,"").replace(/typeof\s+/g,"").trim().substring(0,200);var no=/Layer<([^,]+),\s*([^,]+),\s*([^>]+)>/;function Pr(e){let t=e.getType().getText(),r=no.exec(t);if(r)return{providedType:gn(r[1]),errorType:gn(r[2]),requiredType:gn(r[3]),rawTypeString:t}}var yn=[".catchAll",".catchTag",".catchAllCause",".catchIf",".catchSome",".catchSomeCause",".catchSomeDefect",".catchAllDefect",".catchTags",".orElse",".orElseFail",".orElseSucceed",".orDie",".orDieWith",".flip",".mapError",".mapErrorCause",".mapBoth",".sandbox",".unsandbox",".parallelErrors",".filterOrDie",".filterOrDieMessage",".filterOrElse",".filterOrFail",".match",".matchCause",".matchEffect",".matchCauseEffect",".firstSuccessOf",".ignore",".ignoreLogged",".eventually"],hn=[".if",".when",".whenEffect",".whenFiberRef",".whenRef",".unless",".unlessEffect",".option",".either",".exit",".liftPredicate"],ro=[".acquireRelease",".acquireUseRelease",".ensuring",".addFinalizer",".onExit",".onError",".parallelFinalizers",".sequentialFinalizers",".finalizersMask",".using",".withEarlyRelease"],Sn=[".forEach",".loop",".filter",".filterMap",".partition",".reduce",".reduceRight",".reduceWhile",".reduceEffect",".dropUntil",".dropWhile",".takeUntil",".takeWhile",".every",".exists",".findFirst",".head",".mergeAll",".replicate",".replicateEffect",".validateAll",".validateFirst",".validate",".validateWith"],xn=["Effect.fork",".fork",".forkAll",".forkIn",".forkWithErrorHandler","Fiber."],En={"Effect.map":"map","Effect.flatMap":"flatMap","Effect.andThen":"andThen","Effect.tap":"tap","Effect.tapBoth":"tapBoth","Effect.tapError":"tapError","Effect.tapErrorTag":"tapErrorTag","Effect.tapErrorCause":"tapErrorCause","Effect.tapDefect":"tapDefect","Effect.zipLeft":"zipLeft","Effect.zipRight":"zipRight","Effect.zipWith":"zipWith","Effect.zip":"zip","Effect.as":"as","Effect.asVoid":"asVoid","Effect.asSome":"asSome","Effect.asSomeError":"asSomeError","Effect.flatten":"flatten","Effect.ap":"ap","Effect.negate":"negate","Effect.merge":"merge"},Or=new Set(["flatMap","andThen","tapBoth","tapError","tapErrorTag","tapErrorCause","tapDefect","zipWith","zipLeft","zipRight","zip","ap","flatten"]),Lr=e=>e in En,bn={"Match.type":"type","Match.tag":"tag","Match.value":"value","Match.when":"when","Match.whenOr":"whenOr","Match.whenAnd":"whenAnd","Match.not":"not","Match.is":"is","Match.exhaustive":"exhaustive","Match.orElse":"orElse","Match.option":"option","Match.either":"either","Match.discriminator":"discriminator","Match.discriminatorsExhaustive":"discriminatorsExhaustive","Match.tags":"tags","Match.tagsExhaustive":"tagsExhaustive","Match.withReturnType":"withReturnType","Match.run":"run"},Wr=new Set(["exhaustive","discriminatorsExhaustive","tagsExhaustive"]),Kr=e=>e.startsWith("Match.")&&e in bn,Nn={"Cause.fail":"fail","Cause.die":"die","Cause.interrupt":"interrupt","Cause.parallel":"parallel","Cause.sequential":"sequential","Cause.empty":"empty","Cause.failures":"failures","Cause.defects":"defects","Cause.interruptors":"interruptors","Cause.squash":"squash","Cause.squashWith":"squashWith","Cause.pretty":"pretty","Cause.flatten":"flatten","Cause.isDie":"isDie","Cause.isFailure":"isFailure","Cause.isInterrupted":"isInterrupted","Cause.isEmpty":"isEmpty","Cause.map":"map","Cause.filter":"filter"},Br=new Set(["fail","die","interrupt","parallel","sequential","empty"]),jr=e=>e.startsWith("Cause.")&&e in Nn,Cn={"Exit.succeed":"succeed","Exit.fail":"fail","Exit.die":"die","Exit.interrupt":"interrupt","Exit.void":"void","Exit.unit":"unit","Exit.match":"match","Exit.isSuccess":"isSuccess","Exit.isFailure":"isFailure","Exit.isInterrupted":"isInterrupted","Exit.when":"when","Exit.whenEffect":"whenEffect","Exit.exists":"exists","Exit.contains":"contains","Exit.flatten":"flatten","Exit.map":"map","Exit.mapBoth":"mapBoth","Exit.mapError":"mapError","Exit.flatMap":"flatMap","Exit.zipWith":"zipWith","Exit.tap":"tap","Exit.tapBoth":"tapBoth","Exit.tapError":"tapError"},qr=new Set(["succeed","fail","die","interrupt","void","unit"]),_r=e=>e.startsWith("Exit.")&&(e in Cn||/^Exit\.\w+$/.test(e)),wn={"Schedule.exponential":"exponential","Schedule.fibonacci":"fibonacci","Schedule.spaced":"spaced","Schedule.fixed":"fixed","Schedule.linear":"linear","Schedule.cron":"cron","Schedule.windowed":"windowed","Schedule.duration":"duration","Schedule.elapsed":"elapsed","Schedule.delays":"delays","Schedule.once":"once","Schedule.stop":"stop","Schedule.count":"count","Schedule.forever":"forever","Schedule.jittered":"jittered","Schedule.andThen":"andThen","Schedule.intersect":"intersect","Schedule.union":"union","Schedule.compose":"compose","Schedule.zipWith":"zipWith","Schedule.addDelay":"addDelay","Schedule.modifyDelay":"modifyDelay","Schedule.check":"check","Schedule.resetAfter":"resetAfter","Schedule.resetWhen":"resetWhen","Schedule.ensure":"ensure","Schedule.driver":"driver","Schedule.mapInput":"mapInput"},zr=e=>e.startsWith("Schedule.")&&(e in wn||/^Schedule\.\w+$/.test(e)),Tn=[".interruptible",".uninterruptible",".interruptibleMask",".uninterruptibleMask",".onInterrupt",".disconnect",".allowInterrupt","Effect.interrupt",".interruptWith"],so=[".Do",".bind",".bindAll",".bindTo"],io=[".cached",".cachedWithTTL",".cachedInvalidateWithTTL",".cachedFunction",".once","Cache.","ScopedCache."],kn=["Effect.","Layer.","Schedule.","Stream.","Queue.","PubSub.","Deferred.","Semaphore.","Mailbox.","SubscriptionRef.","Scope.","Fiber.","Runtime.","ManagedRuntime.","NodeRuntime.","BunRuntime.","DenoRuntime.","Cause.","Exit.","Data.","Option.","Either.","Chunk.","HashMap.","HashSet.","List.","SortedMap.","SortedSet.","RedBlackTree.","Trie.","Graph.","Match.","Config.","Schema.","Cache.","ScopedCache.","RcRef.","RcMap.","Reloadable.","Cache.","ScopedCache.","RateLimiter.","PartitionedSemaphore.","FiberSet.","FiberMap.","FiberHandle.","Metric.","Logger.","Tracer.","Context.","HttpClient.","HttpRouter.","HttpApi.","FileSystem.","Command.","Socket.","SocketServer.","Worker.","Terminal.","KeyValueStore.","Multipart.","Ndjson.","MsgPack.","OpenApi.","OpenApiJsonSchema.","Brand.","Encoding.","Predicate.","DateTime.","Cron.","BigDecimal.","HashRing.","Redacted.","GlobalValue.","Channel.","Sink.","CliApp.","Args.","Options.","AiModel.","AiToolkit.","Completions.","AiInput.","AiResponse.","NodeSdk.","WebSdk.","Entity.","ClusterSchema.","MessageState.","Sharding.","RpcGroup.","RpcApi.","RpcClient.","RpcRouter.","SqlResolver.","SqlMigrator.","Printer.","Doc.","DocTree.","PageWidth.","Optimize."],Rt=new Set(["Array","ReadonlyArray","String","Number","Boolean","Object","Function","Promise","Math","Date","RegExp","Error","Map","Set","WeakMap","WeakSet","Symbol","BigInt","JSON","Console","process","Buffer","EventEmitter","Window","Document","AbortController"]),xt=new Set(["Effect","Layer","Stream","Queue","PubSub","Deferred","Semaphore","Mailbox","SubscriptionRef","Scope","Fiber","Runtime","ManagedRuntime","Cause","Exit","Data","Option","Either","Chunk","HashMap","HashSet","List","SortedMap","SortedSet","Match","Config","Schema","Schedule","Metric","Tracer","Logger","FiberRef","FiberHandle","FiberSet","FiberMap","Cache","ScopedCache","RateLimiter","Supervisor"]),Ur=e=>e.includes(".")||xt.has(e)?!1:/^[A-Z][A-Za-z0-9]*$/.test(e),Mr=e=>{if(e.startsWith("Channel."))return"channel";if(e.startsWith("Sink."))return"sink";if(e.endsWith(".never"))return"never";if(e.endsWith(".void"))return"void-effect";if(e.endsWith(".fromNullable"))return"null-coalescing";if(e.endsWith(".fn")||e.endsWith(".fnUntraced"))return"function-lift";if(e.includes(".async")||e.includes(".asyncEffect")||e.includes(".promise")||e.includes(".sync")||e.includes(".suspend")||e.includes(".succeed")||e.includes(".fail")||e.includes(".try"))return"constructor";if(Tn.some(t=>e.includes(t)))return"interruption";if(so.some(t=>e.includes(t)))return"do-notation";if(io.some(t=>e.includes(t)||e.startsWith(t)))return"caching";if(yn.some(t=>e.includes(t)))return"error-handler";if(hn.some(t=>e.includes(t)))return"conditional";if(ro.some(t=>e.includes(t)))return"resource";if(Sn.some(t=>e.includes(t)))return"collection";if(xn.some(t=>e.includes(t)))return"fiber";if(e.startsWith("Stream."))return"stream";if(e.startsWith("Layer."))return"layer";if(e.startsWith("Schema."))return"schema";if(e.startsWith("Config."))return"config";if(e.startsWith("Cause."))return"cause";if(e.startsWith("Exit."))return"exit";if(e==="Data.tagged"||e==="Data.taggedEnum")return"tagged-enum";if(e.startsWith("Data."))return"data";if(e.startsWith("Option."))return"option";if(e.startsWith("Either."))return"either";if(e.startsWith("Match."))return"match";if(e.startsWith("ManagedRuntime.")||e.startsWith("Runtime.")||e.startsWith("NodeRuntime.")||e.startsWith("BunRuntime.")||e.startsWith("DenoRuntime."))return"runtime";if(e.startsWith("Scope."))return"scope";if(e.startsWith("ScopedRef.")||e.startsWith("RcRef.")||e.startsWith("RcMap."))return"resource-ref";if(e.startsWith("Reloadable.")||e.startsWith("Resource."))return"reloadable";if(e.startsWith("Micro."))return"micro";if(e.startsWith("Brand."))return"brand";if(e.startsWith("Encoding."))return"encoding";if(e.startsWith("Predicate."))return"predicate";if(e.startsWith("DateTime."))return"datetime";if(e.startsWith("Cron."))return"cron";if(e.startsWith("Redacted."))return"redacted";if(e.startsWith("GlobalValue."))return"global-value";if(e.startsWith("Supervisor."))return"supervisor";if(e.includes(".locally")||e.includes(".locallyWith")||e.includes(".locallyScoped")||e.includes(".getFiberRefs")||e.includes(".setFiberRefs")||e.includes(".inheritFiberRefs")||e.includes("FiberRef."))return"fiberref";if(e.includes(".withConcurrency")||e.includes(".withScheduler")||e.includes(".withSchedulingPriority")||e.includes(".daemonChildren")||e.includes(".awaitAllChildren")||e.includes(".supervised"))return"structured-concurrency";if(e.startsWith("Context.pick")||e.startsWith("Context.omit")||e==="Effect.provide"||e.startsWith("Effect.")&&e.includes(".provide")&&!e.includes("provideService"))return"context";if(e.includes(".serviceOption")||e.includes(".serviceOptional")||e.includes(".serviceFunction")||e.includes(".serviceFunctionEffect")||e.includes(".serviceFunctions")||e.includes(".serviceConstants")||e.includes(".serviceMembers")||e.includes(".updateService"))return"service";if(e.startsWith("CliApp.")||e.startsWith("Args.")||e.startsWith("Options."))return"cli";if(e.startsWith("AiModel.")||e.startsWith("AiToolkit.")||e.startsWith("Completions.")||e.startsWith("AiInput.")||e.startsWith("AiResponse."))return"ai";if(e.startsWith("NodeSdk.")||e.startsWith("WebSdk.")||e.startsWith("OtelMetrics."))return"opentelemetry";if(e.startsWith("Entity.")||e.startsWith("ClusterSchema.")||e.startsWith("MessageState.")||e.startsWith("Sharding."))return"cluster";if(e.startsWith("RpcGroup.")||e.startsWith("RpcApi.")||e.startsWith("RpcClient.")||e.startsWith("RpcRouter."))return"rpc";if(e.startsWith("SqlResolver.")||e.startsWith("SqlMigrator."))return"sql";if(e.startsWith("DevTools.")||e.startsWith("Server."))return"devtools";if(e.startsWith("BigDecimal."))return"big-decimal";if(e.startsWith("Graph."))return"graph";if(e.startsWith("HashRing."))return"hash-ring";if(e.startsWith("Chunk."))return"chunk";if(e.startsWith("HashMap.")||e.startsWith("HashSet.")||e.startsWith("List.")||e.startsWith("SortedMap.")||e.startsWith("SortedSet.")||e.startsWith("RedBlackTree.")||e.startsWith("Trie."))return"immutable-collection";if(e.includes(".map")||e.includes(".flatMap")||e.includes(".andThen")||e.includes(".tap")||e.includes(".tapBoth")||e.includes(".tapError")||e.includes(".tapErrorTag")||e.includes(".tapErrorCause")||e.includes(".tapDefect")||e.includes(".zip")||e.includes(".zipLeft")||e.includes(".zipRight")||e.includes(".zipWith")||e.includes(".as")||e.includes(".asVoid")||e.includes(".flatten")||e.includes(".merge")||e.includes(".ap")||e.includes(".validate")||e.includes(".negate"))return"transformation";if(e.startsWith("Printer.")||e.startsWith("Doc.")||e.startsWith("DocTree.")||e.startsWith("PageWidth.")||e.startsWith("Optimize."))return"printer";if(e.startsWith("Http")||e.startsWith("FileSystem.")||e.startsWith("Command.")||e.startsWith("Socket.")||e.startsWith("Worker."))return"platform";if(e.includes("channel.")&&!e.includes("Channel"))return"channel"},Hr=(e,t)=>{let r=Mr(e);if(r)return r;if(t){let s=e.indexOf(".");if(s>0){let n=e.substring(0,s);if(t.has(n)){let i=e.substring(s+1);return Mr(`Effect.${i}`)}}}},ce=(e,t,r=new Set)=>{let{SyntaxKind:s}=T(),n=f=>r.has(f),i=f=>/\.run(?:Promise(?:Exit)?|Sync(?:Exit)?|Fork|Callback|Main)$/.test(f)||/^Runtime\.run(?:Promise|Sync|Fork)$/.test(f),c=f=>{if(i(f))return!1;let u=f==="pipe"||f.endsWith(".pipe"),g=f.indexOf(".");return g>0&&n(f.slice(0,g))?!1:u||[...t].some(p=>f.startsWith(`${p}.`))},o=f=>{let u=f.getExpression(),g=u.getText();if(i(g))return!1;let p=g==="pipe",m=u.getKind()===s.PropertyAccessExpression&&u.getName()==="pipe";if(p||m){if(f.getArguments().some(h=>ce(h,t,r)))return!0;if(m){let h=u.getExpression();return ce(h,t,r)}return!1}return u.getKind()===s.Identifier&&t.has(g)&&!n(g)||c(g)||u.getKind()===s.PropertyAccessExpression&&ce(u.getExpression(),t,r)?!0:f.getArguments().some(y=>ce(y,t,r))},a=(f,u)=>{let g=f.getParent();for(;g&&g!==u;){let p=g.getKind();if(p===s.FunctionDeclaration||p===s.FunctionExpression||p===s.ArrowFunction||p===s.MethodDeclaration||p===s.GetAccessor||p===s.SetAccessor||p===s.ClassDeclaration||p===s.ClassExpression||p===s.Constructor||p===s.ClassStaticBlockDeclaration)return!1;g=g.getParent()}return!0},d=f=>f.getDescendantsOfKind(s.CallExpression).some(m=>a(m,f)&&o(m))||f.getDescendantsOfKind(s.AwaitExpression).some(m=>a(m,f)&&ce(m,t,r))?!0:f.getDescendantsOfKind(s.PropertyAccessExpression).some(m=>a(m,f)&&ce(m,t,r)),l=f=>f.getDescendantsOfKind(s.CallExpression).some(u=>a(u,f)&&i(u.getExpression().getText()));if(e.getKind()===s.ObjectLiteralExpression)return e.getProperties().some(u=>{if(u.getKind()===s.PropertyAssignment||u.getKind()===s.ShorthandPropertyAssignment){let g=u.getKind()===s.PropertyAssignment?u.getInitializer():void 0;return g?ce(g,t,r):!1}if(u.getKind()===s.MethodDeclaration||u.getKind()===s.GetAccessor||u.getKind()===s.SetAccessor){let g=u.getBody();return g?d(g):!1}return!1});if(e.getKind()===s.ArrowFunction||e.getKind()===s.FunctionExpression){let u=e.getBody();if(u.getKind()===s.Block){let g=u;return g.getDescendantsOfKind(s.ReturnStatement).some(y=>{if(!a(y,g))return!1;let h=y.getExpression();return h!==void 0&&ce(h,t,r)})?!0:l(g)?!1:d(g)}return ce(u,t,r)}if(e.getKind()===s.CallExpression)return o(e);if(e.getKind()===s.AwaitExpression){let f=e.getExpression();return f.getKind()!==s.CallExpression?!1:o(f)}if(e.getKind()===s.ConditionalExpression){let f=e;return ce(f.getWhenTrue(),t,r)||ce(f.getWhenFalse(),t,r)}if(e.getKind()===s.PropertyAccessExpression){let f=e.getText(),u=f.indexOf(".");return u>0&&n(f.slice(0,u))?!1:[...t].some(g=>f.startsWith(`${g}.`))}return!1};function Pe(e){return e==="effect"||e.startsWith("effect/")||e.startsWith("@effect/")}var vn=new Set(["Effect","Layer","Schedule","Stream","Queue","PubSub","Deferred","Semaphore","Mailbox","SubscriptionRef","Scope","Fiber","Runtime","ManagedRuntime","Cause","Exit","Data","Option","Either","Chunk","HashMap","HashSet","Match","Config","Schema","Cache","ScopedCache","Metric","Logger","Tracer","Context","Brand","Encoding","Predicate","DateTime","Cron","BigDecimal","Graph","HashRing","Redacted","GlobalValue","NodeRuntime","BunRuntime","DenoRuntime","Channel","Sink"]),Gr=new Set(["core","core-effect","core-stream","fiberRuntime","effectable","channel","sink","layer","schedule","mailbox","pubsub"]);function Vr(e){let t=new Set(["never","unknown","any","{}","object"]),r=e.trim();return!r||t.has(r)?[]:r.split(/[\s|&]+/).map(n=>n.trim().split("<")[0]?.trim()??"").filter(n=>n.length>0&&!t.has(n))}function Et(e){let{SyntaxKind:t}=T(),r=e.getKind();if(r===t.NumericLiteral){let s=e.getText(),n=Number(s);return Number.isFinite(n)?n:void 0}if(r===t.PrefixUnaryExpression){let s=e;if(s.getOperatorToken()===t.MinusToken){let n=s.getOperand(),i=Et(n);return i!==void 0?-i:void 0}}}var In={tsConfigPath:"./tsconfig.json",resolveReferences:!0,maxReferenceDepth:5,includeLocations:!0,assumeImported:!1,enableEffectWorkflow:!1,knownEffectInternalsRoot:void 0,minDiscoveryConfidence:"low",onlyExportedPrograms:!1,enableEffectFlow:!1},Zr=0,Dt=()=>{Zr=0},w=()=>`effect-${++Zr}`,Jr=new WeakMap;function Pt(e){let t=Jr.get(e);return t===void 0&&(t=e.getText(),Jr.set(e,t)),t}function Yr(e){let t=new Set,r=s=>{for(let n of s){if(n.type==="effect"){let c=n.typeSignature?.errorType?.trim();if(c&&c!=="never")for(let o of De(c))t.add(o)}let i=Qr.getOrElse(P(n),()=>[]);i.length>0&&r(i)}};return r(e),Array.from(t).sort()}function Xr(e){let t=new Map,r=s=>{for(let n of s){if(n.type==="effect"){let c=n.requiredServices;if(c)for(let o of c)t.has(o.serviceId)||t.set(o.serviceId,{name:o.serviceId,typeSignature:o.serviceType,isLayer:!1});if((n.semanticRole==="environment"||n.semanticRole==="side-effect")&&n.callee){let o=n.callee;/^[A-Z]/.test(o)&&!o.startsWith("Effect.")&&!o.startsWith("Schema.")&&!o.startsWith("Data.")&&!o.startsWith("Config.")&&!o.startsWith("Command.")&&!o.startsWith("Stream.")&&!o.startsWith("Option.")&&!o.startsWith("Either.")&&!o.startsWith("Cause.")&&!o.startsWith("Exit.")&&!t.has(o)&&t.set(o,{name:o,typeSignature:n.typeSignature?.requirementsType,isLayer:!1})}}let i=Qr.getOrElse(P(n),()=>[]);i.length>0&&r(i)}};return r(e),Array.from(t.values())}var _=(e,t,r)=>{if(!r)return;let s=e.getSourceFile(),n=e.getStart(),{line:i,column:c}=s.getLineAndColumnAtPos(n),o=e.getEnd(),a=s.getLineAndColumnAtPos(o);return{filePath:t,line:i,column:c,endLine:a.line,endColumn:a.column}},Ze=e=>{let t=e.getJsDocs?.();if(t&&t.length>0){let s=t[0];if(!s)return;let n=s.getComment?.();if(n){let o;if(typeof n=="string")o=n;else if(Array.isArray(n))o=n.map(d=>d.text).join(`
|
|
3
|
+
`);else return;let a=o.search(/\n\s*@/);return a!==-1&&(o=o.substring(0,a)),o.trim()||void 0}let i=s.getText(),c=/\/\*\*\s*\n?\s*\*\s*([^@]*?)(?=\n\s*\*\s*@|\*\/)/.exec(i);if(c?.[1])return c[1].replace(/\n\s*\*\s*/g," ").trim()||void 0}let r=e.getLeadingCommentRanges();if(r.length>0){let s=r[r.length-1];if(!s)return;let n=s.getText();if(n.startsWith("/**")){let i=n.replace(/^\/\*\*\s*/,"").replace(/\s*\*\/\s*$/,"").replace(/^\s*\*\s?/gm,"").trim(),c=i.search(/\n@/);return c!==-1?i.substring(0,c).trim()||void 0:i||void 0}}},it=e=>{let t=s=>{let n=s.getJsDocs?.();if(n&&n.length>0)return n[0].getText();let i=s.getLeadingCommentRanges();if(i.length>0){let c=i[i.length-1];if(c){let o=c.getText();if(o.startsWith("/**"))return o}}},r=t(e);if(!r){let{SyntaxKind:s}=T(),n=e.getParent();for(;n&&!r;){let i=n.getKind();if(i===s.VariableStatement){r=t(n);break}if(i===s.VariableDeclarationList){let c=n.getParent();c&&(r=t(c));break}if(i===s.CallExpression||i===s.ArrowFunction||i===s.VariableDeclaration||i===s.ParenthesizedExpression)n=n.getParent();else break}}if(r)return oo(r)};function oo(e){let t=e.replace(/^\/\*\*/,"").replace(/\*\/$/,"").split(`
|
|
4
4
|
`).map(a=>a.replace(/^\s*\*\s?/,"")).join(`
|
|
5
|
-
`),r=[],s,n=[],i,c=/@(param|returns?|throws?|exception|example)\s*(.*)/gi,o;for(;(o=c.exec(t))!==null;){let a=o[1].toLowerCase(),d=o[2].trim();if(a==="param"){let l=/^(?:\{[^}]*\}\s*)?(\[?\w+(?:=[^\]]*)?]?)\s*(?:-\s*(.*))?$/.exec(d);if(l){let f=l[1].replace(/^\[|\]$/g,"").replace(/=.*/,""),u=l[2]?.trim();r.push(u?{name:f,description:u}:{name:f})}}else if(a==="returns"||a==="return")s=d.replace(/^\{[^}]*\}\s*/,"").trim()||void 0;else if(a==="throws"||a==="throw"||a==="exception"){let l=d.replace(/^\{[^}]*\}\s*/,"").trim();l&&n.push(l)}else if(a==="example"){let l=o.index+o[0].length,f=/\n\s*@\w/.exec(t.slice(l));f?i=t.slice(o.index+o[0].length-d.length,l+f.index).trim()||void 0:i=t.slice(o.index+o[0].length-d.length).trim()||void 0}}if(!(r.length===0&&!s&&n.length===0&&!i))return{params:r,returns:s,throws:n,example:i}}var Ar=e=>{let t=e.getParent(),{SyntaxKind:r}=w();if(t){let s=t.getKind();if(s===r.VariableDeclaration)return _e(t);if(s===r.ArrowFunction){let n=t.getParent();if(n?.getKind()===r.VariableDeclaration)return _e(n)}}};function Rr(e){return e.endsWith(".js")||e.endsWith(".jsx")}var vt=e=>{let t=e.getParent(),{SyntaxKind:r}=w();if(t?.getKind()===r.VariableDeclaration)return t.getName()},He=e=>{let{SyntaxKind:t}=w(),r=i=>{let c=i;for(;c!==void 0;){if(c.getKind()===t.VariableDeclaration)return c.getName();c=c.getParent()}},s=e.getParent();if(s){let i=s.getKind();if(i===t.VariableDeclaration)return s.getName();if(i===t.AwaitExpression){let c=s.getParent();if(c?.getKind()===t.VariableDeclaration)return c.getName()}if(i===t.PropertyAssignment){let o=s.getName(),a=r(s);return a?`${a}.${o}`:o}if(i===t.ArrowFunction){let c=s.getParent();if(c?.getKind()===t.VariableDeclaration)return c.getName();if(c?.getKind()===t.PropertyAssignment){let a=c.getName(),d=r(c);return d?`${d}.${a}`:a}}}let n=e;for(let i=0;n&&i<6&&(n=n.getParent(),!!n);i++){let c=n.getKind();if(c===t.VariableDeclaration)return n.getName();if(c===t.PropertyAssignment){let a=n.getName(),d=r(n);return d?`${d}.${a}`:a}if(c===t.Block||c===t.SourceFile)break}},Dr=e=>{let{SyntaxKind:t}=w(),r=e.getParent();for(let s=0;r&&s<10;s++){if(r.getKind()===t.CallExpression){let n=r,i=n.getExpression().getText();if(i==="Effect.fn"||i.endsWith(".fn")){let c=n.getArguments();if(c.length>0){let o=c[0].getText(),a=/^["'](.+)["']$/.exec(o);if(a?.[1])return a[1]}}}r=r.getParent()}},Pr=()=>({totalEffects:0,parallelCount:0,raceCount:0,errorHandlerCount:0,retryCount:0,timeoutCount:0,resourceCount:0,loopCount:0,conditionalCount:0,layerCount:0,interruptionCount:0,unknownCount:0,decisionCount:0,switchCount:0,tryCatchCount:0,terminalCount:0,opaqueCount:0}),ft=(e,t)=>e.length<=t?e:`${e.slice(0,t)}\u2026`;function G(e,t){switch(e.type){case"effect":{let r=t??e.name;return r?`${r} <- ${e.callee}`:e.callee}case"generator":return`Generator (${e.yields.length} yields)`;case"pipe":return`Pipe (${e.transformations.length} steps)`;case"parallel":return`${e.callee} (${e.children.length})`;case"race":return`${e.callee} (${e.children.length} racing)`;case"error-handler":return e.name?`${e.name}: ${e.handlerType}`:e.handlerType;case"retry":return e.schedule?`retry: ${e.schedule}`:"retry";case"timeout":return e.duration?`timeout: ${e.duration}`:"timeout";case"resource":return"Resource";case"conditional":return ft(e.condition,30);case"loop":return e.iterSource?`${e.loopType}(${e.iterSource})`:e.loopType;case"layer":return e.isMerged?"Layer (merged)":"Layer";case"stream":{let s=["Stream",...e.pipeline.map(n=>n.operation)];return e.sink&&s.push(e.sink),s.join(" \u2192 ")}case"concurrency-primitive":return`${e.primitive}.${e.operation}`;case"fiber":{let r=e.operation;return e.isDaemon?`${r} (daemon)`:e.isScoped?`${r} (scoped)`:r}case"transform":return e.transformType;case"match":return`Match.${e.matchOp}`;case"cause":return`Cause.${e.causeOp}`;case"exit":return`Exit.${e.exitOp}`;case"schedule":return`Schedule.${e.scheduleOp}`;case"interruption":return e.interruptionType;case"channel":{let r=e.pipeline.map(s=>s.operation);return r.length>0?`Channel: ${r.join(" \u2192 ")}`:"Channel"}case"sink":{let r=e.pipeline.map(s=>s.operation);return r.length>0?`Sink: ${r.join(" \u2192 ")}`:"Sink"}case"decision":return ft(e.condition,30);case"switch":return`switch(${ft(e.expression,25)})`;case"try-catch":return"try/catch";case"terminal":return e.label?`${e.terminalKind} ${e.label}`:e.terminalKind;case"opaque":return`Opaque: ${ft(e.reason,25)}`;case"unknown":return`Unknown: ${ft(e.reason,30)}`}}function Q(e){switch(e.type){case"effect":{if(e.serviceCall||e.serviceMethod)return"service-call";let t=e.description?.toLowerCase()??"";if(t.includes("service"))return"service-call";if(t.includes("layer")||e.provideKind==="layer")return"layer";let r=e.callee.toLowerCase();return/^[A-Z][A-Za-z0-9_]*$/.test(e.callee)&&!e.constructorKind?"environment":r.includes("sync")||r.includes("promise")||r.includes("async")||r.includes("log")||r.includes("console")?"side-effect":r.includes("succeed")||r.includes("fail")||r.includes("die")||r.includes("void")||r.includes("never")||r.includes("gen")||r.includes("make")||e.constructorKind?"constructor":"side-effect"}case"generator":case"pipe":return"constructor";case"parallel":case"race":case"concurrency-primitive":return"concurrency";case"error-handler":case"cause":case"exit":return"error-handler";case"retry":case"timeout":case"schedule":return"scheduling";case"resource":return"resource";case"conditional":case"loop":case"match":case"decision":case"switch":case"terminal":return"control-flow";case"try-catch":return"error-handler";case"opaque":return"unknown";case"layer":return"layer";case"stream":case"channel":case"sink":return"stream";case"fiber":case"interruption":return"fiber";case"transform":return"transform";case"unknown":return"unknown"}}var cn=[".catchAll",".catchTag",".catchAllCause",".catchIf",".catchSome",".catchSomeCause",".catchSomeDefect",".catchAllDefect",".catchTags",".orElse",".orElseFail",".orElseSucceed",".orDie",".orDieWith",".flip",".mapError",".mapErrorCause",".mapBoth",".sandbox",".unsandbox",".parallelErrors",".filterOrDie",".filterOrDieMessage",".filterOrElse",".filterOrFail",".match",".matchCause",".matchEffect",".matchCauseEffect",".firstSuccessOf",".ignore",".ignoreLogged",".eventually"],ln=[".if",".when",".whenEffect",".whenFiberRef",".whenRef",".unless",".unlessEffect",".option",".either",".exit",".liftPredicate"],Qi=[".acquireRelease",".acquireUseRelease",".ensuring",".addFinalizer",".onExit",".onError",".parallelFinalizers",".sequentialFinalizers",".finalizersMask",".using",".withEarlyRelease"],dn=[".forEach",".loop",".filter",".filterMap",".partition",".reduce",".reduceRight",".reduceWhile",".reduceEffect",".dropUntil",".dropWhile",".takeUntil",".takeWhile",".every",".exists",".findFirst",".head",".mergeAll",".replicate",".replicateEffect",".validateAll",".validateFirst",".validate",".validateWith"],un=["Effect.fork",".fork",".forkAll",".forkIn",".forkWithErrorHandler","Fiber."],fn={"Effect.map":"map","Effect.flatMap":"flatMap","Effect.andThen":"andThen","Effect.tap":"tap","Effect.tapBoth":"tapBoth","Effect.tapError":"tapError","Effect.tapErrorTag":"tapErrorTag","Effect.tapErrorCause":"tapErrorCause","Effect.tapDefect":"tapDefect","Effect.zipLeft":"zipLeft","Effect.zipRight":"zipRight","Effect.zipWith":"zipWith","Effect.zip":"zip","Effect.as":"as","Effect.asVoid":"asVoid","Effect.asSome":"asSome","Effect.asSomeError":"asSomeError","Effect.flatten":"flatten","Effect.ap":"ap","Effect.negate":"negate","Effect.merge":"merge"},Or=new Set(["flatMap","andThen","tapBoth","tapError","tapErrorTag","tapErrorCause","tapDefect","zipWith","zipLeft","zipRight","zip","ap","flatten"]),Lr=e=>e in fn,pn={"Match.type":"type","Match.tag":"tag","Match.value":"value","Match.when":"when","Match.whenOr":"whenOr","Match.whenAnd":"whenAnd","Match.not":"not","Match.is":"is","Match.exhaustive":"exhaustive","Match.orElse":"orElse","Match.option":"option","Match.either":"either","Match.discriminator":"discriminator","Match.discriminatorsExhaustive":"discriminatorsExhaustive","Match.tags":"tags","Match.tagsExhaustive":"tagsExhaustive","Match.withReturnType":"withReturnType","Match.run":"run"},Wr=new Set(["exhaustive","discriminatorsExhaustive","tagsExhaustive"]),Kr=e=>e.startsWith("Match.")&&e in pn,gn={"Cause.fail":"fail","Cause.die":"die","Cause.interrupt":"interrupt","Cause.parallel":"parallel","Cause.sequential":"sequential","Cause.empty":"empty","Cause.failures":"failures","Cause.defects":"defects","Cause.interruptors":"interruptors","Cause.squash":"squash","Cause.squashWith":"squashWith","Cause.pretty":"pretty","Cause.flatten":"flatten","Cause.isDie":"isDie","Cause.isFailure":"isFailure","Cause.isInterrupted":"isInterrupted","Cause.isEmpty":"isEmpty","Cause.map":"map","Cause.filter":"filter"},jr=new Set(["fail","die","interrupt","parallel","sequential","empty"]),Br=e=>e.startsWith("Cause.")&&e in gn,mn={"Exit.succeed":"succeed","Exit.fail":"fail","Exit.die":"die","Exit.interrupt":"interrupt","Exit.void":"void","Exit.unit":"unit","Exit.match":"match","Exit.isSuccess":"isSuccess","Exit.isFailure":"isFailure","Exit.isInterrupted":"isInterrupted","Exit.when":"when","Exit.whenEffect":"whenEffect","Exit.exists":"exists","Exit.contains":"contains","Exit.flatten":"flatten","Exit.map":"map","Exit.mapBoth":"mapBoth","Exit.mapError":"mapError","Exit.flatMap":"flatMap","Exit.zipWith":"zipWith","Exit.tap":"tap","Exit.tapBoth":"tapBoth","Exit.tapError":"tapError"},qr=new Set(["succeed","fail","die","interrupt","void","unit"]),zr=e=>e.startsWith("Exit.")&&(e in mn||/^Exit\.\w+$/.test(e)),yn={"Schedule.exponential":"exponential","Schedule.fibonacci":"fibonacci","Schedule.spaced":"spaced","Schedule.fixed":"fixed","Schedule.linear":"linear","Schedule.cron":"cron","Schedule.windowed":"windowed","Schedule.duration":"duration","Schedule.elapsed":"elapsed","Schedule.delays":"delays","Schedule.once":"once","Schedule.stop":"stop","Schedule.count":"count","Schedule.forever":"forever","Schedule.jittered":"jittered","Schedule.andThen":"andThen","Schedule.intersect":"intersect","Schedule.union":"union","Schedule.compose":"compose","Schedule.zipWith":"zipWith","Schedule.addDelay":"addDelay","Schedule.modifyDelay":"modifyDelay","Schedule.check":"check","Schedule.resetAfter":"resetAfter","Schedule.resetWhen":"resetWhen","Schedule.ensure":"ensure","Schedule.driver":"driver","Schedule.mapInput":"mapInput"},_r=e=>e.startsWith("Schedule.")&&(e in yn||/^Schedule\.\w+$/.test(e)),hn=[".interruptible",".uninterruptible",".interruptibleMask",".uninterruptibleMask",".onInterrupt",".disconnect",".allowInterrupt","Effect.interrupt",".interruptWith"],Zi=[".Do",".bind",".bindAll",".bindTo"],Yi=[".cached",".cachedWithTTL",".cachedInvalidateWithTTL",".cachedFunction",".once","Cache.","ScopedCache."],Sn=["Effect.","Layer.","Schedule.","Stream.","Queue.","PubSub.","Deferred.","Semaphore.","Mailbox.","SubscriptionRef.","Scope.","Fiber.","Runtime.","ManagedRuntime.","NodeRuntime.","BunRuntime.","DenoRuntime.","Cause.","Exit.","Data.","Option.","Either.","Chunk.","HashMap.","HashSet.","List.","SortedMap.","SortedSet.","RedBlackTree.","Trie.","Graph.","Match.","Config.","Schema.","Cache.","ScopedCache.","RcRef.","RcMap.","Reloadable.","Cache.","ScopedCache.","RateLimiter.","PartitionedSemaphore.","FiberSet.","FiberMap.","FiberHandle.","Metric.","Logger.","Tracer.","Context.","HttpClient.","HttpRouter.","HttpApi.","FileSystem.","Command.","Socket.","SocketServer.","Worker.","Terminal.","KeyValueStore.","Multipart.","Ndjson.","MsgPack.","OpenApi.","OpenApiJsonSchema.","Brand.","Encoding.","Predicate.","DateTime.","Cron.","BigDecimal.","HashRing.","Redacted.","GlobalValue.","Channel.","Sink.","CliApp.","Args.","Options.","AiModel.","AiToolkit.","Completions.","AiInput.","AiResponse.","NodeSdk.","WebSdk.","Entity.","ClusterSchema.","MessageState.","Sharding.","RpcGroup.","RpcApi.","RpcClient.","RpcRouter.","SqlResolver.","SqlMigrator.","Printer.","Doc.","DocTree.","PageWidth.","Optimize."],Hr=new Set(["Array","ReadonlyArray","String","Number","Boolean","Object","Function","Promise","Math","Date","RegExp","Error","Map","Set","WeakMap","WeakSet","Symbol","BigInt","JSON","Console","process","Buffer","EventEmitter","Window","Document","AbortController"]),xn=new Set(["Effect","Layer","Stream","Queue","PubSub","Deferred","Semaphore","Mailbox","SubscriptionRef","Scope","Fiber","Runtime","ManagedRuntime","Cause","Exit","Data","Option","Either","Chunk","HashMap","HashSet","List","SortedMap","SortedSet","Match","Config","Schema","Schedule","Metric","Tracer","Logger","FiberRef","FiberHandle","FiberSet","FiberMap","Cache","ScopedCache","RateLimiter","Supervisor"]),Ur=e=>e.includes(".")||xn.has(e)?!1:/^[A-Z][A-Za-z0-9]*$/.test(e),Mr=e=>{if(e.startsWith("Channel."))return"channel";if(e.startsWith("Sink."))return"sink";if(e.endsWith(".never"))return"never";if(e.endsWith(".void"))return"void-effect";if(e.endsWith(".fromNullable"))return"null-coalescing";if(e.endsWith(".fn")||e.endsWith(".fnUntraced"))return"function-lift";if(e.includes(".async")||e.includes(".asyncEffect")||e.includes(".promise")||e.includes(".sync")||e.includes(".suspend")||e.includes(".succeed")||e.includes(".fail")||e.includes(".try"))return"constructor";if(hn.some(t=>e.includes(t)))return"interruption";if(Zi.some(t=>e.includes(t)))return"do-notation";if(Yi.some(t=>e.includes(t)||e.startsWith(t)))return"caching";if(cn.some(t=>e.includes(t)))return"error-handler";if(ln.some(t=>e.includes(t)))return"conditional";if(Qi.some(t=>e.includes(t)))return"resource";if(dn.some(t=>e.includes(t)))return"collection";if(un.some(t=>e.includes(t)))return"fiber";if(e.startsWith("Stream."))return"stream";if(e.startsWith("Layer."))return"layer";if(e.startsWith("Schema."))return"schema";if(e.startsWith("Config."))return"config";if(e.startsWith("Cause."))return"cause";if(e.startsWith("Exit."))return"exit";if(e==="Data.tagged"||e==="Data.taggedEnum")return"tagged-enum";if(e.startsWith("Data."))return"data";if(e.startsWith("Option."))return"option";if(e.startsWith("Either."))return"either";if(e.startsWith("Match."))return"match";if(e.startsWith("ManagedRuntime.")||e.startsWith("Runtime.")||e.startsWith("NodeRuntime.")||e.startsWith("BunRuntime.")||e.startsWith("DenoRuntime."))return"runtime";if(e.startsWith("Scope."))return"scope";if(e.startsWith("ScopedRef.")||e.startsWith("RcRef.")||e.startsWith("RcMap."))return"resource-ref";if(e.startsWith("Reloadable.")||e.startsWith("Resource."))return"reloadable";if(e.startsWith("Micro."))return"micro";if(e.startsWith("Brand."))return"brand";if(e.startsWith("Encoding."))return"encoding";if(e.startsWith("Predicate."))return"predicate";if(e.startsWith("DateTime."))return"datetime";if(e.startsWith("Cron."))return"cron";if(e.startsWith("Redacted."))return"redacted";if(e.startsWith("GlobalValue."))return"global-value";if(e.startsWith("Supervisor."))return"supervisor";if(e.includes(".locally")||e.includes(".locallyWith")||e.includes(".locallyScoped")||e.includes(".getFiberRefs")||e.includes(".setFiberRefs")||e.includes(".inheritFiberRefs")||e.includes("FiberRef."))return"fiberref";if(e.includes(".withConcurrency")||e.includes(".withScheduler")||e.includes(".withSchedulingPriority")||e.includes(".daemonChildren")||e.includes(".awaitAllChildren")||e.includes(".supervised"))return"structured-concurrency";if(e.startsWith("Context.pick")||e.startsWith("Context.omit")||e==="Effect.provide"||e.startsWith("Effect.")&&e.includes(".provide")&&!e.includes("provideService"))return"context";if(e.includes(".serviceOption")||e.includes(".serviceOptional")||e.includes(".serviceFunction")||e.includes(".serviceFunctionEffect")||e.includes(".serviceFunctions")||e.includes(".serviceConstants")||e.includes(".serviceMembers")||e.includes(".updateService"))return"service";if(e.startsWith("CliApp.")||e.startsWith("Args.")||e.startsWith("Options."))return"cli";if(e.startsWith("AiModel.")||e.startsWith("AiToolkit.")||e.startsWith("Completions.")||e.startsWith("AiInput.")||e.startsWith("AiResponse."))return"ai";if(e.startsWith("NodeSdk.")||e.startsWith("WebSdk.")||e.startsWith("OtelMetrics."))return"opentelemetry";if(e.startsWith("Entity.")||e.startsWith("ClusterSchema.")||e.startsWith("MessageState.")||e.startsWith("Sharding."))return"cluster";if(e.startsWith("RpcGroup.")||e.startsWith("RpcApi.")||e.startsWith("RpcClient.")||e.startsWith("RpcRouter."))return"rpc";if(e.startsWith("SqlResolver.")||e.startsWith("SqlMigrator."))return"sql";if(e.startsWith("DevTools.")||e.startsWith("Server."))return"devtools";if(e.startsWith("BigDecimal."))return"big-decimal";if(e.startsWith("Graph."))return"graph";if(e.startsWith("HashRing."))return"hash-ring";if(e.startsWith("Chunk."))return"chunk";if(e.startsWith("HashMap.")||e.startsWith("HashSet.")||e.startsWith("List.")||e.startsWith("SortedMap.")||e.startsWith("SortedSet.")||e.startsWith("RedBlackTree.")||e.startsWith("Trie."))return"immutable-collection";if(e.includes(".map")||e.includes(".flatMap")||e.includes(".andThen")||e.includes(".tap")||e.includes(".tapBoth")||e.includes(".tapError")||e.includes(".tapErrorTag")||e.includes(".tapErrorCause")||e.includes(".tapDefect")||e.includes(".zip")||e.includes(".zipLeft")||e.includes(".zipRight")||e.includes(".zipWith")||e.includes(".as")||e.includes(".asVoid")||e.includes(".flatten")||e.includes(".merge")||e.includes(".ap")||e.includes(".validate")||e.includes(".negate"))return"transformation";if(e.startsWith("Printer.")||e.startsWith("Doc.")||e.startsWith("DocTree.")||e.startsWith("PageWidth.")||e.startsWith("Optimize."))return"printer";if(e.startsWith("Http")||e.startsWith("FileSystem.")||e.startsWith("Command.")||e.startsWith("Socket.")||e.startsWith("Worker."))return"platform";if(e.includes("channel.")&&!e.includes("Channel"))return"channel"},Gr=(e,t)=>{let r=Mr(e);if(r)return r;if(t){let s=e.indexOf(".");if(s>0){let n=e.substring(0,s);if(t.has(n)){let i=e.substring(s+1);return Mr(`Effect.${i}`)}}}},oe=(e,t,r=new Set)=>{let{SyntaxKind:s}=w(),n=f=>r.has(f),i=f=>/\.run(?:Promise(?:Exit)?|Sync(?:Exit)?|Fork|Callback|Main)$/.test(f)||/^Runtime\.run(?:Promise|Sync|Fork)$/.test(f),c=f=>{if(i(f))return!1;let u=f==="pipe"||f.endsWith(".pipe"),g=f.indexOf(".");return g>0&&n(f.slice(0,g))?!1:u||[...t].some(p=>f.startsWith(`${p}.`))},o=f=>{let u=f.getExpression(),g=u.getText();if(i(g))return!1;let p=g==="pipe",m=u.getKind()===s.PropertyAccessExpression&&u.getName()==="pipe";if(p||m){if(f.getArguments().some(y=>oe(y,t,r)))return!0;if(m){let y=u.getExpression();return oe(y,t,r)}return!1}return u.getKind()===s.Identifier&&t.has(g)&&!n(g)||c(g)||u.getKind()===s.PropertyAccessExpression&&oe(u.getExpression(),t,r)?!0:f.getArguments().some(h=>oe(h,t,r))},a=(f,u)=>{let g=f.getParent();for(;g&&g!==u;){let p=g.getKind();if(p===s.FunctionDeclaration||p===s.FunctionExpression||p===s.ArrowFunction||p===s.MethodDeclaration||p===s.GetAccessor||p===s.SetAccessor||p===s.ClassDeclaration||p===s.ClassExpression||p===s.Constructor||p===s.ClassStaticBlockDeclaration)return!1;g=g.getParent()}return!0},d=f=>f.getDescendantsOfKind(s.CallExpression).some(m=>a(m,f)&&o(m))||f.getDescendantsOfKind(s.AwaitExpression).some(m=>a(m,f)&&oe(m,t,r))?!0:f.getDescendantsOfKind(s.PropertyAccessExpression).some(m=>a(m,f)&&oe(m,t,r)),l=f=>f.getDescendantsOfKind(s.CallExpression).some(u=>a(u,f)&&i(u.getExpression().getText()));if(e.getKind()===s.ObjectLiteralExpression)return e.getProperties().some(u=>{if(u.getKind()===s.PropertyAssignment||u.getKind()===s.ShorthandPropertyAssignment){let g=u.getKind()===s.PropertyAssignment?u.getInitializer():void 0;return g?oe(g,t,r):!1}if(u.getKind()===s.MethodDeclaration||u.getKind()===s.GetAccessor||u.getKind()===s.SetAccessor){let g=u.getBody();return g?d(g):!1}return!1});if(e.getKind()===s.ArrowFunction||e.getKind()===s.FunctionExpression){let u=e.getBody();if(u.getKind()===s.Block){let g=u;return g.getDescendantsOfKind(s.ReturnStatement).some(h=>{if(!a(h,g))return!1;let y=h.getExpression();return y!==void 0&&oe(y,t,r)})?!0:l(g)?!1:d(g)}return oe(u,t,r)}if(e.getKind()===s.CallExpression)return o(e);if(e.getKind()===s.AwaitExpression){let f=e.getExpression();return f.getKind()!==s.CallExpression?!1:o(f)}if(e.getKind()===s.ConditionalExpression){let f=e;return oe(f.getWhenTrue(),t,r)||oe(f.getWhenFalse(),t,r)}if(e.getKind()===s.PropertyAccessExpression){let f=e.getText(),u=f.indexOf(".");return u>0&&n(f.slice(0,u))?!1:[...t].some(g=>f.startsWith(`${g}.`))}return!1};function Me(e){return e==="effect"||e.startsWith("effect/")||e.startsWith("@effect/")}var En=new Set(["Effect","Layer","Schedule","Stream","Queue","PubSub","Deferred","Semaphore","Mailbox","SubscriptionRef","Scope","Fiber","Runtime","ManagedRuntime","Cause","Exit","Data","Option","Either","Chunk","HashMap","HashSet","Match","Config","Schema","Cache","ScopedCache","Metric","Logger","Tracer","Context","Brand","Encoding","Predicate","DateTime","Cron","BigDecimal","Graph","HashRing","Redacted","GlobalValue","NodeRuntime","BunRuntime","DenoRuntime","Channel","Sink"]),Vr=new Set(["core","core-effect","core-stream","fiberRuntime","effectable","channel","sink","layer","schedule","mailbox","pubsub"]);function Jr(e){let t=new Set(["never","unknown","any","{}","object"]),r=e.trim();return!r||t.has(r)?[]:r.split(/[\s|&]+/).map(n=>n.trim().split("<")[0]?.trim()??"").filter(n=>n.length>0&&!t.has(n))}function pt(e){let{SyntaxKind:t}=w(),r=e.getKind();if(r===t.NumericLiteral){let s=e.getText(),n=Number(s);return Number.isFinite(n)?n:void 0}if(r===t.PrefixUnaryExpression){let s=e;if(s.getOperatorToken()===t.MinusToken){let n=s.getOperand(),i=pt(n);return i!==void 0?-i:void 0}}}import{existsSync as Xi}from"fs";import{dirname as bn,resolve as gt,join as Oe,sep as Qr}from"path";var Zr=new WeakMap,Yr=new WeakMap;function Nn(e){let t=new Set;for(let r of e.getExportDeclarations()){let s=r.getModuleSpecifierValue();if(!(!s||!Me(s))){if(r.isNamespaceExport()){En.forEach(n=>t.add(n));continue}for(let n of r.getNamedExports()){t.add(n.getName());let i=n.getAliasNode()?.getText();i&&t.add(i)}}}return t}function Xe(e,t,r){if(!r.startsWith("."))return;let s=bn(t),n=gt(s,r),i=[n,`${n}.ts`,`${n}.tsx`,`${n}.js`,`${n}.jsx`,Oe(n,"index.ts"),Oe(n,"index.tsx"),Oe(n,"index.js"),Oe(n,"index.jsx")];for(let c of i){let o=e.getSourceFile(c);if(o)return o}}function mt(e,t){if(!t.startsWith("."))return;let r=bn(e),s=gt(r,t);return[s,`${s}.ts`,`${s}.tsx`,`${s}.js`,`${s}.jsx`,Oe(s,"index.ts"),Oe(s,"index.tsx"),Oe(s,"index.js"),Oe(s,"index.jsx")].find(i=>Xi(i))}function It(e,t,r){if(!r||!t.startsWith("."))return!1;let s=t.replace(/\\/g,"/"),n=gt(bn(e),t),i=gt(n),c=gt(r);return i===c||i.startsWith(c+Qr)?!0:e==="temp.ts"||e.endsWith(`${Qr}temp.ts`)?s.startsWith("./internal/")||s.startsWith("../internal/"):!1}function eo(e){let t=new Set(En),r=e.getProject(),s=e.getFilePath();for(let n of e.getImportDeclarations()){let i=n.getModuleSpecifierValue();if(Me(i)){let c=n.getDefaultImport();c&&t.add(c.getText());let o=n.getNamespaceImport();o&&t.add(o.getText());for(let a of n.getNamedImports()){let d=a.getAliasNode()?.getText();t.add(d??a.getName())}continue}if(i.startsWith(".")){let c=Xe(r,s,i);if(!c)continue;let o=Nn(c);if(o.size===0)continue;let a=n.getDefaultImport();if(a){let l=a.getText();o.has(l)&&t.add(l)}let d=n.getNamespaceImport();if(d){let l=d.getText();o.has(l)&&t.add(l)}for(let l of n.getNamedImports())o.has(l.getName())&&t.add(l.getAliasNode()?.getText()??l.getName())}}return t}function Cn(e,t){let r=eo(e);for(let s of e.getImportDeclarations()){let n=s.getModuleSpecifierValue(),i=s.getNamespaceImport();if(!i)continue;let c=i.getText();if(n.startsWith("effect")||n.startsWith("@effect/")){r.add(c);continue}if(It(e.getFilePath(),n,t)){r.add(c);continue}let o=n.replace(/\.(js|ts)$/,"").split("/").pop()??"";Vr.has(o)&&r.add(c)}return r}var to=new Set(["BigDecimal","BigInt","Brand","Cause","Chunk","Data","Exit","Option","Either","HashMap","HashSet","List","Redacted"]);function es(e){let t=new Set;for(let r of e.getImportDeclarations()){let i=r.getModuleSpecifierValue().replace(/\\/g,"/").replace(/\.(js|ts|tsx|jsx)$/,"").split("/").pop()??"";if(!to.has(i))continue;let c=r.getDefaultImport();c&&t.add(c.getText());let o=r.getNamespaceImport();o&&t.add(o.getText());for(let a of r.getNamedImports())t.add(a.getAliasNode()?.getText()??a.getName())}return t}function Le(e){let t=Zr.get(e);return t||(t=Cn(e),Zr.set(e,t)),t}var Xr=new WeakMap;function no(e){let t=e.replace(/\\/g,"/").replace(/\.(js|ts|mts|cts)$/,"");return t==="effect"||t.endsWith("/Effect")?"Effect":(t.split("/").pop()??"")||"Effect"}function ro(e){let t=Xr.get(e);if(t)return t;t=new Map;for(let r of e.getImportDeclarations()){let s=r.getModuleSpecifierValue();if(!s||!Me(s))continue;let n=r.getNamespaceImport();if(!n)continue;let i=n.getText(),c=no(s);t.set(i,c)}return Xr.set(e,t),t}function wn(e,t){let r=e.indexOf(".");if(r<=0)return e;let s=e.slice(0,r),n=e.slice(r+1),c=ro(t).get(s);return c?`${c}.${n}`:e}function so(e,t){let r=Yr.get(t);r||(r=new Map,Yr.set(t,r));let s=e.indexOf("."),n=s>0?e.slice(0,s):e,i=r.get(n);if(i!==void 0)return i;let c=!1;try{for(let o of t.getImportDeclarations()){let a=o.getModuleSpecifierValue();if(o.getNamespaceImport()?.getText()===n){c=Me(a);break}if(o.getDefaultImport()?.getText()===n){c=Me(a);break}for(let f of o.getNamedImports())if((f.getAliasNode()?.getText()??f.getName())===n){if(Me(a))c=!0;else if(a.startsWith(".")){let p=Xe(t.getProject(),t.getFilePath(),a);p&&(c=Nn(p).has(f.getName()))}break}if(c)break}}catch{c=!1}return r.set(n,c),c}function io(e,t){let s=e.getExpression().getText();for(let n of t.getImportDeclarations()){let i=n.getModuleSpecifierValue();if(n.getNamespaceImport()?.getText()===s||n.getDefaultImport()?.getText()===s)return i;for(let a of n.getNamedImports())if((a.getAliasNode()?.getText()??a.getName())===s)return i}}function et(e,t,r,s){let n=e.getExpression(),i=n.getText();if(Sn.some(d=>i.startsWith(d))||i.startsWith("pipe("))return!0;for(let d of r)if(i.startsWith(`${d}.`))return!0;let{SyntaxKind:c}=w();if(n.getKind()!==c.PropertyAccessExpression)return!1;let o=n,a=io(o,t);if(!a)return!1;if(Me(a))return!0;if(a.startsWith(".")){let d=Xe(t.getProject(),t.getFilePath(),a);if(d){let l=Nn(d),f=o.getExpression().getText();for(let u of t.getImportDeclarations())if(u.getModuleSpecifierValue()===a){for(let g of u.getNamedImports())if((g.getAliasNode()?.getText()??g.getName())===f&&l.has(g.getName()))return!0}}if(It(t.getFilePath(),a,s))return!0}return!1}function $t(e,t,r){if(Sn.some(s=>e.startsWith(s))||e.startsWith("pipe("))return!0;if(t){for(let s of t)if(e.startsWith(`${s}.`))return!0}return r&&e.includes(".")?so(e,r):!1}var oo=new Set(["createWorkflow","createSagaWorkflow","runSaga"]),ao=e=>Array.from(oo).some(t=>e===t||e.endsWith(`.${t}`)),ts=e=>{let t=e.getExpression();if(t.getKind()!==w().SyntaxKind.PropertyAccessExpression)return!1;let r=t,s=e.getArguments();if(r.getName()!=="make"||s.length<3||!s[2])return!1;let n=s[2].getKind(),{SyntaxKind:i}=w();return n===i.ArrowFunction||n===i.FunctionExpression};function is(e,t){let r=e.replace(/\\/g,"/");return!!(r==="@effect/workflow"||r==="effect/workflow"||r.endsWith("/workflow")||r.includes("/workflow/")||r.endsWith("/Workflow.js")||r.endsWith("/Workflow.ts")||r.endsWith("/Activity.js")||r.endsWith("/Activity.ts")||r.startsWith(".")&&(r.endsWith("Workflow.js")||r.endsWith("Workflow.ts")||r.endsWith("Activity.js")||r.endsWith("Activity.ts")))}function co(e,t,r){return e!=="Workflow"?!1:is(t,r)}function lo(e,t,r){return e!=="Activity"?!1:is(t,r)}function os(e,t){let{SyntaxKind:r}=w(),s=e.getArguments();if(s.length!==1||!s[0])return!1;let n=s[0];if(n.getKind()!==r.ObjectLiteralExpression)return!1;let c=n.getProperties(),o=new Set(t);for(let a of c)if(a.getKind()===r.PropertyAssignment){let d=a.getName();if(o.has(d))return!0}return!1}function uo(e,t,r){let{SyntaxKind:s}=w(),n=e.getExpression();if(n.getKind()!==s.PropertyAccessExpression)return!1;let i=n;if(i.getName()!=="make")return!1;let c=i.getExpression().getText(),o=t.get(c);return!o||!co(c,o,r)?!1:os(e,["name","payload","idempotencyKey"])}function fo(e,t,r){let{SyntaxKind:s}=w(),n=e.getExpression();if(n.getKind()!==s.PropertyAccessExpression)return!1;let i=n;if(i.getName()!=="make")return!1;let c=i.getExpression().getText(),o=t.get(c);return!o||!lo(c,o,r)?!1:os(e,["name","execute"])}var as=(e,t)=>{let r=e.getExpression();if(r.getKind()!==w().SyntaxKind.PropertyAccessExpression||r.getName()!=="run")return null;let n=e.getArguments();if(n.length<1||!n[0])return null;let i=n[0],{SyntaxKind:c}=w();if(i.getKind()===c.CallExpression){let l=i;return ts(l)?l.getArguments()[2]??null:null}if(i.getKind()!==c.Identifier)return null;let a=i.getText(),d=t.getDescendantsOfKind(c.VariableDeclaration);for(let l of d){if(l.getName()!==a)continue;let f=l.getInitializer();if(f?.getKind()===c.CallExpression&&ts(f))return f.getArguments()[2]??null}return null},po=e=>{let{SyntaxKind:t}=w(),r=e.getParent();for(;r;){if(r.getKind()===t.CallExpression){let n=r.getExpression().getText();if(n.includes(".gen")||n==="gen")return!0}r=r.getParent()}return!1},go=e=>{let{SyntaxKind:t}=w();return e.getFirstAncestorByKind(t.VariableStatement)?.getParent()?.getKind()===t.SourceFile},mo=e=>{let{SyntaxKind:t}=w(),r=e.getInitializer();return r?r.getKind()===t.YieldExpression||r.getKind()===t.AwaitExpression&&r.getExpression().getKind()===t.YieldExpression:!1},ns=e=>{let{SyntaxKind:t}=w();if(e.getKind()===t.CallExpression)return e;if(e.getKind()===t.AwaitExpression){let r=e.getExpression();if(r.getKind()===t.CallExpression)return r}},V=(e,t)=>({discoveryConfidence:e,discoveryReason:t}),yo=["Effect<","Layer<","Layer.Layer<","Stream<","Stream.Stream<","Channel<","Channel.Channel<","Sink<","Sink.Sink<","STM<","STM.STM<","Schedule<","Schedule.Schedule<"],Ft=e=>e!==void 0&&yo.some(t=>e.includes(t)),rs={low:0,medium:1,high:2},Tn=e=>{let t=e.getExpression().getText();return t.includes(".runPromise")||t.includes(".runPromiseExit")||t.includes(".runSync")||t.includes(".runSyncExit")||t.includes(".runFork")||t.includes(".runCallback")||t.includes(".runMain")||t.includes("Runtime.runPromise")||t.includes("Runtime.runSync")||t.includes("Runtime.runFork")};function ss(e){let t=e.getBody?.();if(!t)return!1;let r=t.getText();return r.includes(".runMain")||r.includes(".runPromise")||r.includes(".runSync")||r.includes(".runFork")||r.includes("Runtime.runPromise")||r.includes("Runtime.runSync")||r.includes("NodeRuntime.runMain")||r.includes("BunRuntime.runMain")||r.includes("DenoRuntime.runMain")}function ho(e,t){let r=e.getExpression();if(r.getKind()!==w().SyntaxKind.Identifier)return!1;let i=r.getSymbol()?.getValueDeclaration();if(!i)return!1;let c=i.getKind(),{SyntaxKind:o}=w();if(c===o.FunctionDeclaration||c===o.ArrowFunction||c===o.FunctionExpression)return ss(i);if(c===o.VariableDeclaration){let a=i.getInitializer();if(a&&(a.getKind()===o.ArrowFunction||a.getKind()===o.FunctionExpression))return ss(a)}return!1}function So(e){let t=e.getExpression();if(e.getArguments().length!==1)return!1;let{SyntaxKind:r}=w();if(t.getKind()!==r.CallExpression)return!1;let s=t;if(s.getArguments().length!==1)return!1;let n=s.getExpression().getText();return n.includes(".runPromise")||n.includes(".runSync")||n.includes(".runFork")||n.includes(".runCallback")||n.includes("Runtime.runPromise")||n.includes("Runtime.runSync")||n.includes("Runtime.runFork")}var kn=(e,t)=>{let r=[],{SyntaxKind:s}=w(),n=new Set,i=new Set,c=Cn(e,t.knownEffectInternalsRoot),o=es(e),a=new Map;for(let S of e.getImportDeclarations()){let b=S.getModuleSpecifierValue(),T=S.getDefaultImport();T&&a.set(T.getText(),b);let v=S.getNamespaceImport();v&&a.set(v.getText(),b);for(let x of S.getNamedImports())a.set(x.getAliasNode()?.getText()??x.getName(),b)}let d=S=>{let b=a.get(S);if(b){if(b.startsWith("effect")||b.startsWith("@effect/"))return V("high",`imported from ${b}`);if(It(e.getFilePath(),b,t.knownEffectInternalsRoot))return V("high","namespace import resolved under knownEffectInternalsRoot");if(b.startsWith(".")&&/(?:^|\/)Effect(?:\.[jt]sx?)?$/.test(b))return V("high",`relative Effect module namespace import (${b})`)}},l=S=>{let b=v=>{let x=v.getDescendantsOfKind(s.PropertyAccessExpression);for(let F of x){let j=F.getExpression().getText();if(c.has(j)&&!o.has(j))return d(j)?.discoveryConfidence==="high"?V("high",`function body uses ${j}.* from trusted Effect alias`):V("medium",`function body uses Effect-like alias ${j}.*`)}let K=v.getDescendantsOfKind(s.CallExpression);for(let F of K){let j=F.getExpression();if(j.getKind()===s.Identifier){let I=j.getText();if(c.has(I)&&!o.has(I))return d(I)?.discoveryConfidence==="high"?V("high",`function body calls trusted Effect import ${I}(...)`):V("medium",`function body calls Effect-like import ${I}(...)`)}}};if(S.getKind()===s.ArrowFunction||S.getKind()===s.FunctionExpression){let x=S.getBody();if(x.getKind()===s.Block){let K=b(x);if(K)return K}else{let K=b(x);if(K)return K}}let T=ns(S);if(T){let v=T.getExpression(),x=v.getText();if(v.getKind()===s.Identifier){let K=x;if(c.has(K)&&!o.has(K))return d(K)??V("high",`named import call (${K})`);if(K==="pipe")return V("medium","exact pipe() call detection")}if(v.getKind()===s.PropertyAccessExpression){let K=v,F=K.getExpression().getText();if(c.has(F)&&!o.has(F))return d(F)??V("medium",`Effect-like namespace prefix (${F}.*)`);if(K.getName()==="pipe")return V("medium","exact .pipe() call detection")}}if(S.getKind()===s.PropertyAccessExpression){let x=S.getExpression().getText();if(c.has(x)&&!o.has(x))return d(x)??V("medium",`Effect-like namespace property access (${x}.*)`)}if(S.getKind()===s.AwaitExpression){let v=S.getExpression();if(v.getKind()===s.CallExpression)return l(v)}return V("low","heuristic direct initializer match")},f=S=>{let T=(x=>x.getTypeNode?.()?.getText())(S);if(Ft(T))return V("high","explicit Effect-family type annotation");let v=S.getKind()===s.VariableDeclaration?S.getFirstAncestorByKind(s.VariableStatement)?.isExported()??!1:S.getKind()===s.PropertyDeclaration||S.getKind()===s.MethodDeclaration||S.getKind()===s.GetAccessor?S.getFirstAncestorByKind(s.ClassDeclaration)?.isExported()??!1:!1;if(S.getKind()===s.VariableDeclaration||S.getKind()===s.PropertyDeclaration){let x=S.getInitializer();if(x&&(x.getKind()===s.ArrowFunction||x.getKind()===s.FunctionExpression)){let F=x.getReturnTypeNode()?.getText();if(Ft(F))return V("high","function return type annotated as Effect-family");if(v&&T)return V("medium","explicit exported function API type signature")}if(x?.getKind()===s.CallExpression){let F=x.getTypeArguments().map(j=>j.getText()).join(" ");if(Ft(F))return V("high","call type arguments reference Effect-family types");if(v&&T)return V("medium","explicit exported call-based API type signature")}}if(S.getKind()===s.MethodDeclaration||S.getKind()===s.GetAccessor){let x=S.getReturnTypeNode?.()?.getText();if(Ft(x))return V("high","method/getter return type annotated as Effect-family");if(v&&T)return V("medium","explicit exported method/getter API type signature")}},u=S=>{let b=S.node,T=b.getKind();return T===s.CallExpression?!0:T===s.VariableDeclaration?b.getFirstAncestorByKind(s.VariableStatement)?.isExported()??!1:T===s.FunctionDeclaration||T===s.ClassDeclaration?b.isExported():T===s.PropertyDeclaration||T===s.MethodDeclaration||T===s.GetAccessor?b.getFirstAncestorByKind(s.ClassDeclaration)?.isExported()??!1:!0},g=S=>{for(let b of S){let T=b.getExpression();if(T&&oe(T,c,o))return l(T)}return V("low","heuristic method return match")},p=e.getFilePath(),m=e.getDescendantsOfKind(s.VariableDeclaration);for(let S of m){let b=S.getInitializer();if(b?.getKind()===s.CallExpression&&ao(b.getExpression().getText())&&i.add(S.getName()),t.enableEffectWorkflow&&b?.getKind()===s.CallExpression){let T=b;(uo(T,a,p)||fo(T,a,p))&&i.add(S.getName())}}let h=e.getDescendantsOfKind(s.CallExpression);for(let S of h){let b=S.getExpression(),T=b.getText(),v=S.getStart(),x=!1;if(b.getKind()===s.Identifier)x=i.has(T);else if(b.getKind()===s.PropertyAccessExpression){let F=b,j=F.getExpression().getText(),I=F.getName();if(x=i.has(j)&&I==="run",t.enableEffectWorkflow&&!x&&I==="run"&&S.getArguments().length===1&&!T.includes("runPromise")&&!T.includes("runSync")&&!T.includes("runFork")&&!T.includes("runCallback")&&!n.has(v)){let q=He(S)??`workflow-${r.length+1}`;r.push({name:q,node:S,type:"run",...V("low","workflow-like .run(...) shape heuristic")}),n.add(v);continue}}if(x&&!n.has(v)){let F=He(S)??`workflow-${r.length+1}`;r.push({name:F,node:S,type:"run",...V("medium","workflow builder invocation")}),n.add(v);continue}if(t.enableEffectWorkflow&&b.getKind()===s.PropertyAccessExpression){let F=b,j=F.getExpression().getText(),I=F.getName();if((I==="execute"||I==="executeEncoded")&&i.has(j)&&!n.has(v)){let z=He(S)??`${j}.${I}`;r.push({name:z,node:S,type:"workflow-execute",...V("medium","workflow/activity .execute entrypoint")}),n.add(v);continue}}if((T==="gen"||T.includes(".gen")&&et(S,e,c,t.knownEffectInternalsRoot))&&!n.has(v)){let F=He(S)??Dr(S)??`program-${r.length+1}`;r.push({name:F,node:S,type:"generator",...T==="gen"?V("medium","unqualified gen(...) call"):V("high","Effect-like .gen(...) call")}),n.add(v)}let K=He(S);if(T.includes("pipe")&&xo(S,c)&&!n.has(v)&&b.getKind()!==s.PropertyAccessExpression&&K!==void 0&&!po(S)&&(r.push({name:K,node:S,type:"pipe",...V("medium","exact pipe(...) call with Effect-like args")}),n.add(v)),(Tn(S)||So(S))&&!n.has(v)){let F=He(S)??`run-${r.length+1}`;r.push({name:F,node:S,type:"run",...V("high","recognized Runtime/Effect run* entrypoint")}),n.add(v)}}for(let S of m){if(!go(S)||mo(S))continue;let b=S.getInitializer();if(b){let T=S.getName(),v=ns(b);if(v&&Tn(v)||b.getKind()===s.ObjectLiteralExpression)continue;oe(b,c,o)&&!r.some(K=>K.name===T)&&r.push({name:T,node:S,type:"direct",...f(S)??l(b)})}}let y=e.getStatements();for(let S of y){if(S.getKind()!==s.ExpressionStatement)continue;let b=S.getExpression();if(b.getKind()!==s.CallExpression)continue;let T=b,v=T.getStart();if(n.has(v))continue;let x=T.getExpression(),K=x.getText();if(Tn(T)){let F=`run-${r.length+1}`;r.push({name:F,node:T,type:"run",...V("high","recognized top-level run* entrypoint")}),n.add(v);continue}if(K.endsWith(".pipe")||K==="pipe"){let F=T.getArguments(),j=F[F.length-1];if(!j)continue;let I=j.getText();if(I.includes(".runMain")||I.includes(".runPromise")||I.includes(".runSync")||I.includes(".runFork")){let z;x.getKind()===s.PropertyAccessExpression&&(z=x.getExpression().getText().split(".").pop());let Y=z&&!r.some(Z=>Z.name===z)?z:`entrypoint-${r.length+1}`;r.push({name:Y,node:T,type:"run",...V("medium","top-level pipe(...).run* terminator pattern")}),n.add(v)}}if(x.getKind()===s.Identifier&&T.getArguments().length>=1){let F=x.getText();ho(T,e)&&!r.some(I=>I.name===F)&&(r.push({name:F,node:T,type:"run",...V("low","indirect run wrapper body heuristic")}),n.add(v))}}let N=["Data.TaggedError","Data.TaggedClass","Data.Class","Data.Error","Schema.Class","Schema.TaggedClass","Schema.TaggedError","Schema.TaggedRequest","Context.Tag","Context.Reference","Effect.Service"],E=e.getDescendantsOfKind(s.ClassDeclaration);for(let S of E){let b=S.getName();if(!b||r.some(x=>x.name===b))continue;S.getHeritageClauses().some(x=>{let K=x.getText();return N.some(F=>K.includes(F))})&&r.push({name:b,node:S,type:"class",...V("medium","known Data/Schema/Context class pattern")})}let $=E.filter(S=>{let b=S.getParent();return b===e||b?.getParent()===e});for(let S of $){let b=S.getName()??"Anonymous",T=S.getMembers(),v=T.filter(F=>F.getKind()===s.PropertyDeclaration);for(let F of v){let j=F.getInitializer();if(!j)continue;let I=F.getName(),q=`${b}.${I}`;r.some(z=>z.name===q)||oe(j,c,o)&&r.push({name:q,node:F,type:"classProperty",...f(F)??l(j)})}let x=T.filter(F=>F.getKind()===s.MethodDeclaration);for(let F of x){let j=F.getName(),I=`${b}.${j}`;if(r.some(Z=>Z.name===I))continue;let q=F.getBody();if(!q)continue;let z=q.getDescendantsOfKind(s.ReturnStatement);z.some(Z=>{let L=Z.getExpression();return L?oe(L,c,o):!1})&&r.push({name:I,node:F,type:"classMethod",...f(F)??g(z)})}let K=T.filter(F=>F.getKind()===s.GetAccessor);for(let F of K){let j=F.getName(),I=`${b}.${j}`;if(r.some(Z=>Z.name===I))continue;let q=F.getBody();if(!q)continue;let z=q.getDescendantsOfKind(s.ReturnStatement);z.some(Z=>{let L=Z.getExpression();return L?oe(L,c,o):!1})&&r.push({name:I,node:F,type:"classMethod",...f(F)??g(z)})}}return r.filter(S=>{let b=t.minDiscoveryConfidence??"low",T=S.discoveryConfidence??"low";return!(rs[T]<rs[b]||t.onlyExportedPrograms&&!u(S))})},xo=(e,t)=>e.getArguments().map(n=>n.getText()).some(n=>[...t].some(i=>n.includes(`${i}.`)));function cs(e){let{SyntaxKind:t}=w(),r=[],s=e.getProject().getTypeChecker(),n=e.getDescendantsOfKind(t.ClassDeclaration);for(let i of n){let c=i.getName();if(!c)continue;let o=i.getExtends();if(!o)continue;let a=o.getText();if(!a.includes("Context.Tag")&&!a.includes("Effect.Service"))continue;let d=o.getTypeArguments();if(d.length<2){let f=o.getExpression();f&&"getTypeArguments"in f&&typeof f.getTypeArguments=="function"&&(d=f.getTypeArguments())}if(d.length<2)continue;let l=d[1];if(l)try{let f=s.getTypeAtLocation(l),u=[],g=[];for(let y of f.getProperties()){let N=y.getName();if(N.startsWith("_")||N==="constructor")continue;s.getTypeOfSymbolAtLocation(y,l).getCallSignatures().length>0?u.push(N):g.push(N)}let p=i.getText(),m=p.includes("Equal.symbol")||p.includes("[Equal")||p.includes("equal("),h=p.includes("Hash.symbol")||p.includes("[Hash")||p.includes("hash(");r.push({tagId:c,methods:u,properties:g,...m?{hasCustomEquality:m}:{},...h?{hasCustomHash:h}:{}})}catch{}}for(let i of n){let c=i.getName();if(!c)continue;let o=i.getExtends();if(!o)continue;let a=o.getText();if(!a.includes("Data.Class")&&!a.includes("Data.TaggedClass")||r.some(u=>u.tagId===c))continue;let d=i.getText(),l=d.includes("Equal.symbol")||d.includes("[Equal")||d.includes("equal("),f=d.includes("Hash.symbol")||d.includes("[Hash")||d.includes("hash(");(l||f)&&r.push({tagId:c,methods:[],properties:[],hasCustomEquality:l,hasCustomHash:f})}return r}import{Effect as xe,Option as yt}from"effect";import{Effect as ee,Option as Eo}from"effect";var Rt=(e,t,r,s,n,i)=>ee.gen(function*(){let{SyntaxKind:c}=w(),o=e.getArguments(),a=e.getExpression(),d=a.getKind()===c.PropertyAccessExpression&&a.getName()==="pipe",l=d?a.getExpression():o[0],f=d?o:o.slice(1);if(!l)return[];let u=ds(l),g=u.getSourceFile(),p=g.getFilePath(),m=t.getProject();if(m.getSourceFile(p)){let S=m.getSourceFile(p);S&&(g=S)}else{let S=m.addSourceFileAtPath(p);S&&(g=S)}let h=yield*M(u,g,g.getFilePath(),s,n,i),y=[];for(let S of f)if(S){let b=yield*M(S,t,r,s,n,i);y.push(b)}let N;try{let S=t.getProject().getTypeChecker(),b=[],T=Ze(l,S);T&&b.push(T);for(let v of f)if(v){let x=Ze(v,S);x&&b.push(x)}b.length>0&&(N=b)}catch{}let E={id:C(),type:"pipe",initial:h,transformations:y,...N?{typeFlow:N}:{}};return[{...E,displayName:G(E),semanticRole:Q(E)}]}),M=(e,t,r,s,n,i,c)=>ee.gen(function*(){let{SyntaxKind:o}=w();if(e.getKind()===o.ArrowFunction||e.getKind()===o.FunctionExpression){let l=e.getBody();if(!l){let u={id:C(),type:"unknown",reason:"Function has no body",sourceCode:e.getText().slice(0,100),location:_(e,r,s.includeLocations??!1)};return i.unknownCount++,u}if(l.getKind()===o.Block){let p=l.getStatements().find(m=>m.getKind()===o.ReturnStatement)?.getExpression();if(p)return yield*M(p,t,r,s,n,i,c)}else return yield*M(l,t,r,s,n,i,c);let f={id:C(),type:"unknown",reason:"Function does not return an Effect expression",sourceCode:e.getText().slice(0,100),location:_(e,r,s.includeLocations??!1)};return i.unknownCount++,f}if(e.getKind()===o.CallExpression)return yield*vn(e,t,r,s,n,i,c);if(e.getKind()===o.PropertyAccessExpression){let d=e.getText();if(d==="Fiber.roots"||d==="Fiber.getCurrentFiber"){let l=d==="Fiber.roots"?"roots":"getCurrentFiber";return{id:C(),type:"fiber",operation:l,isScoped:!1,isDaemon:!1,location:_(e,r,s.includeLocations??!1)}}if($t(d,Le(t),t)){let l={id:C(),type:"effect",callee:d,location:_(e,r,s.includeLocations??!1)};return i.totalEffects++,l}}if(e.getKind()===o.Identifier){let d={id:C(),type:"effect",callee:e.getText(),location:_(e,r,s.includeLocations??!1)};return i.totalEffects++,d}if(e.getKind()===o.ObjectLiteralExpression){let d=e,l=new Set(["onNone","onSome","onFailure","onSuccess","onLeft","onRight"]),f=d.getProperties(),u=[],g=!1;for(let p of f){if(p.getKind()!==o.PropertyAssignment)continue;let m=p,h=m.getName();if(!l.has(h))continue;g=!0;let y=m.getInitializer();if(y){let N=yield*M(y,t,r,s,n,i,c);u.push(N)}}if(g&&u.length>0)return u.length===1?u[0]:{id:C(),type:"parallel",callee:"match-handlers",mode:"sequential",children:u,location:_(e,r,s.includeLocations??!1)}}let a={id:C(),type:"unknown",reason:"Could not determine effect type",sourceCode:e.getText().slice(0,100),location:_(e,r,s.includeLocations??!1)};return i.unknownCount++,a}),vn=(e,t,r,s,n,i,c)=>ee.gen(function*(){let{SyntaxKind:o}=w(),a=e.getExpression().getText(),d=wn(a,t),l=/([A-Za-z_$][\w$]*)$/.exec(d)?.[1]??d,f=_(e,r,s.includeLocations??!1);if(a==="pipe"&&e.getArguments().length>=1){let L=yield*Rt(e,t,r,s,n,i);if(L.length>0&&L[0])return L[0]}if(d==="Context.pick"||d==="Context.omit"){let L={id:C(),type:"effect",callee:d,description:"context",location:f};return i.totalEffects++,{...L,displayName:G(L),semanticRole:Q(L)}}if(d.startsWith("Layer."))return yield*wo(e,d,t,r,s,n,i);if(d.startsWith("Stream."))return yield*To(e,d,t,r,s,n,i);if(d.startsWith("Channel."))return yield*vo(e,d,t,r,s,n,i);if(a.startsWith("Sink."))return yield*$o(e,a,t,r,s,n,i);if(a.startsWith("Queue.")||a.startsWith("PubSub.")||a.startsWith("Deferred.")||a.startsWith("Semaphore.")||a.startsWith("Mailbox.")||a.startsWith("SubscriptionRef.")||a.startsWith("RateLimiter.")||a.startsWith("PartitionedSemaphore.")||a.startsWith("FiberHandle.")||a.startsWith("FiberSet.")||a.startsWith("FiberMap.")||a.startsWith("Cache.")||a.startsWith("ScopedCache.")||a.startsWith("RcRef.")||a.includes(".RcRef.")||a.startsWith("RcMap.")||a.includes(".RcMap.")||a.startsWith("Reloadable.")||a.includes(".Reloadable.")||a.includes("makeLatch")||a.includes("Latch."))return yield*Fo(e,a,t,r,s,n,i);if(un.some(L=>a.includes(L)||a.startsWith(L)))return yield*Ao(e,a,t,r,s,n,i);if(hn.some(L=>a.includes(L)))return yield*Ro(e,a,t,r,s,n,i);if(a.includes(".all")||a==="all")return yield*Po(e,a,t,r,s,n,i);if(a.includes(".race")||a==="race")return yield*Mo(e,a,t,r,s,n,i);if(cn.some(L=>a.includes(L)))return yield*Oo(e,a,t,r,s,n,i);if(a.includes(".retry"))return yield*Lo(e,t,r,s,n,i);if(a.includes(".timeout"))return yield*Wo(e,t,r,s,n,i);let g=new Set(["acquireRelease","acquireUseRelease","ensuring","addFinalizer","onExit","onError","parallelFinalizers","sequentialFinalizers","finalizersMask","using","withEarlyRelease"]),p=["acquireRelease","acquireUseRelease"],m=L=>g.has(L)||p.some(H=>L.startsWith(H));if(l==="pipe"&&e.getExpression().getKind()===o.PropertyAccessExpression){let H=e.getExpression().getExpression();if(H.getKind()===o.CallExpression){let ge=H,de=ge.getExpression().getText(),ne=/([A-Za-z_$][\w$]*)$/.exec(de)?.[1]??de;if(m(ne))return yield*ls(ge,ne,t,r,s,n,i)}}if(m(l))return yield*ls(e,l,t,r,s,n,i);if(ln.some(L=>a.includes(L)))return yield*Ko(e,a,t,r,s,n,i);if(dn.some(L=>a.includes(L)))return yield*jo(e,a,t,r,s,n,i);if(Lr(a))return yield*Ho(e,a,t,r,s,n,i);if(Kr(a))return Bo(e,a,r,s);if(Br(a))return yield*qo(e,a,t,r,s,n,i);if(zr(a))return zo(e,a,r,s);if(_r(a))return yield*_o(e,a,r,s);i.totalEffects++;let h,N=["Effect.sync","Effect.promise","Effect.async","Effect.asyncEffect","Effect.tryPromise","Effect.suspend"].some(L=>a.includes(L))&&e.getArguments().length>0&&e.getArguments()[0],E;if(N){let L=e.getArguments()[0],{SyntaxKind:H}=w();if(L.getKind()===H.ArrowFunction||L.getKind()===H.FunctionExpression){let de=L,ne=de.getBody(),we=[];if(ne){if(ne.getKind()===H.Block){let ve=ne;for(let te of ve.getStatements())if(te.getKind()===H.ReturnStatement){let A=te.getExpression();if(A&&$t(A.getText(),Le(t),t)){let W=yield*M(A,t,r,s,n,i,void 0);we.push(W)}}else if(te.getKind()===H.ExpressionStatement){let A=te.getExpression();if(A.getKind()===H.CallExpression&&et(A,t,Le(t),s.knownEffectInternalsRoot)){let W=yield*M(A,t,r,s,n,i,void 0);we.push(W)}}}else if($t(ne.getText(),Le(t),t)){let ve=yield*M(ne,t,r,s,n,i,void 0);we.push(ve)}}if(we.length>0&&(h=we),a.includes("Effect.async")||a.includes("Effect.asyncEffect")){let ve=de.getParameters()[0]?.getName?.()??"resume",te=0,A=Ie=>{if(Ie.getKind()===H.CallExpression){let ut=Ie.getExpression();ut.getKind()===H.Identifier&&ut.getText()===ve&&te++}Ie.getChildren().forEach(A)};ne&&A(ne);let W=!1;if(ne?.getKind()===H.Block){let Ie=ne;for(let nn of Ie.getStatements())if(nn.getKind()===H.ReturnStatement){let ut=nn.getExpression();if(ut){let xr=ut.getKind();if(xr===H.ArrowFunction||xr===H.FunctionExpression){W=!0;break}}}}else ne&&(ne.getKind()===H.ArrowFunction||ne.getKind()===H.FunctionExpression)&&(W=!0);E={resumeParamName:ve,resumeCallCount:te,returnsCanceller:W}}}}let $=_e(e),S=t.getProject().getTypeChecker(),b=Ze(e,S),T=wt(e,S),v=bo(e,t),x,K=e.getExpression();if(K.getKind()===w().SyntaxKind.PropertyAccessExpression){let L=K,H=L.getExpression().getText(),ge=L.getName();if(c){let de=c.get(H);de&&(x={serviceId:de,methodName:ge})}!x&&T?.length===1&&T[0]&&(x={serviceId:T[0].serviceId,methodName:ge})}let F;if(a==="Effect.provide"||a.startsWith("Effect.")&&a.includes(".provide")&&!a.includes("provideService")){let L=e.getArguments(),H=(L.length>=2?L[1]:L[0])?.getText()??"";/Runtime\.|defaultRuntime|\.runSync|\.runPromise|\.runFork|\.runCallback/.test(H)||/^\s*runtime\s*$|^\s*rt\s*$/i.test(H.trim())?F="runtime":H.includes("Layer.")?F="layer":F="context"}let j;a.endsWith(".sync")||a.endsWith(".succeed")||a.endsWith(".fail")||a.endsWith(".try")||a.endsWith(".suspend")?j="sync":a.endsWith(".promise")?j="promise":a.endsWith(".async")||a.endsWith(".asyncEffect")?j="async":a.endsWith(".never")?j="never":a.endsWith(".void")?j="void":a.endsWith(".fromNullable")?j="fromNullable":a.endsWith(".fn")?j="fn":a.endsWith(".fnUntraced")&&(j="fnUntraced");let I,q=["currentConcurrency","currentLogLevel","currentScheduler","currentTracerEnabled","currentLogSpan","currentLogAnnotations","currentContext","currentRequestBatching","currentMaxOpsBeforeYield","currentSupervisor","currentMetricLabels","interruptedCause","unhandledLogLevel"];for(let L of q)if(a.includes(L)){I=L;break}let z;if(j==="fn"||j==="fnUntraced"){let L=e.getArguments();if(L.length>0){let H=L[0].getText(),ge=/^["'`](.+?)["'`]$/.exec(H);ge&&(z=ge[1])}}let Y={id:C(),type:"effect",callee:a,description:v?"service-call":Gr(a,Le(t)),location:f,jsdocDescription:$,jsdocTags:Ye(e),typeSignature:b,requiredServices:T,serviceCall:v,serviceMethod:x,callbackBody:h,...E?{asyncCallback:E}:{},...F?{provideKind:F}:{},...j?{constructorKind:j}:{},...I?{fiberRefName:I}:{},...z?{tracedName:z}:{}};return{...Y,displayName:G(Y),semanticRole:Q(Y)}}),bo=(e,t)=>{let{SyntaxKind:r}=w(),s=e.getExpression();if(s.getKind()!==r.PropertyAccessExpression)return;let n=s,i=n.getExpression(),c=n.getName(),o=i.getText(),a=o.split(".")[0]??o;if(!xn.has(a))try{let d=i.getType(),l=d.getSymbol()??d.getAliasSymbol();if(!l)return;let f=l.getName();return!f||f==="__type"||f==="unknown"||f==="any"||Hr.has(f)?void 0:{serviceType:f,methodName:c,objectName:o}}catch{return}};function At(e){let t=e.getExpression().getText(),r=e.getSourceFile(),s=wn(t,r);return s.startsWith("Layer.")||s.startsWith("Effect.")||t==="pipe"||t.endsWith(".pipe")}function No(e,t,r){let{SyntaxKind:s}=w(),n=e.getSourceFile(),i=n.getProject(),c=n.getFilePath(),a=t.getImportDeclaration().getModuleSpecifierValue();if(!a?.startsWith("."))return;let d=Xe(i,c,a);if(!d){let m=mt(c,a);if(m){let h=i.addSourceFileAtPath(m);h&&(d=h)}}if(!d)return;d=i.getSourceFile(d.getFilePath())??d;let l=m=>{if(m.getKind()===s.VariableDeclaration){let y=m.getInitializer();if(y?.getKind()===s.CallExpression&&r(y))return y}if(m.getKind()===s.VariableStatement){let h=m.getDeclarationList();for(let y of h.getDeclarations()){let N=y.getInitializer();if(N?.getKind()===s.CallExpression&&r(N))return N}}},f=t.getName(),u=d.getExportedDeclarations(),g=u.get(f)??[];for(let m of g){let h=l(m);if(h)return h}let p=t.getTargetName?.();if(p&&p!==f)for(let m of u.get(p)??[]){let h=l(m);if(h)return h}for(let[,m]of u)for(let h of m){let y=l(h);if(y)return y}}function Co(e,t,r){let{SyntaxKind:s}=w(),n=e.getSourceFile(),i=n.getProject(),c=n.getFilePath(),o=t.getModuleSpecifierValue();if(!o?.startsWith("."))return;let a=Xe(i,c,o);if(!a){let l=mt(c,o);if(l){let f=i.addSourceFileAtPath(l);f&&(a=f)}}if(!a)return;a=i.getSourceFile(a.getFilePath())??a;let d=l=>{if(l.getKind()===s.VariableDeclaration){let u=l.getInitializer();if(u?.getKind()===s.CallExpression&&r(u))return u}if(l.getKind()===s.VariableStatement){let f=l.getDeclarationList();for(let u of f.getDeclarations()){let g=u.getInitializer();if(g?.getKind()===s.CallExpression&&r(g))return g}}};for(let l of a.getDefaultExportSymbol()?.getDeclarations()??[]){let f=d(l);if(f)return f}for(let l of a.getExportedDeclarations().get("default")??[]){let f=d(l);if(f)return f}}function ds(e){let{SyntaxKind:t}=w();if(e.getKind()!==t.Identifier)return e;let r=e,s=r.getText(),n=r.getSymbol(),i=n?.getValueDeclaration(),c=i?.getKind()===t.ImportSpecifier?i:void 0;if(!c&&n){let o=n.getDeclarations().find(a=>a.getKind()===t.ImportSpecifier);o&&(c=o)}if(!c){let o=r.getSourceFile();for(let a of o.getImportDeclarations()){if(a.getDefaultImport()?.getText()===s){let f=Co(r,a,At);if(f)return f}let l=a.getNamedImports().find(f=>f.getName()===s||f.getAliasNode()?.getText()===s);if(l){c=l;break}}}if(c){let o=No(r,c,At);if(o)return o;n=n?.getImmediatelyAliasedSymbol()??n?.getAliasedSymbol(),i=n?.getValueDeclaration()}if(i?.getKind()===t.ExportSpecifier&&(n=n?.getImmediatelyAliasedSymbol()??n?.getAliasedSymbol(),i=n?.getValueDeclaration()),n&&i?.getKind()!==t.VariableDeclaration){for(let o of n.getDeclarations())if(o.getKind()===t.VariableDeclaration){let d=o.getInitializer();if(d?.getKind()===t.CallExpression&&At(d))return d}}if(i?.getKind()===t.VariableDeclaration){let a=i.getInitializer();if(a?.getKind()===t.CallExpression&&At(a))return a}return e}var wo=(e,t,r,s,n,i,c)=>ee.gen(function*(){let o=e.getArguments(),a=[],{SyntaxKind:d}=w();if(o.length>0&&o[0]){let b=o[0];if(t.includes("mergeAll")&&b.getKind()===d.ArrayLiteralExpression){let v=b.getElements();for(let x of v){let K=yield*M(x,r,s,n,i,c);a.push(K)}}else for(let v of o){if(!v)continue;let x=ds(v),K=x.getSourceFile(),F=yield*M(x,K,K.getFilePath(),n,i,c);a.push(F)}}let l=t.includes("merge")||t.includes("mergeAll"),f;t.includes("fresh")?f="fresh":t.includes("memoize")?f="memoized":t.includes("scoped")?f="scoped":f="default";let u=[],g=b=>{if(b.getKind()===d.Identifier)return b.getText();if(b.getKind()===d.PropertyAccessExpression){let T=b,v=T.getExpression();return v.getKind()===d.Identifier?v.getText():T.getText().split(".")[0]}};if((t.includes("succeed")||t.includes("sync")||t.includes("effect")||t.includes("scoped")||t.includes("scopedDiscard")||t.includes("effectDiscard"))&&o.length>0&&o[0]){let b=g(o[0]);b&&u.push(b)}let p=t.includes("provide")&&!t.includes("provideService"),m=new Set;if(p&&o.length>=1&&o[0]){let b=g(o[0]);b&&m.add(b)}if(p&&o.length>=2&&o[1]){let b=g(o[1]);b&&m.add(b);let T=g(o[0]);T&&u.push(T)}if(t.includes("provideService")&&o.length>0&&o[0]){let b=g(o[0]);b&&u.push(b)}let h=b=>{if(b.type==="effect"){let v=b;for(let K of v.requiredServices??[])m.add(K.serviceId);let x=v.callee??"";(/^[A-Z][A-Za-z0-9_]*(Service|Tag)$/.test(x)||x.endsWith(".Tag"))&&m.add(x)}else if(b.type==="layer"){let v=b;for(let x of v.requires??[])m.add(x)}Eo.getOrElse(P(b),()=>[]).forEach(h)};if(a.forEach(h),m.size===0)try{let b=Tr(e);b?.requiredType&&b.requiredType!=="never"&&Jr(b.requiredType).forEach(v=>m.add(v))}catch{}let y=t.replace(/^Layer\./,"").replace(/^[a-zA-Z]+\./,""),E=new Set(["catchAll","catchAllCause","orDie","orElse","retry","tap","mapError","mapErrorCause","build","launch","toRuntime","passthrough","project","flatMap","flatten","annotateLogs","annotateSpans","setConfigProvider","setClock","setTracer","locally","withSpan","withLogger","withTracer","withClock","mock","suspend","unwrapEffect","unwrapScoped"]).has(y)?`Layer.${y}`:void 0,$=t.includes("MemoMap")||a.some(b=>b.type==="layer"&&b.isMemoMap===!0),S={id:C(),type:"layer",name:E,operations:a,isMerged:l,provides:u.length>0?u:void 0,requires:m.size>0?Array.from(m).sort():void 0,lifecycle:f,...$?{isMemoMap:!0}:{},location:_(e,s,n.includeLocations??!1)};return{...S,displayName:G(S),semanticRole:Q(S)}});function To(e,t,r,s,n,i,c){return ee.gen(function*(){let o=e.getArguments(),a;o.length>0&&o[0]?a=yield*M(o[0],r,s,n,i,c):a={id:C(),type:"unknown",reason:"Stream source not determined"};let d=t.replace(/^Stream\./,"")||"unknown",l;t.startsWith("Stream.")&&(d==="fromIterable"||d==="fromChunk"||d==="fromChunkQueue"?l="fromIterable":d==="fromArray"?l="fromArray":d==="fromQueue"||d==="fromChunkQueue"?l="fromQueue":d==="fromPubSub"||d==="fromChunkPubSub"?l="fromPubSub":d==="fromEffect"||d==="unwrap"||d==="unwrapScoped"?l="fromEffect":d==="fromAsyncIterable"?l="fromAsyncIterable":d==="fromReadableStream"||d==="fromReadableStreamByob"?l="fromReadableStream":d==="fromEventListener"?l="fromEventListener":d==="fromSchedule"?l="fromSchedule":d==="range"?l="range":d==="tick"?l="tick":d==="iterate"||d==="iterateEffect"?l="iterate":d==="unfold"||d==="unfoldEffect"||d==="unfoldChunk"||d==="unfoldChunkEffect"?l="unfold":d==="make"?l="make":d==="empty"?l="empty":d==="never"?l="never":d==="succeed"||d==="sync"?l="succeed":(d==="fail"||d==="failSync"||d==="failCause"||d==="failCauseSync")&&(l="fail"));let f=x=>l!==void 0?"constructor":x.startsWith("run")?"sink":x==="toQueue"||x==="toPubSub"||x==="toReadableStream"||x==="toAsyncIterable"||x==="toChannel"?"conversion":x.includes("pipeThroughChannel")||x.includes("Channel")||x.includes("channel")||x.includes("duplex")?"channel":x.includes("grouped")||x.includes("sliding")||x.includes("groupBy")||x.includes("aggregate")||x.includes("window")?"windowing":x.includes("broadcast")||x==="share"?"broadcasting":x.includes("haltAfter")||x.includes("haltWhen")||x.includes("interruptAfter")?"halting":x.includes("decodeText")||x.includes("encodeText")||x.includes("splitLines")?"text":x.includes("merge")||x==="concat"||x.includes("interleave")||x.includes("zip")?"merge":x.includes("buffer")||x.includes("debounce")||x.includes("throttle")?"backpressure":x.includes("catchAll")||x.includes("catchTag")||x.includes("orElse")||x.includes("orDie")||x.includes("retry")?"error":x.includes("filter")||x.includes("take")||x.includes("drop")||x.includes("head")||x==="first"||x==="last"?"filter":x.includes("acquireRelease")||x.includes("scoped")||x.includes("ensuring")||x.includes("onDone")||x.includes("onError")?"resource":x.includes("provide")||x.includes("withSpan")||x.includes("annotate")?"context":x.includes("map")||x.includes("tap")||x.includes("flatMap")||x.includes("mapChunk")||x.includes("scan")||x.includes("transduce")?"transform":"other",u=d.includes("Effect")||d.startsWith("run")||d.includes("tap"),g=f(d),p=g==="filter"?"fewer":g==="merge"||g==="broadcasting"?"more":g==="halting"||g==="sink"||g==="windowing"?"fewer":"unknown",m,h;(d==="grouped"||d==="groupedWithin"||d.includes("sliding")||d.includes("Sliding"))&&o.length>0&&o[0]&&(m=pt(o[0]),(d.includes("sliding")||d.includes("Sliding"))&&o.length>1&&o[1]&&(h=pt(o[1])));let N={operation:d,isEffectful:u,estimatedCardinality:p,category:g,...m!==void 0?{windowSize:m}:{},...h!==void 0?{stride:h}:{}},E;d.startsWith("run")&&(E=d);let $;d.includes("buffer")?$="buffer":d.includes("drop")||d.includes("Drop")?$="drop":(d.includes("sliding")||d.includes("Sliding"))&&($="sliding");let S=a,b=[N],T=l;if(a.type==="stream"){let x=a;b=[...x.pipeline,N],S=x.source,!T&&x.constructorType&&(T=x.constructorType),!E&&x.sink&&(E=x.sink),!$&&x.backpressureStrategy&&($=x.backpressureStrategy)}let v={id:C(),type:"stream",source:S,pipeline:b,sink:E,backpressureStrategy:$,constructorType:T,location:_(e,s,n.includeLocations??!1)};return{...v,displayName:G(v),semanticRole:Q(v)}})}function ko(e){return e==="fromReadableStream"||e==="fromWritableStream"||e==="fromDuplexStream"||e==="make"||e==="succeed"||e==="fail"||e==="empty"||e==="never"?"constructor":e.includes("map")||e.includes("flatMap")||e.includes("filter")||e.includes("concat")||e.includes("zip")?"transform":e.includes("pipe")||e==="pipeTo"||e==="pipeThrough"?"pipe":"other"}function vo(e,t,r,s,n,i,c){return ee.gen(function*(){let o=e.getArguments(),a;o.length>0&&o[0]&&(a=yield*M(o[0],r,s,n,i,c));let d=t.replace(/^Channel\./,"")||"unknown",l=[{operation:d,category:ko(d)}];if(a?.type==="channel"){let u=a;l.unshift(...u.pipeline),a=u.source}let f={id:C(),type:"channel",source:a,pipeline:l,location:_(e,s,n.includeLocations??!1)};return{...f,displayName:G(f),semanticRole:Q(f)}})}function Io(e){return e==="forEach"||e==="forEachWhile"||e==="run"||e==="runDrain"||e==="runFor"||e==="make"||e==="fromEffect"||e==="fromQueue"?"constructor":e.includes("map")||e.includes("contramap")||e.includes("filter")||e.includes("zip")?"transform":"other"}function $o(e,t,r,s,n,i,c){return ee.gen(function*(){let o=e.getArguments(),a;o.length>0&&o[0]&&(a=yield*M(o[0],r,s,n,i,c));let d=t.replace(/^Sink\./,"")||"unknown",l=[{operation:d,category:Io(d)}];if(a?.type==="sink"){let u=a;l.unshift(...u.pipeline),a=u.source}let f={id:C(),type:"sink",source:a,pipeline:l,location:_(e,s,n.includeLocations??!1)};return{...f,displayName:G(f),semanticRole:Q(f)}})}function Fo(e,t,r,s,n,i,c){let{SyntaxKind:o}=w(),a="queue",d="create",l,f,u;t.startsWith("Queue.")?(a="queue",t.includes("bounded")?l="bounded":t.includes("unbounded")?l="unbounded":t.includes("sliding")?l="sliding":t.includes("dropping")&&(l="dropping"),t.includes("offer")||t.includes("offerAll")?d="offer":t.includes("take")||t.includes("takeAll")||t.includes("poll")?d="take":d="create"):t.startsWith("PubSub.")?(a="pubsub",t.includes("bounded")?l="bounded":t.includes("unbounded")&&(l="unbounded"),t.includes("publish")?d="publish":t.includes("subscribe")?d="subscribe":d="create"):t.startsWith("Deferred.")?(a="deferred",t.includes("succeed")?d="succeed":t.includes("fail")?d="fail":t.includes("await")?d="await":d="create"):t.startsWith("Semaphore.")?(a="semaphore",t.includes("withPermit")?d="withPermit":t.includes("take")?d="take":t.includes("release")?d="release":t.includes("available")?d="available":d="create"):t.startsWith("Mailbox.")?(a="mailbox",t.includes("offer")?d="offer":t.includes("takeAll")?d="takeAll":t.includes("take")?d="take":t.includes("end")?d="end":t.includes("toStream")?d="toStream":d="create"):t.startsWith("SubscriptionRef.")?(a="subscriptionRef",t.includes("changes")?d="changes":t.includes("get")?d="get":t.includes("set")?d="set":t.includes("update")?d="update":d="create"):t.includes("makeLatch")||t.includes("Latch.")?(a="latch",t.includes("open")?d="open":t.includes("close")?d="close":t.includes("await")||t.includes("whenOpen")?d="await":d="create"):t.startsWith("FiberHandle.")?(a="fiberHandle",t.includes("run")?d="run":t.includes("await")?d="await":d="create"):t.startsWith("FiberSet.")?(a="fiberSet",t.includes("run")?d="run":t.includes("join")?d="await":d="create"):t.startsWith("FiberMap.")?(a="fiberMap",t.includes("run")?d="run":t.includes("join")?d="await":d="create"):t.startsWith("RateLimiter.")?(a="rateLimiter",t.includes("withCost")?d="withPermit":d="create"):t.startsWith("ScopedCache.")?(a="scopedCache",t.includes("make")||t.includes("Make")?d="create":t.includes("get")&&!t.includes("getOrElse")||t.includes("getOrElse")?d="get":t.includes("set")||t.includes("Set")?d="set":t.includes("invalidate")?d="invalidate":t.includes("contains")?d="contains":d="create"):t.startsWith("Cache.")?(a="cache",t.includes("make")||t.includes("Make")?d="create":t.includes("get")&&!t.includes("getOrElse")||t.includes("getOrElse")?d="get":t.includes("set")||t.includes("Set")?d="set":t.includes("invalidate")?d="invalidate":t.includes("contains")?d="contains":d="create"):t.startsWith("Reloadable.")||t.includes(".Reloadable.")?(a="reloadable",t.includes("make")||t.includes("Make")?d="create":t.includes("get")&&!t.includes("reload")?d="get":t.includes("reload")?d="reload":d="create"):t.startsWith("RcMap.")||t.includes(".RcMap.")?(a="rcMap",t.includes("make")||t.includes("Make")?d="create":t.includes("get")?d="get":t.includes("set")||t.includes("Set")?d="set":t.includes("update")?d="update":d="create"):(t.startsWith("RcRef.")||t.includes(".RcRef."))&&(a="rcRef",t.includes("make")||t.includes("Make")?d="create":t.includes("get")?d="get":t.includes("set")||t.includes("Set")?d="set":t.includes("update")?d="update":d="create");let g=e.getArguments();if(g.length>0&&l==="bounded"){let h=g[0];h?.getKind()===o.NumericLiteral&&(f=Number.parseInt(h.getText(),10))}a==="semaphore"&&(d==="take"||d==="release")&&g.length>0&&g[0]&&(u=pt(g[0]));let p;if(a==="fiberHandle"&&d==="run")for(let h of g){let y=h.getText();y.includes("onlyIfMissing")&&(p={onlyIfMissing:y.includes("true")})}if(a==="mailbox"&&d==="toStream"||a==="subscriptionRef"&&d==="changes"){let h=a==="mailbox"?"fromMailbox":"fromSubscriptionRef",y={id:C(),type:"concurrency-primitive",primitive:a,operation:d,location:_(e,s,n.includeLocations??!1)},N={id:C(),type:"stream",source:{...y,displayName:G(y),semanticRole:Q(y)},pipeline:[],constructorType:h,location:_(e,s,n.includeLocations??!1)};return ee.succeed({...N,displayName:G(N),semanticRole:Q(N)})}let m={id:C(),type:"concurrency-primitive",primitive:a,operation:d,strategy:l,capacity:f,...u!==void 0?{permitCount:u}:{},...p?{lifecycleOptions:p}:{},location:_(e,s,n.includeLocations??!1)};return ee.succeed({...m,displayName:G(m),semanticRole:Q(m)})}function Ao(e,t,r,s,n,i,c){return ee.gen(function*(){let o=e.getArguments(),a="fork",d=!1,l=!1,f;t.startsWith("Fiber.")?t.includes("awaitAll")?a="awaitAll":t.includes("join")?a="join":t.includes("await")?a="await":t.includes("interruptFork")?a="interruptFork":t.includes("interrupt")?a="interrupt":t.includes("poll")?a="poll":t.includes("status")?a="status":t.includes("all")?a="all":t.includes("children")?a="children":t.includes("dump")?a="dump":t.includes("scoped")?(a="scoped",d=!0):t.includes("inheritAll")?a="inheritAll":t.includes("mapFiber")?a="mapFiber":t.includes("mapEffect")?a="mapEffect":t.includes("map")?a="map":t.includes("roots")?a="roots":t.includes("getCurrentFiber")&&(a="getCurrentFiber"):t.includes("forkWithErrorHandler")?a="forkWithErrorHandler":t.includes("forkAll")?a="forkAll":t.includes("forkIn")?a="forkIn":t.includes("fork")&&(t.includes("forkDaemon")?(a="forkDaemon",l=!0):t.includes("forkScoped")?(a="forkScoped",d=!0):a="fork"),(a==="fork"||a==="forkScoped"||a==="forkDaemon"||a==="forkAll"||a==="forkIn"||a==="forkWithErrorHandler")&&o.length>0&&o[0]&&(f=yield*M(o[0],r,s,n,i,c));let u;if(d)u="safe";else{let p=e.getParent();for(;p;){let m=p.getText?.();if(m&&(m.includes("Effect.scoped")||m.includes("Scope.make"))){u="safe";break}if(p=p.getParent(),p&&p===r)break}}let g={id:C(),type:"fiber",operation:a,fiberSource:f,isScoped:d,isDaemon:l,...u?{scopeContext:u}:{},location:_(e,s,n.includeLocations??!1)};return{...g,displayName:G(g),semanticRole:Q(g)}})}function Ro(e,t,r,s,n,i,c){return ee.gen(function*(){let o=e.getArguments(),{SyntaxKind:a}=w(),d;t.includes("uninterruptibleMask")?d="uninterruptibleMask":t.includes("interruptibleMask")?d="interruptibleMask":t.includes("uninterruptible")?d="uninterruptible":t.includes("interruptible")?d="interruptible":t.includes("onInterrupt")?d="onInterrupt":t.includes("disconnect")?d="disconnect":t.includes("allowInterrupt")?d="allowInterrupt":t.includes("interruptWith")?d="interruptWith":d="interrupt";let l,f,u=e.getExpression();u.getKind()===a.PropertyAccessExpression?(l=yield*M(u.getExpression(),r,s,n,i,c),o.length>0&&o[0]&&(f=yield*M(o[0],r,s,n,i,c))):o.length>0&&o[0]&&(l=yield*M(o[0],r,s,n,i,c),o.length>1&&o[1]&&(f=yield*M(o[1],r,s,n,i,c))),c.interruptionCount++;let g={id:C(),type:"interruption",interruptionType:d,source:l,handler:f,location:_(e,s,n.includeLocations??!1)};return{...g,displayName:G(g),semanticRole:Q(g)}})}function Do(e){let{SyntaxKind:t}=w(),r,s,n;for(let i of e.getProperties()){if(i.getKind()!==t.PropertyAssignment)continue;let c=i.getNameNode().getText(),o=i.getInitializer();if(!o)continue;let a=o.getText();if(c==="concurrency")if(a==='"unbounded"'||a==="'unbounded'")r="unbounded";else if(a==='"sequential"'||a==="'sequential'")r="sequential";else if(a==='"inherit"'||a==="'inherit'")r="sequential";else{let d=Number.parseInt(a,10);!Number.isNaN(d)&&d>=0&&(r=d)}else c==="batching"&&(a==="true"||a==="false")?s=a==="true":c==="discard"&&(a==="true"||a==="false")&&(n=a==="true")}return{concurrency:r,batching:s,discard:n}}var Po=(e,t,r,s,n,i,c)=>ee.gen(function*(){let o=e.getArguments(),a=[],{SyntaxKind:d}=w();if(o.length>0&&o[0]){let h=o[0];if(h.getKind()===d.ArrayLiteralExpression){let y=h.getElements();for(let N of y){let E=yield*M(N,r,s,n,i,c);a.push(E)}}else if(h.getKind()===d.ObjectLiteralExpression){let y=h.getProperties();for(let N of y)if(N.getKind()===d.PropertyAssignment){let E=N.getInitializer();if(E){let $=yield*M(E,r,s,n,i,c);a.push($)}}}}let l,f,u;if(o.length>1&&o[1]?.getKind()===d.ObjectLiteralExpression){let h=Do(o[1]);l=h.concurrency,f=h.batching,u=h.discard}let g=t.includes("Par")?"parallel":"sequential";l===void 0&&(l=g==="parallel"?"unbounded":"sequential"),c.parallelCount++;let p=a.map(h=>G(h)),m={id:C(),type:"parallel",callee:t,mode:g,children:a,concurrency:l,batching:f,discard:u,branchLabels:p,location:_(e,s,n.includeLocations??!1)};return{...m,displayName:G(m),semanticRole:Q(m)}}),Mo=(e,t,r,s,n,i,c)=>ee.gen(function*(){let o=e.getArguments(),a=[];for(let f of o)if(f){let u=yield*M(f,r,s,n,i,c);a.push(u)}c.raceCount++;let d=a.map(f=>G(f)),l={id:C(),type:"race",callee:t,children:a,raceLabels:d,location:_(e,s,n.includeLocations??!1)};return{...l,displayName:G(l),semanticRole:Q(l)}}),Oo=(e,t,r,s,n,i,c)=>ee.gen(function*(){let o=e.getArguments(),a;t.includes("catchAllCause")?a="catchAllCause":t.includes("catchSomeCause")?a="catchSomeCause":t.includes("catchSomeDefect")?a="catchSomeDefect":t.includes("catchAllDefect")?a="catchAllDefect":t.includes("catchTags")?a="catchTags":t.includes("catchIf")?a="catchIf":t.includes("catchSome")?a="catchSome":t.includes("catchTag")?a="catchTag":t.includes("catchAll")?a="catchAll":t.includes("orElseFail")?a="orElseFail":t.includes("orElseSucceed")?a="orElseSucceed":t.includes("orElse")?a="orElse":t.includes("orDieWith")?a="orDieWith":t.includes("orDie")?a="orDie":t.includes("flip")?a="flip":t.includes("mapErrorCause")?a="mapErrorCause":t.includes("mapBoth")?a="mapBoth":t.includes("mapError")?a="mapError":t.includes("unsandbox")?a="unsandbox":t.includes("sandbox")?a="sandbox":t.includes("parallelErrors")?a="parallelErrors":t.includes("filterOrDieMessage")?a="filterOrDieMessage":t.includes("filterOrDie")?a="filterOrDie":t.includes("filterOrElse")?a="filterOrElse":t.includes("filterOrFail")?a="filterOrFail":t.includes("matchCauseEffect")?a="matchCauseEffect":t.includes("matchCause")?a="matchCause":t.includes("matchEffect")?a="matchEffect":t.includes("match")?a="match":t.includes("firstSuccessOf")?a="firstSuccessOf":t.includes("ignoreLogged")?a="ignoreLogged":t.includes("ignore")?a="ignore":t.includes("eventually")?a="eventually":a="catchAll";let d,l,f=e.getExpression();if(f.getKind()===w().SyntaxKind.PropertyAccessExpression){let h=f.getExpression();d=yield*M(h,r,s,n,i,c),o.length>0&&o[0]&&(l=yield*M(o[0],r,s,n,i,c))}else o.length>0&&o[0]?d=yield*M(o[0],r,s,n,i,c):d={id:C(),type:"unknown",reason:"Could not determine source effect"},o.length>1&&o[1]&&(l=yield*M(o[1],r,s,n,i,c));c.errorHandlerCount++;let u,g;if(a==="catchTag"){let m=o[0];m?.getKind()===w().SyntaxKind.StringLiteral&&(u=m.getLiteralValue())}else if(a==="catchTags"){let m=[...o].find(h=>h?.getKind()===w().SyntaxKind.ObjectLiteralExpression);m&&(g=m.getProperties().filter(y=>y.getKind()===w().SyntaxKind.PropertyAssignment||y.getKind()===w().SyntaxKind.MethodDeclaration).map(y=>(y.getKind()===w().SyntaxKind.PropertyAssignment,y.getName())))}let p={id:C(),type:"error-handler",handlerType:a,source:d,handler:l,errorTag:u,errorTags:g,errorEdgeLabel:u?`on ${u}`:g&&g.length>0?`on ${g.join(" | ")}`:"on error",location:_(e,s,n.includeLocations??!1)};return{...p,displayName:G(p),semanticRole:Q(p)}}),Lo=(e,t,r,s,n,i)=>ee.gen(function*(){let c=e.getArguments(),o,a,d,l,f=e.getExpression();if(f.getKind()===w().SyntaxKind.PropertyAccessExpression){let m=f.getExpression();o=yield*M(m,t,r,s,n,i),c.length>0&&c[0]&&(a=c[0].getText(),d=yield*M(c[0],t,r,s,n,i)),l=f.getText().includes("retryOrElse")}else c.length>0&&c[0]?o=yield*M(c[0],t,r,s,n,i):o={id:C(),type:"unknown",reason:"Could not determine source effect"},c.length>1&&c[1]&&(a=c[1].getText(),d=yield*M(c[1],t,r,s,n,i)),l=c.length>2;i.retryCount++;let u=a?us(a):void 0,g={id:C(),type:"retry",source:o,schedule:a,...d!==void 0?{scheduleNode:d}:{},hasFallback:l,scheduleInfo:u,retryEdgeLabel:a?`retry: ${a}`:"retry",location:_(e,r,s.includeLocations??!1)};return{...g,displayName:G(g),semanticRole:Q(g)}});function us(e){let t=e.replace(/\s+/g," "),r="custom";t.includes("Schedule.exponential")||t.includes("exponential(")?r="exponential":t.includes("Schedule.fibonacci")||t.includes("fibonacci(")?r="fibonacci":t.includes("Schedule.spaced")||t.includes("spaced(")?r="spaced":t.includes("Schedule.fixed")||t.includes("fixed(")?r="fixed":t.includes("Schedule.linear")||t.includes("linear(")?r="linear":t.includes("Schedule.cron")||t.includes("cron(")?r="cron":t.includes("Schedule.windowed")||t.includes("windowed(")?r="windowed":t.includes("Schedule.duration")||t.includes("duration(")?r="duration":t.includes("Schedule.elapsed")||t.includes("elapsed(")?r="elapsed":t.includes("Schedule.delays")||t.includes("delays(")?r="delays":t.includes("Schedule.once")||t.includes("once(")?r="once":t.includes("Schedule.stop")||t.includes("stop(")?r="stop":(t.includes("Schedule.count")||t.includes("count("))&&(r="count");let s,n=/recurs\s*\(\s*(\d+)\s*\)/.exec(t);n&&(s=Number.parseInt(n[1],10));let i=/recurUpTo\s*\(\s*(\d+)\s*\)/.exec(t);i?s=Number.parseInt(i[1],10):(t.includes("forever")||t.includes("Schedule.forever"))&&(s="unlimited");let c=t.includes("jittered")||t.includes("Schedule.jittered"),o=[];return t.includes("whileInput")&&o.push("whileInput"),t.includes("whileOutput")&&o.push("whileOutput"),t.includes("untilInput")&&o.push("untilInput"),t.includes("untilOutput")&&o.push("untilOutput"),t.includes("recurUntil")&&o.push("recurUntil"),t.includes("recurWhile")&&o.push("recurWhile"),t.includes("andThen")&&o.push("andThen"),t.includes("intersect")&&o.push("intersect"),t.includes("union")&&o.push("union"),t.includes("compose")&&o.push("compose"),t.includes("zipWith")&&o.push("zipWith"),t.includes("addDelay")&&o.push("addDelay"),t.includes("modifyDelay")&&o.push("modifyDelay"),t.includes("check")&&o.push("check"),t.includes("resetAfter")&&o.push("resetAfter"),t.includes("resetWhen")&&o.push("resetWhen"),t.includes("ensure")&&o.push("ensure"),t.includes("driver")&&o.push("driver"),t.includes("mapInput")&&o.push("mapInput"),{baseStrategy:r,maxRetries:s,jittered:c,conditions:o}}var Wo=(e,t,r,s,n,i)=>ee.gen(function*(){let c=e.getArguments(),o,a,d,l=e.getExpression();if(l.getKind()===w().SyntaxKind.PropertyAccessExpression){let g=l.getExpression();o=yield*M(g,t,r,s,n,i),c.length>0&&c[0]&&(a=kt(c[0]));let p=kt(l);d=p.includes("timeoutFail")||p.includes("timeoutTo")}else c.length>0&&c[0]?o=yield*M(c[0],t,r,s,n,i):o={id:C(),type:"unknown",reason:"Could not determine source effect"},c.length>1&&c[1]&&(a=kt(c[1])),d=c.length>2;i.timeoutCount++;let f={id:C(),type:"timeout",source:o,duration:a,hasFallback:d,location:_(e,r,s.includeLocations??!1)};return{...f,displayName:G(f),semanticRole:Q(f)}}),ls=(e,t,r,s,n,i,c)=>ee.gen(function*(){let o=e.getArguments(),a=/([A-Za-z_$][\w$]*)$/.exec(t)?.[1]??t,d,l,f;if(a.startsWith("acquireUseRelease"))o.length>=3&&o[0]&&o[2]?(d=yield*M(o[0],r,s,n,i,c),l=yield*M(o[2],r,s,n,i,c),o[1]&&(f=yield*M(o[1],r,s,n,i,c))):(d={id:C(),type:"unknown",reason:"Missing acquire"},l={id:C(),type:"unknown",reason:"Missing release"});else if(a.startsWith("acquireRelease"))o.length>=2&&o[0]&&o[1]?(d=yield*M(o[0],r,s,n,i,c),l=yield*M(o[1],r,s,n,i,c)):(d={id:C(),type:"unknown",reason:"Missing acquire"},l={id:C(),type:"unknown",reason:"Missing release"});else if(a==="addFinalizer"||a==="onExit"||a==="onError"||a==="parallelFinalizers"||a==="sequentialFinalizers"||a==="finalizersMask"||a==="using"||a==="withEarlyRelease"){let g=e.getExpression();g.getKind()===w().SyntaxKind.PropertyAccessExpression?d=yield*M(g.getExpression(),r,s,n,i,c):d={id:C(),type:"unknown",reason:"Scoped acquire"},l=o.length>0&&o[0]?yield*M(o[0],r,s,n,i,c):{id:C(),type:"unknown",reason:"Missing finalizer"}}else if(a==="ensuring"){let g=e.getExpression();if(g.getKind()===w().SyntaxKind.PropertyAccessExpression){let m=g.getExpression();d=yield*M(m,r,s,n,i,c),l=o.length>0&&o[0]?yield*M(o[0],r,s,n,i,c):{id:C(),type:"unknown",reason:"Missing cleanup"}}else d=o.length>0&&o[0]?yield*M(o[0],r,s,n,i,c):{id:C(),type:"unknown",reason:"Missing effect"},l=o.length>1&&o[1]?yield*M(o[1],r,s,n,i,c):{id:C(),type:"unknown",reason:"Missing cleanup"}}else d={id:C(),type:"unknown",reason:"Unknown resource pattern"},l={id:C(),type:"unknown",reason:"Unknown resource pattern"};c.resourceCount++;let u={id:C(),type:"resource",acquire:d,release:l,use:f,location:_(e,s,n.includeLocations??!1)};return{...u,displayName:G(u),semanticRole:Q(u)}}),Ko=(e,t,r,s,n,i,c)=>ee.gen(function*(){let o=e.getArguments(),a;t.includes(".if")||t==="if"?a="if":t.includes("whenEffect")?a="whenEffect":t.includes("whenFiberRef")?a="whenFiberRef":t.includes("whenRef")?a="whenRef":t.includes(".when")||t==="when"?a="when":t.includes("unlessEffect")?a="unlessEffect":t.includes(".unless")||t==="unless"?a="unless":t.includes(".option")||t==="option"?a="option":t.includes(".either")||t==="either"?a="either":t.includes(".exit")||t==="exit"?a="exit":t.includes("liftPredicate")?a="liftPredicate":a="unless";let d="<dynamic>",l,f;if(a==="if"){if(o.length>0&&o[0]&&(d=o[0].getText()),o.length>1&&o[1]){let p=o[1],{SyntaxKind:m}=w();if(p.getKind()===m.ObjectLiteralExpression){let h=p.getProperties();for(let y of h)if(y.getKind()===m.PropertyAssignment){let N=y,E=N.getName(),$=N.getInitializer();$&&(E==="onTrue"?l=yield*M($,r,s,n,i,c):E==="onFalse"&&(f=yield*M($,r,s,n,i,c)))}}}}else{let p=e.getExpression();if(p.getKind()===w().SyntaxKind.PropertyAccessExpression){let h=p.getExpression();l||(l=yield*M(h,r,s,n,i,c))}o.length>0&&o[0]&&(d=o[0].getText())}l||(l={id:C(),type:"unknown",reason:"Could not determine true branch"}),c.conditionalCount++;let u=d.length<=30?d:`${d.slice(0,30)}\u2026`,g={id:C(),type:"conditional",conditionalType:a,condition:d,onTrue:l,onFalse:f,conditionLabel:u,trueEdgeLabel:"true",falseEdgeLabel:"false",location:_(e,s,n.includeLocations??!1)};return{...g,displayName:G(g),semanticRole:Q(g)}}),jo=(e,t,r,s,n,i,c)=>ee.gen(function*(){let o=e.getArguments(),a=t.includes("forEach")?"forEach":t.includes("filterMap")?"filterMap":t.includes("filter")?"filter":t.includes("partition")?"partition":t.includes("reduce")?"reduce":t.includes("validateAll")||t.includes("validateFirst")||t.includes("validateWith")?"validate":t.includes("replicate")?"replicate":t.includes("dropUntil")?"dropUntil":t.includes("dropWhile")?"dropWhile":t.includes("takeUntil")?"takeUntil":t.includes("takeWhile")?"takeWhile":t.includes("every")?"every":t.includes("exists")?"exists":t.includes("findFirst")?"findFirst":t.includes("head")?"head":t.includes("mergeAll")?"mergeAll":"loop",d=a==="reduce"||t.includes("reduceRight")||t.includes("reduceWhile")||t.includes("reduceEffect")?2:1,l,f;o.length>0&&o[0]&&(l=o[0].getText()),o.length>d&&o[d]?f=yield*M(o[d],r,s,n,i,c):f={id:C(),type:"unknown",reason:"Could not determine loop body"},c.loopCount++;let u={id:C(),type:"loop",loopType:a,iterSource:l,body:f,location:_(e,s,n.includeLocations??!1)};return{...u,displayName:G(u),semanticRole:Q(u)}}),Bo=(e,t,r,s)=>{let n=pn[t]??"other",i=Wr.has(n),c=e.getArguments(),o=[];if((n==="when"||n==="tag")&&c[0]){let d=c[0].getText().replace(/["'`]/g,"").trim();/^[A-Za-z_][A-Za-z0-9_]*$/.test(d)&&o.push(d)}if(n==="tags"||n==="tagsExhaustive"){let{SyntaxKind:d}=w();for(let l of c)if(l.getKind()===d.ObjectLiteralExpression){let f=l;for(let u of f.getProperties()){let g=u.getKind()===d.PropertyAssignment?u.getName():void 0;g&&o.push(g.replace(/["'`]/g,""))}}}let a={id:C(),type:"match",matchOp:n,isExhaustive:i,...o.length>0?{matchedTags:o}:{},location:_(e,r,s.includeLocations??!1)};return{...a,displayName:G(a),semanticRole:Q(a)}},qo=(e,t,r,s,n,i,c)=>ee.gen(function*(){let o=gn[t]??"other",a=jr.has(o),d;if(o==="parallel"||o==="sequential"){let u=e.getArguments(),g=[];for(let p of u)if(p){let m=yield*M(p,r,s,n,i,c);g.push(m)}g.length>0&&(d=g)}let l;if(o==="fail")l="fail";else if(o==="die")l="die";else if(o==="interrupt")l="interrupt";else if((o==="parallel"||o==="sequential")&&d&&d.length>0){let u=d.filter(g=>g.type==="cause").map(g=>g.causeKind).filter(g=>g!==void 0);u.length>0&&(l=u.every(g=>g===u[0])?u[0]:"mixed")}let f={id:C(),type:"cause",causeOp:o,isConstructor:a,...d?{children:d}:{},...l?{causeKind:l}:{},location:_(e,s,n.includeLocations??!1)};return{...f,displayName:G(f),semanticRole:Q(f)}}),zo=(e,t,r,s)=>{let n=mn[t]??"other",i=qr.has(n),c={id:C(),type:"exit",exitOp:n,isConstructor:i,location:_(e,r,s.includeLocations??!1)};return{...c,displayName:G(c),semanticRole:Q(c)}},_o=(e,t,r,s)=>ee.sync(()=>{let n=yn[t]??"other",i=e.getText(),c=us(i),o={id:C(),type:"schedule",scheduleOp:n,...c?{scheduleInfo:c}:{},location:_(e,r,s.includeLocations??!1)};return{...o,displayName:G(o),semanticRole:Q(o)}}),Ho=(e,t,r,s,n,i,c)=>ee.gen(function*(){let o=e.getArguments(),a=fn[t]??"other",d=Or.has(a),l,f;if(o.length>=2&&o[0]){if(l=yield*M(o[0],r,s,n,i,c),o[1]){let g=o[1].getText();f=g.length<=120?g:g.slice(0,120)+"\u2026"}}else if(o.length===1&&o[0]){let g=o[0].getText();f=g.length<=120?g:g.slice(0,120)+"\u2026"}c.totalEffects++;let u={id:C(),type:"transform",transformType:a,isEffectful:d,...l!==void 0?{source:l}:{},...f!==void 0?{fn:f}:{},location:_(e,s,n.includeLocations??!1)};return{...u,displayName:G(u),semanticRole:Q(u)}});var In=(e,t,r,s,n)=>xe.gen(function*(){let i=[],c=Pr(),o=yield*Uo(e.node,e.type,t,r,s,i,c),a=Ar(e.node),d=t.getProject().getTypeChecker(),l=Ze(e.node,d),f=wt(e.node,d),u={id:C(),type:"program",programName:e.name,source:e.type,...e.discoveryConfidence?{discoveryConfidence:e.discoveryConfidence}:{},...e.discoveryReason?{discoveryReason:e.discoveryReason}:{},children:o,dependencies:Fr(o),errorTypes:$r(o),typeSignature:l,requiredServices:f,location:_(e.node,r,s.includeLocations??!1),jsdocDescription:a,jsdocTags:Ye(e.node)},g=cs(t);return{root:u,metadata:{analyzedAt:Date.now(),filePath:r,tsVersion:n,warnings:i,stats:c,...g.length>0?{serviceDefinitions:g}:{}},references:new Map}}),Uo=(e,t,r,s,n,i,c)=>xe.gen(function*(){switch(t){case"generator":{let o=e.getArguments();if(o.length>0&&o[0]){let a=o[0];return yield*Yo(a,r,s,n,i,c)}return[]}case"pipe":return yield*Rt(e,r,s,n,i,c);case"run":{let o=e,{SyntaxKind:a}=w(),d=yield*Xo(o,r,s,n,i,c);if(yt.isSome(d))return d.value;let l=o.getArguments(),f=l.find(p=>p.getKind()===a.ArrowFunction||p.getKind()===a.FunctionExpression),u=n.enableEffectWorkflow&&f===void 0&&l.length===1?as(o,r):null,g=f??u??l[0];return g?[yield*M(g,r,s,n,i,c)]:[]}case"workflow-execute":{let o=e,a=o.getExpression().getText();return[{id:C(),type:"effect",callee:a,name:a,semanticRole:"side-effect",location:_(o,s,n.includeLocations??!1)}]}case"direct":{let o=e.getInitializer();return o?[yield*M(o,r,s,n,i,c)]:[]}case"class":{let o=e,a="Data.Class";for(let f of o.getHeritageClauses()){let u=f.getText();if(u.includes("Data.TaggedError")){a="Data.TaggedError";break}if(u.includes("Data.TaggedClass")){a="Data.TaggedClass";break}if(u.includes("Data.Error")){a="Data.Error";break}if(u.includes("Schema.TaggedRequest")){a="Schema.TaggedRequest";break}if(u.includes("Schema.TaggedError")){a="Schema.TaggedError";break}if(u.includes("Schema.TaggedClass")){a="Schema.TaggedClass";break}if(u.includes("Schema.Class")){a="Schema.Class";break}if(u.includes("Context.Tag")){a="Context.Tag";break}if(u.includes("Context.Reference")){a="Context.Reference";break}if(u.includes("Effect.Service")){a="Effect.Service";break}}let d=a.includes("Error")?"error-type":a.includes("Schema")?"schema":a==="Context.Tag"||a==="Context.Reference"||a==="Effect.Service"?"service-tag":"data",l={id:C(),type:"effect",callee:a,description:d,location:_(e,s,n.includeLocations??!1),jsdocDescription:_e(o),jsdocTags:Ye(o)};return c.totalEffects++,[l]}case"classProperty":{let a=e.getInitializer();return a?[yield*M(a,r,s,n,i,c)]:[]}case"classMethod":{let a=e.getBody();if(!a)return[];let{SyntaxKind:d}=w(),l=a.getDescendantsOfKind(d.ReturnStatement),f=[];for(let u of l){let g=u.getExpression();if(g){let p=yield*M(g,r,s,n,i,c);f.push(p)}}return f}default:return[]}});function $n(e){let{SyntaxKind:t}=w(),r=e.getKind();return r===t.FunctionDeclaration||r===t.FunctionExpression||r===t.ArrowFunction||r===t.MethodDeclaration||r===t.ClassDeclaration||r===t.ClassExpression||r===t.Constructor}function ae(e){let{SyntaxKind:t}=w();if(e.getKind()===t.YieldExpression)return!0;let r=!1;return e.forEachChild(s=>{if(!r&&!$n(s)){if(s.getKind()===t.YieldExpression){r=!0;return}if(ae(s)){r=!0;return}}}),r}function Go(e){let{SyntaxKind:t}=w();switch(e.getKind()){case t.StringLiteral:return e.getLiteralValue();case t.NumericLiteral:return e.getLiteralValue().toString();case t.TrueKeyword:return"true";case t.FalseKeyword:return"false";case t.NullKeyword:return"null";case t.NoSubstitutionTemplateLiteral:return e.getText().replace(/^`|`$/g,"");default:return}}function nt(e,t){if(t.size===0)return e;let r=e;for(let[s,n]of t){let i=new RegExp(`\\b${s}\\b`,"g"),c=/^\d/.test(n)||n==="true"||n==="false"||n==="null"?n:`'${n}'`;r=r.replace(i,c)}return r}function ht(e){let t=e;return t=t.replace(/\btrue\b\s*&&\s*/g,""),t=t.replace(/\s*&&\s*\btrue\b/g,""),t=t.replace(/\bfalse\b\s*\|\|\s*/g,""),t=t.replace(/\s*\|\|\s*\bfalse\b/g,""),t=t.replace(/\bfalse\b\s*&&\s*[^|&]+/g,"false"),t=t.replace(/\btrue\b\s*\|\|\s*[^|&]+/g,"true"),t.trim()}function Fn(e){let{SyntaxKind:t}=w();switch(e.getKind()){case t.ParenthesizedExpression:case t.AsExpression:case t.TypeAssertionExpression:case t.NonNullExpression:case t.SatisfiesExpression:{let s=e.getExpression();return Fn(s)}default:return e}}function fs(e){let{SyntaxKind:t}=w();if(e.length===0)return!1;let r=e[e.length-1];if(!r)return!1;let s=r.getKind();return s===t.ReturnStatement||s===t.ThrowStatement||s===t.BreakStatement||s===t.ContinueStatement}function gs(e){let{SyntaxKind:t}=w(),r=[];return e.forEachChild(s=>{$n(s)||(s.getKind()===t.YieldExpression?r.push(s):r.push(...gs(s)))}),r}var Vo=new Set(["Step.run","Step.decide","Step.branch","Step.all","Step.forEach","Step.retry","Step.race","Step.sleep"]);function Jo(e){let{SyntaxKind:t}=w();if(e.getKind()!==t.CallExpression)return!1;let r=e.getExpression().getText();return Vo.has(r)}function Ae(e){if(!e)return;let{SyntaxKind:t}=w();if(e.getKind()===t.StringLiteral)return e.getLiteralText()}function Qo(e){if(!e)return[];let{SyntaxKind:t}=w();if(e.getKind()!==t.ObjectLiteralExpression)return[];let r=[],s=e;for(let n of s.getProperties())if(n.getKind()===t.PropertyAssignment){let i=n.getName();r.push({labels:[i],isDefault:i==="default",body:[]})}return r}function Zo(e,t){return xe.gen(function*(){let{SyntaxKind:r}=w(),s=e.getExpression().getText(),n=e.getArguments();switch(s){case"Step.run":{let i=Ae(n[0]),c=n[1];if(!c){let a={id:C(),type:"effect",callee:"Step.run",name:i,displayName:i};return t.stats.totalEffects++,a}let o=yield*M(c,t.sourceFile,t.filePath,t.opts,t.warnings,t.stats,t.serviceScope);return{...o,displayName:i??o.displayName,name:i??o.name}}case"Step.decide":{let i=Ae(n[0]),c=Ae(n[1]);return t.stats.decisionCount++,{id:C(),type:"decision",decisionId:i??C(),label:c??i??"decision",condition:n[2]?.getText()??"unknown",source:"effect-flow",onTrue:[],onFalse:void 0}}case"Step.branch":{let i=Ae(n[0]),c=n[1]?.getText()??"unknown",o=n[2],a=Qo(o);return t.stats.switchCount++,{id:C(),type:"switch",switchId:i,expression:c,cases:a,source:"effect-flow",hasDefault:a.some(l=>l.isDefault),hasFallthrough:!1}}case"Step.all":{let i=Ae(n[0]),c=n[1],o=[];if(c?.getKind()===r.ArrayLiteralExpression){let d=c;for(let l of d.getElements()){let f=yield*M(l,t.sourceFile,t.filePath,t.opts,t.warnings,t.stats,t.serviceScope);o.push(f)}}return t.stats.parallelCount++,{id:C(),type:"parallel",name:i,displayName:i,children:o,mode:"parallel",callee:"Step.all"}}case"Step.forEach":{let i=Ae(n[0]),c=n[1]?.getText(),o=n[2],a={id:C(),type:"effect",callee:"unknown"};return o&&(a=yield*M(o,t.sourceFile,t.filePath,t.opts,t.warnings,t.stats,t.serviceScope)),t.stats.loopCount++,{id:C(),type:"loop",name:i,displayName:i,loopType:"forEach",iterSource:c,body:a}}case"Step.retry":{let i=Ae(n[0]),c=n[1];if(!c){let d={id:C(),type:"effect",callee:"Step.retry",name:i,displayName:i};return t.stats.totalEffects++,d}let o=yield*M(c,t.sourceFile,t.filePath,t.opts,t.warnings,t.stats,t.serviceScope);return t.stats.retryCount++,{id:C(),type:"retry",name:i,displayName:i,source:o,hasFallback:!1}}case"Step.race":{let i=Ae(n[0]),c=n[1],o=[];if(c?.getKind()===r.ArrayLiteralExpression){let d=c;for(let l of d.getElements()){let f=yield*M(l,t.sourceFile,t.filePath,t.opts,t.warnings,t.stats,t.serviceScope);o.push(f)}}return t.stats.raceCount++,{id:C(),type:"race",name:i,displayName:i,children:o,callee:"Step.race"}}case"Step.sleep":{let i=Ae(n[0]),c={id:C(),type:"effect",callee:"Step.sleep",name:i,displayName:i,semanticRole:"scheduling"};return t.stats.totalEffects++,c}default:{let i={id:C(),type:"effect",callee:s,name:s,displayName:s};return t.stats.totalEffects++,i}}})}function ps(e,t){return xe.gen(function*(){let r=e,s=r.getText().startsWith("yield*"),n=r.getExpression();if(!s){let d={id:C(),type:"opaque",reason:"plain-yield",sourceText:e.getText().slice(0,80)};return t.stats.opaqueCount++,t.warnings.push({code:"PLAIN_YIELD",message:`Plain yield (not yield*) detected; this is unusual in Effect generators: ${e.getText().slice(0,60)}`,location:_(e,t.filePath,t.opts.includeLocations??!1)}),{variableName:vt(e),effect:d}}if(!n){let d={id:C(),type:"opaque",reason:"yield-no-expression",sourceText:e.getText().slice(0,80)};return t.stats.opaqueCount++,{variableName:void 0,effect:d}}let i=Fn(n);if(t.opts.enableEffectFlow&&Jo(i)){let d=yield*Zo(i,t),l=vt(e),f={...d,displayName:d.displayName??G(d,l),semanticRole:d.semanticRole??Q(d)};return{variableName:l,effect:f}}let c=yield*M(n,t.sourceFile,t.filePath,t.opts,t.warnings,t.stats,t.serviceScope),o=vt(e);o&&c.type==="effect"&&Ur(c.callee)&&t.serviceScope.set(o,c.callee);let a={...c,displayName:G(c,o),semanticRole:c.semanticRole??Q(c)};return{variableName:o,effect:a}})}function rt(e,t){return xe.gen(function*(){let r=e.getStatements(),s=[];for(let n of r){let i=yield*Dt(n,t);s.push(...i)}return s})}function Dt(e,t){return xe.gen(function*(){let{SyntaxKind:r}=w();switch(e.getKind()){case r.ExpressionStatement:{let i=e.getExpression();return yield*ye(i,t)}case r.VariableStatement:{let n=e,i=[],{VariableDeclarationKind:c}=w(),o=n.getDeclarationKind()===c.Const;for(let a of n.getDeclarations()){let d=a.getInitializer();if(o&&d){let l=Go(d);l!==void 0&&t.constValues.set(a.getName(),l)}if(d&&!ae(d)&&d.getKind()===r.CallExpression){let l=d,f=l.getExpression().getText();if(f==="Context.pick"||f==="Context.omit"){let u=yield*M(l,t.sourceFile,t.filePath,t.opts,t.warnings,t.stats,t.serviceScope);u.type==="effect"&&u.description==="context"&&i.push({variableName:a.getName(),effect:u});continue}}if(d&&ae(d)){let l=yield*ye(d,t);if(l.length>0){let f=a.getName(),u=l[l.length-1];u&&(l[l.length-1]={...u,variableName:u.variableName??f})}i.push(...l)}}return i}case r.IfStatement:{if(!ae(e))return[];let n=e,i=n.getExpression().getText(),c=yield*ye(n.getExpression(),t),o=n.getThenStatement(),a=n.getElseStatement(),d=yield*Ue(o,t),l=a?yield*Ue(a,t):void 0,f=ht(nt(i,t.constValues)),u=f.length>40?f.slice(0,40)+"...":f,g={id:C(),type:"decision",decisionId:C(),label:u,condition:i,source:"raw-if",onTrue:d.map(p=>p.effect),onFalse:l&&l.length>0?l.map(p=>p.effect):void 0};return t.stats.decisionCount++,[...c,{effect:g}]}case r.SwitchStatement:{if(!ae(e))return[];let n=e,i=n.getExpression().getText(),c=n.getClauses(),o=[],a=!1,d=!1,l=[],f=[],u=!1;for(let m of c){if(m.getKind()===r.DefaultClause)d=!0,u=!0,l.push("default");else{let E=m;l.push(E.getExpression().getText())}let y=m.getStatements();if(y.length===0){a=!0;continue}for(let E of y){let $=yield*Dt(E,t);f.push(...$)}fs(y)||(a=!0),o.push({labels:l,isDefault:u,body:f.map(E=>E.effect)}),l=[],f=[],u=!1}l.length>0&&o.push({labels:l,isDefault:u,body:f.map(m=>m.effect)});let g=nt(i,t.constValues),p={id:C(),type:"switch",switchId:C(),expression:g,cases:o,source:"raw-js",hasDefault:d,hasFallthrough:a};return t.stats.switchCount++,[{effect:p}]}case r.ForStatement:{if(!ae(e))return[];let n=e,i=[],c=n.getInitializer();if(c&&ae(c)){let m=yield*ye(c,t);i.push(...m.map(h=>h.effect))}let o=n.getIncrementor();if(o&&ae(o)){let m=yield*ye(o,t);i.push(...m.map(h=>h.effect))}let a=n.getStatement(),d=yield*Ue(a,t),l=tt(a),f=n.getCondition(),u=f?f.getText():void 0,g=d.length===1&&d[0]?d[0].effect:{id:C(),type:"generator",yields:d},p={id:C(),type:"loop",loopType:"for",iterSource:u,body:g,...l?{hasEarlyExit:l}:{},...i.length>0?{headerYields:i}:{}};return t.stats.loopCount++,[{effect:p}]}case r.ForOfStatement:{if(!ae(e))return[];let n=e,i=n.getExpression(),c=i.getText(),o=[];if(ae(i)){let p=yield*ye(i,t);o.push(...p.map(m=>m.effect))}let a=n.getInitializer().getText(),d=n.getStatement(),l=yield*Ue(d,t),f=tt(d),u=l.length===1&&l[0]?l[0].effect:{id:C(),type:"generator",yields:l},g={id:C(),type:"loop",loopType:"forOf",iterSource:c,body:u,...f?{hasEarlyExit:f}:{},...o.length>0?{headerYields:o}:{},iterVariable:a};return t.stats.loopCount++,[{effect:g}]}case r.ForInStatement:{if(!ae(e))return[];let n=e,i=n.getExpression().getText(),c=n.getInitializer().getText(),o=n.getStatement(),a=yield*Ue(o,t),d=tt(o),l=a.length===1&&a[0]?a[0].effect:{id:C(),type:"generator",yields:a},f={id:C(),type:"loop",loopType:"forIn",iterSource:i,body:l,...d?{hasEarlyExit:d}:{},iterVariable:c};return t.stats.loopCount++,[{effect:f}]}case r.WhileStatement:{if(!ae(e))return[];let n=e,i=n.getExpression().getText(),c=n.getStatement(),o=yield*Ue(c,t),a=tt(c),d=o.length===1&&o[0]?o[0].effect:{id:C(),type:"generator",yields:o},l={id:C(),type:"loop",loopType:"while",iterSource:i,body:d,...a?{hasEarlyExit:a}:{}};return t.stats.loopCount++,[{effect:l}]}case r.DoStatement:{if(!ae(e))return[];let n=e,i=n.getExpression().getText(),c=n.getStatement(),o=yield*Ue(c,t),a=tt(c),d=o.length===1&&o[0]?o[0].effect:{id:C(),type:"generator",yields:o},l={id:C(),type:"loop",loopType:"doWhile",iterSource:i,body:d,...a?{hasEarlyExit:a}:{}};return t.stats.loopCount++,[{effect:l}]}case r.TryStatement:{if(!ae(e))return[];let n=e,i=n.getTryBlock(),c=yield*rt(i,t),o=n.getCatchClause(),a,d;if(o){a=o.getVariableDeclaration()?.getName();let m=o.getBlock();d=yield*rt(m,t)}let l=n.getFinallyBlock(),f;l&&(f=yield*rt(l,t));let u=fs(i.getStatements()),g={id:C(),type:"try-catch",tryBody:c.map(p=>p.effect),...a?{catchVariable:a}:{},...d&&d.length>0?{catchBody:d.map(p=>p.effect)}:{},...f&&f.length>0?{finallyBody:f.map(p=>p.effect)}:{},hasTerminalInTry:u};return t.stats.tryCatchCount++,[{effect:g}]}case r.ReturnStatement:{let i=e.getExpression();if(!i||!ae(i))return[];let c=yield*ye(i,t),o={id:C(),type:"terminal",terminalKind:"return",value:c.map(a=>a.effect)};return t.stats.terminalCount++,[{effect:o}]}case r.ThrowStatement:{let i=e.getExpression();if(!ae(i))return[];let c=yield*ye(i,t),o={id:C(),type:"terminal",terminalKind:"throw",...c.length>0?{value:c.map(a=>a.effect)}:{}};return t.stats.terminalCount++,[{effect:o}]}case r.BreakStatement:return[];case r.ContinueStatement:return[];case r.LabeledStatement:return yield*Dt(e.getStatement(),t);case r.Block:return yield*rt(e,t);default:return[]}})}function Ue(e,t){let{SyntaxKind:r}=w();return e.getKind()===r.Block?rt(e,t):Dt(e,t)}function tt(e){let{SyntaxKind:t}=w(),r=!1;return e.forEachChild(s=>{if(r||$n(s))return;let n=s.getKind();if(n===t.BreakStatement||n===t.ReturnStatement){r=!0;return}if(tt(s)){r=!0;return}}),r}function ye(e,t){return xe.gen(function*(){let{SyntaxKind:r}=w();if(!ae(e))return[];let s=Fn(e),n=s.getKind();if(n===r.YieldExpression)return[yield*ps(s,t)];if(n===r.ConditionalExpression){let o=s,a=o.getCondition().getText(),d=o.getWhenTrue(),l=o.getWhenFalse(),f=yield*ye(d,t),u=yield*ye(l,t);if(f.length>0||u.length>0){let g=ht(nt(a,t.constValues)),p={id:C(),type:"decision",decisionId:C(),label:g.length>40?g.slice(0,40)+"...":g,condition:a,source:"raw-ternary",onTrue:f.map(m=>m.effect),onFalse:u.length>0?u.map(m=>m.effect):void 0};return t.stats.decisionCount++,[{effect:p}]}}if(n===r.BinaryExpression){let o=s,a=o.getOperatorToken().getKind(),d=o.getLeft(),l=o.getRight();if(a===r.AmpersandAmpersandToken){let f=yield*ye(l,t);if(f.length>0){let u=d.getText(),g=ht(nt(u,t.constValues)),p={id:C(),type:"decision",decisionId:C(),label:g.length>40?g.slice(0,40)+"...":g,condition:u,source:"raw-short-circuit",onTrue:f.map(m=>m.effect),onFalse:[]};return t.stats.decisionCount++,[{effect:p}]}}if(a===r.BarBarToken){let f=yield*ye(l,t);if(f.length>0){let u=d.getText(),g=ht(nt(u,t.constValues)),p={id:C(),type:"decision",decisionId:C(),label:g.length>40?g.slice(0,40)+"...":g,condition:u,source:"raw-short-circuit",onTrue:[],onFalse:f.map(m=>m.effect)};return t.stats.decisionCount++,[{effect:p}]}}if(a===r.QuestionQuestionToken){let f=yield*ye(l,t);if(f.length>0){let u=`${d.getText()} != null`,g=ht(nt(u,t.constValues)),p={id:C(),type:"decision",decisionId:C(),label:g.length>40?g.slice(0,40)+"...":g,condition:u,source:"raw-short-circuit",onTrue:[],onFalse:f.map(m=>m.effect)};return t.stats.decisionCount++,[{effect:p}]}}}let i=gs(e),c=[];for(let o of i){let a=yield*ps(o,t);c.push(a)}return c})}var Yo=(e,t,r,s,n,i)=>xe.gen(function*(){let{SyntaxKind:c}=w(),o;if((e.getKind()===c.ArrowFunction||e.getKind()===c.FunctionExpression||e.getKind()===c.FunctionDeclaration)&&(o=e.getBody()),!o)return[];let a=new Map,l={sourceFile:t,filePath:r,opts:s,warnings:n,stats:i,serviceScope:a,constValues:new Map},f;o.getKind()===c.Block?f=yield*rt(o,l):f=yield*ye(o,l);let u=o.getDescendantsOfKind(c.CallExpression);for(let h of u){let y=Le(t);if(et(h,t,y,s.knownEffectInternalsRoot)){let N=yield*vn(h,t,r,s,n,i,a);f.push({effect:N})}}let g=_e(e),p={id:C(),type:"generator",yields:f,jsdocDescription:g,jsdocTags:Ye(e)};return[{...p,displayName:G(p),semanticRole:Q(p)}]});function Xo(e,t,r,s,n,i){let o=e.getExpression().getText();if(!(o.endsWith(".pipe")||o==="pipe"))return xe.succeed(yt.none());let d=e.getArguments(),l=d[d.length-1];if(!l)return xe.succeed(yt.none());let f=l.getText();return f.includes(".runMain")||f.includes(".runPromise")||f.includes(".runSync")||f.includes(".runFork")?xe.map(Rt(e,t,r,s,n,i),g=>yt.some(g)):xe.succeed(yt.none())}var St=(e,t)=>Re.gen(function*(){let r={...an,...t},{ts:s,Project:n}=w(),i=yield*Re.try({try:()=>Rr(e)?new n({skipAddingFilesFromTsConfig:!0,compilerOptions:{allowJs:!0}}):Nr(r.tsConfigPath),catch:d=>new Se("PROJECT_CREATION_FAILED",`Failed to create project: ${String(d)}`)}),c=i.getSourceFile(e);c&&i.removeSourceFile(c);let o=yield*Re.try({try:()=>i.addSourceFileAtPath(e),catch:d=>new Se("FILE_NOT_FOUND",`Failed to load file ${e}: ${String(d)}`)}),a=kn(o,r);return a.length===0?yield*Re.fail(new Se("NO_EFFECTS_FOUND",`No Effect programs found in ${e}`)):yield*Re.forEach(a,d=>In(d,o,e,r,s.version),{concurrency:"unbounded"})}),Ge=(e,t="temp.ts",r)=>Re.gen(function*(){let s={...an,...r},{ts:n}=w(),i=yield*Re.try({try:()=>Cr(e,t),catch:o=>new Se("SOURCE_PARSE_FAILED",`Failed to parse source: ${String(o)}`)}),c=kn(i,s);return c.length===0?yield*Re.fail(new Se("NO_EFFECTS_FOUND","No Effect programs found in source")):yield*Re.forEach(c,o=>In(o,i,t,s,n.version),{concurrency:"unbounded"})});var Te=e=>({single:()=>X.gen(function*(){if(e.length===1){let t=e[0];if(t)return t}return yield*X.fail(new Se("NOT_SINGLE_PROGRAM",`Expected exactly 1 program, found ${String(e.length)}`))}),singleOption:()=>X.gen(function*(){if(e.length===1){let t=e[0];if(t)return Pt.some(t)}return Pt.none()}),all:()=>X.succeed(e),named:t=>X.gen(function*(){let r=e.find(s=>s.root.programName===t);if(!r){let s=e.map(n=>n.root.programName).join(", ");return yield*X.fail(new Se("PROGRAM_NOT_FOUND",`Program "${t}" not found. Available: ${s||"(none)"}`))}return r}),first:()=>X.gen(function*(){let t=e[0];return t||(yield*X.fail(new Se("NO_PROGRAMS","No programs found")))}),firstOption:()=>X.gen(function*(){let t=e[0];return t?Pt.some(t):Pt.none()})}),We=(e,t)=>{Tt();let r=St(e,t);return{single:()=>X.gen(function*(){let s=yield*r;return yield*Te(s).single()}),singleOption:()=>X.gen(function*(){let s=yield*r;return yield*Te(s).singleOption()}).pipe(X.orDie),all:()=>r,named:s=>X.gen(function*(){let n=yield*r;return yield*Te(n).named(s)}),first:()=>X.gen(function*(){let s=yield*r;return yield*Te(s).first()}),firstOption:()=>X.gen(function*(){let s=yield*r;return yield*Te(s).firstOption()}).pipe(X.orDie)}};We.source=(e,t)=>{Tt();let r=Ge(e,"temp.ts",t);return{single:()=>X.gen(function*(){let s=yield*r;return yield*Te(s).single()}),singleOption:()=>X.gen(function*(){let s=yield*r;return yield*Te(s).singleOption()}).pipe(X.orDie),all:()=>r,named:s=>X.gen(function*(){let n=yield*r;return yield*Te(n).named(s)}),first:()=>X.gen(function*(){let s=yield*r;return yield*Te(s).first()}),firstOption:()=>X.gen(function*(){let s=yield*r;return yield*Te(s).firstOption()}).pipe(X.orDie)}};import{Effect as ra,Option as au}from"effect";import{Option as ea}from"effect";function ms(e,t){for(let r of e){r.type==="effect"&&t.push(r);let s=ea.getOrElse(P(r),()=>[]);s.length>0&&ms(s,t)}}function ys(e){let t=[],r=[],s=new Set,n=new Map,i=[];ms(e.root.children,i);for(let d of i){let l=d.typeSignature?.successType,f=(d.requiredServices??[]).map(u=>u.serviceId);if(l){s.add(l);let u=n.get(l)??[];u.push(d.id),n.set(l,u)}t.push({id:d.id,name:d.callee,writes:l,reads:f,location:d.location?{line:d.location.line,column:d.location.column}:void 0})}for(let d=0;d<i.length-1;d++){let l=i[d],f=i[d+1];if(l===void 0||f===void 0)continue;let u=l.typeSignature?.successType??"value";r.push({from:l.id,to:f.id,key:u})}let c="__context__";for(let d of t)for(let l of d.reads)r.push({from:c,to:d.id,key:l});let o=[];for(let d of t)for(let l of d.reads)!s.has(l)&&l!==c&&o.push({key:l,readerId:d.id,readerName:d.name});let a=[];for(let[d,l]of n)l.length>1&&a.push({key:d,writerIds:l});return{nodes:t,edges:r,producedKeys:s,undefinedReads:o,duplicateWrites:a}}import{Option as it}from"effect";function An(e){let t=e.trim();return t==="never"||t==="unknown"?[]:Fe(t)}function hs(e,t){for(let r of e){if(r.type==="effect"){let n=r,i=n.typeSignature?.errorType?An(n.typeSignature.errorType):[];t.push({stepId:n.id,stepName:n.callee,errors:i,location:n.location?{line:n.location.line,column:n.location.column}:void 0})}let s=it.getOrElse(P(r),()=>[]);s.length>0&&hs(s,t)}}function Ot(e){let t=[],r=new Set,s=new Map,n=[];hs(e.root.children,t);for(let i of t){i.errors.length===0&&n.push(i.stepId);for(let c of i.errors){r.add(c);let o=s.get(c)??[];o.push(i.stepId),s.set(c,o)}}return{allErrors:Array.from(r).sort(),stepErrors:t,errorToSteps:s,stepsWithoutErrors:n,allStepsDeclareErrors:n.length===0&&t.length>0}}function Mt(e,t){return Array.from(new Set([...e,...t])).sort()}function ta(e,t){let r=new Set(t);return e.filter(s=>!r.has(s))}function na(e){let t=[],r=s=>{if(s.type==="effect"){let i=s.typeSignature?.errorType;i&&t.push(...An(i))}it.getOrElse(P(s),()=>[]).forEach(r)};return r(e),Mt([],t)}function Ss(e){if(e.type==="cause")return e.causeKind;let t=it.getOrElse(P(e),()=>[]);for(let r of t){let s=Ss(r);if(s)return s}}function st(e,t,r){let s=[...t];for(let n of e)if(n.type==="effect"){let i=n,c=i.typeSignature?.errorType?An(i.typeSignature.errorType):[];s=Mt(s,c),r.push({atNode:i.id,possibleErrors:[...s],defects:[],interruptible:!1});let o=it.getOrElse(P(n),()=>[]);o.length>0&&(s=st(o,s,r))}else if(n.type==="error-handler"){let i=n;s=st([i.source],s,r);let c=[...s],o=[];i.handlerType==="catchTag"&&i.errorTag?o.push(i.errorTag):i.handlerType==="catchTags"?i.errorTags&&i.errorTags.length>0?o.push(...c.filter(l=>i.errorTags?i.errorTags.includes(l):!1)):o.push(...c.filter(l=>/Error$|^[A-Z]/.test(l))):i.handlerType==="catchIf"||i.handlerType==="catchSome"||i.handlerType==="catchSomeCause"||i.handlerType==="catchSomeDefect"?o.push(...c.slice(0,Math.ceil(c.length/2))):i.handlerType==="catchAll"||i.handlerType==="catchAllCause"||i.handlerType==="catchAllDefect"||i.handlerType==="orElse"||i.handlerType==="orDie"||i.handlerType==="orDieWith"?o.push(...c):i.handlerType==="mapError"||i.handlerType==="mapErrorCause"||i.handlerType==="mapBoth"?o.push(...c):i.handlerType==="sandbox"?o.push(...c):i.handlerType==="ignore"||i.handlerType==="ignoreLogged"?o.push(...c):i.handlerType==="orElseFail"||i.handlerType==="orElseSucceed"?o.push(...c):(i.handlerType==="filterOrDie"||i.handlerType==="filterOrDieMessage")&&o.push(...c);let a=ta(s,o),d=i.handler?na(i.handler):[];if((i.handlerType==="mapError"||i.handlerType==="mapErrorCause"||i.handlerType==="mapBoth")&&o.length>0&&d.length===0){let l=Ss(i.source);l==="fail"?d=["<mapped-fail>"]:l==="die"?d=["<mapped-defect>"]:d=["<mapped-error>"]}s=Mt(a,d),r.push({atNode:i.id,possibleErrors:[...s],narrowedBy:{handler:i.handlerType,removedErrors:o,addedErrors:d},defects:[],interruptible:!1}),i.handler&&(s=st([i.handler],s,r))}else if(n.type==="parallel"||n.type==="race"){let i=it.getOrElse(P(n),()=>[]),c=[];for(let o of i){let a=st([o],s,r);c=Mt(c,a)}s=c}else{let i=it.getOrElse(P(n),()=>[]);i.length>0&&(s=st(i,s,r))}return s}function Lt(e){let t=[];st(e.root.children,[],t);let r=new Map;for(let s of t)r.set(s.atNode,s);return{propagation:t,byNodeId:r}}var Ns={effect:"fill:#90EE90,stroke:#333,stroke-width:2px",generator:"fill:#FFB6C1,stroke:#333,stroke-width:2px",pipe:"fill:#ADD8E6,stroke:#333,stroke-width:2px",parallel:"fill:#FFA500,stroke:#333,stroke-width:2px",race:"fill:#FF6347,stroke:#333,stroke-width:2px",errorHandler:"fill:#FFD700,stroke:#333,stroke-width:2px",retry:"fill:#EE82EE,stroke:#333,stroke-width:2px",timeout:"fill:#87CEEB,stroke:#333,stroke-width:2px",resource:"fill:#98FB98,stroke:#333,stroke-width:2px",conditional:"fill:#DDA0DD,stroke:#333,stroke-width:2px",loop:"fill:#F0E68C,stroke:#333,stroke-width:2px",layer:"fill:#E6E6FA,stroke:#333,stroke-width:2px",stream:"fill:#E0F7FA,stroke:#333,stroke-width:2px",concurrencyPrimitive:"fill:#B0E0E6,stroke:#333,stroke-width:2px",fiber:"fill:#DDA0DD,stroke:#333,stroke-width:2px",decision:"fill:#DDA0DD,stroke:#333,stroke-width:2px",switch:"fill:#FFD700,stroke:#333,stroke-width:2px",tryCatch:"fill:#FFE4B5,stroke:#333,stroke-width:2px",terminal:"fill:#FF6B6B,stroke:#333,stroke-width:2px",opaque:"fill:#FF9800,stroke:#333,stroke-width:2px",unknown:"fill:#D3D3D3,stroke:#333,stroke-width:1px",start:"fill:#c8e6c9,stroke:#2e7d32",end:"fill:#ffcdd2,stroke:#c62828",cause:"fill:#FF8A80,stroke:#D32F2F,stroke-width:2px",exit:"fill:#B39DDB,stroke:#512DA8,stroke-width:2px",schedule:"fill:#80DEEA,stroke:#00838F,stroke-width:2px",match:"fill:#FFE082,stroke:#F57F17,stroke-width:2px",transform:"fill:#A5D6A7,stroke:#388E3C,stroke-width:2px",channel:"fill:#90CAF9,stroke:#1565C0,stroke-width:2px",sink:"fill:#CE93D8,stroke:#7B1FA2,stroke-width:2px",interruption:"fill:#FFAB91,stroke:#BF360C,stroke-width:2px"},Rn={direction:"TB",includeIds:!1,includeDescriptions:!0,styles:Ns,compact:!1,includeTypeSignatures:!0,useSubgraphs:!0,showConditions:!0,detail:"verbose"};function ie(e){return e.replace(/\r?\n/g," ").replace(/"/g,"'").replace(/\[/g,"(").replace(/\]/g,")").replace(/\{/g,"(").replace(/\}/g,")").replace(/#/g,"#").replace(/\|/g,"|")}function ot(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}function sa(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}function Cs(e,t,r){let s={...Rn,...t,useSubgraphs:t?.useSubgraphs??!0,showConditions:t?.showConditions??!0,detail:t?.detail??"verbose"},n={opts:s,nodeCounter:0,edges:[],subgraphs:[],styleClasses:new Map,nodeIdMap:new Map,nodeLabelAnnotations:r},i=[];i.push(`flowchart ${s.direction}`),i.push(""),i.push(` %% Program: ${e.root.programName}`),i.push("");let c="start",o="end_node";i.push(` ${c}((Start))`),i.push(` ${o}((End))`),i.push("");let{firstNodeId:a,lastNodeIds:d}=Ee(e.root.children,n,i);a&&n.edges.push({from:c,to:a});for(let f of d)n.edges.push({from:f,to:o});for(let f of n.subgraphs){i.push(""),i.push(` subgraph ${f.id}["${f.label}"]`);for(let u of f.content)i.push(` ${u}`);i.push(" end")}i.push(""),i.push(" %% Edges");for(let f of n.edges)f.label&&s.showConditions?i.push(` ${f.from} -->|${ie(f.label)}| ${f.to}`):i.push(` ${f.from} --> ${f.to}`);let l={...Ns,...s.styles};i.push(""),i.push(" %% Styles"),l.start&&i.push(` classDef startStyle ${l.start}`),l.end&&i.push(` classDef endStyle ${l.end}`);for(let[f,u]of Object.entries(l))u&&f!=="start"&&f!=="end"&&i.push(` classDef ${f}Style ${u}`);i.push(` class ${c} startStyle`),i.push(` class ${o} endStyle`);for(let[f,u]of n.styleClasses)i.push(` class ${f} ${u}`);if(t?.dataFlowOverlay){let f=ys(e),u=n.nodeIdMap;i.push(""),i.push(" %% Data-flow variable annotations"),i.push(" linkStyle default stroke:#999");for(let g of f.edges){if(g.from==="__context__")continue;let p=u.get(g.from),m=u.get(g.to);p&&m&&g.key&&g.key!=="value"&&i.push(` ${p} -.->|${g.key}| ${m}`)}if(f.undefinedReads.length>0){i.push(""),i.push(" %% Data-flow warnings"),i.push(" classDef dataFlowWarning fill:#fff3cd,stroke:#856404,stroke-width:2px");for(let g of f.undefinedReads){let p=u.get(g.readerId);p&&i.push(` class ${p} dataFlowWarning`)}}if(f.duplicateWrites.length>0){i.push(" classDef duplicateWrite fill:#f8d7da,stroke:#721c24,stroke-width:2px");for(let g of f.duplicateWrites)for(let p of g.writerIds){let m=u.get(p);m&&i.push(` class ${m} duplicateWrite`)}}}if(t?.errorFlowOverlay){let f=Ot(e),u=Lt(e),g=n.nodeIdMap;i.push(""),i.push(" %% Error-flow overlay"),i.push(" classDef canFail fill:#FFECB3,stroke:#F57F17,stroke-width:2px"),i.push(" classDef unhandledError fill:#FFCDD2,stroke:#C62828,stroke-width:3px");for(let p of f.stepErrors)if(p.errors.length>0){let m=g.get(p.stepId);m&&i.push(` class ${m} canFail`)}for(let p of u.propagation)if(p.possibleErrors.length>0&&!p.narrowedBy){let m=g.get(p.atNode);m&&i.push(` class ${m} unhandledError`)}for(let p of u.propagation)if(p.narrowedBy&&p.narrowedBy.removedErrors.length>0){let m=g.get(p.narrowedBy.handler),h=g.get(p.atNode);if(m&&h){let y=p.narrowedBy.removedErrors.join(", ");i.push(` ${h} -.->|catches ${y}| ${m}`)}}}return{lines:i,context:n}}function Ee(e,t,r){if(e.length===0)return{firstNodeId:null,lastNodeIds:[]};let s=null,n=[];for(let i of e){let c=se(i,t,r);if(s===null&&c.firstNodeId&&(s=c.firstNodeId),c.firstNodeId)for(let o of n)t.edges.push({from:o,to:c.firstNodeId});n=c.lastNodeIds}return{firstNodeId:s,lastNodeIds:n}}function ia(e,t){let r=t.opts.includeIds&&"id"in e?e.id:`n${String(++t.nodeCounter)}`;return sa(r)}function oa(e,t,r){if(!t.includeDescriptions)return e.type;let s;switch(e.type){case"effect":s=e.callee||"Effect";break;case"generator":s=`Generator (${e.yields.length} yields)`;break;case"pipe":s=`Pipe (${e.transformations.length+1} steps)`;break;case"parallel":s=`${e.callee} (${e.children.length} effects)`;break;case"race":s=`${e.callee} (${e.children.length} racing)`;break;case"error-handler":s=e.handlerType;break;case"retry":s=`Retry${e.schedule?`(${e.schedule})`:""}`;break;case"timeout":s=`Timeout${e.duration?`(${e.duration})`:""}`;break;case"resource":s="Resource";break;case"conditional":s=`${e.conditionalType} (${ot(e.condition,20)})`;break;case"loop":s=`${e.loopType}${e.iterSource?`(${e.iterSource})`:""}`;break;case"layer":s=`Layer${e.isMerged?" (merged)":""}`;break;case"stream":s=`Stream${e.pipeline.length>0?`.${e.pipeline.map(n=>n.operation).join(" \u2192 ")}`:""}${e.sink?` \u2192 ${e.sink}`:""}`;break;case"concurrency-primitive":s=`${e.primitive}.${e.operation}${e.strategy?` (${e.strategy})`:""}`;break;case"fiber":s=`${e.operation}${e.isDaemon?" (daemon)":""}${e.isScoped?" (scoped)":""}`;break;case"decision":s=e.label||ot(e.condition,30);break;case"switch":s=`Switch: ${ot(e.expression,25)}`;break;case"try-catch":s="Try/Catch";break;case"terminal":s=e.terminalKind;break;case"opaque":s=`\u26A0 ${e.reason}`;break;case"cause":s=`Cause: ${e.causeOp}`;break;case"exit":s=`Exit: ${e.exitOp}`;break;case"schedule":s=`Schedule: ${e.scheduleOp}`;break;case"match":s=`Match: ${e.matchOp}${e.matchedTags?.length?` (${e.matchedTags.join(", ")})`:""}`;break;case"transform":s=`${e.transformType}${e.isEffectful?" (effectful)":""}`;break;case"channel":s=`Channel${e.pipeline.length>0?`.${e.pipeline.map(n=>n.operation).join(" \u2192 ")}`:""}`;break;case"sink":s=`Sink${e.pipeline.length>0?`.${e.pipeline.map(n=>n.operation).join(" \u2192 ")}`:""}`;break;case"interruption":s=e.interruptionType;break;case"unknown":s=`Unknown: ${e.reason}`;break;default:{s=e.type??"unknown";break}}if(t.detail!=="compact"&&e.displayName&&(s=e.displayName),t.detail==="verbose"){if(e.type==="effect"&&t.includeTypeSignatures&&e.typeSignature){let n=e.typeSignature;s+=`
|
|
5
|
+
`),r=[],s,n=[],i,c=/@(param|returns?|throws?|exception|example)\s*(.*)/gi,o;for(;(o=c.exec(t))!==null;){let a=o[1].toLowerCase(),d=o[2].trim();if(a==="param"){let l=/^(?:\{[^}]*\}\s*)?(\[?\w+(?:=[^\]]*)?]?)\s*(?:-\s*(.*))?$/.exec(d);if(l){let f=l[1].replace(/^\[|\]$/g,"").replace(/=.*/,""),u=l[2]?.trim();r.push(u?{name:f,description:u}:{name:f})}}else if(a==="returns"||a==="return")s=d.replace(/^\{[^}]*\}\s*/,"").trim()||void 0;else if(a==="throws"||a==="throw"||a==="exception"){let l=d.replace(/^\{[^}]*\}\s*/,"").trim();l&&n.push(l)}else if(a==="example"){let l=o.index+o[0].length,f=/\n\s*@\w/.exec(t.slice(l));f?i=t.slice(o.index+o[0].length-d.length,l+f.index).trim()||void 0:i=t.slice(o.index+o[0].length-d.length).trim()||void 0}}if(!(r.length===0&&!s&&n.length===0&&!i))return{params:r,returns:s,throws:n,example:i}}var es=e=>{let t=e.getParent(),{SyntaxKind:r}=T();if(t){let s=t.getKind();if(s===r.VariableDeclaration)return Ze(t);if(s===r.ArrowFunction){let n=t.getParent();if(n?.getKind()===r.VariableDeclaration)return Ze(n)}}};function ts(e){return e.endsWith(".js")||e.endsWith(".jsx")}var Mt=e=>{let t=e.getParent(),{SyntaxKind:r}=T();if(t?.getKind()===r.VariableDeclaration)return t.getName()},Ye=e=>{let{SyntaxKind:t}=T(),r=i=>{let c=i;for(;c!==void 0;){if(c.getKind()===t.VariableDeclaration)return c.getName();c=c.getParent()}},s=e.getParent();if(s){let i=s.getKind();if(i===t.VariableDeclaration)return s.getName();if(i===t.AwaitExpression){let c=s.getParent();if(c?.getKind()===t.VariableDeclaration)return c.getName()}if(i===t.PropertyAssignment){let o=s.getName(),a=r(s);return a?`${a}.${o}`:o}if(i===t.ArrowFunction){let c=s.getParent();if(c?.getKind()===t.VariableDeclaration)return c.getName();if(c?.getKind()===t.PropertyAssignment){let a=c.getName(),d=r(c);return d?`${d}.${a}`:a}}}let n=e;for(let i=0;n&&i<6&&(n=n.getParent(),!!n);i++){let c=n.getKind();if(c===t.VariableDeclaration)return n.getName();if(c===t.PropertyAssignment){let a=n.getName(),d=r(n);return d?`${d}.${a}`:a}if(c===t.Block||c===t.SourceFile)break}},ns=e=>{let{SyntaxKind:t}=T(),r=e.getParent();for(let s=0;r&&s<10;s++){if(r.getKind()===t.CallExpression){let n=r,i=n.getExpression().getText();if(i==="Effect.fn"||i.endsWith(".fn")){let c=n.getArguments();if(c.length>0){let o=c[0].getText(),a=/^["'](.+)["']$/.exec(o);if(a?.[1])return a[1]}}}r=r.getParent()}},rs=()=>({totalEffects:0,parallelCount:0,raceCount:0,errorHandlerCount:0,retryCount:0,timeoutCount:0,resourceCount:0,loopCount:0,conditionalCount:0,layerCount:0,interruptionCount:0,unknownCount:0,decisionCount:0,switchCount:0,tryCatchCount:0,terminalCount:0,opaqueCount:0}),X=60;function ee(e,t=X){return e.length<=t?e:`${e.slice(0,t)}\u2026`}var $e=ee;function ao(e){let t=e.replace(/\(.*$/,""),r=t.split(".");if(r.length<=1)return t;let s=r[0]??"";return xt.has(s)||Rt.has(s)?r[r.length-1]??t:t}function V(e,t){switch(e.type){case"effect":{let r=ao(e.callee);return t?$e(`${t} <- ${r}`,60):e.name?$e(`${e.name} <- ${r}`,60):$e(r,60)}case"generator":return`Generator (${e.yields.length} yields)`;case"pipe":return`Pipe (${e.transformations.length} steps)`;case"parallel":return`${e.callee} (${e.children.length})`;case"race":return`${e.callee} (${e.children.length} racing)`;case"error-handler":return e.name?`${e.name}: ${e.handlerType}`:e.handlerType;case"retry":return e.schedule?`retry: ${e.schedule}`:"retry";case"timeout":return e.duration?`timeout: ${e.duration}`:"timeout";case"resource":return"Resource";case"conditional":return $e(e.condition,30);case"loop":return e.iterSource?$e(`${e.loopType}(${e.iterSource})`,60):e.loopType;case"layer":return e.isMerged?"Layer (merged)":"Layer";case"stream":{let s=["Stream",...e.pipeline.map(n=>n.operation)];return e.sink&&s.push(e.sink),$e(s.join(" \u2192 "),60)}case"concurrency-primitive":return`${e.primitive}.${e.operation}`;case"fiber":{let r=e.operation;return e.isDaemon?`${r} (daemon)`:e.isScoped?`${r} (scoped)`:r}case"transform":return e.transformType;case"match":return`Match.${e.matchOp}`;case"cause":return`Cause.${e.causeOp}`;case"exit":return`Exit.${e.exitOp}`;case"schedule":return`Schedule.${e.scheduleOp}`;case"interruption":return e.interruptionType;case"channel":{let r=e.pipeline.map(s=>s.operation);return r.length>0?`Channel: ${r.join(" \u2192 ")}`:"Channel"}case"sink":{let r=e.pipeline.map(s=>s.operation);return r.length>0?`Sink: ${r.join(" \u2192 ")}`:"Sink"}case"decision":return $e(e.condition,30);case"switch":return`switch(${$e(e.expression,25)})`;case"try-catch":return"try/catch";case"terminal":return e.label?`${e.terminalKind} ${e.label}`:e.terminalKind;case"opaque":return`Opaque: ${$e(e.reason,25)}`;case"unknown":return`Unknown: ${$e(e.reason,30)}`}}function Y(e){switch(e.type){case"effect":{if(e.serviceCall||e.serviceMethod)return"service-call";let t=e.description?.toLowerCase()??"";if(t.includes("service"))return"service-call";if(t.includes("layer")||e.provideKind==="layer")return"layer";let r=e.callee.toLowerCase();return/^[A-Z][A-Za-z0-9_]*$/.test(e.callee)&&!e.constructorKind?"environment":r.includes("sync")||r.includes("promise")||r.includes("async")||r.includes("log")||r.includes("console")?"side-effect":r.includes("succeed")||r.includes("fail")||r.includes("die")||r.includes("void")||r.includes("never")||r.includes("gen")||r.includes("make")||e.constructorKind?"constructor":"side-effect"}case"generator":case"pipe":return"constructor";case"parallel":case"race":case"concurrency-primitive":return"concurrency";case"error-handler":case"cause":case"exit":return"error-handler";case"retry":case"timeout":case"schedule":return"scheduling";case"resource":return"resource";case"conditional":case"loop":case"match":case"decision":case"switch":case"terminal":return"control-flow";case"try-catch":return"error-handler";case"opaque":return"unknown";case"layer":return"layer";case"stream":case"channel":case"sink":return"stream";case"fiber":case"interruption":return"fiber";case"transform":return"transform";case"unknown":return"unknown"}}import{existsSync as co}from"fs";import{dirname as $n,resolve as bt,join as je,sep as ss}from"path";var is=new WeakMap,os=new WeakMap;function Ot(e){let t=new Set;for(let r of e.getExportDeclarations()){let s=r.getModuleSpecifierValue();if(!(!s||!Pe(s))){if(r.isNamespaceExport()){vn.forEach(n=>t.add(n));continue}for(let n of r.getNamedExports()){t.add(n.getName());let i=n.getAliasNode()?.getText();i&&t.add(i)}}}return t}function Xe(e,t,r){if(!r.startsWith("."))return;let s=$n(t),n=bt(s,r),i=[n,`${n}.ts`,`${n}.tsx`,`${n}.js`,`${n}.jsx`,je(n,"index.ts"),je(n,"index.tsx"),je(n,"index.js"),je(n,"index.jsx")];for(let c of i){let o=e.getSourceFile(c);if(o)return o}}function Nt(e,t){if(!t.startsWith("."))return;let r=$n(e),s=bt(r,t);return[s,`${s}.ts`,`${s}.tsx`,`${s}.js`,`${s}.jsx`,je(s,"index.ts"),je(s,"index.tsx"),je(s,"index.js"),je(s,"index.jsx")].find(i=>co(i))}function Lt(e,t,r){if(!r||!t.startsWith("."))return!1;let s=t.replace(/\\/g,"/"),n=bt($n(e),t),i=bt(n),c=bt(r);return i===c||i.startsWith(c+ss)?!0:e==="temp.ts"||e.endsWith(`${ss}temp.ts`)?s.startsWith("./internal/")||s.startsWith("../internal/"):!1}function lo(e){let t=new Set(vn),r=e.getProject(),s=e.getFilePath();for(let n of e.getImportDeclarations()){let i=n.getModuleSpecifierValue();if(Pe(i)){let c=n.getDefaultImport();c&&t.add(c.getText());let o=n.getNamespaceImport();o&&t.add(o.getText());for(let a of n.getNamedImports()){let d=a.getAliasNode()?.getText();t.add(d??a.getName())}continue}if(i.startsWith(".")){let c=Xe(r,s,i);if(!c)continue;let o=Ot(c),a=[],d=n.getDefaultImport();if(d){let u=d.getText();a.push({name:u,localName:u})}let l=n.getNamespaceImport();if(l){let u=l.getText();a.push({name:u,localName:u})}for(let u of n.getNamedImports())a.push({name:u.getName(),localName:u.getAliasNode()?.getText()??u.getName()});let f=!1;for(let u of a)o.has(u.name)?t.add(u.localName):f=!0;if(f)for(let u of a)!o.has(u.name)&&Rn(c,u.name,r,3)&&t.add(u.localName)}}return t}function Fn(e,t){let r=lo(e);for(let s of e.getImportDeclarations()){let n=s.getModuleSpecifierValue(),i=s.getNamespaceImport();if(!i)continue;let c=i.getText();if(n.startsWith("effect")||n.startsWith("@effect/")){r.add(c);continue}if(Lt(e.getFilePath(),n,t)){r.add(c);continue}let o=n.replace(/\.(js|ts)$/,"").split("/").pop()??"";Gr.has(o)&&r.add(c)}return r}var uo=new Set(["BigDecimal","BigInt","Brand","Cause","Chunk","Data","Exit","Option","Either","HashMap","HashSet","List","Redacted"]);function cs(e){let t=new Set;for(let r of e.getImportDeclarations()){let i=r.getModuleSpecifierValue().replace(/\\/g,"/").replace(/\.(js|ts|tsx|jsx)$/,"").split("/").pop()??"";if(!uo.has(i))continue;let c=r.getDefaultImport();c&&t.add(c.getText());let o=r.getNamespaceImport();o&&t.add(o.getText());for(let a of r.getNamedImports())t.add(a.getAliasNode()?.getText()??a.getName())}return t}function qe(e){let t=is.get(e);return t||(t=Fn(e),is.set(e,t)),t}var as=new WeakMap;function fo(e){let t=e.replace(/\\/g,"/").replace(/\.(js|ts|mts|cts)$/,"");return t==="effect"||t.endsWith("/Effect")?"Effect":(t.split("/").pop()??"")||"Effect"}function po(e){let t=as.get(e);if(t)return t;t=new Map;for(let r of e.getImportDeclarations()){let s=r.getModuleSpecifierValue();if(!s||!Pe(s))continue;let n=r.getNamespaceImport();if(!n)continue;let i=n.getText(),c=fo(s);t.set(i,c)}return as.set(e,t),t}function An(e,t){let r=e.indexOf(".");if(r<=0)return e;let s=e.slice(0,r),n=e.slice(r+1),c=po(t).get(s);return c?`${c}.${n}`:e}function Rn(e,t,r,s){if(s<=0)return!1;for(let n of e.getExportDeclarations()){let i=n.getModuleSpecifierValue();if(!i)continue;let c;if(n.isNamespaceExport())c=t;else for(let o of n.getNamedExports()){if(o.getAliasNode()?.getText()===t){c=o.getName();break}if(o.getName()===t){c=t;break}}if(c!==void 0){if(Pe(i))return!0;if(i.startsWith(".")){let o=Xe(r,e.getFilePath(),i);if(o&&(Ot(o).has(c)||Rn(o,c,r,s-1)))return!0}}}return!1}function go(e,t){let r=os.get(t);r||(r=new Map,os.set(t,r));let s=e.indexOf("."),n=s>0?e.slice(0,s):e,i=r.get(n);if(i!==void 0)return i;let c=!1;try{for(let o of t.getImportDeclarations()){let a=o.getModuleSpecifierValue();if(o.getNamespaceImport()?.getText()===n){c=Pe(a);break}if(o.getDefaultImport()?.getText()===n){c=Pe(a);break}for(let f of o.getNamedImports())if((f.getAliasNode()?.getText()??f.getName())===n){if(Pe(a))c=!0;else if(a.startsWith(".")){let p=Xe(t.getProject(),t.getFilePath(),a);p&&(Ot(p).has(f.getName())?c=!0:c=Rn(p,f.getName(),t.getProject(),3))}break}if(c)break}}catch{c=!1}return r.set(n,c),c}function mo(e,t){let s=e.getExpression().getText();for(let n of t.getImportDeclarations()){let i=n.getModuleSpecifierValue();if(n.getNamespaceImport()?.getText()===s||n.getDefaultImport()?.getText()===s)return i;for(let a of n.getNamedImports())if((a.getAliasNode()?.getText()??a.getName())===s)return i}}function ot(e,t,r,s){let n=e.getExpression(),i=n.getText();if(kn.some(d=>i.startsWith(d))||i.startsWith("pipe("))return!0;for(let d of r)if(i.startsWith(`${d}.`))return!0;let{SyntaxKind:c}=T();if(n.getKind()!==c.PropertyAccessExpression)return!1;let o=n,a=mo(o,t);if(!a)return!1;if(Pe(a))return!0;if(a.startsWith(".")){let d=Xe(t.getProject(),t.getFilePath(),a);if(d){let l=Ot(d),f=o.getExpression().getText();for(let u of t.getImportDeclarations())if(u.getModuleSpecifierValue()===a){for(let g of u.getNamedImports())if((g.getAliasNode()?.getText()??g.getName())===f&&l.has(g.getName()))return!0}}if(Lt(t.getFilePath(),a,s))return!0}return!1}function Wt(e,t,r){if(kn.some(s=>e.startsWith(s))||e.startsWith("pipe("))return!0;if(t){for(let s of t)if(e.startsWith(`${s}.`))return!0}return r&&e.includes(".")?go(e,r):!1}var yo=new Set(["createWorkflow","createSagaWorkflow","runSaga"]),ho=e=>Array.from(yo).some(t=>e===t||e.endsWith(`.${t}`)),ls=e=>{let t=e.getExpression();if(t.getKind()!==T().SyntaxKind.PropertyAccessExpression)return!1;let r=t,s=e.getArguments();if(r.getName()!=="make"||s.length<3||!s[2])return!1;let n=s[2].getKind(),{SyntaxKind:i}=T();return n===i.ArrowFunction||n===i.FunctionExpression};function ps(e,t){let r=e.replace(/\\/g,"/");return!!(r==="@effect/workflow"||r==="effect/workflow"||r.endsWith("/workflow")||r.includes("/workflow/")||r.endsWith("/Workflow.js")||r.endsWith("/Workflow.ts")||r.endsWith("/Activity.js")||r.endsWith("/Activity.ts")||r.startsWith(".")&&(r.endsWith("Workflow.js")||r.endsWith("Workflow.ts")||r.endsWith("Activity.js")||r.endsWith("Activity.ts")))}function So(e,t,r){return e!=="Workflow"?!1:ps(t,r)}function xo(e,t,r){return e!=="Activity"?!1:ps(t,r)}function gs(e,t){let{SyntaxKind:r}=T(),s=e.getArguments();if(s.length!==1||!s[0])return!1;let n=s[0];if(n.getKind()!==r.ObjectLiteralExpression)return!1;let c=n.getProperties(),o=new Set(t);for(let a of c)if(a.getKind()===r.PropertyAssignment){let d=a.getName();if(o.has(d))return!0}return!1}function Eo(e,t,r){let{SyntaxKind:s}=T(),n=e.getExpression();if(n.getKind()!==s.PropertyAccessExpression)return!1;let i=n;if(i.getName()!=="make")return!1;let c=i.getExpression().getText(),o=t.get(c);return!o||!So(c,o,r)?!1:gs(e,["name","payload","idempotencyKey"])}function bo(e,t,r){let{SyntaxKind:s}=T(),n=e.getExpression();if(n.getKind()!==s.PropertyAccessExpression)return!1;let i=n;if(i.getName()!=="make")return!1;let c=i.getExpression().getText(),o=t.get(c);return!o||!xo(c,o,r)?!1:gs(e,["name","execute"])}var ms=(e,t)=>{let r=e.getExpression();if(r.getKind()!==T().SyntaxKind.PropertyAccessExpression||r.getName()!=="run")return null;let n=e.getArguments();if(n.length<1||!n[0])return null;let i=n[0],{SyntaxKind:c}=T();if(i.getKind()===c.CallExpression){let l=i;return ls(l)?l.getArguments()[2]??null:null}if(i.getKind()!==c.Identifier)return null;let a=i.getText(),d=t.getDescendantsOfKind(c.VariableDeclaration);for(let l of d){if(l.getName()!==a)continue;let f=l.getInitializer();if(f?.getKind()===c.CallExpression&&ls(f))return f.getArguments()[2]??null}return null},No=e=>{let{SyntaxKind:t}=T(),r=e.getParent();for(;r;){if(r.getKind()===t.CallExpression){let n=r.getExpression().getText();if(n.includes(".gen")||n==="gen")return!0}r=r.getParent()}return!1},Co=e=>{let{SyntaxKind:t}=T();return e.getFirstAncestorByKind(t.VariableStatement)?.getParent()?.getKind()===t.SourceFile},wo=e=>{let{SyntaxKind:t}=T(),r=e.getInitializer();return r?r.getKind()===t.YieldExpression||r.getKind()===t.AwaitExpression&&r.getExpression().getKind()===t.YieldExpression:!1},ds=e=>{let{SyntaxKind:t}=T();if(e.getKind()===t.CallExpression)return e;if(e.getKind()===t.AwaitExpression){let r=e.getExpression();if(r.getKind()===t.CallExpression)return r}},J=(e,t)=>({discoveryConfidence:e,discoveryReason:t}),To=["Effect<","Layer<","Layer.Layer<","Stream<","Stream.Stream<","Channel<","Channel.Channel<","Sink<","Sink.Sink<","STM<","STM.STM<","Schedule<","Schedule.Schedule<"],Kt=e=>e!==void 0&&To.some(t=>e.includes(t)),us={low:0,medium:1,high:2},Dn=e=>{let t=e.getExpression().getText();return t.includes(".runPromise")||t.includes(".runPromiseExit")||t.includes(".runSync")||t.includes(".runSyncExit")||t.includes(".runFork")||t.includes(".runCallback")||t.includes(".runMain")||t.includes("Runtime.runPromise")||t.includes("Runtime.runSync")||t.includes("Runtime.runFork")};function fs(e){let t=e.getBody?.();if(!t)return!1;let r=t.getText();return r.includes(".runMain")||r.includes(".runPromise")||r.includes(".runSync")||r.includes(".runFork")||r.includes("Runtime.runPromise")||r.includes("Runtime.runSync")||r.includes("NodeRuntime.runMain")||r.includes("BunRuntime.runMain")||r.includes("DenoRuntime.runMain")}function ko(e,t){let r=e.getExpression();if(r.getKind()!==T().SyntaxKind.Identifier)return!1;let i=r.getSymbol()?.getValueDeclaration();if(!i)return!1;let c=i.getKind(),{SyntaxKind:o}=T();if(c===o.FunctionDeclaration||c===o.ArrowFunction||c===o.FunctionExpression)return fs(i);if(c===o.VariableDeclaration){let a=i.getInitializer();if(a&&(a.getKind()===o.ArrowFunction||a.getKind()===o.FunctionExpression))return fs(a)}return!1}function vo(e){let t=e.getExpression();if(e.getArguments().length!==1)return!1;let{SyntaxKind:r}=T();if(t.getKind()!==r.CallExpression)return!1;let s=t;if(s.getArguments().length!==1)return!1;let n=s.getExpression().getText();return n.includes(".runPromise")||n.includes(".runSync")||n.includes(".runFork")||n.includes(".runCallback")||n.includes("Runtime.runPromise")||n.includes("Runtime.runSync")||n.includes("Runtime.runFork")}var Pn=(e,t)=>{let r=[],{SyntaxKind:s}=T(),n=new Set,i=new Set,c=Fn(e,t.knownEffectInternalsRoot),o=cs(e),a=new Map;for(let E of e.getImportDeclarations()){let b=E.getModuleSpecifierValue(),C=E.getDefaultImport();C&&a.set(C.getText(),b);let k=E.getNamespaceImport();k&&a.set(k.getText(),b);for(let S of E.getNamedImports())a.set(S.getAliasNode()?.getText()??S.getName(),b)}let d=E=>{let b=a.get(E);if(b){if(b.startsWith("effect")||b.startsWith("@effect/"))return J("high",`imported from ${b}`);if(Lt(e.getFilePath(),b,t.knownEffectInternalsRoot))return J("high","namespace import resolved under knownEffectInternalsRoot");if(b.startsWith(".")&&/(?:^|\/)Effect(?:\.[jt]sx?)?$/.test(b))return J("high",`relative Effect module namespace import (${b})`)}},l=E=>{let b=k=>{let S=k.getDescendantsOfKind(s.PropertyAccessExpression);for(let A of S){let z=A.getExpression().getText();if(c.has(z)&&!o.has(z))return d(z)?.discoveryConfidence==="high"?J("high",`function body uses ${z}.* from trusted Effect alias`):J("medium",`function body uses Effect-like alias ${z}.*`)}let W=k.getDescendantsOfKind(s.CallExpression);for(let A of W){let z=A.getExpression();if(z.getKind()===s.Identifier){let $=z.getText();if(c.has($)&&!o.has($))return d($)?.discoveryConfidence==="high"?J("high",`function body calls trusted Effect import ${$}(...)`):J("medium",`function body calls Effect-like import ${$}(...)`)}}};if(E.getKind()===s.ArrowFunction||E.getKind()===s.FunctionExpression){let S=E.getBody();if(S.getKind()===s.Block){let W=b(S);if(W)return W}else{let W=b(S);if(W)return W}}let C=ds(E);if(C){let k=C.getExpression(),S=k.getText();if(k.getKind()===s.Identifier){let W=S;if(c.has(W)&&!o.has(W))return d(W)??J("high",`named import call (${W})`);if(W==="pipe")return J("medium","exact pipe() call detection")}if(k.getKind()===s.PropertyAccessExpression){let W=k,A=W.getExpression().getText();if(c.has(A)&&!o.has(A))return d(A)??J("medium",`Effect-like namespace prefix (${A}.*)`);if(W.getName()==="pipe")return J("medium","exact .pipe() call detection")}}if(E.getKind()===s.PropertyAccessExpression){let S=E.getExpression().getText();if(c.has(S)&&!o.has(S))return d(S)??J("medium",`Effect-like namespace property access (${S}.*)`)}if(E.getKind()===s.AwaitExpression){let k=E.getExpression();if(k.getKind()===s.CallExpression)return l(k)}return J("low","heuristic direct initializer match")},f=E=>{let C=(S=>S.getTypeNode?.()?.getText())(E);if(Kt(C))return J("high","explicit Effect-family type annotation");let k=E.getKind()===s.VariableDeclaration?E.getFirstAncestorByKind(s.VariableStatement)?.isExported()??!1:E.getKind()===s.PropertyDeclaration||E.getKind()===s.MethodDeclaration||E.getKind()===s.GetAccessor?E.getFirstAncestorByKind(s.ClassDeclaration)?.isExported()??!1:!1;if(E.getKind()===s.VariableDeclaration||E.getKind()===s.PropertyDeclaration){let S=E.getInitializer();if(S&&(S.getKind()===s.ArrowFunction||S.getKind()===s.FunctionExpression)){let A=S.getReturnTypeNode()?.getText();if(Kt(A))return J("high","function return type annotated as Effect-family");if(k&&C)return J("medium","explicit exported function API type signature")}if(S?.getKind()===s.CallExpression){let A=S.getTypeArguments().map(z=>z.getText()).join(" ");if(Kt(A))return J("high","call type arguments reference Effect-family types");if(k&&C)return J("medium","explicit exported call-based API type signature")}}if(E.getKind()===s.MethodDeclaration||E.getKind()===s.GetAccessor){let S=E.getReturnTypeNode?.()?.getText();if(Kt(S))return J("high","method/getter return type annotated as Effect-family");if(k&&C)return J("medium","explicit exported method/getter API type signature")}},u=E=>{let b=E.node,C=b.getKind();return C===s.CallExpression?!0:C===s.VariableDeclaration?b.getFirstAncestorByKind(s.VariableStatement)?.isExported()??!1:C===s.FunctionDeclaration||C===s.ClassDeclaration?b.isExported():C===s.PropertyDeclaration||C===s.MethodDeclaration||C===s.GetAccessor?b.getFirstAncestorByKind(s.ClassDeclaration)?.isExported()??!1:!0},g=E=>{for(let b of E){let C=b.getExpression();if(C&&ce(C,c,o))return l(C)}return J("low","heuristic method return match")},p=e.getFilePath(),m=e.getDescendantsOfKind(s.VariableDeclaration);for(let E of m){let b=E.getInitializer();if(b?.getKind()===s.CallExpression&&ho(b.getExpression().getText())&&i.add(E.getName()),t.enableEffectWorkflow&&b?.getKind()===s.CallExpression){let C=b;(Eo(C,a,p)||bo(C,a,p))&&i.add(E.getName())}}let y=e.getDescendantsOfKind(s.CallExpression);for(let E of y){let b=E.getExpression(),C=b.getText(),k=E.getStart(),S=!1;if(b.getKind()===s.Identifier)S=i.has(C);else if(b.getKind()===s.PropertyAccessExpression){let A=b,z=A.getExpression().getText(),$=A.getName();if(S=i.has(z)&&$==="run",t.enableEffectWorkflow&&!S&&$==="run"&&E.getArguments().length===1&&!C.includes("runPromise")&&!C.includes("runSync")&&!C.includes("runFork")&&!C.includes("runCallback")&&!n.has(k)){let q=Ye(E)??`workflow-${r.length+1}`;r.push({name:q,node:E,type:"run",...J("low","workflow-like .run(...) shape heuristic")}),n.add(k);continue}}if(S&&!n.has(k)){let A=Ye(E)??`workflow-${r.length+1}`;r.push({name:A,node:E,type:"run",...J("medium","workflow builder invocation")}),n.add(k);continue}if(t.enableEffectWorkflow&&b.getKind()===s.PropertyAccessExpression){let A=b,z=A.getExpression().getText(),$=A.getName();if(($==="execute"||$==="executeEncoded")&&i.has(z)&&!n.has(k)){let B=Ye(E)??`${z}.${$}`;r.push({name:B,node:E,type:"workflow-execute",...J("medium","workflow/activity .execute entrypoint")}),n.add(k);continue}}if((C==="gen"||C.endsWith(".gen")&&ot(E,e,c,t.knownEffectInternalsRoot))&&!n.has(k)){let A=Ye(E)??ns(E)??`program-${r.length+1}`;r.push({name:A,node:E,type:"generator",...C==="gen"?J("medium","unqualified gen(...) call"):J("high","Effect-like .gen(...) call")}),n.add(k)}let W=Ye(E);if(C.includes("pipe")&&Io(E,c)&&!n.has(k)&&b.getKind()!==s.PropertyAccessExpression&&W!==void 0&&!No(E)&&(r.push({name:W,node:E,type:"pipe",...J("medium","exact pipe(...) call with Effect-like args")}),n.add(k)),(Dn(E)||vo(E))&&!n.has(k)){let A=Ye(E)??`run-${r.length+1}`;r.push({name:A,node:E,type:"run",...J("high","recognized Runtime/Effect run* entrypoint")}),n.add(k)}}for(let E of m){if(!Co(E)||wo(E))continue;let b=E.getInitializer();if(b){let C=E.getName(),k=ds(b);if(k&&Dn(k)||b.getKind()===s.ObjectLiteralExpression)continue;ce(b,c,o)&&!r.some(W=>W.name===C)&&r.push({name:C,node:E,type:"direct",...f(E)??l(b)})}}let h=e.getStatements();for(let E of h){if(E.getKind()!==s.ExpressionStatement)continue;let b=E.getExpression();if(b.getKind()!==s.CallExpression)continue;let C=b,k=C.getStart();if(n.has(k))continue;let S=C.getExpression(),W=S.getText();if(Dn(C)){let A=`run-${r.length+1}`;r.push({name:A,node:C,type:"run",...J("high","recognized top-level run* entrypoint")}),n.add(k);continue}if(W.endsWith(".pipe")||W==="pipe"){let A=C.getArguments(),z=A[A.length-1];if(!z)continue;let $=z.getText();if($.includes(".runMain")||$.includes(".runPromise")||$.includes(".runSync")||$.includes(".runFork")){let B;S.getKind()===s.PropertyAccessExpression&&(B=S.getExpression().getText().split(".").pop());let H=B&&!r.some(Z=>Z.name===B)?B:`entrypoint-${r.length+1}`;r.push({name:H,node:C,type:"run",...J("medium","top-level pipe(...).run* terminator pattern")}),n.add(k)}}if(S.getKind()===s.Identifier&&C.getArguments().length>=1){let A=S.getText();ko(C,e)&&!r.some($=>$.name===A)&&(r.push({name:A,node:C,type:"run",...J("low","indirect run wrapper body heuristic")}),n.add(k))}}let N=["Data.TaggedError","Data.TaggedClass","Data.Class","Data.Error","Schema.Class","Schema.TaggedClass","Schema.TaggedError","Schema.TaggedRequest","Context.Tag","Context.Reference","Effect.Service"],x=e.getDescendantsOfKind(s.ClassDeclaration);for(let E of x){let b=E.getName();if(!b||r.some(S=>S.name===b))continue;E.getHeritageClauses().some(S=>{let W=S.getText();return N.some(A=>W.includes(A))})&&r.push({name:b,node:E,type:"class",...J("medium","known Data/Schema/Context class pattern")})}let F=x.filter(E=>{let b=E.getParent();return b===e||b?.getParent()===e});for(let E of F){let b=E.getName()??"Anonymous",C=E.getMembers(),k=C.filter(A=>A.getKind()===s.PropertyDeclaration);for(let A of k){let z=A.getInitializer();if(!z)continue;let $=A.getName(),q=`${b}.${$}`;r.some(B=>B.name===q)||ce(z,c,o)&&r.push({name:q,node:A,type:"classProperty",...f(A)??l(z)})}let S=C.filter(A=>A.getKind()===s.MethodDeclaration);for(let A of S){let z=A.getName(),$=`${b}.${z}`;if(r.some(Z=>Z.name===$))continue;let q=A.getBody();if(!q)continue;let B=q.getDescendantsOfKind(s.ReturnStatement);B.some(Z=>{let ae=Z.getExpression();return ae?ce(ae,c,o):!1})&&r.push({name:$,node:A,type:"classMethod",...f(A)??g(B)})}let W=C.filter(A=>A.getKind()===s.GetAccessor);for(let A of W){let z=A.getName(),$=`${b}.${z}`;if(r.some(Z=>Z.name===$))continue;let q=A.getBody();if(!q)continue;let B=q.getDescendantsOfKind(s.ReturnStatement);B.some(Z=>{let ae=Z.getExpression();return ae?ce(ae,c,o):!1})&&r.push({name:$,node:A,type:"classMethod",...f(A)??g(B)})}}return r.filter(E=>{let b=t.minDiscoveryConfidence??"low",C=E.discoveryConfidence??"low";return!(us[C]<us[b]||t.onlyExportedPrograms&&!u(E))})},Io=(e,t)=>e.getArguments().map(n=>n.getText()).some(n=>[...t].some(i=>n.includes(`${i}.`)));function ys(e){let{SyntaxKind:t}=T(),r=[],s=e.getProject().getTypeChecker(),n=e.getDescendantsOfKind(t.ClassDeclaration);for(let i of n){let c=i.getName();if(!c)continue;let o=i.getExtends();if(!o)continue;let a=o.getText();if(!a.includes("Context.Tag")&&!a.includes("Effect.Service"))continue;let d=o.getTypeArguments();if(d.length<2){let f=o.getExpression();f&&"getTypeArguments"in f&&typeof f.getTypeArguments=="function"&&(d=f.getTypeArguments())}if(d.length<2)continue;let l=d[1];if(l)try{let f=s.getTypeAtLocation(l),u=[],g=[];for(let h of f.getProperties()){let N=h.getName();if(N.startsWith("_")||N==="constructor")continue;s.getTypeOfSymbolAtLocation(h,l).getCallSignatures().length>0?u.push(N):g.push(N)}let p=i.getText(),m=p.includes("Equal.symbol")||p.includes("[Equal")||p.includes("equal("),y=p.includes("Hash.symbol")||p.includes("[Hash")||p.includes("hash(");r.push({tagId:c,methods:u,properties:g,...m?{hasCustomEquality:m}:{},...y?{hasCustomHash:y}:{}})}catch{}}for(let i of n){let c=i.getName();if(!c)continue;let o=i.getExtends();if(!o)continue;let a=o.getText();if(!a.includes("Data.Class")&&!a.includes("Data.TaggedClass")||r.some(u=>u.tagId===c))continue;let d=i.getText(),l=d.includes("Equal.symbol")||d.includes("[Equal")||d.includes("equal("),f=d.includes("Hash.symbol")||d.includes("[Hash")||d.includes("hash(");(l||f)&&r.push({tagId:c,methods:[],properties:[],hasCustomEquality:l,hasCustomHash:f})}return r}import{Effect as Ee,Option as Ct}from"effect";import{Effect as re,Option as $o}from"effect";var Fo=["Schema.decode","Schema.decodeUnknown","Schema.encode","Schema.validate","Schema.decodeOption","Schema.decodeEither","Schema.encodeUnknown","Schema.decodeSync","Schema.encodeSync","Schema.decodeUnknownSync","Schema.decodeUnknownOption","Schema.decodeUnknownEither","Schema.decodePromise","Schema.encodePromise","Schema.decodeUnknownPromise"],jt=(e,t,r,s,n,i)=>re.gen(function*(){let{SyntaxKind:c}=T(),o=e.getArguments(),a=e.getExpression(),d=a.getKind()===c.PropertyAccessExpression&&a.getName()==="pipe",l=d?a.getExpression():o[0],f=d?o:o.slice(1);if(!l)return[];let u=Ss(l),g=u.getSourceFile(),p=g.getFilePath(),m=t.getProject();if(m.getSourceFile(p)){let C=m.getSourceFile(p);C&&(g=C)}else{let C=m.addSourceFileAtPath(p);C&&(g=C)}let y=yield*M(u,g,g.getFilePath(),s,n,i),h=[];for(let C of f)if(C){let k=yield*M(C,t,r,s,n,i);h.push(k)}let N,x=h.filter(C=>!(C.type==="effect"&&C.callee.includes("withSpan")));if(!N){for(let C of f)if(C){let k=C.getText();if(k.includes("withSpan")){let S=/withSpan\s*\(\s*["']([^"']+)["']/.exec(k);S?.[1]&&(N=S[1])}}}let F;try{let C=t.getProject().getTypeChecker(),k=[],S=Be(l,C);S&&k.push(S);for(let W of f)if(W){let A=Be(W,C);A&&k.push(A)}k.length>0&&(F=k)}catch{}let E={id:w(),type:"pipe",initial:y,transformations:x,...F?{typeFlow:F}:{},...N?{spanName:N}:{}};return[{...E,displayName:V(E),semanticRole:Y(E)}]}),M=(e,t,r,s,n,i,c)=>re.gen(function*(){let{SyntaxKind:o}=T();if(e.getKind()===o.ArrowFunction||e.getKind()===o.FunctionExpression){let l=e.getBody();if(!l){let u={id:w(),type:"unknown",reason:"Function has no body",sourceCode:e.getText().slice(0,100),location:_(e,r,s.includeLocations??!1)};return i.unknownCount++,u}if(l.getKind()===o.Block){let p=l.getStatements().find(m=>m.getKind()===o.ReturnStatement)?.getExpression();if(p)return yield*M(p,t,r,s,n,i,c)}else return yield*M(l,t,r,s,n,i,c);let f={id:w(),type:"unknown",reason:"Function does not return an Effect expression",sourceCode:e.getText().slice(0,100),location:_(e,r,s.includeLocations??!1)};return i.unknownCount++,f}if(e.getKind()===o.CallExpression)return yield*Mn(e,t,r,s,n,i,c);if(e.getKind()===o.PropertyAccessExpression){let d=e.getText();if(d==="Fiber.roots"||d==="Fiber.getCurrentFiber"){let l=d==="Fiber.roots"?"roots":"getCurrentFiber";return{id:w(),type:"fiber",operation:l,isScoped:!1,isDaemon:!1,location:_(e,r,s.includeLocations??!1)}}if(Wt(d,qe(t),t)){let l={id:w(),type:"effect",callee:d,location:_(e,r,s.includeLocations??!1)};return i.totalEffects++,l}}if(e.getKind()===o.Identifier){let d={id:w(),type:"effect",callee:e.getText(),location:_(e,r,s.includeLocations??!1)};return i.totalEffects++,d}if(e.getKind()===o.ObjectLiteralExpression){let d=e,l=new Set(["onNone","onSome","onFailure","onSuccess","onLeft","onRight"]),f=d.getProperties(),u=[],g=!1;for(let p of f){if(p.getKind()!==o.PropertyAssignment)continue;let m=p,y=m.getName();if(!l.has(y))continue;g=!0;let h=m.getInitializer();if(h){let N=yield*M(h,t,r,s,n,i,c);u.push(N)}}if(g&&u.length>0)return u.length===1?u[0]:{id:w(),type:"parallel",callee:"match-handlers",mode:"sequential",children:u,location:_(e,r,s.includeLocations??!1)}}let a={id:w(),type:"unknown",reason:"Could not determine effect type",sourceCode:e.getText().slice(0,100),location:_(e,r,s.includeLocations??!1)};return i.unknownCount++,a}),Mn=(e,t,r,s,n,i,c)=>re.gen(function*(){let{SyntaxKind:o}=T(),a=e.getExpression().getText(),d=An(a,t),l=/([A-Za-z_$][\w$]*)$/.exec(d)?.[1]??d,f=_(e,r,s.includeLocations??!1),u=a.endsWith(".pipe")&&a!=="pipe"&&a.startsWith("Effect.");if((a==="pipe"||u)&&e.getArguments().length>=1){let L=yield*jt(e,t,r,s,n,i);if(L.length>0&&L[0])return L[0]}if(d==="Context.pick"||d==="Context.omit"){let L={id:w(),type:"effect",callee:d,description:"context",location:f};return i.totalEffects++,{...L,displayName:V(L),semanticRole:Y(L)}}if(d.startsWith("Layer."))return yield*Po(e,d,t,r,s,n,i);if(d.startsWith("Stream."))return yield*Mo(e,d,t,r,s,n,i);if(d.startsWith("Channel."))return yield*Lo(e,d,t,r,s,n,i);if(a.startsWith("Sink."))return yield*Ko(e,a,t,r,s,n,i);if(a.startsWith("Queue.")||a.startsWith("PubSub.")||a.startsWith("Deferred.")||a.startsWith("Semaphore.")||a.startsWith("Mailbox.")||a.startsWith("SubscriptionRef.")||a.startsWith("RateLimiter.")||a.startsWith("PartitionedSemaphore.")||a.startsWith("FiberHandle.")||a.startsWith("FiberSet.")||a.startsWith("FiberMap.")||a.startsWith("Cache.")||a.startsWith("ScopedCache.")||a.startsWith("RcRef.")||a.includes(".RcRef.")||a.startsWith("RcMap.")||a.includes(".RcMap.")||a.startsWith("Reloadable.")||a.includes(".Reloadable.")||a.includes("makeLatch")||a.includes("Latch."))return yield*Bo(e,a,t,r,s,n,i);if(xn.some(L=>a.includes(L)||a.startsWith(L)))return yield*jo(e,a,t,r,s,n,i);if(Tn.some(L=>a.includes(L)))return yield*qo(e,a,t,r,s,n,i);if(a.includes(".all")||a==="all")return yield*zo(e,a,t,r,s,n,i);if(a.includes(".race")||a==="race")return yield*Uo(e,a,t,r,s,n,i);if(yn.some(L=>a.includes(L)))return yield*Ho(e,a,t,r,s,n,i);if(a.includes(".retry"))return yield*Go(e,t,r,s,n,i);if(a.includes(".timeout"))return yield*Vo(e,t,r,s,n,i);let p=new Set(["acquireRelease","acquireUseRelease","ensuring","addFinalizer","onExit","onError","parallelFinalizers","sequentialFinalizers","finalizersMask","using","withEarlyRelease"]),m=["acquireRelease","acquireUseRelease"],y=L=>p.has(L)||m.some(G=>L.startsWith(G));if(l==="pipe"&&e.getExpression().getKind()===o.PropertyAccessExpression){let G=e.getExpression().getExpression();if(G.getKind()===o.CallExpression){let Se=G,ne=Se.getExpression().getText(),I=/([A-Za-z_$][\w$]*)$/.exec(ne)?.[1]??ne;if(y(I))return yield*hs(Se,I,t,r,s,n,i)}}if(y(l))return yield*hs(e,l,t,r,s,n,i);let h=`.${l}`;if(hn.some(L=>h===L||a.endsWith(L)))return yield*Jo(e,a,t,r,s,n,i);let N=Fo.some(L=>a.startsWith(L)||d.startsWith(L)),x=`.${l}`;if(!N&&Sn.some(L=>x===L||a.endsWith(L)))return yield*Qo(e,a,t,r,s,n,i);if(Lr(a))return yield*ta(e,a,t,r,s,n,i);if(Kr(a))return Zo(e,a,r,s);if(jr(a))return yield*Yo(e,a,t,r,s,n,i);if(_r(a))return Xo(e,a,r,s);if(zr(a))return yield*ea(e,a,r,s);i.totalEffects++;let F,b=["Effect.sync","Effect.promise","Effect.async","Effect.asyncEffect","Effect.tryPromise","Effect.suspend"].some(L=>a.includes(L))&&e.getArguments().length>0&&e.getArguments()[0],C;if(b){let L=e.getArguments()[0],{SyntaxKind:G}=T();if(L.getKind()===G.ArrowFunction||L.getKind()===G.FunctionExpression){let ne=L,I=ne.getBody(),K=[];if(I){if(I.getKind()===G.Block){let ve=I;for(let Je of ve.getStatements())if(Je.getKind()===G.ReturnStatement){let Ie=Je.getExpression();if(Ie&&Wt(Ie.getText(),qe(t),t)){let Qe=yield*M(Ie,t,r,s,n,i,void 0);K.push(Qe)}}else if(Je.getKind()===G.ExpressionStatement){let Ie=Je.getExpression();if(Ie.getKind()===G.CallExpression&&ot(Ie,t,qe(t),s.knownEffectInternalsRoot)){let Qe=yield*M(Ie,t,r,s,n,i,void 0);K.push(Qe)}}}else if(Wt(I.getText(),qe(t),t)){let ve=yield*M(I,t,r,s,n,i,void 0);K.push(ve)}}if(K.length>0&&(F=K),a.includes("Effect.async")||a.includes("Effect.asyncEffect")){let ve=ne.getParameters()[0]?.getName?.()??"resume",Je=0,Ie=ht=>{if(ht.getKind()===G.CallExpression){let St=ht.getExpression();St.getKind()===G.Identifier&&St.getText()===ve&&Je++}ht.getChildren().forEach(Ie)};I&&Ie(I);let Qe=!1;if(I?.getKind()===G.Block){let ht=I;for(let fn of ht.getStatements())if(fn.getKind()===G.ReturnStatement){let St=fn.getExpression();if(St){let vr=St.getKind();if(vr===G.ArrowFunction||vr===G.FunctionExpression){Qe=!0;break}}}}else I&&(I.getKind()===G.ArrowFunction||I.getKind()===G.FunctionExpression)&&(Qe=!0);C={resumeParamName:ve,resumeCallCount:Je,returnsCanceller:Qe}}}}let k=Ze(e),S=t.getProject().getTypeChecker(),W=Be(e,S),A=At(e,S),z=Ao(e,t),$,q=e.getExpression();if(q.getKind()===T().SyntaxKind.PropertyAccessExpression){let L=q,G=L.getExpression().getText(),Se=L.getName();if(c){let ne=c.get(G);ne&&($={serviceId:ne,methodName:Se})}!$&&A?.length===1&&A[0]&&($={serviceId:A[0].serviceId,methodName:Se})}let B;if(a==="Effect.provide"||a.startsWith("Effect.")&&a.includes(".provide")&&!a.includes("provideService")){let L=e.getArguments(),G=(L.length>=2?L[1]:L[0])?.getText()??"";/Runtime\.|defaultRuntime|\.runSync|\.runPromise|\.runFork|\.runCallback/.test(G)||/^\s*runtime\s*$|^\s*rt\s*$/i.test(G.trim())?B="runtime":G.includes("Layer.")?B="layer":B="context"}let H;a.endsWith(".sync")||a.endsWith(".succeed")||a.endsWith(".fail")||a.endsWith(".try")||a.endsWith(".suspend")?H="sync":a.endsWith(".promise")?H="promise":a.endsWith(".async")||a.endsWith(".asyncEffect")?H="async":a.endsWith(".never")?H="never":a.endsWith(".void")?H="void":a.endsWith(".fromNullable")?H="fromNullable":a.endsWith(".fn")?H="fn":a.endsWith(".fnUntraced")&&(H="fnUntraced");let Z,ae=["currentConcurrency","currentLogLevel","currentScheduler","currentTracerEnabled","currentLogSpan","currentLogAnnotations","currentContext","currentRequestBatching","currentMaxOpsBeforeYield","currentSupervisor","currentMetricLabels","interruptedCause","unhandledLogLevel"];for(let L of ae)if(a.includes(L)){Z=L;break}let ke;if(H==="fn"||H==="fnUntraced"){let L=e.getArguments();if(L.length>0){let G=L[0].getText(),Se=/^["'`](.+?)["'`]$/.exec(G);Se&&(ke=Se[1])}}let Re={id:w(),type:"effect",callee:a,description:z?"service-call":Hr(a,qe(t)),location:f,jsdocDescription:k,jsdocTags:it(e),typeSignature:W,requiredServices:A,serviceCall:z,serviceMethod:$,callbackBody:F,...C?{asyncCallback:C}:{},...B?{provideKind:B}:{},...H?{constructorKind:H}:{},...Z?{fiberRefName:Z}:{},...ke?{tracedName:ke}:{}};return{...Re,displayName:V(Re),semanticRole:Y(Re)}}),Ao=(e,t)=>{let{SyntaxKind:r}=T(),s=e.getExpression();if(s.getKind()!==r.PropertyAccessExpression)return;let n=s,i=n.getExpression(),c=n.getName(),o=i.getText(),a=o.split(".")[0]??o;if(!xt.has(a))try{let d=i.getType(),l=d.getSymbol()??d.getAliasSymbol();if(!l)return;let f=l.getName();return!f||f==="__type"||f==="unknown"||f==="any"||Rt.has(f)?void 0:{serviceType:f,methodName:c,objectName:o}}catch{return}};function Bt(e){let t=e.getExpression().getText(),r=e.getSourceFile(),s=An(t,r);return s.startsWith("Layer.")||s.startsWith("Effect.")||t==="pipe"||t.endsWith(".pipe")}function Ro(e,t,r){let{SyntaxKind:s}=T(),n=e.getSourceFile(),i=n.getProject(),c=n.getFilePath(),a=t.getImportDeclaration().getModuleSpecifierValue();if(!a?.startsWith("."))return;let d=Xe(i,c,a);if(!d){let m=Nt(c,a);if(m){let y=i.addSourceFileAtPath(m);y&&(d=y)}}if(!d)return;d=i.getSourceFile(d.getFilePath())??d;let l=m=>{if(m.getKind()===s.VariableDeclaration){let h=m.getInitializer();if(h?.getKind()===s.CallExpression&&r(h))return h}if(m.getKind()===s.VariableStatement){let y=m.getDeclarationList();for(let h of y.getDeclarations()){let N=h.getInitializer();if(N?.getKind()===s.CallExpression&&r(N))return N}}},f=t.getName(),u=d.getExportedDeclarations(),g=u.get(f)??[];for(let m of g){let y=l(m);if(y)return y}let p=t.getTargetName?.();if(p&&p!==f)for(let m of u.get(p)??[]){let y=l(m);if(y)return y}for(let[,m]of u)for(let y of m){let h=l(y);if(h)return h}}function Do(e,t,r){let{SyntaxKind:s}=T(),n=e.getSourceFile(),i=n.getProject(),c=n.getFilePath(),o=t.getModuleSpecifierValue();if(!o?.startsWith("."))return;let a=Xe(i,c,o);if(!a){let l=Nt(c,o);if(l){let f=i.addSourceFileAtPath(l);f&&(a=f)}}if(!a)return;a=i.getSourceFile(a.getFilePath())??a;let d=l=>{if(l.getKind()===s.VariableDeclaration){let u=l.getInitializer();if(u?.getKind()===s.CallExpression&&r(u))return u}if(l.getKind()===s.VariableStatement){let f=l.getDeclarationList();for(let u of f.getDeclarations()){let g=u.getInitializer();if(g?.getKind()===s.CallExpression&&r(g))return g}}};for(let l of a.getDefaultExportSymbol()?.getDeclarations()??[]){let f=d(l);if(f)return f}for(let l of a.getExportedDeclarations().get("default")??[]){let f=d(l);if(f)return f}}function Ss(e){let{SyntaxKind:t}=T();if(e.getKind()!==t.Identifier)return e;let r=e,s=r.getText(),n=r.getSymbol(),i=n?.getValueDeclaration(),c=i?.getKind()===t.ImportSpecifier?i:void 0;if(!c&&n){let o=n.getDeclarations().find(a=>a.getKind()===t.ImportSpecifier);o&&(c=o)}if(!c){let o=r.getSourceFile();for(let a of o.getImportDeclarations()){if(a.getDefaultImport()?.getText()===s){let f=Do(r,a,Bt);if(f)return f}let l=a.getNamedImports().find(f=>f.getName()===s||f.getAliasNode()?.getText()===s);if(l){c=l;break}}}if(c){let o=Ro(r,c,Bt);if(o)return o;n=n?.getImmediatelyAliasedSymbol()??n?.getAliasedSymbol(),i=n?.getValueDeclaration()}if(i?.getKind()===t.ExportSpecifier&&(n=n?.getImmediatelyAliasedSymbol()??n?.getAliasedSymbol(),i=n?.getValueDeclaration()),n&&i?.getKind()!==t.VariableDeclaration){for(let o of n.getDeclarations())if(o.getKind()===t.VariableDeclaration){let d=o.getInitializer();if(d?.getKind()===t.CallExpression&&Bt(d))return d}}if(i?.getKind()===t.VariableDeclaration){let a=i.getInitializer();if(a?.getKind()===t.CallExpression&&Bt(a))return a}return e}var Po=(e,t,r,s,n,i,c)=>re.gen(function*(){let o=e.getArguments(),a=[],{SyntaxKind:d}=T();if(o.length>0&&o[0]){let b=o[0];if(t.includes("mergeAll")&&b.getKind()===d.ArrayLiteralExpression){let k=b.getElements();for(let S of k){let W=yield*M(S,r,s,n,i,c);a.push(W)}}else for(let k of o){if(!k)continue;let S=Ss(k),W=S.getSourceFile(),A=yield*M(S,W,W.getFilePath(),n,i,c);a.push(A)}}let l=t.includes("merge")||t.includes("mergeAll"),f;t.includes("fresh")?f="fresh":t.includes("memoize")?f="memoized":t.includes("scoped")?f="scoped":f="default";let u=[],g=b=>{if(b.getKind()===d.Identifier)return b.getText();if(b.getKind()===d.PropertyAccessExpression){let C=b,k=C.getExpression();return k.getKind()===d.Identifier?k.getText():C.getText().split(".")[0]}};if((t.includes("succeed")||t.includes("sync")||t.includes("effect")||t.includes("scoped")||t.includes("scopedDiscard")||t.includes("effectDiscard"))&&o.length>0&&o[0]){let b=g(o[0]);b&&u.push(b)}let p=t.includes("provide")&&!t.includes("provideService"),m=new Set;if(p&&o.length>=1&&o[0]){let b=g(o[0]);b&&m.add(b)}if(p&&o.length>=2&&o[1]){let b=g(o[1]);b&&m.add(b);let C=g(o[0]);C&&u.push(C)}if(t.includes("provideService")&&o.length>0&&o[0]){let b=g(o[0]);b&&u.push(b)}let y=b=>{if(b.type==="effect"){let k=b;for(let W of k.requiredServices??[])m.add(W.serviceId);let S=k.callee??"";(/^[A-Z][A-Za-z0-9_]*(Service|Tag)$/.test(S)||S.endsWith(".Tag"))&&m.add(S)}else if(b.type==="layer"){let k=b;for(let S of k.requires??[])m.add(S)}$o.getOrElse(P(b),()=>[]).forEach(y)};if(a.forEach(y),m.size===0)try{let b=Pr(e);b?.requiredType&&b.requiredType!=="never"&&Vr(b.requiredType).forEach(k=>m.add(k))}catch{}let h=t.replace(/^Layer\./,"").replace(/^[a-zA-Z]+\./,""),x=new Set(["catchAll","catchAllCause","orDie","orElse","retry","tap","mapError","mapErrorCause","build","launch","toRuntime","passthrough","project","flatMap","flatten","annotateLogs","annotateSpans","setConfigProvider","setClock","setTracer","locally","withSpan","withLogger","withTracer","withClock","mock","suspend","unwrapEffect","unwrapScoped"]).has(h)?`Layer.${h}`:void 0,F=t.includes("MemoMap")||a.some(b=>b.type==="layer"&&b.isMemoMap===!0),E={id:w(),type:"layer",name:x,operations:a,isMerged:l,provides:u.length>0?u:void 0,requires:m.size>0?Array.from(m).sort():void 0,lifecycle:f,...F?{isMemoMap:!0}:{},location:_(e,s,n.includeLocations??!1)};return{...E,displayName:V(E),semanticRole:Y(E)}});function Mo(e,t,r,s,n,i,c){return re.gen(function*(){let o=e.getArguments(),a;o.length>0&&o[0]?a=yield*M(o[0],r,s,n,i,c):a={id:w(),type:"unknown",reason:"Stream source not determined"};let d=t.replace(/^Stream\./,"")||"unknown",l;t.startsWith("Stream.")&&(d==="fromIterable"||d==="fromChunk"||d==="fromChunkQueue"?l="fromIterable":d==="fromArray"?l="fromArray":d==="fromQueue"||d==="fromChunkQueue"?l="fromQueue":d==="fromPubSub"||d==="fromChunkPubSub"?l="fromPubSub":d==="fromEffect"||d==="unwrap"||d==="unwrapScoped"?l="fromEffect":d==="fromAsyncIterable"?l="fromAsyncIterable":d==="fromReadableStream"||d==="fromReadableStreamByob"?l="fromReadableStream":d==="fromEventListener"?l="fromEventListener":d==="fromSchedule"?l="fromSchedule":d==="range"?l="range":d==="tick"?l="tick":d==="iterate"||d==="iterateEffect"?l="iterate":d==="unfold"||d==="unfoldEffect"||d==="unfoldChunk"||d==="unfoldChunkEffect"?l="unfold":d==="make"?l="make":d==="empty"?l="empty":d==="never"?l="never":d==="succeed"||d==="sync"?l="succeed":(d==="fail"||d==="failSync"||d==="failCause"||d==="failCauseSync")&&(l="fail"));let f=S=>l!==void 0?"constructor":S.startsWith("run")?"sink":S==="toQueue"||S==="toPubSub"||S==="toReadableStream"||S==="toAsyncIterable"||S==="toChannel"?"conversion":S.includes("pipeThroughChannel")||S.includes("Channel")||S.includes("channel")||S.includes("duplex")?"channel":S.includes("grouped")||S.includes("sliding")||S.includes("groupBy")||S.includes("aggregate")||S.includes("window")?"windowing":S.includes("broadcast")||S==="share"?"broadcasting":S.includes("haltAfter")||S.includes("haltWhen")||S.includes("interruptAfter")?"halting":S.includes("decodeText")||S.includes("encodeText")||S.includes("splitLines")?"text":S.includes("merge")||S==="concat"||S.includes("interleave")||S.includes("zip")?"merge":S.includes("buffer")||S.includes("debounce")||S.includes("throttle")?"backpressure":S.includes("catchAll")||S.includes("catchTag")||S.includes("orElse")||S.includes("orDie")||S.includes("retry")?"error":S.includes("filter")||S.includes("take")||S.includes("drop")||S.includes("head")||S==="first"||S==="last"?"filter":S.includes("acquireRelease")||S.includes("scoped")||S.includes("ensuring")||S.includes("onDone")||S.includes("onError")?"resource":S.includes("provide")||S.includes("withSpan")||S.includes("annotate")?"context":S.includes("map")||S.includes("tap")||S.includes("flatMap")||S.includes("mapChunk")||S.includes("scan")||S.includes("transduce")?"transform":"other",u=d.includes("Effect")||d.startsWith("run")||d.includes("tap"),g=f(d),p=g==="filter"?"fewer":g==="merge"||g==="broadcasting"?"more":g==="halting"||g==="sink"||g==="windowing"?"fewer":"unknown",m,y;(d==="grouped"||d==="groupedWithin"||d.includes("sliding")||d.includes("Sliding"))&&o.length>0&&o[0]&&(m=Et(o[0]),(d.includes("sliding")||d.includes("Sliding"))&&o.length>1&&o[1]&&(y=Et(o[1])));let N={operation:d,isEffectful:u,estimatedCardinality:p,category:g,...m!==void 0?{windowSize:m}:{},...y!==void 0?{stride:y}:{}},x;d.startsWith("run")&&(x=d);let F;d.includes("buffer")?F="buffer":d.includes("drop")||d.includes("Drop")?F="drop":(d.includes("sliding")||d.includes("Sliding"))&&(F="sliding");let E=a,b=[N],C=l;if(a.type==="stream"){let S=a;b=[...S.pipeline,N],E=S.source,!C&&S.constructorType&&(C=S.constructorType),!x&&S.sink&&(x=S.sink),!F&&S.backpressureStrategy&&(F=S.backpressureStrategy)}let k={id:w(),type:"stream",source:E,pipeline:b,sink:x,backpressureStrategy:F,constructorType:C,location:_(e,s,n.includeLocations??!1)};return{...k,displayName:V(k),semanticRole:Y(k)}})}function Oo(e){return e==="fromReadableStream"||e==="fromWritableStream"||e==="fromDuplexStream"||e==="make"||e==="succeed"||e==="fail"||e==="empty"||e==="never"?"constructor":e.includes("map")||e.includes("flatMap")||e.includes("filter")||e.includes("concat")||e.includes("zip")?"transform":e.includes("pipe")||e==="pipeTo"||e==="pipeThrough"?"pipe":"other"}function Lo(e,t,r,s,n,i,c){return re.gen(function*(){let o=e.getArguments(),a;o.length>0&&o[0]&&(a=yield*M(o[0],r,s,n,i,c));let d=t.replace(/^Channel\./,"")||"unknown",l=[{operation:d,category:Oo(d)}];if(a?.type==="channel"){let u=a;l.unshift(...u.pipeline),a=u.source}let f={id:w(),type:"channel",source:a,pipeline:l,location:_(e,s,n.includeLocations??!1)};return{...f,displayName:V(f),semanticRole:Y(f)}})}function Wo(e){return e==="forEach"||e==="forEachWhile"||e==="run"||e==="runDrain"||e==="runFor"||e==="make"||e==="fromEffect"||e==="fromQueue"?"constructor":e.includes("map")||e.includes("contramap")||e.includes("filter")||e.includes("zip")?"transform":"other"}function Ko(e,t,r,s,n,i,c){return re.gen(function*(){let o=e.getArguments(),a;o.length>0&&o[0]&&(a=yield*M(o[0],r,s,n,i,c));let d=t.replace(/^Sink\./,"")||"unknown",l=[{operation:d,category:Wo(d)}];if(a?.type==="sink"){let u=a;l.unshift(...u.pipeline),a=u.source}let f={id:w(),type:"sink",source:a,pipeline:l,location:_(e,s,n.includeLocations??!1)};return{...f,displayName:V(f),semanticRole:Y(f)}})}function Bo(e,t,r,s,n,i,c){let{SyntaxKind:o}=T(),a="queue",d="create",l,f,u;t.startsWith("Queue.")?(a="queue",t.includes("bounded")?l="bounded":t.includes("unbounded")?l="unbounded":t.includes("sliding")?l="sliding":t.includes("dropping")&&(l="dropping"),t.includes("offer")||t.includes("offerAll")?d="offer":t.includes("take")||t.includes("takeAll")||t.includes("poll")?d="take":d="create"):t.startsWith("PubSub.")?(a="pubsub",t.includes("bounded")?l="bounded":t.includes("unbounded")&&(l="unbounded"),t.includes("publish")?d="publish":t.includes("subscribe")?d="subscribe":d="create"):t.startsWith("Deferred.")?(a="deferred",t.includes("succeed")?d="succeed":t.includes("fail")?d="fail":t.includes("await")?d="await":d="create"):t.startsWith("Semaphore.")?(a="semaphore",t.includes("withPermit")?d="withPermit":t.includes("take")?d="take":t.includes("release")?d="release":t.includes("available")?d="available":d="create"):t.startsWith("Mailbox.")?(a="mailbox",t.includes("offer")?d="offer":t.includes("takeAll")?d="takeAll":t.includes("take")?d="take":t.includes("end")?d="end":t.includes("toStream")?d="toStream":d="create"):t.startsWith("SubscriptionRef.")?(a="subscriptionRef",t.includes("changes")?d="changes":t.includes("get")?d="get":t.includes("set")?d="set":t.includes("update")?d="update":d="create"):t.includes("makeLatch")||t.includes("Latch.")?(a="latch",t.includes("open")?d="open":t.includes("close")?d="close":t.includes("await")||t.includes("whenOpen")?d="await":d="create"):t.startsWith("FiberHandle.")?(a="fiberHandle",t.includes("run")?d="run":t.includes("await")?d="await":d="create"):t.startsWith("FiberSet.")?(a="fiberSet",t.includes("run")?d="run":t.includes("join")?d="await":d="create"):t.startsWith("FiberMap.")?(a="fiberMap",t.includes("run")?d="run":t.includes("join")?d="await":d="create"):t.startsWith("RateLimiter.")?(a="rateLimiter",t.includes("withCost")?d="withPermit":d="create"):t.startsWith("ScopedCache.")?(a="scopedCache",t.includes("make")||t.includes("Make")?d="create":t.includes("get")&&!t.includes("getOrElse")||t.includes("getOrElse")?d="get":t.includes("set")||t.includes("Set")?d="set":t.includes("invalidate")?d="invalidate":t.includes("contains")?d="contains":d="create"):t.startsWith("Cache.")?(a="cache",t.includes("make")||t.includes("Make")?d="create":t.includes("get")&&!t.includes("getOrElse")||t.includes("getOrElse")?d="get":t.includes("set")||t.includes("Set")?d="set":t.includes("invalidate")?d="invalidate":t.includes("contains")?d="contains":d="create"):t.startsWith("Reloadable.")||t.includes(".Reloadable.")?(a="reloadable",t.includes("make")||t.includes("Make")?d="create":t.includes("get")&&!t.includes("reload")?d="get":t.includes("reload")?d="reload":d="create"):t.startsWith("RcMap.")||t.includes(".RcMap.")?(a="rcMap",t.includes("make")||t.includes("Make")?d="create":t.includes("get")?d="get":t.includes("set")||t.includes("Set")?d="set":t.includes("update")?d="update":d="create"):(t.startsWith("RcRef.")||t.includes(".RcRef."))&&(a="rcRef",t.includes("make")||t.includes("Make")?d="create":t.includes("get")?d="get":t.includes("set")||t.includes("Set")?d="set":t.includes("update")?d="update":d="create");let g=e.getArguments();if(g.length>0&&l==="bounded"){let y=g[0];y?.getKind()===o.NumericLiteral&&(f=Number.parseInt(y.getText(),10))}a==="semaphore"&&(d==="take"||d==="release")&&g.length>0&&g[0]&&(u=Et(g[0]));let p;if(a==="fiberHandle"&&d==="run")for(let y of g){let h=y.getText();h.includes("onlyIfMissing")&&(p={onlyIfMissing:h.includes("true")})}if(a==="mailbox"&&d==="toStream"||a==="subscriptionRef"&&d==="changes"){let y=a==="mailbox"?"fromMailbox":"fromSubscriptionRef",h={id:w(),type:"concurrency-primitive",primitive:a,operation:d,location:_(e,s,n.includeLocations??!1)},N={id:w(),type:"stream",source:{...h,displayName:V(h),semanticRole:Y(h)},pipeline:[],constructorType:y,location:_(e,s,n.includeLocations??!1)};return re.succeed({...N,displayName:V(N),semanticRole:Y(N)})}let m={id:w(),type:"concurrency-primitive",primitive:a,operation:d,strategy:l,capacity:f,...u!==void 0?{permitCount:u}:{},...p?{lifecycleOptions:p}:{},location:_(e,s,n.includeLocations??!1)};return re.succeed({...m,displayName:V(m),semanticRole:Y(m)})}function jo(e,t,r,s,n,i,c){return re.gen(function*(){let o=e.getArguments(),a="fork",d=!1,l=!1,f;t.startsWith("Fiber.")?t.includes("awaitAll")?a="awaitAll":t.includes("join")?a="join":t.includes("await")?a="await":t.includes("interruptFork")?a="interruptFork":t.includes("interrupt")?a="interrupt":t.includes("poll")?a="poll":t.includes("status")?a="status":t.includes("all")?a="all":t.includes("children")?a="children":t.includes("dump")?a="dump":t.includes("scoped")?(a="scoped",d=!0):t.includes("inheritAll")?a="inheritAll":t.includes("mapFiber")?a="mapFiber":t.includes("mapEffect")?a="mapEffect":t.includes("map")?a="map":t.includes("roots")?a="roots":t.includes("getCurrentFiber")&&(a="getCurrentFiber"):t.includes("forkWithErrorHandler")?a="forkWithErrorHandler":t.includes("forkAll")?a="forkAll":t.includes("forkIn")?a="forkIn":t.includes("fork")&&(t.includes("forkDaemon")?(a="forkDaemon",l=!0):t.includes("forkScoped")?(a="forkScoped",d=!0):a="fork"),(a==="fork"||a==="forkScoped"||a==="forkDaemon"||a==="forkAll"||a==="forkIn"||a==="forkWithErrorHandler")&&o.length>0&&o[0]&&(f=yield*M(o[0],r,s,n,i,c));let u;if(d)u="safe";else{let p=e.getParent();for(;p;){let m=p.getText?.();if(m&&(m.includes("Effect.scoped")||m.includes("Scope.make"))){u="safe";break}if(p=p.getParent(),p&&p===r)break}}let g={id:w(),type:"fiber",operation:a,fiberSource:f,isScoped:d,isDaemon:l,...u?{scopeContext:u}:{},location:_(e,s,n.includeLocations??!1)};return{...g,displayName:V(g),semanticRole:Y(g)}})}function qo(e,t,r,s,n,i,c){return re.gen(function*(){let o=e.getArguments(),{SyntaxKind:a}=T(),d;t.includes("uninterruptibleMask")?d="uninterruptibleMask":t.includes("interruptibleMask")?d="interruptibleMask":t.includes("uninterruptible")?d="uninterruptible":t.includes("interruptible")?d="interruptible":t.includes("onInterrupt")?d="onInterrupt":t.includes("disconnect")?d="disconnect":t.includes("allowInterrupt")?d="allowInterrupt":t.includes("interruptWith")?d="interruptWith":d="interrupt";let l,f,u=e.getExpression();u.getKind()===a.PropertyAccessExpression?(l=yield*M(u.getExpression(),r,s,n,i,c),o.length>0&&o[0]&&(f=yield*M(o[0],r,s,n,i,c))):o.length>0&&o[0]&&(l=yield*M(o[0],r,s,n,i,c),o.length>1&&o[1]&&(f=yield*M(o[1],r,s,n,i,c))),c.interruptionCount++;let g={id:w(),type:"interruption",interruptionType:d,source:l,handler:f,location:_(e,s,n.includeLocations??!1)};return{...g,displayName:V(g),semanticRole:Y(g)}})}function _o(e){let{SyntaxKind:t}=T(),r,s,n;for(let i of e.getProperties()){if(i.getKind()!==t.PropertyAssignment)continue;let c=i.getNameNode().getText(),o=i.getInitializer();if(!o)continue;let a=o.getText();if(c==="concurrency")if(a==='"unbounded"'||a==="'unbounded'")r="unbounded";else if(a==='"sequential"'||a==="'sequential'")r="sequential";else if(a==='"inherit"'||a==="'inherit'")r="sequential";else{let d=Number.parseInt(a,10);!Number.isNaN(d)&&d>=0&&(r=d)}else c==="batching"&&(a==="true"||a==="false")?s=a==="true":c==="discard"&&(a==="true"||a==="false")&&(n=a==="true")}return{concurrency:r,batching:s,discard:n}}var zo=(e,t,r,s,n,i,c)=>re.gen(function*(){let o=e.getArguments(),a=[],{SyntaxKind:d}=T();if(o.length>0&&o[0]){let y=o[0];if(y.getKind()===d.ArrayLiteralExpression){let h=y.getElements();for(let N of h){let x=yield*M(N,r,s,n,i,c);a.push(x)}}else if(y.getKind()===d.ObjectLiteralExpression){let h=y.getProperties();for(let N of h)if(N.getKind()===d.PropertyAssignment){let x=N.getInitializer();if(x){let F=yield*M(x,r,s,n,i,c);a.push(F)}}}}let l,f,u;if(o.length>1&&o[1]?.getKind()===d.ObjectLiteralExpression){let y=_o(o[1]);l=y.concurrency,f=y.batching,u=y.discard}let g=t.includes("Par")?"parallel":"sequential";l===void 0&&(l=g==="parallel"?"unbounded":"sequential"),c.parallelCount++;let p=a.map(y=>V(y)),m={id:w(),type:"parallel",callee:t,mode:g,children:a,concurrency:l,batching:f,discard:u,branchLabels:p,location:_(e,s,n.includeLocations??!1)};return{...m,displayName:V(m),semanticRole:Y(m)}}),Uo=(e,t,r,s,n,i,c)=>re.gen(function*(){let o=e.getArguments(),a=[];for(let f of o)if(f){let u=yield*M(f,r,s,n,i,c);a.push(u)}c.raceCount++;let d=a.map(f=>V(f)),l={id:w(),type:"race",callee:t,children:a,raceLabels:d,location:_(e,s,n.includeLocations??!1)};return{...l,displayName:V(l),semanticRole:Y(l)}}),Ho=(e,t,r,s,n,i,c)=>re.gen(function*(){let o=e.getArguments(),a;t.includes("catchAllCause")?a="catchAllCause":t.includes("catchSomeCause")?a="catchSomeCause":t.includes("catchSomeDefect")?a="catchSomeDefect":t.includes("catchAllDefect")?a="catchAllDefect":t.includes("catchTags")?a="catchTags":t.includes("catchIf")?a="catchIf":t.includes("catchSome")?a="catchSome":t.includes("catchTag")?a="catchTag":t.includes("catchAll")?a="catchAll":t.includes("orElseFail")?a="orElseFail":t.includes("orElseSucceed")?a="orElseSucceed":t.includes("orElse")?a="orElse":t.includes("orDieWith")?a="orDieWith":t.includes("orDie")?a="orDie":t.includes("flip")?a="flip":t.includes("mapErrorCause")?a="mapErrorCause":t.includes("mapBoth")?a="mapBoth":t.includes("mapError")?a="mapError":t.includes("unsandbox")?a="unsandbox":t.includes("sandbox")?a="sandbox":t.includes("parallelErrors")?a="parallelErrors":t.includes("filterOrDieMessage")?a="filterOrDieMessage":t.includes("filterOrDie")?a="filterOrDie":t.includes("filterOrElse")?a="filterOrElse":t.includes("filterOrFail")?a="filterOrFail":t.includes("matchCauseEffect")?a="matchCauseEffect":t.includes("matchCause")?a="matchCause":t.includes("matchEffect")?a="matchEffect":t.includes("match")?a="match":t.includes("firstSuccessOf")?a="firstSuccessOf":t.includes("ignoreLogged")?a="ignoreLogged":t.includes("ignore")?a="ignore":t.includes("eventually")?a="eventually":a="catchAll";let d,l,f=e.getExpression();if(f.getKind()===T().SyntaxKind.PropertyAccessExpression){let y=f.getExpression();d=yield*M(y,r,s,n,i,c),o.length>0&&o[0]&&(l=yield*M(o[0],r,s,n,i,c))}else o.length>0&&o[0]?d=yield*M(o[0],r,s,n,i,c):d={id:w(),type:"unknown",reason:"Could not determine source effect"},o.length>1&&o[1]&&(l=yield*M(o[1],r,s,n,i,c));c.errorHandlerCount++;let u,g;if(a==="catchTag"){let m=o[0];m?.getKind()===T().SyntaxKind.StringLiteral&&(u=m.getLiteralValue())}else if(a==="catchTags"){let m=[...o].find(y=>y?.getKind()===T().SyntaxKind.ObjectLiteralExpression);m&&(g=m.getProperties().filter(h=>h.getKind()===T().SyntaxKind.PropertyAssignment||h.getKind()===T().SyntaxKind.MethodDeclaration).map(h=>(h.getKind()===T().SyntaxKind.PropertyAssignment,h.getName())))}let p={id:w(),type:"error-handler",handlerType:a,source:d,handler:l,errorTag:u,errorTags:g,errorEdgeLabel:u?`on ${u}`:g&&g.length>0?`on ${g.join(" | ")}`:"on error",location:_(e,s,n.includeLocations??!1)};return{...p,displayName:V(p),semanticRole:Y(p)}}),Go=(e,t,r,s,n,i)=>re.gen(function*(){let c=e.getArguments(),o,a,d,l,f=e.getExpression();if(f.getKind()===T().SyntaxKind.PropertyAccessExpression){let m=f.getExpression();o=yield*M(m,t,r,s,n,i),c.length>0&&c[0]&&(a=c[0].getText(),d=yield*M(c[0],t,r,s,n,i)),l=f.getText().includes("retryOrElse")}else c.length>0&&c[0]?o=yield*M(c[0],t,r,s,n,i):o={id:w(),type:"unknown",reason:"Could not determine source effect"},c.length>1&&c[1]&&(a=c[1].getText(),d=yield*M(c[1],t,r,s,n,i)),l=c.length>2;i.retryCount++;let u=a?xs(a):void 0,g={id:w(),type:"retry",source:o,schedule:a,...d!==void 0?{scheduleNode:d}:{},hasFallback:l,scheduleInfo:u,retryEdgeLabel:a?`retry: ${a}`:"retry",location:_(e,r,s.includeLocations??!1)};return{...g,displayName:V(g),semanticRole:Y(g)}});function xs(e){let t=e.replace(/\s+/g," "),r="custom";t.includes("Schedule.exponential")||t.includes("exponential(")?r="exponential":t.includes("Schedule.fibonacci")||t.includes("fibonacci(")?r="fibonacci":t.includes("Schedule.spaced")||t.includes("spaced(")?r="spaced":t.includes("Schedule.fixed")||t.includes("fixed(")?r="fixed":t.includes("Schedule.linear")||t.includes("linear(")?r="linear":t.includes("Schedule.cron")||t.includes("cron(")?r="cron":t.includes("Schedule.windowed")||t.includes("windowed(")?r="windowed":t.includes("Schedule.duration")||t.includes("duration(")?r="duration":t.includes("Schedule.elapsed")||t.includes("elapsed(")?r="elapsed":t.includes("Schedule.delays")||t.includes("delays(")?r="delays":t.includes("Schedule.once")||t.includes("once(")?r="once":t.includes("Schedule.stop")||t.includes("stop(")?r="stop":(t.includes("Schedule.count")||t.includes("count("))&&(r="count");let s,n=/recurs\s*\(\s*(\d+)\s*\)/.exec(t);n&&(s=Number.parseInt(n[1],10));let i=/recurUpTo\s*\(\s*(\d+)\s*\)/.exec(t);i?s=Number.parseInt(i[1],10):(t.includes("forever")||t.includes("Schedule.forever"))&&(s="unlimited");let c=t.includes("jittered")||t.includes("Schedule.jittered"),o=[];return t.includes("whileInput")&&o.push("whileInput"),t.includes("whileOutput")&&o.push("whileOutput"),t.includes("untilInput")&&o.push("untilInput"),t.includes("untilOutput")&&o.push("untilOutput"),t.includes("recurUntil")&&o.push("recurUntil"),t.includes("recurWhile")&&o.push("recurWhile"),t.includes("andThen")&&o.push("andThen"),t.includes("intersect")&&o.push("intersect"),t.includes("union")&&o.push("union"),t.includes("compose")&&o.push("compose"),t.includes("zipWith")&&o.push("zipWith"),t.includes("addDelay")&&o.push("addDelay"),t.includes("modifyDelay")&&o.push("modifyDelay"),t.includes("check")&&o.push("check"),t.includes("resetAfter")&&o.push("resetAfter"),t.includes("resetWhen")&&o.push("resetWhen"),t.includes("ensure")&&o.push("ensure"),t.includes("driver")&&o.push("driver"),t.includes("mapInput")&&o.push("mapInput"),{baseStrategy:r,maxRetries:s,jittered:c,conditions:o}}var Vo=(e,t,r,s,n,i)=>re.gen(function*(){let c=e.getArguments(),o,a,d,l=e.getExpression();if(l.getKind()===T().SyntaxKind.PropertyAccessExpression){let g=l.getExpression();o=yield*M(g,t,r,s,n,i),c.length>0&&c[0]&&(a=Pt(c[0]));let p=Pt(l);d=p.includes("timeoutFail")||p.includes("timeoutTo")}else c.length>0&&c[0]?o=yield*M(c[0],t,r,s,n,i):o={id:w(),type:"unknown",reason:"Could not determine source effect"},c.length>1&&c[1]&&(a=Pt(c[1])),d=c.length>2;i.timeoutCount++;let f={id:w(),type:"timeout",source:o,duration:a,hasFallback:d,location:_(e,r,s.includeLocations??!1)};return{...f,displayName:V(f),semanticRole:Y(f)}}),hs=(e,t,r,s,n,i,c)=>re.gen(function*(){let o=e.getArguments(),a=/([A-Za-z_$][\w$]*)$/.exec(t)?.[1]??t,d,l,f;if(a.startsWith("acquireUseRelease"))o.length>=3&&o[0]&&o[2]?(d=yield*M(o[0],r,s,n,i,c),l=yield*M(o[2],r,s,n,i,c),o[1]&&(f=yield*M(o[1],r,s,n,i,c))):(d={id:w(),type:"unknown",reason:"Missing acquire"},l={id:w(),type:"unknown",reason:"Missing release"});else if(a.startsWith("acquireRelease"))o.length>=2&&o[0]&&o[1]?(d=yield*M(o[0],r,s,n,i,c),l=yield*M(o[1],r,s,n,i,c)):(d={id:w(),type:"unknown",reason:"Missing acquire"},l={id:w(),type:"unknown",reason:"Missing release"});else if(a==="addFinalizer"||a==="onExit"||a==="onError"||a==="parallelFinalizers"||a==="sequentialFinalizers"||a==="finalizersMask"||a==="using"||a==="withEarlyRelease"){let g=e.getExpression();g.getKind()===T().SyntaxKind.PropertyAccessExpression?d=yield*M(g.getExpression(),r,s,n,i,c):d={id:w(),type:"unknown",reason:"Scoped acquire"},l=o.length>0&&o[0]?yield*M(o[0],r,s,n,i,c):{id:w(),type:"unknown",reason:"Missing finalizer"}}else if(a==="ensuring"){let g=e.getExpression();if(g.getKind()===T().SyntaxKind.PropertyAccessExpression){let m=g.getExpression();d=yield*M(m,r,s,n,i,c),l=o.length>0&&o[0]?yield*M(o[0],r,s,n,i,c):{id:w(),type:"unknown",reason:"Missing cleanup"}}else d=o.length>0&&o[0]?yield*M(o[0],r,s,n,i,c):{id:w(),type:"unknown",reason:"Missing effect"},l=o.length>1&&o[1]?yield*M(o[1],r,s,n,i,c):{id:w(),type:"unknown",reason:"Missing cleanup"}}else d={id:w(),type:"unknown",reason:"Unknown resource pattern"},l={id:w(),type:"unknown",reason:"Unknown resource pattern"};c.resourceCount++;let u={id:w(),type:"resource",acquire:d,release:l,use:f,location:_(e,s,n.includeLocations??!1)};return{...u,displayName:V(u),semanticRole:Y(u)}}),Jo=(e,t,r,s,n,i,c)=>re.gen(function*(){let o=e.getArguments(),a;t.includes(".if")||t==="if"?a="if":t.includes("whenEffect")?a="whenEffect":t.includes("whenFiberRef")?a="whenFiberRef":t.includes("whenRef")?a="whenRef":t.includes(".when")||t==="when"?a="when":t.includes("unlessEffect")?a="unlessEffect":t.includes(".unless")||t==="unless"?a="unless":t.includes(".option")||t==="option"?a="option":t.includes(".either")||t==="either"?a="either":t.includes(".exit")||t==="exit"?a="exit":t.includes("liftPredicate")?a="liftPredicate":a="unless";let d="<dynamic>",l,f;if(a==="if"){if(o.length>0&&o[0]&&(d=o[0].getText()),o.length>1&&o[1]){let p=o[1],{SyntaxKind:m}=T();if(p.getKind()===m.ObjectLiteralExpression){let y=p.getProperties();for(let h of y)if(h.getKind()===m.PropertyAssignment){let N=h,x=N.getName(),F=N.getInitializer();F&&(x==="onTrue"?l=yield*M(F,r,s,n,i,c):x==="onFalse"&&(f=yield*M(F,r,s,n,i,c)))}}}}else{let p=e.getExpression();if(p.getKind()===T().SyntaxKind.PropertyAccessExpression){let y=p.getExpression();l||(l=yield*M(y,r,s,n,i,c))}o.length>0&&o[0]&&(d=o[0].getText())}l||(l={id:w(),type:"unknown",reason:"Could not determine true branch"}),c.conditionalCount++;let u=d.length<=30?d:`${d.slice(0,30)}\u2026`,g={id:w(),type:"conditional",conditionalType:a,condition:d,onTrue:l,onFalse:f,conditionLabel:u,trueEdgeLabel:"true",falseEdgeLabel:"false",location:_(e,s,n.includeLocations??!1)};return{...g,displayName:V(g),semanticRole:Y(g)}}),Qo=(e,t,r,s,n,i,c)=>re.gen(function*(){let o=e.getArguments(),a=t.includes("forEach")?"forEach":t.includes("filterMap")?"filterMap":t.includes("filter")?"filter":t.includes("partition")?"partition":t.includes("reduce")?"reduce":t.includes("validateAll")||t.includes("validateFirst")||t.includes("validateWith")?"validate":t.includes("replicate")?"replicate":t.includes("dropUntil")?"dropUntil":t.includes("dropWhile")?"dropWhile":t.includes("takeUntil")?"takeUntil":t.includes("takeWhile")?"takeWhile":t.includes("every")?"every":t.includes("exists")?"exists":t.includes("findFirst")?"findFirst":t.includes("head")?"head":t.includes("mergeAll")?"mergeAll":"loop",d=a==="reduce"||t.includes("reduceRight")||t.includes("reduceWhile")||t.includes("reduceEffect")?2:1,l,f;if(o.length>0&&o[0]){let g=o[0].getText();l=g.length>30?g.slice(0,30)+"\u2026":g}o.length>d&&o[d]?f=yield*M(o[d],r,s,n,i,c):f={id:w(),type:"unknown",reason:"Could not determine loop body"},c.loopCount++;let u={id:w(),type:"loop",loopType:a,iterSource:l,body:f,location:_(e,s,n.includeLocations??!1)};return{...u,displayName:V(u),semanticRole:Y(u)}}),Zo=(e,t,r,s)=>{let n=bn[t]??"other",i=Wr.has(n),c=e.getArguments(),o=[];if((n==="when"||n==="tag")&&c[0]){let d=c[0].getText().replace(/["'`]/g,"").trim();/^[A-Za-z_][A-Za-z0-9_]*$/.test(d)&&o.push(d)}if(n==="tags"||n==="tagsExhaustive"){let{SyntaxKind:d}=T();for(let l of c)if(l.getKind()===d.ObjectLiteralExpression){let f=l;for(let u of f.getProperties()){let g=u.getKind()===d.PropertyAssignment?u.getName():void 0;g&&o.push(g.replace(/["'`]/g,""))}}}let a={id:w(),type:"match",matchOp:n,isExhaustive:i,...o.length>0?{matchedTags:o}:{},location:_(e,r,s.includeLocations??!1)};return{...a,displayName:V(a),semanticRole:Y(a)}},Yo=(e,t,r,s,n,i,c)=>re.gen(function*(){let o=Nn[t]??"other",a=Br.has(o),d;if(o==="parallel"||o==="sequential"){let u=e.getArguments(),g=[];for(let p of u)if(p){let m=yield*M(p,r,s,n,i,c);g.push(m)}g.length>0&&(d=g)}let l;if(o==="fail")l="fail";else if(o==="die")l="die";else if(o==="interrupt")l="interrupt";else if((o==="parallel"||o==="sequential")&&d&&d.length>0){let u=d.filter(g=>g.type==="cause").map(g=>g.causeKind).filter(g=>g!==void 0);u.length>0&&(l=u.every(g=>g===u[0])?u[0]:"mixed")}let f={id:w(),type:"cause",causeOp:o,isConstructor:a,...d?{children:d}:{},...l?{causeKind:l}:{},location:_(e,s,n.includeLocations??!1)};return{...f,displayName:V(f),semanticRole:Y(f)}}),Xo=(e,t,r,s)=>{let n=Cn[t]??"other",i=qr.has(n),c={id:w(),type:"exit",exitOp:n,isConstructor:i,location:_(e,r,s.includeLocations??!1)};return{...c,displayName:V(c),semanticRole:Y(c)}},ea=(e,t,r,s)=>re.sync(()=>{let n=wn[t]??"other",i=e.getText(),c=xs(i),o={id:w(),type:"schedule",scheduleOp:n,...c?{scheduleInfo:c}:{},location:_(e,r,s.includeLocations??!1)};return{...o,displayName:V(o),semanticRole:Y(o)}}),ta=(e,t,r,s,n,i,c)=>re.gen(function*(){let o=e.getArguments(),a=En[t]??"other",d=Or.has(a),l,f;if(o.length>=2&&o[0]){if(l=yield*M(o[0],r,s,n,i,c),o[1]){let g=o[1].getText();f=g.length<=120?g:g.slice(0,120)+"\u2026"}}else if(o.length===1&&o[0]){let g=o[0].getText();f=g.length<=120?g:g.slice(0,120)+"\u2026"}c.totalEffects++;let u={id:w(),type:"transform",transformType:a,isEffectful:d,...l!==void 0?{source:l}:{},...f!==void 0?{fn:f}:{},location:_(e,s,n.includeLocations??!1)};return{...u,displayName:V(u),semanticRole:Y(u)}});var On=(e,t,r,s,n)=>Ee.gen(function*(){let i=[],c=rs(),o=yield*na(e.node,e.type,t,r,s,i,c),a=es(e.node),d=t.getProject().getTypeChecker(),l=Be(e.node,d),f=At(e.node,d),u={id:w(),type:"program",programName:e.name,source:e.type,...e.discoveryConfidence?{discoveryConfidence:e.discoveryConfidence}:{},...e.discoveryReason?{discoveryReason:e.discoveryReason}:{},children:o,dependencies:Xr(o),errorTypes:Yr(o),typeSignature:l,requiredServices:f,location:_(e.node,r,s.includeLocations??!1),jsdocDescription:a,jsdocTags:it(e.node)},g=ys(t);return{root:u,metadata:{analyzedAt:Date.now(),filePath:r,tsVersion:n,warnings:i,stats:c,...g.length>0?{serviceDefinitions:g}:{}},references:new Map}}),na=(e,t,r,s,n,i,c)=>Ee.gen(function*(){switch(t){case"generator":{let o=e.getArguments();if(o.length>0&&o[0]){let a=o[0];return yield*ca(a,r,s,n,i,c)}return[]}case"pipe":return yield*jt(e,r,s,n,i,c);case"run":{let o=e,{SyntaxKind:a}=T(),d=yield*la(o,r,s,n,i,c);if(Ct.isSome(d))return d.value;let l=o.getArguments(),f=l.find(p=>p.getKind()===a.ArrowFunction||p.getKind()===a.FunctionExpression),u=n.enableEffectWorkflow&&f===void 0&&l.length===1?ms(o,r):null,g=f??u??l[0];return g?[yield*M(g,r,s,n,i,c)]:[]}case"workflow-execute":{let o=e,a=o.getExpression().getText();return[{id:w(),type:"effect",callee:a,name:a,semanticRole:"side-effect",location:_(o,s,n.includeLocations??!1)}]}case"direct":{let o=e.getInitializer();return o?[yield*M(o,r,s,n,i,c)]:[]}case"class":{let o=e,a="Data.Class";for(let f of o.getHeritageClauses()){let u=f.getText();if(u.includes("Data.TaggedError")){a="Data.TaggedError";break}if(u.includes("Data.TaggedClass")){a="Data.TaggedClass";break}if(u.includes("Data.Error")){a="Data.Error";break}if(u.includes("Schema.TaggedRequest")){a="Schema.TaggedRequest";break}if(u.includes("Schema.TaggedError")){a="Schema.TaggedError";break}if(u.includes("Schema.TaggedClass")){a="Schema.TaggedClass";break}if(u.includes("Schema.Class")){a="Schema.Class";break}if(u.includes("Context.Tag")){a="Context.Tag";break}if(u.includes("Context.Reference")){a="Context.Reference";break}if(u.includes("Effect.Service")){a="Effect.Service";break}}let d=a.includes("Error")?"error-type":a.includes("Schema")?"schema":a==="Context.Tag"||a==="Context.Reference"||a==="Effect.Service"?"service-tag":"data",l={id:w(),type:"effect",callee:a,description:d,location:_(e,s,n.includeLocations??!1),jsdocDescription:Ze(o),jsdocTags:it(o)};return c.totalEffects++,[l]}case"classProperty":{let a=e.getInitializer();return a?[yield*M(a,r,s,n,i,c)]:[]}case"classMethod":{let a=e.getBody();if(!a)return[];let{SyntaxKind:d}=T(),l=a.getDescendantsOfKind(d.ReturnStatement),f=[];for(let u of l){let g=u.getExpression();if(g){let p=yield*M(g,r,s,n,i,c);f.push(p)}}return f}default:return[]}});function Ln(e){let{SyntaxKind:t}=T(),r=e.getKind();return r===t.FunctionDeclaration||r===t.FunctionExpression||r===t.ArrowFunction||r===t.MethodDeclaration||r===t.ClassDeclaration||r===t.ClassExpression||r===t.Constructor}function le(e){let{SyntaxKind:t}=T();if(e.getKind()===t.YieldExpression)return!0;let r=!1;return e.forEachChild(s=>{if(!r&&!Ln(s)){if(s.getKind()===t.YieldExpression){r=!0;return}if(le(s)){r=!0;return}}}),r}function ra(e){let{SyntaxKind:t}=T();switch(e.getKind()){case t.StringLiteral:return e.getLiteralValue();case t.NumericLiteral:return e.getLiteralValue().toString();case t.TrueKeyword:return"true";case t.FalseKeyword:return"false";case t.NullKeyword:return"null";case t.NoSubstitutionTemplateLiteral:return e.getText().replace(/^`|`$/g,"");default:return}}function ct(e,t){if(t.size===0)return e;let r=e;for(let[s,n]of t){let i=new RegExp(`\\b${s}\\b`,"g"),c=/^\d/.test(n)||n==="true"||n==="false"||n==="null"?n:`'${n}'`;r=r.replace(i,c)}return r}function wt(e){let t=e;return t=t.replace(/\btrue\b\s*&&\s*/g,""),t=t.replace(/\s*&&\s*\btrue\b/g,""),t=t.replace(/\bfalse\b\s*\|\|\s*/g,""),t=t.replace(/\s*\|\|\s*\bfalse\b/g,""),t=t.replace(/\bfalse\b\s*&&\s*[^|&]+/g,"false"),t=t.replace(/\btrue\b\s*\|\|\s*[^|&]+/g,"true"),t.trim()}function Wn(e){let{SyntaxKind:t}=T();switch(e.getKind()){case t.ParenthesizedExpression:case t.AsExpression:case t.TypeAssertionExpression:case t.NonNullExpression:case t.SatisfiesExpression:{let s=e.getExpression();return Wn(s)}default:return e}}function Es(e){let{SyntaxKind:t}=T();if(e.length===0)return!1;let r=e[e.length-1];if(!r)return!1;let s=r.getKind();return s===t.ReturnStatement||s===t.ThrowStatement||s===t.BreakStatement||s===t.ContinueStatement}function Ns(e){let{SyntaxKind:t}=T(),r=[];return e.forEachChild(s=>{Ln(s)||(s.getKind()===t.YieldExpression?r.push(s):r.push(...Ns(s)))}),r}var sa=new Set(["Step.run","Step.decide","Step.branch","Step.all","Step.forEach","Step.retry","Step.race","Step.sleep"]);function ia(e){let{SyntaxKind:t}=T();if(e.getKind()!==t.CallExpression)return!1;let r=e.getExpression().getText();return sa.has(r)}function Me(e){if(!e)return;let{SyntaxKind:t}=T();if(e.getKind()===t.StringLiteral)return e.getLiteralText()}function oa(e){if(!e)return[];let{SyntaxKind:t}=T();if(e.getKind()!==t.ObjectLiteralExpression)return[];let r=[],s=e;for(let n of s.getProperties())if(n.getKind()===t.PropertyAssignment){let i=n.getName();r.push({labels:[i],isDefault:i==="default",body:[]})}return r}function aa(e,t){return Ee.gen(function*(){let{SyntaxKind:r}=T(),s=e.getExpression().getText(),n=e.getArguments();switch(s){case"Step.run":{let i=Me(n[0]),c=n[1];if(!c){let a={id:w(),type:"effect",callee:"Step.run",name:i,displayName:i};return t.stats.totalEffects++,a}let o=yield*M(c,t.sourceFile,t.filePath,t.opts,t.warnings,t.stats,t.serviceScope);return{...o,displayName:i??o.displayName,name:i??o.name}}case"Step.decide":{let i=Me(n[0]),c=Me(n[1]);return t.stats.decisionCount++,{id:w(),type:"decision",decisionId:i??w(),label:c??i??"decision",condition:n[2]?.getText()??"unknown",source:"effect-flow",onTrue:[],onFalse:void 0}}case"Step.branch":{let i=Me(n[0]),c=n[1]?.getText()??"unknown",o=n[2],a=oa(o);return t.stats.switchCount++,{id:w(),type:"switch",switchId:i,expression:c,cases:a,source:"effect-flow",hasDefault:a.some(l=>l.isDefault),hasFallthrough:!1}}case"Step.all":{let i=Me(n[0]),c=n[1],o=[];if(c?.getKind()===r.ArrayLiteralExpression){let d=c;for(let l of d.getElements()){let f=yield*M(l,t.sourceFile,t.filePath,t.opts,t.warnings,t.stats,t.serviceScope);o.push(f)}}return t.stats.parallelCount++,{id:w(),type:"parallel",name:i,displayName:i,children:o,mode:"parallel",callee:"Step.all"}}case"Step.forEach":{let i=Me(n[0]),c=n[1]?.getText(),o=n[2],a={id:w(),type:"effect",callee:"unknown"};return o&&(a=yield*M(o,t.sourceFile,t.filePath,t.opts,t.warnings,t.stats,t.serviceScope)),t.stats.loopCount++,{id:w(),type:"loop",name:i,displayName:i,loopType:"forEach",iterSource:c,body:a}}case"Step.retry":{let i=Me(n[0]),c=n[1];if(!c){let d={id:w(),type:"effect",callee:"Step.retry",name:i,displayName:i};return t.stats.totalEffects++,d}let o=yield*M(c,t.sourceFile,t.filePath,t.opts,t.warnings,t.stats,t.serviceScope);return t.stats.retryCount++,{id:w(),type:"retry",name:i,displayName:i,source:o,hasFallback:!1}}case"Step.race":{let i=Me(n[0]),c=n[1],o=[];if(c?.getKind()===r.ArrayLiteralExpression){let d=c;for(let l of d.getElements()){let f=yield*M(l,t.sourceFile,t.filePath,t.opts,t.warnings,t.stats,t.serviceScope);o.push(f)}}return t.stats.raceCount++,{id:w(),type:"race",name:i,displayName:i,children:o,callee:"Step.race"}}case"Step.sleep":{let i=Me(n[0]),c={id:w(),type:"effect",callee:"Step.sleep",name:i,displayName:i,semanticRole:"scheduling"};return t.stats.totalEffects++,c}default:{let i={id:w(),type:"effect",callee:s,name:s,displayName:s};return t.stats.totalEffects++,i}}})}function bs(e,t){return Ee.gen(function*(){let r=e,s=r.getText().startsWith("yield*"),n=r.getExpression();if(!s){let d={id:w(),type:"opaque",reason:"plain-yield",sourceText:e.getText().slice(0,80)};return t.stats.opaqueCount++,t.warnings.push({code:"PLAIN_YIELD",message:`Plain yield (not yield*) detected; this is unusual in Effect generators: ${e.getText().slice(0,60)}`,location:_(e,t.filePath,t.opts.includeLocations??!1)}),{variableName:Mt(e),effect:d}}if(!n){let d={id:w(),type:"opaque",reason:"yield-no-expression",sourceText:e.getText().slice(0,80)};return t.stats.opaqueCount++,{variableName:void 0,effect:d}}let i=Wn(n);if(t.opts.enableEffectFlow&&ia(i)){let d=yield*aa(i,t),l=Mt(e),f={...d,displayName:d.displayName??V(d,l),semanticRole:d.semanticRole??Y(d)};return{variableName:l,effect:f}}let c=yield*M(n,t.sourceFile,t.filePath,t.opts,t.warnings,t.stats,t.serviceScope),o=Mt(e);o&&c.type==="effect"&&Ur(c.callee)&&t.serviceScope.set(o,c.callee);let a={...c,displayName:V(c,o),semanticRole:c.semanticRole??Y(c)};return{variableName:o,effect:a}})}function lt(e,t){return Ee.gen(function*(){let r=e.getStatements(),s=[];for(let n of r){let i=yield*qt(n,t);s.push(...i)}return s})}function qt(e,t){return Ee.gen(function*(){let{SyntaxKind:r}=T();switch(e.getKind()){case r.ExpressionStatement:{let i=e.getExpression();return yield*ye(i,t)}case r.VariableStatement:{let n=e,i=[],{VariableDeclarationKind:c}=T(),o=n.getDeclarationKind()===c.Const;for(let a of n.getDeclarations()){let d=a.getInitializer();if(o&&d){let l=ra(d);l!==void 0&&t.constValues.set(a.getName(),l)}if(d&&!le(d)&&d.getKind()===r.CallExpression){let l=d,f=l.getExpression().getText();if(f==="Context.pick"||f==="Context.omit"){let u=yield*M(l,t.sourceFile,t.filePath,t.opts,t.warnings,t.stats,t.serviceScope);u.type==="effect"&&u.description==="context"&&i.push({variableName:a.getName(),effect:u});continue}}if(d&&le(d)){let l=yield*ye(d,t);if(l.length>0){let f=a.getName(),u=l[l.length-1];u&&(l[l.length-1]={...u,variableName:u.variableName??f})}i.push(...l)}}return i}case r.IfStatement:{if(!le(e))return[];let n=e,i=n.getExpression().getText(),c=yield*ye(n.getExpression(),t),o=n.getThenStatement(),a=n.getElseStatement(),d=yield*et(o,t),l=a?yield*et(a,t):void 0,f=wt(ct(i,t.constValues)),u=f.length>40?f.slice(0,40)+"...":f,g={id:w(),type:"decision",decisionId:w(),label:u,condition:i,source:"raw-if",onTrue:d.map(p=>p.effect),onFalse:l&&l.length>0?l.map(p=>p.effect):void 0};return t.stats.decisionCount++,[...c,{effect:g}]}case r.SwitchStatement:{if(!le(e))return[];let n=e,i=n.getExpression().getText(),c=n.getClauses(),o=[],a=!1,d=!1,l=[],f=[],u=!1;for(let m of c){if(m.getKind()===r.DefaultClause)d=!0,u=!0,l.push("default");else{let x=m;l.push(x.getExpression().getText())}let h=m.getStatements();if(h.length===0){a=!0;continue}for(let x of h){let F=yield*qt(x,t);f.push(...F)}Es(h)||(a=!0),o.push({labels:l,isDefault:u,body:f.map(x=>x.effect)}),l=[],f=[],u=!1}l.length>0&&o.push({labels:l,isDefault:u,body:f.map(m=>m.effect)});let g=ct(i,t.constValues),p={id:w(),type:"switch",switchId:w(),expression:g,cases:o,source:"raw-js",hasDefault:d,hasFallthrough:a};return t.stats.switchCount++,[{effect:p}]}case r.ForStatement:{if(!le(e))return[];let n=e,i=[],c=n.getInitializer();if(c&&le(c)){let m=yield*ye(c,t);i.push(...m.map(y=>y.effect))}let o=n.getIncrementor();if(o&&le(o)){let m=yield*ye(o,t);i.push(...m.map(y=>y.effect))}let a=n.getStatement(),d=yield*et(a,t),l=at(a),f=n.getCondition(),u=f?f.getText():void 0,g=d.length===1&&d[0]?d[0].effect:{id:w(),type:"generator",yields:d},p={id:w(),type:"loop",loopType:"for",iterSource:u,body:g,...l?{hasEarlyExit:l}:{},...i.length>0?{headerYields:i}:{}};return t.stats.loopCount++,[{effect:p}]}case r.ForOfStatement:{if(!le(e))return[];let n=e,i=n.getExpression(),c=i.getText(),o=[];if(le(i)){let p=yield*ye(i,t);o.push(...p.map(m=>m.effect))}let a=n.getInitializer().getText(),d=n.getStatement(),l=yield*et(d,t),f=at(d),u=l.length===1&&l[0]?l[0].effect:{id:w(),type:"generator",yields:l},g={id:w(),type:"loop",loopType:"forOf",iterSource:c,body:u,...f?{hasEarlyExit:f}:{},...o.length>0?{headerYields:o}:{},iterVariable:a};return t.stats.loopCount++,[{effect:g}]}case r.ForInStatement:{if(!le(e))return[];let n=e,i=n.getExpression().getText(),c=n.getInitializer().getText(),o=n.getStatement(),a=yield*et(o,t),d=at(o),l=a.length===1&&a[0]?a[0].effect:{id:w(),type:"generator",yields:a},f={id:w(),type:"loop",loopType:"forIn",iterSource:i,body:l,...d?{hasEarlyExit:d}:{},iterVariable:c};return t.stats.loopCount++,[{effect:f}]}case r.WhileStatement:{if(!le(e))return[];let n=e,i=n.getExpression().getText(),c=n.getStatement(),o=yield*et(c,t),a=at(c),d=o.length===1&&o[0]?o[0].effect:{id:w(),type:"generator",yields:o},l={id:w(),type:"loop",loopType:"while",iterSource:i,body:d,...a?{hasEarlyExit:a}:{}};return t.stats.loopCount++,[{effect:l}]}case r.DoStatement:{if(!le(e))return[];let n=e,i=n.getExpression().getText(),c=n.getStatement(),o=yield*et(c,t),a=at(c),d=o.length===1&&o[0]?o[0].effect:{id:w(),type:"generator",yields:o},l={id:w(),type:"loop",loopType:"doWhile",iterSource:i,body:d,...a?{hasEarlyExit:a}:{}};return t.stats.loopCount++,[{effect:l}]}case r.TryStatement:{if(!le(e))return[];let n=e,i=n.getTryBlock(),c=yield*lt(i,t),o=n.getCatchClause(),a,d;if(o){a=o.getVariableDeclaration()?.getName();let m=o.getBlock();d=yield*lt(m,t)}let l=n.getFinallyBlock(),f;l&&(f=yield*lt(l,t));let u=Es(i.getStatements()),g={id:w(),type:"try-catch",tryBody:c.map(p=>p.effect),...a?{catchVariable:a}:{},...d&&d.length>0?{catchBody:d.map(p=>p.effect)}:{},...f&&f.length>0?{finallyBody:f.map(p=>p.effect)}:{},hasTerminalInTry:u};return t.stats.tryCatchCount++,[{effect:g}]}case r.ReturnStatement:{let i=e.getExpression();if(!i||!le(i))return[];let c=yield*ye(i,t),o={id:w(),type:"terminal",terminalKind:"return",value:c.map(a=>a.effect)};return t.stats.terminalCount++,[{effect:o}]}case r.ThrowStatement:{let i=e.getExpression();if(!le(i))return[];let c=yield*ye(i,t),o={id:w(),type:"terminal",terminalKind:"throw",...c.length>0?{value:c.map(a=>a.effect)}:{}};return t.stats.terminalCount++,[{effect:o}]}case r.BreakStatement:return[];case r.ContinueStatement:return[];case r.LabeledStatement:return yield*qt(e.getStatement(),t);case r.Block:return yield*lt(e,t);default:return[]}})}function et(e,t){let{SyntaxKind:r}=T();return e.getKind()===r.Block?lt(e,t):qt(e,t)}function at(e){let{SyntaxKind:t}=T(),r=!1;return e.forEachChild(s=>{if(r||Ln(s))return;let n=s.getKind();if(n===t.BreakStatement||n===t.ReturnStatement){r=!0;return}if(at(s)){r=!0;return}}),r}function ye(e,t){return Ee.gen(function*(){let{SyntaxKind:r}=T();if(!le(e))return[];let s=Wn(e),n=s.getKind();if(n===r.YieldExpression)return[yield*bs(s,t)];if(n===r.ConditionalExpression){let o=s,a=o.getCondition().getText(),d=o.getWhenTrue(),l=o.getWhenFalse(),f=yield*ye(d,t),u=yield*ye(l,t);if(f.length>0||u.length>0){let g=wt(ct(a,t.constValues)),p={id:w(),type:"decision",decisionId:w(),label:g.length>40?g.slice(0,40)+"...":g,condition:a,source:"raw-ternary",onTrue:f.map(m=>m.effect),onFalse:u.length>0?u.map(m=>m.effect):void 0};return t.stats.decisionCount++,[{effect:p}]}}if(n===r.BinaryExpression){let o=s,a=o.getOperatorToken().getKind(),d=o.getLeft(),l=o.getRight();if(a===r.AmpersandAmpersandToken){let f=yield*ye(l,t);if(f.length>0){let u=d.getText(),g=wt(ct(u,t.constValues)),p={id:w(),type:"decision",decisionId:w(),label:g.length>40?g.slice(0,40)+"...":g,condition:u,source:"raw-short-circuit",onTrue:f.map(m=>m.effect),onFalse:[]};return t.stats.decisionCount++,[{effect:p}]}}if(a===r.BarBarToken){let f=yield*ye(l,t);if(f.length>0){let u=d.getText(),g=wt(ct(u,t.constValues)),p={id:w(),type:"decision",decisionId:w(),label:g.length>40?g.slice(0,40)+"...":g,condition:u,source:"raw-short-circuit",onTrue:[],onFalse:f.map(m=>m.effect)};return t.stats.decisionCount++,[{effect:p}]}}if(a===r.QuestionQuestionToken){let f=yield*ye(l,t);if(f.length>0){let u=`${d.getText()} != null`,g=wt(ct(u,t.constValues)),p={id:w(),type:"decision",decisionId:w(),label:g.length>40?g.slice(0,40)+"...":g,condition:u,source:"raw-short-circuit",onTrue:[],onFalse:f.map(m=>m.effect)};return t.stats.decisionCount++,[{effect:p}]}}}let i=Ns(e),c=[];for(let o of i){let a=yield*bs(o,t);c.push(a)}return c})}var ca=(e,t,r,s,n,i)=>Ee.gen(function*(){let{SyntaxKind:c}=T(),o;if((e.getKind()===c.ArrowFunction||e.getKind()===c.FunctionExpression||e.getKind()===c.FunctionDeclaration)&&(o=e.getBody()),!o)return[];let a=new Map,l={sourceFile:t,filePath:r,opts:s,warnings:n,stats:i,serviceScope:a,constValues:new Map},f;o.getKind()===c.Block?f=yield*lt(o,l):f=yield*ye(o,l);let u=o.getDescendantsOfKind(c.CallExpression);for(let y of u){if(y.getExpression().getText().includes("withSpan"))continue;let N=qe(t);if(ot(y,t,N,s.knownEffectInternalsRoot)){let x=yield*Mn(y,t,r,s,n,i,a);f.push({effect:x})}}let g=Ze(e),p={id:w(),type:"generator",yields:f,jsdocDescription:g,jsdocTags:it(e)};return[{...p,displayName:V(p),semanticRole:Y(p)}]});function la(e,t,r,s,n,i){let o=e.getExpression().getText();if(!(o.endsWith(".pipe")||o==="pipe"))return Ee.succeed(Ct.none());let d=e.getArguments(),l=d[d.length-1];if(!l)return Ee.succeed(Ct.none());let f=l.getText();return f.includes(".runMain")||f.includes(".runPromise")||f.includes(".runSync")||f.includes(".runFork")?Ee.map(jt(e,t,r,s,n,i),g=>Ct.some(g)):Ee.succeed(Ct.none())}var Tt=(e,t)=>Oe.gen(function*(){let r={...In,...t},{ts:s,Project:n}=T(),i=yield*Oe.try({try:()=>ts(e)?new n({skipAddingFilesFromTsConfig:!0,compilerOptions:{allowJs:!0}}):Fr(r.tsConfigPath),catch:d=>new xe("PROJECT_CREATION_FAILED",`Failed to create project: ${String(d)}`)}),c=i.getSourceFile(e);c&&i.removeSourceFile(c);let o=yield*Oe.try({try:()=>i.addSourceFileAtPath(e),catch:d=>new xe("FILE_NOT_FOUND",`Failed to load file ${e}: ${String(d)}`)}),a=Pn(o,r);return a.length===0?yield*Oe.fail(new xe("NO_EFFECTS_FOUND",`No Effect programs found in ${e}`)):yield*Oe.forEach(a,d=>On(d,o,e,r,s.version),{concurrency:"unbounded"})}),tt=(e,t="temp.ts",r)=>Oe.gen(function*(){let s={...In,...r},{ts:n}=T(),i=yield*Oe.try({try:()=>Ar(e,t),catch:o=>new xe("SOURCE_PARSE_FAILED",`Failed to parse source: ${String(o)}`)}),c=Pn(i,s);return c.length===0?yield*Oe.fail(new xe("NO_EFFECTS_FOUND","No Effect programs found in source")):yield*Oe.forEach(c,o=>On(o,i,t,s,n.version),{concurrency:"unbounded"})});var Fe=e=>({single:()=>te.gen(function*(){if(e.length===1){let t=e[0];if(t)return t}return yield*te.fail(new xe("NOT_SINGLE_PROGRAM",`Expected exactly 1 program, found ${String(e.length)}`))}),singleOption:()=>te.gen(function*(){if(e.length===1){let t=e[0];if(t)return _t.some(t)}return _t.none()}),all:()=>te.succeed(e),named:t=>te.gen(function*(){let r=e.find(s=>s.root.programName===t);if(!r){let s=e.map(n=>n.root.programName).join(", ");return yield*te.fail(new xe("PROGRAM_NOT_FOUND",`Program "${t}" not found. Available: ${s||"(none)"}`))}return r}),first:()=>te.gen(function*(){let t=e[0];return t||(yield*te.fail(new xe("NO_PROGRAMS","No programs found")))}),firstOption:()=>te.gen(function*(){let t=e[0];return t?_t.some(t):_t.none()})}),_e=(e,t)=>{Dt();let r=Tt(e,t);return{single:()=>te.gen(function*(){let s=yield*r;return yield*Fe(s).single()}),singleOption:()=>te.gen(function*(){let s=yield*r;return yield*Fe(s).singleOption()}).pipe(te.orDie),all:()=>r,named:s=>te.gen(function*(){let n=yield*r;return yield*Fe(n).named(s)}),first:()=>te.gen(function*(){let s=yield*r;return yield*Fe(s).first()}),firstOption:()=>te.gen(function*(){let s=yield*r;return yield*Fe(s).firstOption()}).pipe(te.orDie)}};_e.source=(e,t)=>{Dt();let r=tt(e,"temp.ts",t);return{single:()=>te.gen(function*(){let s=yield*r;return yield*Fe(s).single()}),singleOption:()=>te.gen(function*(){let s=yield*r;return yield*Fe(s).singleOption()}).pipe(te.orDie),all:()=>r,named:s=>te.gen(function*(){let n=yield*r;return yield*Fe(n).named(s)}),first:()=>te.gen(function*(){let s=yield*r;return yield*Fe(s).first()}),firstOption:()=>te.gen(function*(){let s=yield*r;return yield*Fe(s).firstOption()}).pipe(te.orDie)}};import{Effect as pa,Option as Eu}from"effect";import{Option as da}from"effect";function Cs(e,t){for(let r of e){r.type==="effect"&&t.push(r);let s=da.getOrElse(P(r),()=>[]);s.length>0&&Cs(s,t)}}function ws(e){let t=[],r=[],s=new Set,n=new Map,i=[];Cs(e.root.children,i);for(let d of i){let l=d.typeSignature?.successType,f=(d.requiredServices??[]).map(u=>u.serviceId);if(l){s.add(l);let u=n.get(l)??[];u.push(d.id),n.set(l,u)}t.push({id:d.id,name:d.callee,writes:l,reads:f,location:d.location?{line:d.location.line,column:d.location.column}:void 0})}for(let d=0;d<i.length-1;d++){let l=i[d],f=i[d+1];if(l===void 0||f===void 0)continue;let u=l.typeSignature?.successType??"value";r.push({from:l.id,to:f.id,key:u})}let c="__context__";for(let d of t)for(let l of d.reads)r.push({from:c,to:d.id,key:l});let o=[];for(let d of t)for(let l of d.reads)!s.has(l)&&l!==c&&o.push({key:l,readerId:d.id,readerName:d.name});let a=[];for(let[d,l]of n)l.length>1&&a.push({key:d,writerIds:l});return{nodes:t,edges:r,producedKeys:s,undefinedReads:o,duplicateWrites:a}}import{Option as ut}from"effect";function Kn(e){let t=e.trim();return t==="never"||t==="unknown"?[]:De(t)}function Ts(e,t){for(let r of e){if(r.type==="effect"){let n=r,i=n.typeSignature?.errorType?Kn(n.typeSignature.errorType):[];t.push({stepId:n.id,stepName:n.callee,errors:i,location:n.location?{line:n.location.line,column:n.location.column}:void 0})}let s=ut.getOrElse(P(r),()=>[]);s.length>0&&Ts(s,t)}}function Ut(e){let t=[],r=new Set,s=new Map,n=[];Ts(e.root.children,t);for(let i of t){i.errors.length===0&&n.push(i.stepId);for(let c of i.errors){r.add(c);let o=s.get(c)??[];o.push(i.stepId),s.set(c,o)}}return{allErrors:Array.from(r).sort(),stepErrors:t,errorToSteps:s,stepsWithoutErrors:n,allStepsDeclareErrors:n.length===0&&t.length>0}}function zt(e,t){return Array.from(new Set([...e,...t])).sort()}function ua(e,t){let r=new Set(t);return e.filter(s=>!r.has(s))}function fa(e){let t=[],r=s=>{if(s.type==="effect"){let i=s.typeSignature?.errorType;i&&t.push(...Kn(i))}ut.getOrElse(P(s),()=>[]).forEach(r)};return r(e),zt([],t)}function ks(e){if(e.type==="cause")return e.causeKind;let t=ut.getOrElse(P(e),()=>[]);for(let r of t){let s=ks(r);if(s)return s}}function dt(e,t,r){let s=[...t];for(let n of e)if(n.type==="effect"){let i=n,c=i.typeSignature?.errorType?Kn(i.typeSignature.errorType):[];s=zt(s,c),r.push({atNode:i.id,possibleErrors:[...s],defects:[],interruptible:!1});let o=ut.getOrElse(P(n),()=>[]);o.length>0&&(s=dt(o,s,r))}else if(n.type==="error-handler"){let i=n;s=dt([i.source],s,r);let c=[...s],o=[];i.handlerType==="catchTag"&&i.errorTag?o.push(i.errorTag):i.handlerType==="catchTags"?i.errorTags&&i.errorTags.length>0?o.push(...c.filter(l=>i.errorTags?i.errorTags.includes(l):!1)):o.push(...c.filter(l=>/Error$|^[A-Z]/.test(l))):i.handlerType==="catchIf"||i.handlerType==="catchSome"||i.handlerType==="catchSomeCause"||i.handlerType==="catchSomeDefect"?o.push(...c.slice(0,Math.ceil(c.length/2))):i.handlerType==="catchAll"||i.handlerType==="catchAllCause"||i.handlerType==="catchAllDefect"||i.handlerType==="orElse"||i.handlerType==="orDie"||i.handlerType==="orDieWith"?o.push(...c):i.handlerType==="mapError"||i.handlerType==="mapErrorCause"||i.handlerType==="mapBoth"?o.push(...c):i.handlerType==="sandbox"?o.push(...c):i.handlerType==="ignore"||i.handlerType==="ignoreLogged"?o.push(...c):i.handlerType==="orElseFail"||i.handlerType==="orElseSucceed"?o.push(...c):(i.handlerType==="filterOrDie"||i.handlerType==="filterOrDieMessage")&&o.push(...c);let a=ua(s,o),d=i.handler?fa(i.handler):[];if((i.handlerType==="mapError"||i.handlerType==="mapErrorCause"||i.handlerType==="mapBoth")&&o.length>0&&d.length===0){let l=ks(i.source);l==="fail"?d=["<mapped-fail>"]:l==="die"?d=["<mapped-defect>"]:d=["<mapped-error>"]}s=zt(a,d),r.push({atNode:i.id,possibleErrors:[...s],narrowedBy:{handler:i.handlerType,removedErrors:o,addedErrors:d},defects:[],interruptible:!1}),i.handler&&(s=dt([i.handler],s,r))}else if(n.type==="parallel"||n.type==="race"){let i=ut.getOrElse(P(n),()=>[]),c=[];for(let o of i){let a=dt([o],s,r);c=zt(c,a)}s=c}else{let i=ut.getOrElse(P(n),()=>[]);i.length>0&&(s=dt(i,s,r))}return s}function Ht(e){let t=[];dt(e.root.children,[],t);let r=new Map;for(let s of t)r.set(s.atNode,s);return{propagation:t,byNodeId:r}}var Fs={effect:"fill:#90EE90,stroke:#333,stroke-width:2px",generator:"fill:#FFB6C1,stroke:#333,stroke-width:2px",pipe:"fill:#ADD8E6,stroke:#333,stroke-width:2px",parallel:"fill:#FFA500,stroke:#333,stroke-width:2px",race:"fill:#FF6347,stroke:#333,stroke-width:2px",errorHandler:"fill:#FFD700,stroke:#333,stroke-width:2px",retry:"fill:#EE82EE,stroke:#333,stroke-width:2px",timeout:"fill:#87CEEB,stroke:#333,stroke-width:2px",resource:"fill:#98FB98,stroke:#333,stroke-width:2px",conditional:"fill:#DDA0DD,stroke:#333,stroke-width:2px",loop:"fill:#F0E68C,stroke:#333,stroke-width:2px",layer:"fill:#E6E6FA,stroke:#333,stroke-width:2px",stream:"fill:#E0F7FA,stroke:#333,stroke-width:2px",concurrencyPrimitive:"fill:#B0E0E6,stroke:#333,stroke-width:2px",fiber:"fill:#DDA0DD,stroke:#333,stroke-width:2px",decision:"fill:#DDA0DD,stroke:#333,stroke-width:2px",switch:"fill:#FFD700,stroke:#333,stroke-width:2px",tryCatch:"fill:#FFE4B5,stroke:#333,stroke-width:2px",terminal:"fill:#FF6B6B,stroke:#333,stroke-width:2px",opaque:"fill:#FF9800,stroke:#333,stroke-width:2px",unknown:"fill:#D3D3D3,stroke:#333,stroke-width:1px",start:"fill:#c8e6c9,stroke:#2e7d32",end:"fill:#ffcdd2,stroke:#c62828",cause:"fill:#FF8A80,stroke:#D32F2F,stroke-width:2px",exit:"fill:#B39DDB,stroke:#512DA8,stroke-width:2px",schedule:"fill:#80DEEA,stroke:#00838F,stroke-width:2px",match:"fill:#FFE082,stroke:#F57F17,stroke-width:2px",transform:"fill:#A5D6A7,stroke:#388E3C,stroke-width:2px",channel:"fill:#90CAF9,stroke:#1565C0,stroke-width:2px",sink:"fill:#CE93D8,stroke:#7B1FA2,stroke-width:2px",interruption:"fill:#FFAB91,stroke:#BF360C,stroke-width:2px"},Bn={direction:"TB",includeIds:!1,includeDescriptions:!0,styles:Fs,compact:!1,includeTypeSignatures:!0,useSubgraphs:!0,showConditions:!0,detail:"verbose"};function oe(e){return e.replace(/\r?\n/g," ").replace(/"/g,"'").replace(/\[/g,"(").replace(/\]/g,")").replace(/\{/g,"(").replace(/\}/g,")").replace(/#/g,"#").replace(/\|/g,"|")}function ft(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}function ga(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}function As(e,t,r){let s={...Bn,...t,useSubgraphs:t?.useSubgraphs??!0,showConditions:t?.showConditions??!0,detail:t?.detail??"verbose"},n={opts:s,nodeCounter:0,edges:[],subgraphs:[],styleClasses:new Map,nodeIdMap:new Map,nodeLabelAnnotations:r},i=[];i.push(`flowchart ${s.direction}`),i.push(""),i.push(` %% Program: ${e.root.programName}`),i.push("");let c="start",o="end_node";i.push(` ${c}((Start))`),i.push(` ${o}((End))`),i.push("");let{firstNodeId:a,lastNodeIds:d}=be(e.root.children,n,i);a&&n.edges.push({from:c,to:a});for(let f of d)n.edges.push({from:f,to:o});for(let f of n.subgraphs){i.push(""),i.push(` subgraph ${f.id}["${f.label}"]`);for(let u of f.content)i.push(` ${u}`);i.push(" end")}i.push(""),i.push(" %% Edges");for(let f of n.edges)f.label&&s.showConditions?i.push(` ${f.from} -->|${oe(f.label)}| ${f.to}`):i.push(` ${f.from} --> ${f.to}`);let l={...Fs,...s.styles};i.push(""),i.push(" %% Styles"),l.start&&i.push(` classDef startStyle ${l.start}`),l.end&&i.push(` classDef endStyle ${l.end}`);for(let[f,u]of Object.entries(l))u&&f!=="start"&&f!=="end"&&i.push(` classDef ${f}Style ${u}`);i.push(` class ${c} startStyle`),i.push(` class ${o} endStyle`);for(let[f,u]of n.styleClasses)i.push(` class ${f} ${u}`);if(t?.dataFlowOverlay){let f=ws(e),u=n.nodeIdMap;i.push(""),i.push(" %% Data-flow variable annotations"),i.push(" linkStyle default stroke:#999");for(let g of f.edges){if(g.from==="__context__")continue;let p=u.get(g.from),m=u.get(g.to);p&&m&&g.key&&g.key!=="value"&&i.push(` ${p} -.->|${g.key}| ${m}`)}if(f.undefinedReads.length>0){i.push(""),i.push(" %% Data-flow warnings"),i.push(" classDef dataFlowWarning fill:#fff3cd,stroke:#856404,stroke-width:2px");for(let g of f.undefinedReads){let p=u.get(g.readerId);p&&i.push(` class ${p} dataFlowWarning`)}}if(f.duplicateWrites.length>0){i.push(" classDef duplicateWrite fill:#f8d7da,stroke:#721c24,stroke-width:2px");for(let g of f.duplicateWrites)for(let p of g.writerIds){let m=u.get(p);m&&i.push(` class ${m} duplicateWrite`)}}}if(t?.errorFlowOverlay){let f=Ut(e),u=Ht(e),g=n.nodeIdMap;i.push(""),i.push(" %% Error-flow overlay"),i.push(" classDef canFail fill:#FFECB3,stroke:#F57F17,stroke-width:2px"),i.push(" classDef unhandledError fill:#FFCDD2,stroke:#C62828,stroke-width:3px");for(let p of f.stepErrors)if(p.errors.length>0){let m=g.get(p.stepId);m&&i.push(` class ${m} canFail`)}for(let p of u.propagation)if(p.possibleErrors.length>0&&!p.narrowedBy){let m=g.get(p.atNode);m&&i.push(` class ${m} unhandledError`)}for(let p of u.propagation)if(p.narrowedBy&&p.narrowedBy.removedErrors.length>0){let m=g.get(p.narrowedBy.handler),y=g.get(p.atNode);if(m&&y){let h=p.narrowedBy.removedErrors.join(", ");i.push(` ${y} -.->|catches ${h}| ${m}`)}}}return{lines:i,context:n}}function be(e,t,r){if(e.length===0)return{firstNodeId:null,lastNodeIds:[]};let s=null,n=[];for(let i of e){let c=ie(i,t,r);if(s===null&&c.firstNodeId&&(s=c.firstNodeId),c.firstNodeId)for(let o of n)t.edges.push({from:o,to:c.firstNodeId});n=c.lastNodeIds}return{firstNodeId:s,lastNodeIds:n}}function ma(e,t){let r=t.opts.includeIds&&"id"in e?e.id:`n${String(++t.nodeCounter)}`;return ga(r)}function ya(e,t,r){if(!t.includeDescriptions)return e.type;let s;switch(e.type){case"effect":s=ee(e.callee||"Effect",X);break;case"generator":s=`Generator (${e.yields.length} yields)`;break;case"pipe":s=`Pipe (${e.transformations.length+1} steps)`;break;case"parallel":s=ee(`${e.callee} (${e.children.length} effects)`,X);break;case"race":s=ee(`${e.callee} (${e.children.length} racing)`,X);break;case"error-handler":s=e.handlerType;break;case"retry":s=`Retry${e.schedule?`(${e.schedule})`:""}`;break;case"timeout":s=`Timeout${e.duration?`(${e.duration})`:""}`;break;case"resource":s="Resource";break;case"conditional":s=`${e.conditionalType} (${ft(e.condition,20)})`;break;case"loop":s=e.iterSource?ee(`${e.loopType}(${e.iterSource})`,X):e.loopType;break;case"layer":s=`Layer${e.isMerged?" (merged)":""}`;break;case"stream":s=ee(`Stream${e.pipeline.length>0?`.${e.pipeline.map(n=>n.operation).join(" \u2192 ")}`:""}${e.sink?` \u2192 ${e.sink}`:""}`,X);break;case"concurrency-primitive":s=`${e.primitive}.${e.operation}${e.strategy?` (${e.strategy})`:""}`;break;case"fiber":s=`${e.operation}${e.isDaemon?" (daemon)":""}${e.isScoped?" (scoped)":""}`;break;case"decision":s=e.label||ft(e.condition,30);break;case"switch":s=`Switch: ${ft(e.expression,25)}`;break;case"try-catch":s="Try/Catch";break;case"terminal":s=e.terminalKind;break;case"opaque":s=`\u26A0 ${e.reason}`;break;case"cause":s=`Cause: ${e.causeOp}`;break;case"exit":s=`Exit: ${e.exitOp}`;break;case"schedule":s=`Schedule: ${e.scheduleOp}`;break;case"match":s=`Match: ${e.matchOp}${e.matchedTags?.length?` (${e.matchedTags.join(", ")})`:""}`;break;case"transform":s=`${e.transformType}${e.isEffectful?" (effectful)":""}`;break;case"channel":s=`Channel${e.pipeline.length>0?`.${e.pipeline.map(n=>n.operation).join(" \u2192 ")}`:""}`;break;case"sink":s=`Sink${e.pipeline.length>0?`.${e.pipeline.map(n=>n.operation).join(" \u2192 ")}`:""}`;break;case"interruption":s=e.interruptionType;break;case"unknown":s=`Unknown: ${e.reason}`;break;default:{s=e.type??"unknown";break}}if(t.detail!=="compact"&&e.displayName&&(s=e.displayName),t.detail==="verbose"){if(e.type==="effect"&&t.includeTypeSignatures&&e.typeSignature){let n=e.typeSignature;s+=`
|
|
6
6
|
<${n.successType}, ${n.errorType}, ${n.requirementsType}>`}e.semanticRole&&e.semanticRole!=="unknown"&&e.semanticRole!=="constructor"&&(s+=`
|
|
7
7
|
(${e.semanticRole})`)}return r?.length&&(s+=`
|
|
8
8
|
`+r.join(`
|
|
9
|
-
`)),s}function
|
|
10
|
-
`)}var
|
|
11
|
-
`)}var
|
|
12
|
-
`)}function
|
|
13
|
-
`)}import{Option as
|
|
14
|
-
Empty((No steps))`;let i=[`flowchart ${r}`],c=[],o=n.some(a=>a.errorTypes.length>0);for(let a=0;a<n.length;a++){let d=n[a];if(!d)continue;let l=
|
|
15
|
-
`)}import{Option as
|
|
16
|
-
NoServices((No services))`;let o=[`flowchart ${r}`],a=
|
|
17
|
-
`)}function
|
|
18
|
-
`)}function
|
|
19
|
-
NoErrors((No errors))`;let i=[`flowchart ${r}`],c=[],o=new Set;for(let l of n.propagation)if(l.narrowedBy&&l.narrowedBy.removedErrors.length>0){let f=`handler_${
|
|
20
|
-
`)}import{Option as
|
|
21
|
-
NoDec((No decisions))`;let n=[`flowchart ${r}`],i={value:0};for(let{node:c,nodeId:o}of s)switch(c.type){case"conditional":{let a=c,d=
|
|
22
|
-
`)}import{Option as
|
|
23
|
-
NoCauses((No failure causes))`;let n=[`flowchart ${r}`],i=new Map,c={value:0},o="Root",a=
|
|
24
|
-
`)}import{Option as
|
|
25
|
-
NoConcurrency((No concurrency))`;let n=[`flowchart ${r}`],i=[],c=0,o=[];for(let a of s)switch(a.kind){case"parallel":{let d=a.node,l=
|
|
26
|
-
`)}import{Option as
|
|
9
|
+
`)),s}function ha(e){return e.type==="concurrency-primitive"?"concurrencyPrimitiveStyle":e.type==="try-catch"?"tryCatchStyle":e.type==="error-handler"?"errorHandlerStyle":`${e.type}Style`}function ie(e,t,r){let s=ma(e,t),n=t.nodeLabelAnnotations?.get(e.id),i=ya(e,t.opts,n),c=ha(e);switch(e.type!=="generator"&&(r.push(` ${s}["${oe(i)}"]`),t.styleClasses.set(s,c),t.nodeIdMap.set(e.id,s)),e.type){case"effect":case"unknown":return{firstNodeId:s,lastNodeIds:[s]};case"stream":{let o=ie(e.source,t,r);return o.firstNodeId&&t.edges.push({from:s,to:o.firstNodeId}),{firstNodeId:s,lastNodeIds:o.lastNodeIds}}case"concurrency-primitive":{if(e.source){let o=ie(e.source,t,r);return o.firstNodeId&&t.edges.push({from:s,to:o.firstNodeId}),{firstNodeId:s,lastNodeIds:o.lastNodeIds}}return{firstNodeId:s,lastNodeIds:[s]}}case"fiber":{if(e.fiberSource){let o=ie(e.fiberSource,t,r);return o.firstNodeId&&t.edges.push({from:s,to:o.firstNodeId}),{firstNodeId:s,lastNodeIds:o.lastNodeIds}}return{firstNodeId:s,lastNodeIds:[s]}}case"generator":{let o=e.yields.map(d=>d.effect),a=be(o,t,r);return a.firstNodeId?{firstNodeId:a.firstNodeId,lastNodeIds:a.lastNodeIds.length>0?a.lastNodeIds:[a.firstNodeId]}:(r.push(` ${s}["${oe(i)}"]`),t.styleClasses.set(s,c),t.nodeIdMap.set(e.id,s),{firstNodeId:s,lastNodeIds:[s]})}case"pipe":{let o=[e.initial,...e.transformations],a=be(o,t,r);return a.firstNodeId&&t.edges.push({from:s,to:a.firstNodeId}),{firstNodeId:s,lastNodeIds:a.lastNodeIds.length>0?a.lastNodeIds:[s]}}case"parallel":{let o=`parallel_fork_${++t.nodeCounter}`,a=`parallel_join_${t.nodeCounter}`,d=e.mode==="parallel"?"Parallel":"All";r.push(` ${o}{{"${d} (${e.children.length})"}}`),r.push(` ${a}{{"Join"}}`),t.styleClasses.set(o,"parallelStyle"),t.styleClasses.set(a,"parallelStyle"),t.edges.push({from:s,to:o});for(let l=0;l<e.children.length;l++){let f=e.children[l];if(!f)continue;let u=ie(f,t,r);u.firstNodeId&&t.edges.push({from:o,to:u.firstNodeId,label:e.branchLabels?.[l]??`branch ${l+1}`});for(let g of u.lastNodeIds)t.edges.push({from:g,to:a})}return{firstNodeId:s,lastNodeIds:[a]}}case"race":{let o=`race_fork_${++t.nodeCounter}`,a=`race_join_${t.nodeCounter}`;r.push(` ${o}{{{"Race (${e.children.length})"}}}`),r.push(` ${a}{{{"Winner"}}}`),t.styleClasses.set(o,"raceStyle"),t.styleClasses.set(a,"raceStyle"),t.edges.push({from:s,to:o});for(let d=0;d<e.children.length;d++){let l=e.children[d];if(!l)continue;let f=ie(l,t,r);f.firstNodeId&&t.edges.push({from:o,to:f.firstNodeId,label:e.raceLabels?.[d]??`racer ${d+1}`});for(let u of f.lastNodeIds)t.edges.push({from:u,to:a})}return{firstNodeId:s,lastNodeIds:[a]}}case"error-handler":{let o=ie(e.source,t,r),a=`err_handler_${++t.nodeCounter}`;r.push(` ${a}["${e.handlerType}"]`),t.styleClasses.set(a,"errorHandlerStyle"),o.lastNodeIds.length>0&&t.edges.push({from:o.lastNodeIds[0],to:a,label:e.errorEdgeLabel??"on error"});let d=[a];if(e.handler){let l=ie(e.handler,t,r);l.firstNodeId&&t.edges.push({from:a,to:l.firstNodeId}),d=l.lastNodeIds}return{firstNodeId:o.firstNodeId??s,lastNodeIds:d}}case"retry":case"timeout":{let o=ie(e.source,t,r),a=`${e.type}_${++t.nodeCounter}`,d=e.type==="retry"?`Retry${e.schedule?`(${e.schedule})`:""}`:`Timeout${e.duration?`(${e.duration})`:""}`;return r.push(` ${a}["${d}"]`),t.styleClasses.set(a,`${e.type}Style`),o.lastNodeIds.length>0&&t.edges.push({from:o.lastNodeIds[0],to:a}),{firstNodeId:o.firstNodeId??s,lastNodeIds:[a]}}case"resource":{let o=ie(e.acquire,t,r),a=`resource_${++t.nodeCounter}`;r.push(` ${a}["Resource"]`),t.styleClasses.set(a,"resourceStyle"),o.lastNodeIds.length>0&&t.edges.push({from:o.lastNodeIds[0],to:a});let d=[a];if(e.use){let l=ie(e.use,t,r);l.firstNodeId&&t.edges.push({from:a,to:l.firstNodeId}),d=l.lastNodeIds}return{firstNodeId:o.firstNodeId??s,lastNodeIds:d}}case"conditional":{let o=`cond_${++t.nodeCounter}`,a=e.conditionLabel??ft(e.condition,25);r.push(` ${o}{"${oe(a)}"}`),t.styleClasses.set(o,"conditionalStyle"),t.edges.push({from:s,to:o});let d=ie(e.onTrue,t,r);d.firstNodeId&&t.edges.push({from:o,to:d.firstNodeId,label:e.trueEdgeLabel??"true"});let l=[...d.lastNodeIds];if(e.onFalse){let f=ie(e.onFalse,t,r);f.firstNodeId&&t.edges.push({from:o,to:f.firstNodeId,label:e.falseEdgeLabel??"false"}),l.push(...f.lastNodeIds)}else l.push(o);return{firstNodeId:s,lastNodeIds:l}}case"loop":{let o=`loop_${++t.nodeCounter}`,a=e.iterSource?ee(`${e.loopType}(${e.iterSource})`,X):e.loopType;r.push(` ${o}(["${oe(a)}"])`),t.styleClasses.set(o,"loopStyle"),t.edges.push({from:s,to:o});let d=ie(e.body,t,r);d.firstNodeId&&t.edges.push({from:o,to:d.firstNodeId,label:"iterate"});for(let l of d.lastNodeIds)t.edges.push({from:l,to:o,label:"next"});return{firstNodeId:s,lastNodeIds:[o]}}case"layer":{let o=be(e.operations,t,r);return o.firstNodeId&&t.edges.push({from:s,to:o.firstNodeId}),{firstNodeId:s,lastNodeIds:o.lastNodeIds.length>0?o.lastNodeIds:[s]}}case"decision":{let o=`decision_${++t.nodeCounter}`,a=e.label||ft(e.condition,25);r.push(` ${o}{"${oe(a)}"}`),t.styleClasses.set(o,"decisionStyle");let d=be(e.onTrue,t,r);d.firstNodeId&&t.edges.push({from:o,to:d.firstNodeId,label:"yes"});let l=[...d.lastNodeIds];if(e.onFalse&&e.onFalse.length>0){let f=be(e.onFalse,t,r);f.firstNodeId&&t.edges.push({from:o,to:f.firstNodeId,label:"no"}),l.push(...f.lastNodeIds)}else l.push(o);return{firstNodeId:o,lastNodeIds:l}}case"switch":{let o=`switch_${++t.nodeCounter}`,a=`Switch: ${ft(e.expression,20)}`;r.push(` ${o}{"${oe(a)}"}`),t.styleClasses.set(o,"switchStyle");let d=[];for(let l of e.cases){let f=l.labels.join(" / "),u=be(l.body,t,r);u.firstNodeId&&t.edges.push({from:o,to:u.firstNodeId,label:f}),d.push(...u.lastNodeIds)}if(e.hasFallthrough){let l=`switchWarn_${++t.nodeCounter}`;r.push(` ${l}{{"\u26A0 fallthrough"}}`),t.styleClasses.set(l,"opaqueStyle"),t.edges.push({from:o,to:l,label:"note"})}return d.length===0&&d.push(o),{firstNodeId:o,lastNodeIds:d}}case"try-catch":{let o=be(e.tryBody,t,r),a=[...o.lastNodeIds];if(e.catchBody&&e.catchBody.length>0){let d=`catch_${++t.nodeCounter}`,l=e.catchVariable?`Catch(${e.catchVariable})`:"Catch";r.push(` ${d}["${oe(l)}"]`),t.styleClasses.set(d,"tryCatchStyle");for(let u of o.lastNodeIds)t.edges.push({from:u,to:d,label:"on error"});let f=be(e.catchBody,t,r);f.firstNodeId&&t.edges.push({from:d,to:f.firstNodeId}),a.push(...f.lastNodeIds)}if(e.finallyBody&&e.finallyBody.length>0){let d=be(e.finallyBody,t,r);if(d.firstNodeId)for(let l of a)t.edges.push({from:l,to:d.firstNodeId,label:"finally"});return{firstNodeId:o.firstNodeId??s,lastNodeIds:d.lastNodeIds}}return{firstNodeId:o.firstNodeId??s,lastNodeIds:a.length>0?a:[s]}}case"terminal":{let o=`term_${++t.nodeCounter}`,a=e.terminalKind;if(r.push(` ${o}(["${oe(a)}"])`),t.styleClasses.set(o,"terminalStyle"),e.value&&e.value.length>0){let d=be(e.value,t,r);d.firstNodeId&&t.edges.push({from:s,to:d.firstNodeId});for(let l of d.lastNodeIds)t.edges.push({from:l,to:o})}return{firstNodeId:e.value?.length?s:o,lastNodeIds:[]}}case"opaque":{let o=`opaque_${++t.nodeCounter}`;return r.push(` ${o}{{"${oe(`\u26A0 ${e.reason}`)}"}}`),t.styleClasses.set(o,"opaqueStyle"),{firstNodeId:o,lastNodeIds:[o]}}case"cause":{let o=`cause_${++t.nodeCounter}`;if(r.push(` ${o}{{"${oe(i)}"}}`),t.styleClasses.set(o,"causeStyle"),t.nodeIdMap.set(e.id,o),e.children&&e.children.length>0){let a=be([...e.children],t,r);return a.firstNodeId&&t.edges.push({from:o,to:a.firstNodeId}),{firstNodeId:o,lastNodeIds:a.lastNodeIds.length>0?a.lastNodeIds:[o]}}return{firstNodeId:o,lastNodeIds:[o]}}case"exit":{let o=`exit_${++t.nodeCounter}`;return r.push(` ${o}(["${oe(i)}"])`),t.styleClasses.set(o,"exitStyle"),t.nodeIdMap.set(e.id,o),{firstNodeId:o,lastNodeIds:[o]}}case"schedule":{let o=`schedule_${++t.nodeCounter}`;return r.push(` ${o}[/"${oe(i)}"/]`),t.styleClasses.set(o,"scheduleStyle"),t.nodeIdMap.set(e.id,o),{firstNodeId:o,lastNodeIds:[o]}}case"match":{let o=`match_${++t.nodeCounter}`;if(r.push(` ${o}{"${oe(i)}"}`),t.styleClasses.set(o,"matchStyle"),t.nodeIdMap.set(e.id,o),e.matchedTags&&e.matchedTags.length>0){let a=[];for(let d of e.matchedTags){let l=`match_tag_${++t.nodeCounter}`;r.push(` ${l}["${oe(d)}"]`),t.styleClasses.set(l,"matchStyle"),t.edges.push({from:o,to:l,label:d}),a.push(l)}return a.length===0&&a.push(o),{firstNodeId:o,lastNodeIds:a}}return{firstNodeId:o,lastNodeIds:[o]}}case"transform":{if(e.source){let o=ie(e.source,t,r);return o.lastNodeIds.length>0&&t.edges.push({from:o.lastNodeIds[0],to:s}),{firstNodeId:o.firstNodeId??s,lastNodeIds:[s]}}return{firstNodeId:s,lastNodeIds:[s]}}case"channel":{let o=`channel_${++t.nodeCounter}`;if(r.push(` ${o}[["${oe(i)}"]]`),t.styleClasses.set(o,"channelStyle"),t.nodeIdMap.set(e.id,o),e.source){let a=ie(e.source,t,r);return a.lastNodeIds.length>0&&t.edges.push({from:a.lastNodeIds[0],to:o}),{firstNodeId:a.firstNodeId??o,lastNodeIds:[o]}}return{firstNodeId:o,lastNodeIds:[o]}}case"sink":{let o=`sink_${++t.nodeCounter}`;if(r.push(` ${o}[("${oe(i)}")]`),t.styleClasses.set(o,"sinkStyle"),t.nodeIdMap.set(e.id,o),e.source){let a=ie(e.source,t,r);return a.lastNodeIds.length>0&&t.edges.push({from:a.lastNodeIds[0],to:o}),{firstNodeId:a.firstNodeId??o,lastNodeIds:[o]}}return{firstNodeId:o,lastNodeIds:[o]}}case"interruption":{let o=`interruption_${++t.nodeCounter}`;if(r.push(` ${o}{{"${oe(i)}"}}`),t.styleClasses.set(o,"interruptionStyle"),t.nodeIdMap.set(e.id,o),e.source){let a=ie(e.source,t,r);a.firstNodeId&&t.edges.push({from:o,to:a.firstNodeId});let d=[...a.lastNodeIds];if(e.handler){let l=ie(e.handler,t,r);a.lastNodeIds.length>0&&l.firstNodeId&&t.edges.push({from:a.lastNodeIds[0],to:l.firstNodeId,label:"on interrupt"}),d.push(...l.lastNodeIds)}return{firstNodeId:o,lastNodeIds:d.length>0?d:[o]}}return{firstNodeId:o,lastNodeIds:[o]}}default:return{firstNodeId:s,lastNodeIds:[s]}}}function nt(e,t){let r={...Bn,...t},{lines:s}=As(e,r);return s.join(`
|
|
10
|
+
`)}var Gt=(e,t)=>pa.sync(()=>nt(e,t));function vs(e){let t=e.toLowerCase();return t.includes("log")||t.includes("loginfo")||t.includes("logdebug")||t.includes("logwarning")||t.includes("logerror")||t.includes("taperror")}function Is(e){let t=e.toLowerCase();return t.includes("map")||t.includes("flatmap")||t.includes("filter")||t.includes("transform")||t.includes("tap(")||t==="tap"||t.includes("annotate")||t.includes("hsep")||t.includes("ansidoc.text")}function $s(e){let t=e.trim();return!!(/\(environment\)/i.test(t)||/^[A-Z][A-Za-z0-9_]+$/.test(t)||/^(Context\.Tag|GenericTag|Effect\.serviceOption|Effect\.service)\b/.test(t))}function Sa(e){let t=e.trim();return/^[A-Za-z_$][\w$]*\.[A-Za-z_$][\w$]*/.test(t)?!["Effect.","Layer.","Stream.","Schema.","Schedule.","Option.","Either.","Duration.","Console.","Array.","String.","Number.","Boolean.","Math.","Object.","JSON.","Promise.","Date."].some(s=>t.startsWith(s)):!1}function xa(e,t){if(!(t.prefixServiceBoundaries??t.styleGuide??!1))return[...e];let s=[...e],n=0;for(let i=0;i<s.length&&!(n>=2);i++){let c=s[i];c&&Sa(c.name)&&!c.name.startsWith("svc: ")&&(s[i]={...c,name:`svc: ${c.name}`},n++)}return s}function jn(e,t){let r=t.collapseRepeatedLogs??!0,s=t.collapsePureTransforms??!0,n=t.collapseEnvironmentRuns??t.styleGuide??!1,i=[],c=0,o=0;for(;o<e.steps.length;){let a=e.steps[o];if(!a)break;let d=a.name??a.nodeId;if(r&&vs(d)){let l=o+1;for(;l<e.steps.length;){let u=e.steps[l];if(!u)break;let g=u.name??u.nodeId;if(!vs(g))break;l++}let f=l-o;if(f>1){i.push({key:`${e.id}:logs:${o}`,name:`log steps \xD7${String(f)}`}),c++,o=l;continue}}if(s&&Is(d)){let l=o+1;for(;l<e.steps.length;){let u=e.steps[l];if(!u)break;let g=u.name??u.nodeId;if(!Is(g))break;l++}let f=l-o;if(f>1){i.push({key:`${e.id}:transforms:${o}`,name:`transform steps \xD7${String(f)}`}),c++,o=l;continue}}if(n&&$s(d)){let l=o+1;for(;l<e.steps.length;){let u=e.steps[l];if(!u)break;let g=u.name??u.nodeId;if(!$s(g))break;l++}let f=l-o;if(f>1){i.push({key:`${e.id}:env:${o}`,name:`environment \xD7${String(f)}`}),c++,o=l;continue}}i.push({key:a.nodeId,name:d}),o++}return{steps:xa(i,t),collapsedGroups:c}}function Vt(e,t={}){let r=t.direction??"TB",s=[];s.push(`flowchart ${r}`),s.push("");let n=new Map,i=0,c=e.map(a=>jn(a,t).steps);for(let a of c)for(let d of a){let l=d.key;n.has(l)||n.set(l,{id:`step_${++i}`,name:d.name})}s.push(" start((Start))"),s.push(" end_node((End))"),s.push("");for(let[,a]of n)s.push(` ${a.id}["${oe(a.name)}"]`);s.push("");let o=new Set;for(let a of c){if(a.length===0)continue;let d=a[0],l=n.get(d.key);o.add(`start --> ${l.id}`);for(let g=0;g<a.length-1;g++){let p=a[g],m=a[g+1],y=n.get(p.key),h=n.get(m.key);o.add(`${y.id} --> ${h.id}`)}let f=a[a.length-1],u=n.get(f.key);o.add(`${u.id} --> end_node`)}s.push(" %% Edges");for(let a of o)s.push(` ${a}`);return s.join(`
|
|
11
|
+
`)}var Ea={...Bn,showTypeSignatures:!0,showRequiredServices:!0,showErrorNodes:!1};function ba(e,t){let r=new Map,s=t.showTypeSignatures!==!1,n=t.showRequiredServices===!0;function i(c){if(c.type==="effect"){let o=[];if(s&&c.typeSignature&&o.push(`<${c.typeSignature.successType}, ${c.typeSignature.errorType}, ${c.typeSignature.requirementsType}>`),n&&c.requiredServices&&c.requiredServices.length>0){let a=c.requiredServices.map(d=>d.serviceId).join(", ");o.push(`R: ${a}`)}o.length>0&&r.set(c.id,o)}switch(c.type){case"generator":for(let o of c.yields)i(o.effect);break;case"pipe":i(c.initial);for(let o of c.transformations)i(o);break;case"parallel":case"race":for(let o of c.children)i(o);break;case"error-handler":i(c.source),c.handler&&i(c.handler);break;case"retry":case"timeout":i(c.source);break;case"resource":i(c.acquire),i(c.release),c.use&&i(c.use);break;case"conditional":i(c.onTrue),c.onFalse&&i(c.onFalse);break;case"loop":i(c.body);break;case"layer":for(let o of c.operations)i(o);break;case"decision":for(let o of c.onTrue)i(o);if(c.onFalse)for(let o of c.onFalse)i(o);break;case"switch":for(let o of c.cases)for(let a of o.body)i(a);break;case"try-catch":for(let o of c.tryBody)i(o);if(c.catchBody)for(let o of c.catchBody)i(o);if(c.finallyBody)for(let o of c.finallyBody)i(o);break;case"terminal":if(c.value)for(let o of c.value)i(o);break;case"opaque":break;default:break}}for(let c of e.root.children)i(c);return r}function Jt(e,t){let r={...Ea,...t},s=ba(e,r),{lines:n}=As(e,r,s);return n.join(`
|
|
12
|
+
`)}function Rs(e,t={}){let r=t.direction??"TB",s=[],n=c=>c.replace(/[^a-zA-Z0-9_]/g,"_");s.push(`flowchart ${r}`),s.push(""),s.push(" %% Service Dependency Graph"),s.push("");for(let[c,o]of e.services){let a=n(c),d=o.definition.methods.length,l=d>0?`${c}\\n(${d} method${d===1?"":"s"})`:c;s.push(` ${a}{{{"${l}"}}}`)}for(let c of e.unresolvedServices){let o=`unresolved_${n(c)}`;s.push(` ${o}["? ${c}"]`)}s.push("");let i=new Set;for(let[c,o]of e.services)for(let a of o.layerImplementations)for(let d of a.requires){let l=`${c}->${d}`;if(i.has(l))continue;i.add(l);let f=n(c),u=e.services.has(d)?n(d):`unresolved_${n(d)}`;s.push(` ${f} -->|"${a.name}"| ${u}`)}s.push(""),s.push(" classDef service fill:#E3F2FD,stroke:#1565C0,stroke-width:2px"),s.push(" classDef unresolved fill:#FFF3CD,stroke:#856404,stroke-dasharray:5");for(let c of e.services.keys())s.push(` class ${n(c)} service`);for(let c of e.unresolvedServices)s.push(` class unresolved_${n(c)} unresolved`);return s.join(`
|
|
13
|
+
`)}import{Option as Ps}from"effect";function Qt(e){let t=String.fromCharCode(65+e%26),r=Math.floor(e/26);return r===0?t:`${t}${r}`}function Zt(e){return e.replace(/"/g,"#quot;").replace(/</g,"#lt;").replace(/>/g,"#gt;").replace(/\(/g,"#lpar;").replace(/\)/g,"#rpar;")}function Ds(e){return e.replace(/(Error|Exception)$/,"")}function Na(e){let t;return e.type==="effect"?t=e.typeSignature?.errorType??e.errorType:"typeSignature"in e&&e.typeSignature&&(t=e.typeSignature.errorType),!t||t==="never"||t.trim()===""?[]:De(t).filter(r=>r!=="never")}function Ca(e){let t=new Set,r=[],s=n=>{for(let c of Na(n))t.has(c)||(t.add(c),r.push(c));let i=Ps.getOrElse(P(n),()=>[]);for(let c of i)s(c)};return s(e),r}function wa(e){let t=(()=>{if(e.displayName)return e.displayName;if(e.type==="effect"){if(e.name){let r=e.name.replace(/^Effect\./,"");return r.charAt(0).toUpperCase()+r.slice(1)}return e.callee.replace(/^Effect\./,"")}return e.name?e.name:e.type==="parallel"?"Effect.all":e.type==="race"?"Effect.race":e.type==="error-handler"?"Error Handler":e.type==="retry"?"Retry":e.type==="conditional"?"Conditional":e.type})();return ee(t,X)}function Ta(e){switch(e.type){case"generator":case"pipe":return!0;default:return!1}}function ka(e){switch(e.type){case"loop":case"conditional":case"decision":case"switch":case"parallel":case"race":case"retry":case"timeout":case"resource":return!0;default:return!1}}function va(e){switch(e.type){case"error-handler":case"transform":case"stream":case"channel":case"sink":case"concurrency-primitive":case"fiber":case"interruption":case"try-catch":case"terminal":return!0;default:return!1}}function Ia(e){if(e.type!=="effect")return!1;let t=e.callee??"";if(t==="Effect.fn"||t.startsWith("Effect.fn("))return!0;let r=e.displayName??"";return!!(!(r&&r!==t&&r!==e.type)||t.startsWith("Schema.")||t.startsWith("Data."))}function $a(e){let t=[],r=s=>{if(Ta(s)){let n=Ps.getOrElse(P(s),()=>[]);for(let i of n)r(i);return}if(!va(s)){if(ka(s)){t.push(s);return}Ia(s)||t.push(s)}};for(let s of e)r(s);return t}function Fa(e){return e.map(t=>({label:wa(t),errorTypes:Ca(t)}))}function qn(e,t={}){let r=t.direction??"LR",s=$a(e.root.children),n=Fa(s);if(n.length===0)return`flowchart ${r}
|
|
14
|
+
Empty((No steps))`;let i=[`flowchart ${r}`],c=[],o=n.some(a=>a.errorTypes.length>0);for(let a=0;a<n.length;a++){let d=n[a];if(!d)continue;let l=Qt(a),f=Zt(d.label);if(a<n.length-1){let u=n[a+1];if(!u)continue;let g=Qt(a+1),p=Zt(u.label);a===0?i.push(` ${l}[${f}] -->|ok| ${g}[${p}]`):i.push(` ${l} -->|ok| ${g}[${p}]`)}else a===0?i.push(` ${l}[${f}] -->|ok| Done((Success))`):i.push(` ${l} -->|ok| Done((Success))`)}if(o)for(let a=0;a<n.length;a++){let d=n[a];if(!d)continue;let{errorTypes:l}=d;if(l.length===0)continue;let f=Qt(a),u=`${f}E`,g=Zt(l.map(Ds).join(" / "));c.push(` ${f} -->|err| ${u}[${g}]`)}else if(e.root.errorTypes.length>0){let a=Qt(n.length-1),d=Zt(e.root.errorTypes.map(Ds).join(" / "));c.push(` ${a} -->|err| Errors[${d}]`)}return[...i,...c].join(`
|
|
15
|
+
`)}import{Option as Ms}from"effect";function Os(e,t){if(e.type==="effect"){let n=e.requiredServices??[];for(let i of n)t.some(c=>c.serviceId===i.serviceId)||t.push(i)}let r=Ms.getOrElse(P(e),()=>[]);for(let s of r)Os(s,t)}function Aa(e,t){let r=e.callee;if(r.includes("provideService")||r.includes("provide"))return t(e)}function Ls(e,t){let r=[];for(let f of e.root.children)Os(f,r);let s=Array.from(new Map(r.map(f=>[f.serviceId,f])).values()),n=[],i=[],c=new Map,o=new Set,a=t?.getFirstArgText;function d(f){for(let u of f){if(u.type==="effect"){let p=u,m=a?Aa(p,a):void 0;if(m){o.add(m);let h={nodeId:p.id,serviceId:m};p.location&&(h.location=p.location),n.push(h)}let y=p.requiredServices??[];for(let h of y){let N=c.get(h.serviceId)??[];if(N.push(p.id),c.set(h.serviceId,N),!o.has(h.serviceId)){let x={nodeId:p.id,serviceId:h.serviceId};h.serviceType!==void 0&&(x.serviceType=h.serviceType),h.requiredAt!==void 0&&(x.location=h.requiredAt),i.push(x)}}}let g=Ms.getOrElse(P(u),()=>[]);g.length>0&&d(g)}}d(e.root.children);let l=new Map;for(let f of n)l.set(f.serviceId,{createdAt:f.nodeId,consumedAt:c.get(f.serviceId)??[]});for(let f of s)l.has(f.serviceId)||l.set(f.serviceId,{createdAt:"",consumedAt:c.get(f.serviceId)??[]});return{requiredServices:s,providedServices:n,unsatisfiedAt:i,serviceLifecycle:l}}function _n(e){return e.replace(/"/g,"#quot;").replace(/</g,"#lt;").replace(/>/g,"#gt;").replace(/\(/g,"#lpar;").replace(/\)/g,"#rpar;")}function we(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}function Yt(e,t={}){let r=t.direction??"LR",{requiredServices:s,providedServices:n}=Ls(e),i=e.root.dependencies,c=new Set;for(let d of s)c.add(d.serviceId);for(let d of i)c.add(d.name);if(c.size===0&&n.length===0)return`flowchart ${r}
|
|
16
|
+
NoServices((No services))`;let o=[`flowchart ${r}`],a=_n(e.root.programName);o.push(` prog["${a}"]`),o.push("");for(let d of c){let l=`svc_${we(d)}`,f=_n(d);o.push(` ${l}{{"${f}"}}`),o.push(` prog -->|requires| ${l}`)}for(let d of n){let l=`prov_${we(d.serviceId)}`,f=_n(d.serviceId);o.push(` ${l}{{"${f}"}}`),o.push(` ${l} -->|provides| prog`)}o.push(""),o.push(" classDef required fill:#E3F2FD,stroke:#1565C0,stroke-width:2px"),o.push(" classDef provided fill:#E8F5E9,stroke:#2E7D32,stroke-width:2px");for(let d of s)o.push(` class svc_${we(d.serviceId)} required`);for(let d of n)o.push(` class prov_${we(d.serviceId)} provided`);return o.join(`
|
|
17
|
+
`)}function Ws(e,t={}){let s=[`flowchart ${t.direction??"TB"}`];s.push(""),s.push(" %% Service Dependency Graph"),s.push("");for(let[i,c]of e.services){let o=we(i),a=c.definition.methods.length,d=a>0?`${i}\\n(${a} method${a===1?"":"s"})`:i;s.push(` ${o}{{"${d}"}}`)}for(let i of e.unresolvedServices){let c=`unresolved_${we(i)}`;s.push(` ${c}["? ${i}"]`)}s.push("");let n=new Set;for(let[i,c]of e.services)for(let o of c.layerImplementations)for(let a of o.requires){let d=`${i}->${a}`;if(n.has(d))continue;n.add(d);let l=we(i),f=e.services.has(a)?we(a):`unresolved_${we(a)}`;s.push(` ${l} -->|"${o.name}"| ${f}`)}s.push(""),s.push(" classDef service fill:#E3F2FD,stroke:#1565C0,stroke-width:2px"),s.push(" classDef unresolved fill:#FFF3CD,stroke:#856404,stroke-dasharray:5");for(let i of e.services.keys())s.push(` class ${we(i)} service`);for(let i of e.unresolvedServices)s.push(` class unresolved_${we(i)} unresolved`);return s.join(`
|
|
18
|
+
`)}function zn(e){return e.replace(/"/g,"#quot;").replace(/</g,"#lt;").replace(/>/g,"#gt;").replace(/\(/g,"#lpar;").replace(/\)/g,"#rpar;")}function Le(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}function Ra(e){return e.replace(/(Error|Exception)$/,"")}function Un(e,t={}){let r=t.direction??"LR",s=Ut(e),n=Ht(e);if(s.allErrors.length===0)return`flowchart ${r}
|
|
19
|
+
NoErrors((No errors))`;let i=[`flowchart ${r}`],c=[],o=new Set;for(let l of n.propagation)if(l.narrowedBy&&l.narrowedBy.removedErrors.length>0){let f=`handler_${Le(l.atNode)}`;c.push({id:f,label:l.narrowedBy.handler,removedErrors:l.narrowedBy.removedErrors});for(let u of l.narrowedBy.removedErrors)o.add(u)}let a=s.allErrors.filter(l=>!o.has(l)),d=s.stepErrors.filter(l=>l.errors.length>0);if(d.length>0){i.push(""),i.push(" subgraph Steps");for(let l of d){let f=zn(l.stepName??l.stepId);i.push(` step_${Le(l.stepId)}["${f}"]`)}i.push(" end")}i.push(""),i.push(" subgraph Errors");for(let l of s.allErrors){let f=zn(Ra(l));i.push(` err_${Le(l)}("${f}")`)}if(i.push(" end"),c.length>0){i.push(""),i.push(" subgraph Handlers");for(let l of c){let f=zn(l.label);i.push(` ${l.id}["${f}"]`)}i.push(" end")}a.length>0&&(i.push(""),i.push(' UNHANDLED["UNHANDLED"]')),i.push("");for(let l of d)for(let f of l.errors)i.push(` step_${Le(l.stepId)} --produces--> err_${Le(f)}`);for(let l of c)for(let f of l.removedErrors)s.allErrors.includes(f)&&i.push(` err_${Le(f)} --caught by--> ${l.id}`);for(let l of a)i.push(` err_${Le(l)} --unhandled--> UNHANDLED`);i.push(""),i.push(" classDef stepStyle fill:#BBDEFB"),i.push(" classDef errorStyle fill:#FFE0B2"),i.push(" classDef handlerStyle fill:#C8E6C9"),i.push(" classDef unhandledStyle fill:#FFCDD2");for(let l of d)i.push(` class step_${Le(l.stepId)} stepStyle`);for(let l of s.allErrors)i.push(` class err_${Le(l)} errorStyle`);for(let l of c)i.push(` class ${l.id} handlerStyle`);return a.length>0&&i.push(" class UNHANDLED unhandledStyle"),i.join(`
|
|
20
|
+
`)}import{Option as Da}from"effect";var Pa=new Set(["conditional","decision","switch","match"]);function ze(e){return e.replace(/"/g,"#quot;").replace(/</g,"#lt;").replace(/>/g,"#gt;").replace(/\(/g,"#lpar;").replace(/\)/g,"#rpar;")}function Hn(e,t=40){return e.length>t?e.slice(0,t-3)+"...":e}function Bs(e){return e.displayName?e.displayName:e.name?e.name:e.type==="effect"?e.callee:e.type}function Ma(e){let t=[],r=0,s=n=>{Pa.has(n.type)&&t.push({node:n,nodeId:`D${r++}`});let i=Da.getOrElse(P(n),()=>[]);for(let c of i)s(c);if(n.type==="conditional"){let c=n;s(c.onTrue),c.onFalse&&s(c.onFalse)}else if(n.type==="decision"){let c=n;for(let o of c.onTrue)s(o);if(c.onFalse)for(let o of c.onFalse)s(o)}else if(n.type==="switch"){let c=n;for(let o of c.cases)for(let a of o.body)s(a)}};for(let n of e)s(n);return t}function js(e,t){return e.find(r=>r.node===t)}function Oa(e,t){for(let r of t){let s=js(e,r);if(s)return s}}function Ks(e,t,r){if(!e){let c=`T${r.value++}`;return{targetId:c,extraLine:` ${c}["..."]`}}let s=js(t,e);if(s)return{targetId:s.nodeId};let n=ze(Bs(e)),i=`T${r.value++}`;return{targetId:i,extraLine:` ${i}["${n}"]`}}function Gn(e,t,r){if(!e||e.length===0){let o=`T${r.value++}`;return{targetId:o,extraLine:` ${o}["..."]`}}let s=Oa(t,e);if(s)return{targetId:s.nodeId};let n=e[0];if(!n){let o=`T${r.value++}`;return{targetId:o,extraLine:` ${o}["..."]`}}let i=ze(Bs(n)),c=`T${r.value++}`;return{targetId:c,extraLine:` ${c}["${i}"]`}}function Vn(e,t={}){let r=t.direction??"TB",s=Ma(e.root.children);if(s.length===0)return`flowchart ${r}
|
|
21
|
+
NoDec((No decisions))`;let n=[`flowchart ${r}`],i={value:0};for(let{node:c,nodeId:o}of s)switch(c.type){case"conditional":{let a=c,d=ze(Hn(a.condition));n.push(` ${o}{${d}}`);let l=a.trueEdgeLabel??"true",f=a.falseEdgeLabel??"false",u=Ks(a.onTrue,s,i);if(u.extraLine&&n.push(u.extraLine),n.push(` ${o} -->|${l}| ${u.targetId}`),a.onFalse){let g=Ks(a.onFalse,s,i);g.extraLine&&n.push(g.extraLine),n.push(` ${o} -->|${f}| ${g.targetId}`)}break}case"decision":{let a=c,d=ze(Hn(a.condition));n.push(` ${o}{${d}}`);let l=Gn(a.onTrue,s,i);if(l.extraLine&&n.push(l.extraLine),n.push(` ${o} -->|true| ${l.targetId}`),a.onFalse){let f=Gn(a.onFalse,s,i);f.extraLine&&n.push(f.extraLine),n.push(` ${o} -->|false| ${f.targetId}`)}break}case"switch":{let a=c,d=ze(Hn(a.expression));n.push(` ${o}{${d}}`);for(let l of a.cases){let f=l.isDefault?"default":l.labels.join(", "),u=Gn(l.body,s,i);u.extraLine&&n.push(u.extraLine),n.push(` ${o} -->|${f}| ${u.targetId}`)}break}case"match":{let a=c,d=ze(`Match.${a.matchOp}`);if(n.push(` ${o}{${d}}`),a.matchedTags&&a.matchedTags.length>0)for(let l of a.matchedTags){let f=`T${i.value++}`;n.push(` ${f}["${ze(l)}"]`),n.push(` ${o} -->|${ze(l)}| ${f}`)}else{let l=`T${i.value++}`;n.push(` ${l}["..."]`),n.push(` ${o} -->|match| ${l}`)}break}}return n.join(`
|
|
22
|
+
`)}import{Option as La}from"effect";function qs(e){return e.replace(/"/g,"#quot;").replace(/</g,"#lt;").replace(/>/g,"#gt;").replace(/\(/g,"#lpar;").replace(/\)/g,"#rpar;")}function Xt(e){return e.replace(/[^a-zA-Z0-9]/g,"_")}var Wa=new Set(["Effect.fail","Effect.die","Effect.interrupt"]);function Ka(e){if(e.type==="effect"){let t=e.typeSignature?.errorType??e.errorType;if(t&&t!=="never"&&t.trim()!=="")return t}}function Ba(e){return e==="Effect.die"?"die":e==="Effect.interrupt"?"interrupt":"fail"}function Jn(e){let t=[];if(e.type==="cause"&&e.isConstructor){let s=e.causeOp;if(s==="parallel"||s==="sequential"){let n=[],i=e.children??[];for(let c of i)n.push(...Jn(c));return t.push({id:Xt(e.id),kind:s,label:`Cause.${s}`,children:n}),t}if(s==="fail"||s==="die"||s==="interrupt")return t.push({id:Xt(e.id),kind:s,label:`Cause.${s}`,children:[]}),t}if(e.type==="exit"&&e.isConstructor){let s=e.exitOp;if(s==="fail"||s==="die"||s==="interrupt")return t.push({id:Xt(e.id),kind:s==="fail"?"fail":s==="die"?"die":"interrupt",label:`Exit.${s}`,children:[]}),t}if(e.type==="effect"&&Wa.has(e.callee)){let s=Ba(e.callee),n=Ka(e),i=ee(n?`${e.callee}: ${n}`:e.callee,X);return t.push({id:Xt(e.id),kind:s,label:i,children:[]}),t}let r=La.getOrElse(P(e),()=>[]);for(let s of r)t.push(...Jn(s));return t}function _s(e,t,r,s,n,i){let c=`N${i.value++}`,o=qs(e.label);if(e.kind==="parallel"||e.kind==="sequential"){if(s.push(` ${c}[${o}]`),n.set(c,"composite"),t){let d=r?` -->|${r}| `:" --> ";s.push(` ${t}${d}${c}`)}let a=e.kind==="parallel"?"parallel":"then";for(let d of e.children)_s(d,c,a,s,n,i)}else if(e.kind==="die"?(s.push(` ${c}[${o}]`),n.set(c,"die")):e.kind==="interrupt"?(s.push(` ${c}[${o}]`),n.set(c,"interrupt")):(s.push(` ${c}(${o})`),n.set(c,"fail")),t){let a=r?` -->|${r}| `:" --> ";s.push(` ${t}${a}${c}`)}}function Qn(e,t={}){let r=t.direction??"TB",s=[];for(let l of e.root.children)s.push(...Jn(l));if(s.length===0)return`flowchart ${r}
|
|
23
|
+
NoCauses((No failure causes))`;let n=[`flowchart ${r}`],i=new Map,c={value:0},o="Root",a=qs(e.root.programName);n.push(` ${o}((${a}))`);for(let l of s)_s(l,o,void 0,n,i,c);n.push(""),n.push(" classDef failStyle fill:#FFCDD2,stroke:#C62828"),n.push(" classDef dieStyle fill:#B71C1C,color:#fff"),n.push(" classDef interruptStyle fill:#FFE0B2,stroke:#E65100"),n.push(" classDef compositeStyle fill:#E3F2FD");let d={failStyle:[],dieStyle:[],interruptStyle:[],compositeStyle:[]};for(let[l,f]of i)f==="fail"?d.failStyle.push(l):f==="die"?d.dieStyle.push(l):f==="interrupt"?d.interruptStyle.push(l):d.compositeStyle.push(l);for(let[l,f]of Object.entries(d))f.length>0&&n.push(` class ${f.join(",")} ${l}`);return n.join(`
|
|
24
|
+
`)}import{Option as ja}from"effect";function Ue(e){return e.replace(/"/g,"#quot;").replace(/</g,"#lt;").replace(/>/g,"#gt;").replace(/\(/g,"#lpar;").replace(/\)/g,"#rpar;")}function He(e,t){return`${e}${t}`}function zs(e,t){let r=s=>ee(s,X);return e.displayName?r(e.displayName):e.name?r(e.name):e.type==="effect"?r(e.callee):`child_${t}`}function qa(e){return e.charAt(0).toUpperCase()+e.slice(1)}function _a(e){let t=[],r=s=>{switch(s.type){case"parallel":t.push({kind:"parallel",node:s});break;case"race":t.push({kind:"race",node:s});break;case"fiber":t.push({kind:"fiber",node:s});break;case"concurrency-primitive":t.push({kind:"primitive",node:s});break}let n=ja.getOrElse(P(s),()=>[]);for(let i of n)r(i)};for(let s of e)r(s);return t}function Zn(e,t={}){let r=t.direction??"TB",s=_a(e.root.children);if(s.length===0)return`flowchart ${r}
|
|
25
|
+
NoConcurrency((No concurrency))`;let n=[`flowchart ${r}`],i=[],c=0,o=[];for(let a of s)switch(a.kind){case"parallel":{let d=a.node,l=He("P",c++),f=d.children.length,u=d.mode==="parallel"?"parallel":"sequential",g=Ue(ee(`${d.callee} #lpar;${f} effects, ${u}#rpar;`,X));n.push(` ${l}[${g}]`),i.push(` style ${l} fill:#E3F2FD`);let p=He("PJ",c++);for(let m=0;m<d.children.length;m++){let y=d.children[m];if(!y)continue;let h=He("PC",c++),N=Ue(d.branchLabels?.[m]??zs(y,m)),x=d.branchLabels?.[m],F=x?Ue(x):void 0;n.push(` ${h}[${N}]`),F?n.push(` ${l} -->|${F}| ${h}`):n.push(` ${l} --> ${h}`),n.push(` ${h} --> ${p}`)}n.push(` ${p}([Join])`),i.push(` style ${p} fill:#E3F2FD`),o.push(l),o.push(p);break}case"race":{let d=a.node,l=He("R",c++);n.push(` ${l}{Race}`),i.push(` style ${l} fill:#FFF3E0`);let f=He("RW",c++);for(let u=0;u<d.children.length;u++){let g=d.children[u];if(!g)continue;let p=He("RC",c++),m=Ue(d.raceLabels?.[u]??zs(g,u));n.push(` ${p}[${m}]`),n.push(` ${l} -->|competes| ${p}`),n.push(` ${p} -.->|winner?| ${f}`)}n.push(` ${f}([First to complete])`),i.push(` style ${f} fill:#FFF3E0`),o.push(l),o.push(f);break}case"fiber":{let d=a.node,l=He("F",c++),f=d.operation;if(f==="fork"||f==="forkScoped"||f==="forkDaemon"||f==="forkAll"||f==="forkIn"||f==="forkWithErrorHandler"){let u=d.fiberSource?.displayName??d.fiberSource?.name??"effect",g=Ue(`${f}#lpar;${u}#rpar;`);n.push(` ${l}[${g}]`),f==="forkScoped"?i.push(` style ${l} fill:#C8E6C9`):f==="forkDaemon"?i.push(` style ${l} fill:#FFE0B2`):i.push(` style ${l} fill:#FFF9C4`)}else if(f==="join"||f==="await"){let u=Ue(f);n.push(` ${l}[${u}]`),i.push(` style ${l} fill:#BBDEFB`)}else{let u=Ue(`Fiber.${f}`);n.push(` ${l}[${u}]`),i.push(` style ${l} fill:#BBDEFB`)}o.push(l);break}case"primitive":{let d=a.node,l=He("CP",c++),f=qa(d.primitive),u=Ue(`${f}.${d.operation}`);n.push(` ${l}{{${u}}}`),i.push(` style ${l} fill:#F3E5F5`),o.push(l);break}}for(let a=0;a<o.length-1;a++){let d=o[a],l=o[a+1];!d||!l||n.push(` ${d} --> ${l}`)}return[...n,...i].join(`
|
|
26
|
+
`)}import{Option as Yn}from"effect";function za(e){let t=[],r=s=>{if(s.type==="parallel"){t.push({kind:"parallel",node:s});return}if(s.type==="retry"){t.push({kind:"retry",node:s}),r(s.source);return}if(s.type==="timeout"){t.push({kind:"timeout",node:s}),r(s.source);return}if(s.type==="effect"){let i=s.callee;if(i==="Effect.fn"||i.startsWith("Effect.fn(")||i.startsWith("Schema.")||i.startsWith("Data."))return;let c=s.displayName??"";if(!(c&&c!==i&&c!==s.type)&&(i.startsWith("Effect.")||i==="Effect"))return;s.serviceCall?t.push({kind:"service-call",node:s}):t.push({kind:"effect-constructor",node:s});return}let n=Yn.getOrElse(P(s),()=>[]);for(let i of n)r(i)};for(let s of e)r(s);return t}function Ua(e){let t=new Set,r=[],s=n=>{if(n.kind==="service-call"&&n.node.type==="effect"&&n.node.serviceCall){let i=n.node.serviceCall.serviceType;t.has(i)||(t.add(i),r.push(i))}else if(n.kind==="parallel"){let i=Yn.getOrElse(P(n.node),()=>[]);for(let c of i)if(c.type==="effect"&&c.serviceCall){let o=c.serviceCall.serviceType;t.has(o)||(t.add(o),r.push(o))}}};for(let n of e)s(n);return r}function Ha(e,t,r){let s=Yn.getOrElse(P(e),()=>[]);if(s.length!==0){t.push(`${r}par Parallel`);for(let n=0;n<s.length;n++){n>0&&t.push(`${r}and`);let i=s[n];if(i)if(i.type==="effect"&&i.serviceCall)t.push(`${r} Program->>${i.serviceCall.serviceType}: ${i.serviceCall.methodName}()`),t.push(`${r} ${i.serviceCall.serviceType}-->>Program: result`);else if(i.type==="effect")t.push(`${r} Note over Program: ${ee(i.callee,X)}`);else{let c=i.displayName??i.name??(typeof i.type=="string"?i.type:"node"),o=ee(c,X);t.push(`${r} Note over Program: ${o}`)}}t.push(`${r}end`)}}function Xn(e){let t=za(e.root.children);if(t.length===0)return`sequenceDiagram
|
|
27
27
|
participant Program
|
|
28
|
-
Note over Program: Empty program`;let r=
|
|
29
|
-
`)}import{Option as
|
|
30
|
-
NoLayers((No layers))`;let n=[`flowchart ${r}`],i=new Set;for(let o of s.layers){for(let a of o.provides)i.add(a);for(let a of o.requires)i.add(a)}let c=new Set;for(let o of s.layers){let a=o.name??o.id,d=o.lifecycle!=="default"?` (${o.lifecycle})`:"",l=
|
|
31
|
-
`)}import{Option as
|
|
32
|
-
NoRetry((No retry/timeout patterns))`;let n=[`flowchart ${r}`];for(let{node:i,index:c}of s){let o=`N${c}`,a=
|
|
33
|
-
`)}function
|
|
28
|
+
Note over Program: Empty program`;let r=Ua(t),s=["sequenceDiagram"];s.push(" participant Program");for(let n of r)s.push(` participant ${n}`);for(let n of t)switch(n.kind){case"service-call":{let i=n.node;if(i.type==="effect"&&i.serviceCall){let c=i.serviceCall.serviceType,o=i.serviceCall.methodName;s.push(` Program->>${c}: ${o}()`),s.push(` ${c}-->>Program: result`)}break}case"effect-constructor":{let i=n.node;i.type==="effect"&&s.push(` Note over Program: ${ee(i.callee,X)}`);break}case"retry":{let i=n.node;if(i.type==="retry"){let c=i.scheduleInfo;if(c){let o=c.maxRetries!==void 0?`${c.maxRetries}x`:"unlimited";s.push(` Note over Program: ${ee(`retry (${o}, ${c.baseStrategy})`,X)}`)}else i.schedule?s.push(` Note over Program: ${ee(`retry (${i.schedule})`,X)}`):s.push(" Note over Program: retry")}break}case"timeout":{let i=n.node;if(i.type==="timeout"){let c=i.duration??"unknown";s.push(` Note over Program: timeout(${c})`)}break}case"parallel":{Ha(n.node,s," ");break}}return s.join(`
|
|
29
|
+
`)}import{Option as Ga}from"effect";function Us(e,t){for(let r of e){if(r.type==="layer"){let n=r,i={id:n.id,provides:[...n.provides??[]],requires:[...n.requires??[]],lifecycle:n.lifecycle??"default",isMerged:n.isMerged,operationLayerIds:n.operations.filter(c=>c.type==="layer").map(c=>c.id)};n.name!==void 0&&(i.name=n.name),t.push(i)}let s=Ga.getOrElse(P(r),()=>[]);s.length>0&&Us(s,t)}}function Hs(e){let t=[];Us(e.root.children,t);let r=[],s=new Map;for(let n of t){for(let i of n.operationLayerIds)r.push({from:n.id,to:i,kind:"merge"});for(let i of n.provides){let c=s.get(i)??[];c.push(n.id),s.set(i,c),r.push({from:n.id,to:i,kind:"provides"})}for(let i of n.requires)r.push({from:n.id,to:i,kind:"requires"})}return{layers:t,edges:r,serviceToLayers:s}}function pt(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}function er(e,t={}){let r=t.direction??"TB",s=Hs(e);if(s.layers.length===0)return`flowchart ${r}
|
|
30
|
+
NoLayers((No layers))`;let n=[`flowchart ${r}`],i=new Set;for(let o of s.layers){for(let a of o.provides)i.add(a);for(let a of o.requires)i.add(a)}let c=new Set;for(let o of s.layers){let a=o.name??o.id,d=o.lifecycle!=="default"?` (${o.lifecycle})`:"",l=pt(o.id);n.push(` ${l}["${a}${d}"]`),o.isMerged&&c.add(l)}for(let o of i)n.push(` ${pt(o)}{{"${o}"}}`);for(let o of s.edges){let a=pt(o.from),d=pt(o.to);o.kind==="provides"?n.push(` ${a} -->|provides| ${d}`):o.kind==="requires"?n.push(` ${a} -.->|requires| ${d}`):n.push(` ${a} -->|merge| ${d}`)}n.push(""),n.push(" classDef layerStyle fill:#E8EAF6,stroke:#3F51B5"),n.push(" classDef serviceStyle fill:#E3F2FD,stroke:#1E88E5"),n.push(" classDef mergedStyle fill:#F3E5F5,stroke:#8E24AA");for(let o of s.layers){let a=pt(o.id);c.has(a)?n.push(` class ${a} mergedStyle`):n.push(` class ${a} layerStyle`)}for(let o of i)n.push(` class ${pt(o)} serviceStyle`);return n.join(`
|
|
31
|
+
`)}import{Option as Va}from"effect";function tr(e){return e.replace(/"/g,"#quot;").replace(/</g,"#lt;").replace(/>/g,"#gt;").replace(/\(/g,"#lpar;").replace(/\)/g,"#rpar;")}function Gs(e,t){for(let r of e){(r.type==="retry"||r.type==="timeout")&&t.push({node:r,index:t.length});let s=Va.getOrElse(P(r),()=>[]);s.length>0&&Gs(s,t)}}function Ja(e){if(e.type!=="retry")return"";let t=e.scheduleInfo;if(!t)return"retry";let r=[t.baseStrategy];return t.maxRetries!==void 0&&t.maxRetries!=="unlimited"&&r.push(`${t.maxRetries}x`),t.initialDelay&&r.push(t.initialDelay),t.maxDelay&&r.push(`max ${t.maxDelay}`),t.jittered&&r.push("+jitter"),r.join(" ")}function Qa(e){let t=e.source;return t===void 0?"Operation":t.displayName?t.displayName:t.name?t.name:"Operation"}function nr(e,t={}){let r=t.direction??"LR",s=[];if(Gs(e.root.children,s),s.length===0)return`flowchart ${r}
|
|
32
|
+
NoRetry((No retry/timeout patterns))`;let n=[`flowchart ${r}`];for(let{node:i,index:c}of s){let o=`N${c}`,a=tr(Qa(i));if(i.type==="retry"){let d=i,l=tr(Ja(i));n.push(` ${o}_Op[${a}] -->|fail| ${o}_R{Retry}`),n.push(` ${o}_R -->|"${l}"| ${o}_Op`),d.hasFallback?n.push(` ${o}_R -->|exhausted| ${o}_F[Fallback]`):n.push(` ${o}_R -->|exhausted| ${o}_Fail((Failure))`),n.push(` style ${o}_R fill:#9b59b6,stroke:#8e44ad,color:#fff`),d.hasFallback?n.push(` style ${o}_F fill:#2ecc71,stroke:#27ae60,color:#fff`):n.push(` style ${o}_Fail fill:#e74c3c,stroke:#c0392b,color:#fff`)}else if(i.type==="timeout"){let d=i,l=d.duration??"?",f=tr(`timeout: ${l}ms`);n.push(` ${o}_Op[${a}] -->|within| ${o}_T[${f}]`),d.hasFallback?n.push(` ${o}_T -->|exceeded| ${o}_F[Fallback]`):n.push(` ${o}_T -->|exceeded| ${o}_Fail((Timeout))`),n.push(` style ${o}_T fill:#e67e22,stroke:#d35400,color:#fff`),d.hasFallback?n.push(` style ${o}_F fill:#2ecc71,stroke:#27ae60,color:#fff`):n.push(` style ${o}_Fail fill:#e74c3c,stroke:#c0392b,color:#fff`)}}return n.join(`
|
|
33
|
+
`)}function rr(e,t={}){let r=t.direction??"LR",s=e.root.requiredServices??[],n=e.root.dependencies;if(s.length===0)return`flowchart ${r}
|
|
34
34
|
NoMocks((No services to mock - pure computation))`;let i=new Set(n.filter(l=>l.isLayer).map(l=>l.name)),c=[`flowchart ${r}`],o=[],a=[];for(let l=0;l<s.length;l++){let f=`S${l}`,u=s[l];u&&(c.push(` Prog[${e.root.programName}] -->|needs mock| ${f}{{"${u.serviceId}"}}`),i.has(u.serviceId)?a.push(f):o.push(f))}c.push(""),c.push(" classDef easy fill:#C8E6C9"),c.push(" classDef hard fill:#FFE0B2"),o.length>0&&c.push(` class ${o.join(",")} easy`),a.length>0&&c.push(` class ${a.join(",")} hard`);let d=s.length===1?"mock":"mocks";return c.push(""),c.push(` Note[Requires ${s.length} service ${d}]`),c.join(`
|
|
35
|
-
`)}import{Option as
|
|
36
|
-
NoData((No data transformations))`;let n=[`flowchart ${r}`],i=[],c=0;for(let o of s){let a=c;for(let d=0;d<o.length;d++){let l=o[d];if(!l)continue;let f=
|
|
37
|
-
`)}import{Option as Ja}from"effect";import{Option as Va}from"effect";import{Option as xt}from"effect";function Gt(e){let t=e.root.children,r=Ba(t),s=qa(t),n=_a(t),i=Ha(t),c=Ua(t),o=Ga(t);return{cyclomaticComplexity:r,cognitiveComplexity:s,pathCount:n,maxDepth:i,maxParallelBreadth:c,decisionPoints:o}}function Ba(e){let t=1;for(let r of e)t+=me(r);return t}function me(e){let t=P(e),r=xt.getOrElse(t,()=>[]),s=0;switch(e.type){case"conditional":s+=1;for(let n of r)s+=me(n);break;case"race":s+=Math.max(0,e.children.length-1);for(let n of e.children)s+=me(n);break;case"loop":s+=1,s+=me(e.body);break;case"generator":case"pipe":case"parallel":case"error-handler":case"retry":case"timeout":case"resource":case"layer":for(let n of r)s+=me(n);break;case"decision":s+=1;for(let n of r)s+=me(n);break;case"switch":s+=Math.max(0,e.cases.length-1);for(let n of r)s+=me(n);break;case"try-catch":s+=1;for(let n of r)s+=me(n);break;case"terminal":case"opaque":for(let n of r)s+=me(n);break;case"match":e.matchedTags&&e.matchedTags.length>1&&(s+=e.matchedTags.length-1);break;case"interruption":e.handler&&(s+=1,s+=me(e.handler)),e.source&&(s+=me(e.source));break;case"cause":if(e.children)for(let n of e.children)s+=me(n);break;case"transform":e.source&&(s+=me(e.source));break;case"channel":case"sink":e.source&&(s+=me(e.source));break;case"exit":case"schedule":case"effect":case"unknown":break}return s}function qa(e){return za(e,0)}function za(e,t){let r=0;for(let s of e)r+=ce(s,t);return r}function ce(e,t){let r=P(e),s=xt.getOrElse(r,()=>[]),n=0;switch(e.type){case"conditional":n+=1+t,n+=ce(e.onTrue,t+1),e.onFalse&&(n+=ce(e.onFalse,t+1));break;case"loop":n+=1+t,n+=ce(e.body,t+1);break;case"race":n+=e.children.length;for(let i of e.children)n+=ce(i,t+1);break;case"parallel":n+=Math.max(0,e.children.length-1);for(let i of e.children)n+=ce(i,t);break;case"generator":case"pipe":case"error-handler":case"retry":case"timeout":case"resource":case"layer":for(let i of s)n+=ce(i,t);break;case"decision":n+=1+t;for(let i of e.onTrue)n+=ce(i,t+1);if(e.onFalse)for(let i of e.onFalse)n+=ce(i,t+1);break;case"switch":n+=1+t;for(let i of e.cases)for(let c of i.body)n+=ce(c,t+1);break;case"try-catch":n+=1+t;for(let i of s)n+=ce(i,t+1);break;case"terminal":if(e.value)for(let i of e.value)n+=ce(i,t);break;case"opaque":break;case"match":e.matchedTags&&e.matchedTags.length>0&&(n+=1+t);break;case"interruption":e.handler&&(n+=1+t,n+=ce(e.handler,t+1)),e.source&&(n+=ce(e.source,t));break;case"cause":if(e.children)for(let i of e.children)n+=ce(i,t);break;case"transform":e.source&&(n+=ce(e.source,t));break;case"channel":case"sink":e.source&&(n+=ce(e.source,t));break;case"exit":case"schedule":case"effect":case"unknown":break}return n}function _a(e){let t=1,r=!1;for(let s of e){let n=Ut(s);n==="unbounded"?r=!0:t*=n}return r?"unbounded":t}function Ut(e){let t=P(e),r=xt.getOrElse(t,()=>[]);switch(e.type){case"conditional":{let s=Je([e.onTrue]),n=e.onFalse?Je([e.onFalse]):1;return s==="unbounded"||n==="unbounded"?"unbounded":s+n}case"race":{let s=0;for(let n of e.children){let i=Ut(n);if(i==="unbounded")return"unbounded";s+=i}return Math.max(1,s)}case"parallel":{let s=1;for(let n of e.children){let i=Ut(n);if(i==="unbounded")return"unbounded";s*=i}return s}case"loop":return"unbounded";case"generator":case"pipe":case"error-handler":case"retry":case"timeout":case"resource":case"layer":return Je(r);case"effect":case"unknown":case"opaque":return 1;case"decision":{let s=Je([...e.onTrue]),n=e.onFalse?Je([...e.onFalse]):1;return s==="unbounded"||n==="unbounded"?"unbounded":s+n}case"switch":{let s=0;for(let n of e.cases){let i=Je([...n.body]);if(i==="unbounded")return"unbounded";s+=i}return Math.max(1,s)}case"try-catch":case"terminal":case"stream":case"concurrency-primitive":case"fiber":case"interruption":case"transform":case"match":case"cause":case"exit":case"schedule":case"channel":case"sink":return Je(r)}}function Je(e){let t=1;for(let r of e){let s=Ut(r);if(s==="unbounded")return"unbounded";t*=s}return t}function Ha(e){let t=0;for(let r of e)t=Math.max(t,ue(r,0));return t}function ue(e,t){let r=P(e),s=xt.getOrElse(r,()=>[]),n=t;switch(e.type){case"conditional":n=Math.max(n,ue(e.onTrue,t+1)),e.onFalse&&(n=Math.max(n,ue(e.onFalse,t+1)));break;case"loop":n=Math.max(n,ue(e.body,t+1));break;case"parallel":case"race":for(let i of e.children)n=Math.max(n,ue(i,t+1));break;case"generator":case"pipe":case"error-handler":case"retry":case"timeout":case"resource":case"layer":for(let i of s)n=Math.max(n,ue(i,t));break;case"decision":for(let i of e.onTrue)n=Math.max(n,ue(i,t+1));if(e.onFalse)for(let i of e.onFalse)n=Math.max(n,ue(i,t+1));break;case"switch":for(let i of e.cases)for(let c of i.body)n=Math.max(n,ue(c,t+1));break;case"try-catch":for(let i of s)n=Math.max(n,ue(i,t+1));break;case"terminal":if(e.value)for(let i of e.value)n=Math.max(n,ue(i,t));break;case"opaque":break;case"match":break;case"interruption":e.source&&(n=Math.max(n,ue(e.source,t+1))),e.handler&&(n=Math.max(n,ue(e.handler,t+1)));break;case"cause":if(e.children)for(let i of e.children)n=Math.max(n,ue(i,t));break;case"transform":e.source&&(n=Math.max(n,ue(e.source,t)));break;case"channel":case"sink":e.source&&(n=Math.max(n,ue(e.source,t)));break;case"exit":case"schedule":case"effect":case"unknown":break}return n}function Ua(e){let t=0;for(let r of e)t=Math.max(t,fe(r));return t}function fe(e){let t=P(e),r=xt.getOrElse(t,()=>[]),s=0;switch(e.type){case"parallel":case"race":s=e.children.length;for(let n of e.children)s=Math.max(s,fe(n));break;case"conditional":s=Math.max(fe(e.onTrue),e.onFalse?fe(e.onFalse):0);break;case"loop":s=fe(e.body);break;case"generator":case"pipe":case"error-handler":case"retry":case"timeout":case"resource":case"layer":for(let n of r)s=Math.max(s,fe(n));break;case"decision":for(let n of e.onTrue)s=Math.max(s,fe(n));if(e.onFalse)for(let n of e.onFalse)s=Math.max(s,fe(n));break;case"switch":for(let n of e.cases)for(let i of n.body)s=Math.max(s,fe(i));break;case"try-catch":for(let n of r)s=Math.max(s,fe(n));break;case"terminal":if(e.value)for(let n of e.value)s=Math.max(s,fe(n));break;case"opaque":break;case"interruption":e.source&&(s=Math.max(s,fe(e.source))),e.handler&&(s=Math.max(s,fe(e.handler)));break;case"cause":if(e.children)for(let n of e.children)s=Math.max(s,fe(n));break;case"transform":e.source&&(s=Math.max(s,fe(e.source)));break;case"channel":case"sink":e.source&&(s=Math.max(s,fe(e.source)));break;case"match":case"exit":case"schedule":case"effect":case"unknown":break}return s}function Ga(e){let t=0;for(let r of e)t+=me(r);return t}function _s(e){let t=e.root.children;if(Qe(t,"parallel")||Qe(t,"race")||Qe(t,"switch")||Qe(t,"loop")||Qe(t,"conditional")||Qe(t,"decision"))return"mermaid";let r=e.metadata.stats;if(r.decisionCount>2||r.switchCount>0||r.conditionalCount>2)return"mermaid";let s=Gt(e);return s.cyclomaticComplexity<=3&&s.decisionPoints<=1&&s.maxDepth<=2?"railway":"mermaid"}function Qe(e,t){for(let r of e){if(r.type===t)return!0;let s=Va.getOrElse(P(r),()=>[]);if(s.length>0&&Qe(s,t))return!0}return!1}function Hs(e){return e.type==="cause"||e.type==="exit"||e.type==="effect"&&(e.callee==="Effect.cause"||e.callee==="Effect.exit")?!0:Ja.getOrElse(P(e),()=>[]).some(Hs)}function Us(e){let t=e.metadata.stats,r=e.root,n=[{format:"mermaid-services",score:r.dependencies.length*2+(r.requiredServices?.length??0)},{format:"mermaid-concurrency",score:t.parallelCount*3+t.raceCount*3},{format:"mermaid-errors",score:r.errorTypes.length>0?r.errorTypes.length*2+t.errorHandlerCount*2:0},{format:"mermaid-retry",score:t.retryCount*4+t.timeoutCount*3},{format:"mermaid-decisions",score:t.conditionalCount+t.decisionCount+t.switchCount},{format:"mermaid-layers",score:t.layerCount*3},{format:"mermaid-dataflow",score:r.source==="pipe"?5:0},{format:"mermaid-causes",score:r.children.some(Hs)?4:0},{format:"mermaid-timeline",score:r.dependencies.length>2?3:0},{format:"mermaid-testability",score:(r.requiredServices?.length??0)*2}].filter(c=>c.score>0).sort((c,o)=>o.score-c.score).slice(0,2).map(c=>c.format);return[_s(e)==="railway"?"mermaid-railway":"mermaid",...n]}import{Option as Vs}from"effect";var Js=new Set(["parallel","race","conditional","decision","switch","loop","error-handler","retry","generator","pipe","stream","fiber"]);function Zn(e,t="root",r=0){let s=[];e.type==="effect"&&s.push({stepId:e.id,callee:e.callee,containerType:t,index:r});let n=Vs.getOrElse(P(e),()=>[]),i=Js.has(e.type)?e.type:t,c=0;for(let o of n){let a=Zn(o,i,c);s.push(...a),c++}return s}function Gs(e){let t=new Map;function r(s){Js.has(s.type)&&t.set(s.type,(t.get(s.type)??0)+1);let n=Vs.getOrElse(P(s),()=>[]);for(let i of n)r(i)}return r(e),t}function Yn(e,t,r){let s=r?.detectRenames??!0,n=r?.regressionMode??!1,i=Zn(e.root),c=Zn(t.root),o=new Map;for(let y of i)o.set(y.stepId,y);let a=new Map;for(let y of c)a.set(y.stepId,y);let d=new Set,l=new Set,f=[];for(let y of c){let N=o.get(y.stepId);N&&(d.add(N.stepId),l.add(y.stepId),N.containerType!==y.containerType?f.push({kind:"moved",stepId:y.stepId,callee:y.callee,containerBefore:N.containerType,containerAfter:y.containerType}):f.push({kind:"unchanged",stepId:y.stepId,callee:y.callee}))}if(s){let y=i.filter(E=>!d.has(E.stepId)),N=c.filter(E=>!l.has(E.stepId));for(let E of N){let $=y.find(S=>!d.has(S.stepId)&&S.callee===E.callee&&S.index===E.index);$&&(d.add($.stepId),l.add(E.stepId),f.push({kind:"renamed",stepId:E.stepId,previousStepId:$.stepId,callee:E.callee}))}}for(let y of i)d.has(y.stepId)||f.push({kind:"removed",stepId:y.stepId,callee:y.callee});for(let y of c)l.has(y.stepId)||f.push({kind:"added",stepId:y.stepId,callee:y.callee});let u=[],g=Gs(e.root),p=Gs(t.root),m=new Set([...g.keys(),...p.keys()]);for(let y of m){let N=g.get(y)??0,E=p.get(y)??0;if(E>N)for(let $=0;$<E-N;$++)u.push({kind:"added",nodeType:y,description:`${y} block added`});else if(N>E)for(let $=0;$<N-E;$++)u.push({kind:"removed",nodeType:y,description:`${y} block removed`})}let h={stepsAdded:f.filter(y=>y.kind==="added").length,stepsRemoved:f.filter(y=>y.kind==="removed").length,stepsRenamed:f.filter(y=>y.kind==="renamed").length,stepsMoved:f.filter(y=>y.kind==="moved").length,stepsUnchanged:f.filter(y=>y.kind==="unchanged").length,structuralChanges:u.length,hasRegressions:n?f.some(y=>y.kind==="removed")||u.some(y=>y.kind==="removed"):!1};return{beforeName:e.root.programName,afterName:t.root.programName,diffedAt:Date.now(),steps:f,structuralChanges:u,summary:h}}var Qa={added:"+",removed:"-",unchanged:" ",renamed:"~",moved:">"};function Za(e){let t=Qa[e.kind]??"?",r=e.callee??e.stepId;switch(e.kind){case"renamed":return`${t} **${r}** (renamed from \`${e.previousStepId}\` \u2192 \`${e.stepId}\`)`;case"moved":return`${t} **${r}** (moved from \`${e.containerBefore}\` \u2192 \`${e.containerAfter}\`)`;case"added":return`${t} **${r}** (added, id: \`${e.stepId}\`)`;case"removed":return`${t} **${r}** (removed, id: \`${e.stepId}\`)`;default:return`${t} ${r}`}}function Xn(e,t){let r=t?.showUnchanged??!1,s=t?.title??`Effect Program Diff: ${e.beforeName} \u2192 ${e.afterName}`,n=[];n.push(`# ${s}`),n.push(""),n.push("## Summary"),n.push(""),n.push("| Metric | Count |"),n.push("|--------|-------|"),n.push(`| Added | ${e.summary.stepsAdded} |`),n.push(`| Removed | ${e.summary.stepsRemoved} |`),n.push(`| Renamed | ${e.summary.stepsRenamed} |`),n.push(`| Moved | ${e.summary.stepsMoved} |`),n.push(`| Unchanged | ${e.summary.stepsUnchanged} |`),n.push(`| Structural changes | ${e.summary.structuralChanges} |`),e.summary.hasRegressions&&n.push("| **Regressions** | **Yes** |"),n.push("");let i=r?e.steps:e.steps.filter(c=>c.kind!=="unchanged");if(i.length>0){n.push("## Step Changes"),n.push(""),n.push("```diff");for(let c of i)n.push(Za(c));n.push("```"),n.push("")}if(e.structuralChanges.length>0){n.push("## Structural Changes"),n.push("");for(let c of e.structuralChanges){let o=c.kind==="added"?"+":"-";n.push(`- ${o} ${c.description}`)}n.push("")}return n.join(`
|
|
38
|
-
`)}function
|
|
39
|
-
`),g=[];for(let p of u){let m=/^\s*(n\d+)\["([^"]*)"\]/.exec(p);if(!m)continue;let
|
|
35
|
+
`)}import{Option as Js}from"effect";function Vs(e){return`S${e}`}function en(e){return e.replace(/"/g,"#quot;").replace(/</g,"#lt;").replace(/>/g,"#gt;").replace(/\(/g,"#lpar;").replace(/\)/g,"#rpar;")}function Qs(e){let t=[];if(e.type==="pipe"){let s=e,n=[],i=s.typeFlow?.[0]??("typeSignature"in s.initial?s.initial.typeSignature:void 0);i&&n.push({successType:i.successType,errorType:i.errorType,isEffectful:!1});for(let c=0;c<s.transformations.length;c++){let o=s.transformations[c];if(!o)continue;let a=o.type==="transform"?o.transformType:o.name??o.type,d=o.type==="transform"?o.isEffectful:!1,l=s.typeFlow?.[c+1]??(o.type==="transform"?o.outputType:void 0);l?n.push({successType:l.successType,errorType:l.errorType,transformLabel:a,isEffectful:d}):n.push({successType:"unknown",errorType:"unknown",transformLabel:a,isEffectful:d})}n.length>0&&t.push(n)}let r=Js.getOrElse(P(e),()=>[]);for(let s of r)t.push(...Qs(s));return t}function Zs(e){let t=[];if(e.type==="generator"){let s=e,n=[];for(let i of s.yields){let c="typeSignature"in i.effect?i.effect.typeSignature:void 0;c?n.push({successType:c.successType,errorType:c.errorType,transformLabel:i.variableName??i.effect.name,isEffectful:!0}):n.push({successType:"unknown",errorType:"unknown",transformLabel:i.variableName??i.effect.name,isEffectful:!0})}n.length>0&&t.push(n)}let r=Js.getOrElse(P(e),()=>[]);for(let s of r)t.push(...Zs(s));return t}function sr(e,t={}){let r=t.direction??"LR",s=[];for(let o of e.root.children)s.push(...Qs(o)),s.push(...Zs(o));if(s.length===0)return`flowchart ${r}
|
|
36
|
+
NoData((No data transformations))`;let n=[`flowchart ${r}`],i=[],c=0;for(let o of s){let a=c;for(let d=0;d<o.length;d++){let l=o[d];if(!l)continue;let f=Vs(a+d),u=en(l.successType);if(l.successType==="unknown"?i.push(` style ${f} fill:#EEEEEE`):i.push(` style ${f} fill:#E8F5E9`),d<o.length-1){let g=o[d+1];if(!g)continue;let p=Vs(a+d+1),m=en(g.successType),y=g.transformLabel??"",h=l.errorType,N=g.errorType;N!==h&&N!=="never"&&N!=="unknown"&&(y=y?`${y}<br/>E: ${en(N)}`:`E: ${en(N)}`);let x=g.isEffectful?"==>":"-->";d===0?n.push(` ${f}["${u}"] ${x}|${y}| ${p}["${m}"]`):n.push(` ${f} ${x}|${y}| ${p}["${m}"]`)}else d===0&&n.push(` ${f}["${u}"]`)}c+=o.length}return[...n,...i].join(`
|
|
37
|
+
`)}import{Option as ic}from"effect";import{Option as sc}from"effect";import{Option as kt}from"effect";function nn(e){let t=e.root.children,r=Za(t),s=Ya(t),n=ec(t),i=tc(t),c=nc(t),o=rc(t);return{cyclomaticComplexity:r,cognitiveComplexity:s,pathCount:n,maxDepth:i,maxParallelBreadth:c,decisionPoints:o}}function Za(e){let t=1;for(let r of e)t+=me(r);return t}function me(e){let t=P(e),r=kt.getOrElse(t,()=>[]),s=0;switch(e.type){case"conditional":s+=1;for(let n of r)s+=me(n);break;case"race":s+=Math.max(0,e.children.length-1);for(let n of e.children)s+=me(n);break;case"loop":s+=1,s+=me(e.body);break;case"generator":case"pipe":case"parallel":case"error-handler":case"retry":case"timeout":case"resource":case"layer":for(let n of r)s+=me(n);break;case"decision":s+=1;for(let n of r)s+=me(n);break;case"switch":s+=Math.max(0,e.cases.length-1);for(let n of r)s+=me(n);break;case"try-catch":s+=1;for(let n of r)s+=me(n);break;case"terminal":case"opaque":for(let n of r)s+=me(n);break;case"match":e.matchedTags&&e.matchedTags.length>1&&(s+=e.matchedTags.length-1);break;case"interruption":e.handler&&(s+=1,s+=me(e.handler)),e.source&&(s+=me(e.source));break;case"cause":if(e.children)for(let n of e.children)s+=me(n);break;case"transform":e.source&&(s+=me(e.source));break;case"channel":case"sink":e.source&&(s+=me(e.source));break;case"exit":case"schedule":case"effect":case"unknown":break}return s}function Ya(e){return Xa(e,0)}function Xa(e,t){let r=0;for(let s of e)r+=de(s,t);return r}function de(e,t){let r=P(e),s=kt.getOrElse(r,()=>[]),n=0;switch(e.type){case"conditional":n+=1+t,n+=de(e.onTrue,t+1),e.onFalse&&(n+=de(e.onFalse,t+1));break;case"loop":n+=1+t,n+=de(e.body,t+1);break;case"race":n+=e.children.length;for(let i of e.children)n+=de(i,t+1);break;case"parallel":n+=Math.max(0,e.children.length-1);for(let i of e.children)n+=de(i,t);break;case"generator":case"pipe":case"error-handler":case"retry":case"timeout":case"resource":case"layer":for(let i of s)n+=de(i,t);break;case"decision":n+=1+t;for(let i of e.onTrue)n+=de(i,t+1);if(e.onFalse)for(let i of e.onFalse)n+=de(i,t+1);break;case"switch":n+=1+t;for(let i of e.cases)for(let c of i.body)n+=de(c,t+1);break;case"try-catch":n+=1+t;for(let i of s)n+=de(i,t+1);break;case"terminal":if(e.value)for(let i of e.value)n+=de(i,t);break;case"opaque":break;case"match":e.matchedTags&&e.matchedTags.length>0&&(n+=1+t);break;case"interruption":e.handler&&(n+=1+t,n+=de(e.handler,t+1)),e.source&&(n+=de(e.source,t));break;case"cause":if(e.children)for(let i of e.children)n+=de(i,t);break;case"transform":e.source&&(n+=de(e.source,t));break;case"channel":case"sink":e.source&&(n+=de(e.source,t));break;case"exit":case"schedule":case"effect":case"unknown":break}return n}function ec(e){let t=1,r=!1;for(let s of e){let n=tn(s);n==="unbounded"?r=!0:t*=n}return r?"unbounded":t}function tn(e){let t=P(e),r=kt.getOrElse(t,()=>[]);switch(e.type){case"conditional":{let s=rt([e.onTrue]),n=e.onFalse?rt([e.onFalse]):1;return s==="unbounded"||n==="unbounded"?"unbounded":s+n}case"race":{let s=0;for(let n of e.children){let i=tn(n);if(i==="unbounded")return"unbounded";s+=i}return Math.max(1,s)}case"parallel":{let s=1;for(let n of e.children){let i=tn(n);if(i==="unbounded")return"unbounded";s*=i}return s}case"loop":return"unbounded";case"generator":case"pipe":case"error-handler":case"retry":case"timeout":case"resource":case"layer":return rt(r);case"effect":case"unknown":case"opaque":return 1;case"decision":{let s=rt([...e.onTrue]),n=e.onFalse?rt([...e.onFalse]):1;return s==="unbounded"||n==="unbounded"?"unbounded":s+n}case"switch":{let s=0;for(let n of e.cases){let i=rt([...n.body]);if(i==="unbounded")return"unbounded";s+=i}return Math.max(1,s)}case"try-catch":case"terminal":case"stream":case"concurrency-primitive":case"fiber":case"interruption":case"transform":case"match":case"cause":case"exit":case"schedule":case"channel":case"sink":return rt(r)}}function rt(e){let t=1;for(let r of e){let s=tn(r);if(s==="unbounded")return"unbounded";t*=s}return t}function tc(e){let t=0;for(let r of e)t=Math.max(t,fe(r,0));return t}function fe(e,t){let r=P(e),s=kt.getOrElse(r,()=>[]),n=t;switch(e.type){case"conditional":n=Math.max(n,fe(e.onTrue,t+1)),e.onFalse&&(n=Math.max(n,fe(e.onFalse,t+1)));break;case"loop":n=Math.max(n,fe(e.body,t+1));break;case"parallel":case"race":for(let i of e.children)n=Math.max(n,fe(i,t+1));break;case"generator":case"pipe":case"error-handler":case"retry":case"timeout":case"resource":case"layer":for(let i of s)n=Math.max(n,fe(i,t));break;case"decision":for(let i of e.onTrue)n=Math.max(n,fe(i,t+1));if(e.onFalse)for(let i of e.onFalse)n=Math.max(n,fe(i,t+1));break;case"switch":for(let i of e.cases)for(let c of i.body)n=Math.max(n,fe(c,t+1));break;case"try-catch":for(let i of s)n=Math.max(n,fe(i,t+1));break;case"terminal":if(e.value)for(let i of e.value)n=Math.max(n,fe(i,t));break;case"opaque":break;case"match":break;case"interruption":e.source&&(n=Math.max(n,fe(e.source,t+1))),e.handler&&(n=Math.max(n,fe(e.handler,t+1)));break;case"cause":if(e.children)for(let i of e.children)n=Math.max(n,fe(i,t));break;case"transform":e.source&&(n=Math.max(n,fe(e.source,t)));break;case"channel":case"sink":e.source&&(n=Math.max(n,fe(e.source,t)));break;case"exit":case"schedule":case"effect":case"unknown":break}return n}function nc(e){let t=0;for(let r of e)t=Math.max(t,pe(r));return t}function pe(e){let t=P(e),r=kt.getOrElse(t,()=>[]),s=0;switch(e.type){case"parallel":case"race":s=e.children.length;for(let n of e.children)s=Math.max(s,pe(n));break;case"conditional":s=Math.max(pe(e.onTrue),e.onFalse?pe(e.onFalse):0);break;case"loop":s=pe(e.body);break;case"generator":case"pipe":case"error-handler":case"retry":case"timeout":case"resource":case"layer":for(let n of r)s=Math.max(s,pe(n));break;case"decision":for(let n of e.onTrue)s=Math.max(s,pe(n));if(e.onFalse)for(let n of e.onFalse)s=Math.max(s,pe(n));break;case"switch":for(let n of e.cases)for(let i of n.body)s=Math.max(s,pe(i));break;case"try-catch":for(let n of r)s=Math.max(s,pe(n));break;case"terminal":if(e.value)for(let n of e.value)s=Math.max(s,pe(n));break;case"opaque":break;case"interruption":e.source&&(s=Math.max(s,pe(e.source))),e.handler&&(s=Math.max(s,pe(e.handler)));break;case"cause":if(e.children)for(let n of e.children)s=Math.max(s,pe(n));break;case"transform":e.source&&(s=Math.max(s,pe(e.source)));break;case"channel":case"sink":e.source&&(s=Math.max(s,pe(e.source)));break;case"match":case"exit":case"schedule":case"effect":case"unknown":break}return s}function rc(e){let t=0;for(let r of e)t+=me(r);return t}function Ys(e){let t=e.root.children;if(st(t,"parallel")||st(t,"race")||st(t,"switch")||st(t,"loop")||st(t,"conditional")||st(t,"decision"))return"mermaid";let r=e.metadata.stats;if(r.decisionCount>2||r.switchCount>0||r.conditionalCount>2)return"mermaid";let s=nn(e);return s.cyclomaticComplexity<=3&&s.decisionPoints<=1&&s.maxDepth<=2?"railway":"mermaid"}function st(e,t){for(let r of e){if(r.type===t)return!0;let s=sc.getOrElse(P(r),()=>[]);if(s.length>0&&st(s,t))return!0}return!1}function Xs(e){return e.type==="cause"||e.type==="exit"||e.type==="effect"&&(e.callee==="Effect.cause"||e.callee==="Effect.exit")?!0:ic.getOrElse(P(e),()=>[]).some(Xs)}function ei(e){let t=e.metadata.stats,r=e.root,n=[{format:"mermaid-services",score:r.dependencies.length*2+(r.requiredServices?.length??0)},{format:"mermaid-concurrency",score:t.parallelCount*3+t.raceCount*3},{format:"mermaid-errors",score:r.errorTypes.length>0?r.errorTypes.length*2+t.errorHandlerCount*2:0},{format:"mermaid-retry",score:t.retryCount*4+t.timeoutCount*3},{format:"mermaid-decisions",score:t.conditionalCount+t.decisionCount+t.switchCount},{format:"mermaid-layers",score:t.layerCount*3},{format:"mermaid-dataflow",score:r.source==="pipe"?5:0},{format:"mermaid-causes",score:r.children.some(Xs)?4:0},{format:"mermaid-timeline",score:r.dependencies.length>2?3:0},{format:"mermaid-testability",score:(r.requiredServices?.length??0)*2}].filter(c=>c.score>0).sort((c,o)=>o.score-c.score).slice(0,2).map(c=>c.format);return[Ys(e)==="railway"?"mermaid-railway":"mermaid",...n]}import{Option as ni}from"effect";var ri=new Set(["parallel","race","conditional","decision","switch","loop","error-handler","retry","generator","pipe","stream","fiber"]);function oc(e){return e.type==="effect"?e.displayName??e.callee:`${e.type}:${e.displayName??e.id}`}function ir(e,t="root",r=0){let s=[];e.type==="effect"&&s.push({stepId:e.id,callee:e.callee,containerType:t,index:r,fingerprint:oc(e)});let n=ni.getOrElse(P(e),()=>[]),i=ri.has(e.type)?e.type:t,c=0;for(let o of n){let a=ir(o,i,c);s.push(...a),c++}return s}function ti(e){let t=new Map;function r(s){ri.has(s.type)&&t.set(s.type,(t.get(s.type)??0)+1);let n=ni.getOrElse(P(s),()=>[]);for(let i of n)r(i)}return r(e),t}function or(e,t,r){let s=r?.detectRenames??!0,n=r?.regressionMode??!1,i=ir(e.root),c=ir(t.root),o=new Set,a=new Set,d=[];function l(y){for(let h=0;h<i.length;h++){if(o.has(h))continue;let N=i[h];if(!N)continue;let x=[];for(let C=0;C<c.length;C++)if(!a.has(C)&&c[C]?.fingerprint===N.fingerprint){if(y&&c[C].containerType!==N.containerType)continue;x.push(C)}if(x.length===0)continue;let F=x[0],E=Math.abs(c[F].index-N.index);for(let C=1;C<x.length;C++){let k=x[C],S=Math.abs(c[k].index-N.index);S<E&&(F=k,E=S)}let b=c[F];o.add(h),a.add(F),N.containerType!==b.containerType?d.push({kind:"moved",stepId:b.stepId,callee:b.callee,containerBefore:N.containerType,containerAfter:b.containerType}):d.push({kind:"unchanged",stepId:b.stepId,callee:b.callee})}}if(l(!0),l(!1),s)for(let y=0;y<c.length;y++){if(a.has(y))continue;let h=c[y];if(!h)continue;let N=i.findIndex((x,F)=>!o.has(F)&&x.callee===h.callee);if(N>=0){let x=i[N];if(!x)continue;o.add(N),a.add(y),d.push({kind:"renamed",stepId:h.stepId,previousStepId:x.stepId,callee:h.callee})}}for(let y=0;y<i.length;y++)if(!o.has(y)){let h=i[y];if(!h)continue;d.push({kind:"removed",stepId:h.stepId,callee:h.callee})}for(let y=0;y<c.length;y++)if(!a.has(y)){let h=c[y];if(!h)continue;d.push({kind:"added",stepId:h.stepId,callee:h.callee})}let f=[],u=ti(e.root),g=ti(t.root),p=new Set([...u.keys(),...g.keys()]);for(let y of p){let h=u.get(y)??0,N=g.get(y)??0;if(N>h)for(let x=0;x<N-h;x++)f.push({kind:"added",nodeType:y,description:`${y} block added`});else if(h>N)for(let x=0;x<h-N;x++)f.push({kind:"removed",nodeType:y,description:`${y} block removed`})}let m={stepsAdded:d.filter(y=>y.kind==="added").length,stepsRemoved:d.filter(y=>y.kind==="removed").length,stepsRenamed:d.filter(y=>y.kind==="renamed").length,stepsMoved:d.filter(y=>y.kind==="moved").length,stepsUnchanged:d.filter(y=>y.kind==="unchanged").length,structuralChanges:f.length,hasRegressions:n?d.some(y=>y.kind==="removed")||f.some(y=>y.kind==="removed"):!1};return{beforeName:e.root.programName,afterName:t.root.programName,diffedAt:Date.now(),steps:d,structuralChanges:f,summary:m}}var ac={added:"+",removed:"-",unchanged:" ",renamed:"~",moved:">"};function cc(e){let t=ac[e.kind]??"?",r=e.callee??e.stepId;switch(e.kind){case"renamed":return`${t} **${r}** (renamed from \`${e.previousStepId}\` \u2192 \`${e.stepId}\`)`;case"moved":return`${t} **${r}** (moved from \`${e.containerBefore}\` \u2192 \`${e.containerAfter}\`)`;case"added":return`${t} **${r}** (added, id: \`${e.stepId}\`)`;case"removed":return`${t} **${r}** (removed, id: \`${e.stepId}\`)`;default:return`${t} ${r}`}}function ar(e,t){let r=t?.showUnchanged??!1,s=t?.title??`Effect Program Diff: ${e.beforeName} \u2192 ${e.afterName}`,n=[];n.push(`# ${s}`),n.push(""),n.push("## Summary"),n.push(""),n.push("| Metric | Count |"),n.push("|--------|-------|"),n.push(`| Added | ${e.summary.stepsAdded} |`),n.push(`| Removed | ${e.summary.stepsRemoved} |`),n.push(`| Renamed | ${e.summary.stepsRenamed} |`),n.push(`| Moved | ${e.summary.stepsMoved} |`),n.push(`| Unchanged | ${e.summary.stepsUnchanged} |`),n.push(`| Structural changes | ${e.summary.structuralChanges} |`),e.summary.hasRegressions&&n.push("| **Regressions** | **Yes** |"),n.push("");let i=r?e.steps:e.steps.filter(c=>c.kind!=="unchanged");if(i.length>0){n.push("## Step Changes"),n.push(""),n.push("```diff");for(let c of i)n.push(cc(c));n.push("```"),n.push("")}if(e.structuralChanges.length>0){n.push("## Structural Changes"),n.push("");for(let c of e.structuralChanges){let o=c.kind==="added"?"+":"-";n.push(`- ${o} ${c.description}`)}n.push("")}return n.join(`
|
|
38
|
+
`)}function cr(e,t){return t?.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e)}function lc(e){let t=new Map,r=/^\s*(n\d+)\["[^"]*"\]/gm,s;for(;(s=r.exec(e))!==null;){let n=s[1]??"";t.set(n,n)}return t}function lr(e,t,r){let s=r?.direction??"TB",n=r?.showRemovedSteps??!1,i=nt(e,{direction:s}),c=lc(i),o=new Set(t.steps.filter(p=>p.kind==="added").map(p=>p.stepId)),a=new Set(t.steps.filter(p=>p.kind==="removed").map(p=>p.stepId)),d=new Set(t.steps.filter(p=>p.kind==="moved").map(p=>p.stepId)),l=new Set(t.steps.filter(p=>p.kind==="renamed").map(p=>p.stepId)),f=new Map,u=i.split(`
|
|
39
|
+
`),g=[];for(let p of u){let m=/^\s*(n\d+)\["([^"]*)"\]/.exec(p);if(!m)continue;let y=m[1]??"",h=m[2]??"";for(let N of t.steps)if(N.callee&&h.includes(N.callee)){f.set(N.stepId,y);break}}for(let[p,m]of f)o.has(p)?g.push(` style ${m} fill:#d4edda,stroke:#28a745,stroke-width:2px`):d.has(p)?g.push(` style ${m} fill:#fff3cd,stroke:#ffc107,stroke-width:2px`):l.has(p)&&g.push(` style ${m} fill:#cce5ff,stroke:#007bff,stroke-width:2px`);if(n){for(let p of t.steps)if(p.kind==="removed"){let m=`removed_${p.stepId.replace(/[^a-zA-Z0-9]/g,"_")}`;g.push(` ${m}["\u274C ${p.callee??p.stepId}"]`),g.push(` style ${m} fill:#f8d7da,stroke:#dc3545,stroke-width:2px,stroke-dasharray: 5 5`)}}return g.length===0?i:i.trimEnd()+`
|
|
40
40
|
`+g.join(`
|
|
41
41
|
`)+`
|
|
42
|
-
`}import{execSync as Qs}from"child_process";function Et(e){if(/^https?:\/\/github\.com\/.+\/pull\/\d+/.test(e))return{kind:"github-pr",prUrl:e};let t=/^([^:]+):(.+)$/.exec(e);return t?.[1]&&t[2]&&!e.startsWith("/")&&!e.startsWith(".")&&!(/^[A-Za-z]$/.test(t[1])&&t[2].startsWith("\\"))?{kind:"git-ref",ref:t[1],filePath:t[2]}:{kind:"file",filePath:e}}function ct(e,t,r){try{return Qs(`git show ${e}:${t}`,{cwd:r??process.cwd(),encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(s){let n=s instanceof Error?s.message:String(s);throw new Error(`Failed to resolve git source ${e}:${t}: ${n}`,{cause:s})}}function nr(e){try{let t=Qs(`gh pr view "${e}" --json baseRefName,headRefName,baseRefOid,headRefOid`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),r=JSON.parse(t);return{baseRef:r.baseRefOid,headRef:r.headRefOid,baseBranch:r.baseRefName,headBranch:r.headRefName}}catch(t){let r=t instanceof Error?t.message:String(t);throw new Error(`Failed to resolve GitHub PR ${e}: ${r}`,{cause:t})}}var Xa={maxPaths:1e3,expandLoops:!1,maxLoopIterations:3};function lt(e,t={}){return ec(e,t).paths}function ec(e,t={}){let s={opts:{...Xa,...t},pathCount:0,hasHitLimit:!1,controlStack:[]},n={steps:[],conditions:[],hasLoops:!1,hasUnresolvedRefs:!1};return{paths:he(e.root.children,n,s).map((o,a)=>({id:`path-${a+1}`,description:Tc(o),steps:o.steps,conditions:o.conditions,hasLoops:o.hasLoops,hasUnresolvedRefs:o.hasUnresolvedRefs})),limitHit:s.hasHitLimit}}function he(e,t,r){if(e.length===0)return[t];let s=[t];for(let n of e){let i=[];for(let c of s)i.push(...le(n,c,r));if(s=i,n.type==="terminal"){let c=n;if(c.terminalKind==="return"||c.terminalKind==="throw")return s}}return s}function le(e,t,r){switch(e.type){case"effect":return tc(e,t);case"generator":return nc(e,t,r);case"pipe":return rc(e,t,r);case"parallel":return sc(e,t,r);case"race":return ic(e,t,r);case"error-handler":return oc(e,t,r);case"retry":case"timeout":return ac(e,t,r);case"resource":return cc(e,t,r);case"conditional":return lc(e,t,r);case"loop":return dc(e,t,r);case"layer":return uc(e,t,r);case"stream":return fc(e,t,r);case"concurrency-primitive":case"fiber":return pc(e,t,r);case"decision":return gc(e,t,r);case"switch":return mc(e,t,r);case"try-catch":return yc(e,t,r);case"terminal":return hc(e,t,r);case"cause":return xc(e,t,r);case"exit":case"schedule":return Sc(e,t);case"match":return Ec(e,t,r);case"transform":return bc(e,t,r);case"channel":return Nc(e,t,r);case"sink":return Cc(e,t,r);case"interruption":return wc(e,t,r);case"opaque":return[t];case"unknown":return[t];default:return[t]}}function tc(e,t){let r={nodeId:e.id,name:e.name??e.callee,repeated:!1};return[{...t,steps:[...t.steps,r]}]}function nc(e,t,r){let s=e.yields.map(n=>n.effect);return he(s,t,r)}function rc(e,t,r){let s=[e.initial,...e.transformations];return he(s,t,r)}function sc(e,t,r){let s=[t];for(let n of e.children){let i=[];for(let c of s){let o=le(n,c,r);for(let a of o)i.push({steps:a.steps,conditions:a.conditions,hasLoops:c.hasLoops||a.hasLoops,hasUnresolvedRefs:c.hasUnresolvedRefs||a.hasUnresolvedRefs})}s=i}return s}function ic(e,t,r){if(e.children.length===0)return[t];if(r.hasHitLimit||r.pathCount+e.children.length>=r.opts.maxPaths){r.hasHitLimit=!0;let c=e.children[0];return c?le(c,t,r):[t]}let n=[],i=r.opts.maxPaths;for(let c of e.children){if(n.length>=i){r.hasHitLimit=!0;break}let o=le(c,t,r),a=i-n.length,d=o.slice(0,a);n.push(...d),d.length<o.length&&(r.hasHitLimit=!0)}return r.pathCount+=Math.max(0,n.length-1),n.length>0?n:[t]}function oc(e,t,r){let s=le(e.source,t,r);if(!e.handler)return s;let n=le(e.handler,t,r);return[...s,...n]}function ac(e,t,r){return le(e.source,t,r)}function cc(e,t,r){let s=[e.acquire,e.release];return e.use&&s.push(e.use),he(s,t,r)}function lc(e,t,r){let s={expression:e.condition,mustBe:e.conditionalType!=="unless",location:e.location},n={...t,conditions:[...t.conditions,s]},i=le(e.onTrue,n,r),c={expression:e.condition,mustBe:e.conditionalType==="unless",location:e.location},o={...t,conditions:[...t.conditions,c]};if(e.onFalse){let a=le(e.onFalse,o,r);return[...i,...a]}return[...i,o]}function dc(e,t,r){return le(e.body,t,r).map(n=>({...n,steps:n.steps.map((i,c)=>c>=t.steps.length?{...i,repeated:!0}:i),hasLoops:!0}))}function uc(e,t,r){return he(e.operations,t,r)}function fc(e,t,r){let s={nodeId:e.id,name:e.pipeline.length>0?`Stream.${e.pipeline.map(i=>i.operation).join(" \u2192 ")}`:"Stream",repeated:!1},n={...t,steps:[...t.steps,s]};return le(e.source,n,r)}function pc(e,t,r){let s={nodeId:e.id,name:e.type==="concurrency-primitive"?`${e.primitive}.${e.operation}`:e.operation,repeated:!1},n={...t,steps:[...t.steps,s]},i=e.type==="concurrency-primitive"?e.source:e.fiberSource;return i?le(i,n,r):[n]}function gc(e,t,r){let s={expression:e.condition,mustBe:!0,location:e.location},n={...t,conditions:[...t.conditions,s]},i=he(e.onTrue,n,r);if(e.onFalse&&e.onFalse.length>0){let a={expression:e.condition,mustBe:!1,location:e.location},d={...t,conditions:[...t.conditions,a]},l=he(e.onFalse,d,r);return[...i,...l]}let c={expression:e.condition,mustBe:!1,location:e.location},o={...t,conditions:[...t.conditions,c]};return[...i,o]}function mc(e,t,r){let s=[];for(let n of e.cases){let i=n.labels.join(" / "),c={expression:`${e.expression} === ${i}`,mustBe:!0,location:e.location},o={...t,conditions:[...t.conditions,c]},a=he(n.body,o,r);s.push(...a)}return s.length>0?s:[t]}function yc(e,t,r){let s=he(e.tryBody,t,r),n=[];if(e.catchBody&&e.catchBody.length>0){let c={expression:"throws",mustBe:!0,location:e.location},o={...t,conditions:[...t.conditions,c]};n.push(...he(e.catchBody,o,r))}let i=[...s,...n];if(e.finallyBody&&e.finallyBody.length>0){let c=[];for(let o of i)c.push(...he(e.finallyBody,o,r));return c}return i}function hc(e,t,r){let s=t;switch(e.value&&e.value.length>0&&(s=he(e.value,t,r)[0]??t),e.terminalKind){case"return":case"throw":return[{...s,steps:[...s.steps,{nodeId:e.id,name:e.terminalKind,repeated:!1}]}];case"break":case"continue":return[s]}}function Sc(e,t){let r={nodeId:e.id,name:e.name??e.type,repeated:!1};return[{...t,steps:[...t.steps,r]}]}function xc(e,t,r){let s={nodeId:e.id,name:e.name??`Cause.${e.causeOp}`,repeated:!1},n={...t,steps:[...t.steps,s]};return e.children&&e.children.length>0?he([...e.children],n,r):[n]}function Ec(e,t,r){let s={nodeId:e.id,name:e.name??`Match.${e.matchOp}`,repeated:!1};return[{...t,steps:[...t.steps,s]}]}function bc(e,t,r){let s=t;e.source&&(s=le(e.source,t,r)[0]??t);let n={nodeId:e.id,name:e.name??e.transformType,repeated:!1};return[{...s,steps:[...s.steps,n]}]}function Nc(e,t,r){let s=t;e.source&&(s=le(e.source,t,r)[0]??t);let n={nodeId:e.id,name:e.name??`Channel${e.pipeline.length>0?`.${e.pipeline.map(i=>i.operation).join(".")}`:""}`,repeated:!1};return[{...s,steps:[...s.steps,n]}]}function Cc(e,t,r){let s=t;e.source&&(s=le(e.source,t,r)[0]??t);let n={nodeId:e.id,name:e.name??`Sink${e.pipeline.length>0?`.${e.pipeline.map(i=>i.operation).join(".")}`:""}`,repeated:!1};return[{...s,steps:[...s.steps,n]}]}function wc(e,t,r){let s={nodeId:e.id,name:e.name??e.interruptionType,repeated:!1},n={...t,steps:[...t.steps,s]};if(e.source){let i=le(e.source,n,r);if(e.handler){let c=le(e.handler,n,r);return[...i,...c]}return i}return[n]}function Tc(e){let t=[];if(e.conditions.length>0){let s=e.conditions.map(n=>{let i=n.mustBe?"is true":"is false";return`${n.expression.length>30?n.expression.slice(0,30)+"...":n.expression} ${i}`});t.push(`When ${s.join(" AND ")}`)}let r=e.steps.map(s=>{let n=s.name??s.nodeId;return s.repeated?`${n} (repeated)`:n}).join(" \u2192 ");return r&&t.push(`Steps: ${r}`),e.hasLoops&&t.push("[contains loops]"),e.hasUnresolvedRefs&&t.push("[has unresolved refs]"),t.join(". ")||"Empty path"}import{Effect as Zs}from"effect";var Ys={pretty:!0,includeMetadata:!0,compact:!1},Xs=(e,t)=>Zs.gen(function*(){let r={...Ys,...t},s=r.pretty?2:void 0,n=r.includeMetadata?{root:e.root,metadata:e.metadata,references:e.references instanceof Map?Object.fromEntries(e.references):e.references}:{root:e.root};return JSON.stringify(n,ti,s)}),ei=(e,t)=>Zs.gen(function*(){let r={...Ys,...t},s=r.pretty?2:void 0,n=e.map(i=>r.includeMetadata?{root:i.root,metadata:i.metadata,references:i.references instanceof Map?Object.fromEntries(i.references):i.references}:{root:i.root});return JSON.stringify(n,ti,s)}),ti=(e,t)=>t instanceof Map?Object.fromEntries(t):t instanceof Set?Array.from(t):typeof t=="bigint"?t.toString():(t&&typeof t=="object"&&"_tag"in t,t);import{Option as kc}from"effect";function vc(e){return e?e.typeConfidence:"unknown"}function Ic(e){return!e||e==="never"?"never":e}function $c(e){return!e||e==="never"?[]:Fe(e).filter(t=>t!=="never")}function rr(e){switch(e.type){case"effect":return e.displayName??e.callee;case"generator":return e.name??"generator";case"pipe":return e.name??"pipe";default:return e.name??e.type}}function Pe(e,t,r){for(let s of e){let n=Fc(s,r);n&&t.push(n);let i=r;if(s.type==="loop"){i={...i,inLoop:!0,loopType:s.loopType,iterationSource:s.iterSource},Pe([s.body],t,i);continue}if(s.type==="retry"){let o=s.scheduleInfo?{attempts:s.scheduleInfo.maxRetries??"unlimited",backoff:s.scheduleInfo.baseStrategy}:{attempts:"unlimited",backoff:s.schedule??"unknown"};i={...i,inRetry:o},Pe([s.source],t,i);continue}if(s.type==="timeout"){i={...i,inTimeout:{ms:s.duration??"unknown"}},Pe([s.source],t,i);continue}if(s.type==="resource"){s.use&&Pe([s.use],t,r);continue}if(s.type==="error-handler"){Pe([s.source],t,r),s.handler&&Pe([s.handler],t,r);continue}if(s.type==="generator"){let o=s.yields.map(a=>a.effect);Pe(o,t,i);continue}let c=kc.getOrElse(P(s),()=>[]);c.length>0&&Pe(c,t,i)}}function Fc(e,t){switch(e.type){case"effect":{let r=e.typeSignature,s=r?.successType??"unknown",n=r?.errorType??"never";return{stepId:e.id,name:e.displayName??e.callee,callee:e.callee,outputType:s,outputTypeKind:vc(r),outputTypeDisplay:s,outputTypeText:r?`Effect<${r.successType}, ${r.errorType}, ${r.requirementsType}>`:`Effect<${s}>`,errorTypeDisplay:Ic(n),errors:$c(n),depSource:e.serviceCall?.serviceType,stepKind:"effect",...t.inRetry?{retry:t.inRetry}:{},...t.inTimeout?{timeout:t.inTimeout}:{},...t.inLoop?{repeats:"loop",loopType:t.loopType,iterationSource:t.iterationSource}:{}}}case"retry":{let r=e.scheduleInfo?{attempts:e.scheduleInfo.maxRetries??"unlimited",backoff:e.scheduleInfo.baseStrategy}:{attempts:"unlimited",backoff:e.schedule??"unknown"};return{stepId:e.id,name:e.name??"Retry",callee:"Effect.retry",outputType:"void",outputTypeKind:"unknown",outputTypeDisplay:"void",outputTypeText:"retry wrapper",errorTypeDisplay:"never",errors:[],stepKind:"retry",retry:r}}case"timeout":return{stepId:e.id,name:e.name??"Timeout",callee:"Effect.timeout",outputType:"void",outputTypeKind:"unknown",outputTypeDisplay:"void",outputTypeText:"timeout wrapper",errorTypeDisplay:"TimeoutException",errors:["TimeoutException"],stepKind:"timeout",timeout:{ms:e.duration??"unknown"}};case"resource":return{stepId:e.id,name:e.name??"Resource",callee:"Effect.acquireRelease",outputType:"void",outputTypeKind:"unknown",outputTypeDisplay:"void",outputTypeText:"resource lifecycle",errorTypeDisplay:"never",errors:[],stepKind:"resource",kind:"resource",acquire:rr(e.acquire),use:e.use?rr(e.use):void 0,release:rr(e.release)};case"error-handler":{if(e.handlerType==="catchTag"||e.handlerType==="catchTags"){let r=e.errorTags?[...e.errorTags]:e.errorTag?[e.errorTag]:[];return{stepId:e.id,name:e.name??e.handlerType,callee:`Effect.${e.handlerType}`,outputType:"void",outputTypeKind:"unknown",outputTypeDisplay:"void",outputTypeText:`error handler (${e.handlerType})`,errorTypeDisplay:r.join(" | ")||"unknown",errors:r,stepKind:"error-handler"}}return null}default:return null}}function Ac(e,t,r){let s=Ve(e,{direction:t?.direction??"TB"}),n=[];return Pe(e.root.children,n,{}),{title:e.root.programName,code:r??"",mermaid:s,stepDetails:n}}function ni(e,t,r){return e.map(s=>Ac(s,t,r))}import{readdir as Rc}from"fs/promises";import{join as Dc,extname as Pc}from"path";import{Project as Mc,SyntaxKind as O}from"ts-morph";function R(e,t,r,s,n,i,c){let{line:o,column:a}=s.getLineAndColumnAtPos(r.getStart());e.push({filePath:t,line:o+1,column:a,pattern:n,suggestion:i,codeSnippet:c??s.getText().slice(r.getStart(),r.getStart()+80).replace(/\n/g," ")})}function sr(e,t){let r=[],s=new Mc({skipAddingFilesFromTsConfig:!0}),n=t?s.createSourceFile(e,t):s.addSourceFileAtPath(e);for(let l of n.getDescendantsOfKind(O.TryStatement))R(r,e,l,n,"try/catch","Effect.try or Effect.tryPromise with catch handler");for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u==="Promise.all"||u.endsWith(".all")&&u.includes("Promise"))&&R(r,e,l,n,"Promise.all",'Effect.all([...], { concurrency: "unbounded" })'),(u==="Promise.race"||u.endsWith(".race")&&u.includes("Promise"))&&R(r,e,l,n,"Promise.race","Effect.race(first, second)")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u==="setTimeout"||u==="setInterval")&&R(r,e,l,n,u,u==="setTimeout"?"Effect.sleep(Duration.millis(n))":"Schedule.spaced(Duration.millis(n))"),(u==="setImmediate"||u==="process.setImmediate")&&R(r,e,l,n,"setImmediate","Effect.sync + queueMicrotask or Effect.async")}for(let l of n.getDescendantsOfKind(O.NewExpression)){let u=l.getExpression().getText();(u==="XMLHttpRequest"||u.includes("XMLHttpRequest"))&&R(r,e,l,n,"new XMLHttpRequest()","HttpClient.request or @effect/platform HttpClient")}for(let l of n.getDescendantsOfKind(O.NewExpression)){let u=l.getExpression().getText();(u==="Worker"||u.includes("Worker"))&&R(r,e,l,n,"new Worker()","Worker.make or @effect/platform Worker")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u==="fs.exists"||u.endsWith(".exists")&&u.startsWith("fs."))&&l.getArguments().length>=2&&R(r,e,l,n,"fs.exists (callback)","Effect.promise or fs.promises.access")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u.endsWith(".request")&&(u.includes("http")||u.includes("https"))||u==="request"&&n.getText().includes("http"))&&R(r,e,l,n,"http.request / https.request","HttpClient.request or @effect/platform HttpClient")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u.startsWith("dns.")||u.includes("dns."))&&(u.includes("lookup")||u.includes("resolve")||u.includes("reverse"))&&R(r,e,l,n,"dns (callback)","Effect.promise or dns.promises")}for(let l of n.getDescendantsOfKind(O.CallExpression))l.getExpression().getText()==="fetch"&&R(r,e,l,n,"fetch()","HttpClient.request or @effect/platform HttpClient");for(let l of n.getDescendantsOfKind(O.NewExpression)){let u=l.getExpression().getText();(u==="EventEmitter"||u.includes("EventEmitter"))&&R(r,e,l,n,"new EventEmitter()","PubSub.bounded<EventType>() or PubSub.unbounded<EventType>()")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u.endsWith(".on(")||u.endsWith(".addListener("))&&(u.includes("Emitter")||u.includes("emitter"))&&R(r,e,l,n,"EventEmitter.on / addListener","PubSub.subscribe for PubSub"),u.endsWith(".emit(")&&(u.includes("Emitter")||u.includes("emitter"))&&R(r,e,l,n,"EventEmitter.emit","PubSub.publish for PubSub")}for(let l of n.getDescendantsOfKind(O.ClassDeclaration)){let f=l.getName(),u=l.getText();f&&(u.includes("new ")||u.includes("constructor"))&&(f.endsWith("Service")||f.endsWith("Repository")||f.endsWith("Client"))&&R(r,e,l,n,`class ${f} (manual DI)`,`Context.Tag<${f}>() + Layer.effect or Layer.succeed`)}for(let l of n.getDescendantsOfKind(O.NewExpression)){let u=l.getExpression().getText();(u.endsWith("Service")||u.endsWith("Repository")||u.endsWith("Client"))&&!u.includes("Context")&&!u.includes("Layer")&&R(r,e,l,n,`new ${u}()`,"Context.Tag + Layer.effect for dependency injection")}for(let l of n.getDescendantsOfKind(O.FunctionDeclaration))(l.getModifiers().some(f=>f.getText()==="async")||l.getText().startsWith("async"))&&R(r,e,l,n,"async function","Effect.gen or Effect.pipe with flatMap");for(let l of n.getDescendantsOfKind(O.ArrowFunction))l.getText().startsWith("async")&&R(r,e,l,n,"async arrow function","Effect.gen or Effect.pipe with flatMap");for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();u.endsWith(".then")&&u.includes("Promise")&&R(r,e,l,n,"Promise.then","Effect.flatMap for sequential composition"),(u==="Promise.allSettled"||u.endsWith(".allSettled")&&u.includes("Promise"))&&R(r,e,l,n,"Promise.allSettled","Effect.all with merge or separate error handling"),u.endsWith(".catch")&&(u.includes("Promise")||u.includes(".then"))&&R(r,e,l,n,"Promise.catch","Effect.catchAll or Effect.catchTag for typed error handling"),u.endsWith(".finally")&&(u.includes("Promise")||u.includes(".then"))&&R(r,e,l,n,"Promise.finally","Effect.ensuring for cleanup")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u==="addEventListener"||u.endsWith(".addEventListener"))&&R(r,e,l,n,"addEventListener","Effect.async or EventTarget + Effect.asyncInterrupt")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u==="fs.readFile"||u==="fs.writeFile"||u==="readFile"||u==="writeFile"||u.endsWith(".readFile")&&u.startsWith("fs.")||u.endsWith(".writeFile")&&u.startsWith("fs."))&&l.getArguments().length>=2&&R(r,e,l,n,u.includes("write")?"fs.writeFile (callback)":"fs.readFile (callback)","Effect.promise or fs.promises + Effect.tryPromise")}for(let l of n.getDescendantsOfKind(O.ThrowStatement))R(r,e,l,n,"throw","Effect.fail(error) for typed error channel");for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u==="promisify"||u.endsWith(".promisify"))&&R(r,e,l,n,"util.promisify","Effect.tryPromise or Effect.async for callback-style APIs")}for(let l of n.getDescendantsOfKind(O.NewExpression))l.getExpression().getText()==="Promise"&&R(r,e,l,n,"new Promise(...)","Effect.async or Effect.promise for callback-style");for(let l of n.getDescendantsOfKind(O.ForOfStatement))l.getAwaitKeyword()&&R(r,e,l,n,"for await...of","Stream.iterate or Effect.asyncIterable for async iteration");for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u==="readFileSync"||u==="writeFileSync"||u==="existsSync"||u.endsWith(".readFileSync")||u.endsWith(".writeFileSync")||u.endsWith(".existsSync"))&&R(r,e,l,n,u,"Effect.promise or fs/promises + Effect.tryPromise")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u==="process.nextTick"||u.endsWith(".nextTick")&&u.includes("process"))&&R(r,e,l,n,"process.nextTick","Effect.sync + queueMicrotask or Effect.async")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u==="queueMicrotask"||u.endsWith(".queueMicrotask"))&&R(r,e,l,n,"queueMicrotask","Effect.sync for deferred execution")}for(let l of n.getDescendantsOfKind(O.NewExpression)){let u=l.getExpression().getText();(u==="WebSocket"||u.includes("WebSocket"))&&R(r,e,l,n,"new WebSocket()","Effect.async or @effect/platform WebSocket")}for(let l of n.getDescendantsOfKind(O.NewExpression)){let u=l.getExpression().getText();(u==="MessageChannel"||u.includes("MessageChannel"))&&R(r,e,l,n,"new MessageChannel()","Effect.async or Queue for cross-context messaging")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u==="fs.appendFile"||u.endsWith(".appendFile")&&u.startsWith("fs."))&&l.getArguments().length>=2&&R(r,e,l,n,"fs.appendFile (callback)","Effect.promise or fs.promises.appendFile")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();if((u==="fs.mkdir"||u==="fs.stat"||u==="fs.unlink"||u.endsWith(".mkdir")&&u.startsWith("fs.")||u.endsWith(".stat")&&u.startsWith("fs.")||u.endsWith(".unlink")&&u.startsWith("fs."))&&l.getArguments().length>=2){let p=u.includes("mkdir")?"fs.mkdir":u.includes("stat")?"fs.stat":"fs.unlink";R(r,e,l,n,`${p} (callback)`,"Effect.promise or fs.promises")}}for(let l of n.getDescendantsOfKind(O.NewExpression)){let u=l.getExpression().getText();(u==="MutationObserver"||u.includes("MutationObserver"))&&R(r,e,l,n,"new MutationObserver()","Effect.async or Effect.asyncInterrupt for DOM observation")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u==="requestIdleCallback"||u.endsWith(".requestIdleCallback"))&&R(r,e,l,n,"requestIdleCallback","Effect.async or Effect.sync for idle-time work")}for(let l of n.getDescendantsOfKind(O.NewExpression)){let u=l.getExpression().getText();(u==="BroadcastChannel"||u.includes("BroadcastChannel"))&&R(r,e,l,n,"new BroadcastChannel()","PubSub or Effect.async for cross-tab messaging")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();if((u==="fs.rename"||u==="fs.realpath"||u.endsWith(".rename")&&u.startsWith("fs.")||u.endsWith(".realpath")&&u.startsWith("fs."))&&l.getArguments().length>=2){let p=u.includes("realpath")?"fs.realpath":"fs.rename";R(r,e,l,n,`${p} (callback)`,"Effect.promise or fs.promises")}}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText(),g=(u==="fs.readdir"||u.endsWith(".readdir")&&u.startsWith("fs."))&&l.getArguments().length>=2,p=(u==="fs.copyFile"||u.endsWith(".copyFile")&&u.startsWith("fs."))&&l.getArguments().length>=2;g&&R(r,e,l,n,"fs.readdir (callback)","Effect.promise or fs.promises.readdir"),p&&R(r,e,l,n,"fs.copyFile (callback)","Effect.promise or fs.promises.copyFile")}for(let l of n.getDescendantsOfKind(O.NewExpression)){let u=l.getExpression().getText();(u==="FileReader"||u.includes("FileReader"))&&R(r,e,l,n,"new FileReader()","Effect.async or FileReader + Effect.asyncInterrupt")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText(),g=(u==="fs.mkdtemp"||u.endsWith(".mkdtemp")&&u.startsWith("fs."))&&l.getArguments().length>=2,p=(u==="fs.symlink"||u.endsWith(".symlink")&&u.startsWith("fs."))&&l.getArguments().length>=2;g&&R(r,e,l,n,"fs.mkdtemp (callback)","Effect.promise or fs.promises.mkdtemp"),p&&R(r,e,l,n,"fs.symlink (callback)","Effect.promise or fs.promises.symlink")}for(let l of n.getDescendantsOfKind(O.NewExpression)){let u=l.getExpression().getText();(u==="ResizeObserver"||u==="IntersectionObserver"||u.includes("ResizeObserver")||u.includes("IntersectionObserver"))&&R(r,e,l,n,`new ${u}()`,"Effect.async or Effect.asyncInterrupt for DOM observation")}let i=n.getText().includes("child_process");for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u.includes("child_process")&&u.endsWith(".fork")||i&&u==="fork")&&R(r,e,l,n,"child_process.fork","Worker.make or @effect/platform Worker")}for(let l of n.getDescendantsOfKind(O.NewExpression)){let u=l.getExpression().getText();(u==="AbortController"||u.includes("AbortController"))&&R(r,e,l,n,"new AbortController()","Effect.Scoped or Effect.interruptible for cancellation")}let c=n.getText(),o=c.includes("child_process");for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();((u.endsWith(".exec")||u.endsWith(".execSync")||u.endsWith(".spawn"))&&u.includes("child_process")||o&&(u==="exec"||u==="execSync"||u==="spawn"))&&R(r,e,l,n,"child_process.exec/spawn","@effect/platform CommandExecutor or Effect.promise")}for(let l of n.getDescendantsOfKind(O.PropertyAccessExpression))l.getExpression().getText()==="process"&&l.getName()==="env"&&R(r,e,l,n,"process.env","Config.string or Config.forEffect for typed config");if(c.includes("rxjs")||c.includes("Observable"))for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u.includes("Observable")||u.includes("of")&&u.includes("rxjs"))&&R(r,e,l,n,"RxJS Observable","Stream from @effect/platform or Effect Stream")}for(let l of n.getDescendantsOfKind(O.NewExpression)){let u=l.getExpression().getText();(u.includes("Observable")||u.includes("Subject"))&&R(r,e,l,n,"RxJS Observable/Subject","Stream or PubSub for Effect")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u==="requestAnimationFrame"||u.endsWith(".requestAnimationFrame"))&&R(r,e,l,n,"requestAnimationFrame","Effect.async or Effect.sync + queueMicrotask for scheduling")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u.includes("crypto.")||u.includes("randomBytes")||u.includes("scrypt")||u.includes("pbkdf2"))&&l.getArguments().length>=2&&R(r,e,l,n,"crypto (callback)","Effect.promise or crypto.webcrypto / node:crypto promises")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u==="createReadStream"||u==="createWriteStream"||u.endsWith(".createReadStream")||u.endsWith(".createWriteStream"))&&R(r,e,l,n,u,"Stream.fromReadable or @effect/platform FileSystem/Stream")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();u.includes("cluster")&&u.endsWith(".fork")&&R(r,e,l,n,"cluster.fork","Worker.make or @effect/platform Worker pool")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let f=l.getExpression(),u=f.getText();if(u==="createServer"||u==="connect"||u.endsWith(".createServer")||u.endsWith(".connect")){let g=f.getText();(g.includes("net")||g.includes("tls"))&&R(r,e,l,n,g,"Effect.async or @effect/platform Socket/Server")}}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();u.includes("zlib.")&&(u.includes("deflate")||u.includes("inflate")||u.includes("gzip")||u.includes("gunzip"))&&R(r,e,l,n,"zlib (callback)","Effect.promise or zlib.promises")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u==="createInterface"||u.endsWith(".createInterface"))&&u.includes("readline")&&R(r,e,l,n,"readline.createInterface","Effect.async or Stream for line-by-line reading")}let d=n.getText().includes("stream");for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u.endsWith(".pipeline")&&u.includes("stream")||d&&u==="pipeline")&&R(r,e,l,n,"stream.pipeline (callback)","Effect.promise or stream.promises.pipeline")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u==="once"||u.endsWith(".once"))&&(u.includes("events")||n.getText().includes("from 'events'"))&&R(r,e,l,n,"events.once","Effect.async for one-shot event")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let f=l.getExpression(),u=f.getText();(u==="watch"||u==="watchFile"||u.endsWith(".watch")||u.endsWith(".watchFile"))&&(u.includes("fs")||f.getText().includes("fs."))&&R(r,e,l,n,"fs.watch / fs.watchFile","Effect.async or fs.watch with EventEmitter")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u.includes("runInNewContext")||u.includes("runInContext")||u.includes("runInThisContext"))&&u.includes("vm")&&R(r,e,l,n,"vm.runIn*","Effect.sync for isolated code execution")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u==="parse"||u.endsWith(".parse"))&&u.includes("url")&&R(r,e,l,n,"url.parse (deprecated)","new URL() or URL.parse for standard parsing")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u.endsWith(".spawnSync")&&u.includes("child_process")||n.getText().includes("child_process")&&u==="spawnSync")&&R(r,e,l,n,"child_process.spawnSync","@effect/platform CommandExecutor or Effect.promise")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u==="glob"||u.endsWith(".glob"))&&n.getText().includes("glob")&&l.getArguments().length>=2&&R(r,e,l,n,"glob (callback)","Effect.promise or glob promise API")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText(),g=u.includes("assert")&&u.endsWith(".throws"),p=u.endsWith(".rejects")&&u.includes("expect");(g||p)&&R(r,e,l,n,p?"expect().rejects":"assert.throws","Effect.runPromiseExit + Exit.match for testing Effect failures")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();u.includes("tls")&&(u.endsWith(".connect")||u.endsWith(".createServer"))&&R(r,e,l,n,"tls.connect / tls.createServer","Effect.async or @effect/platform Socket/TLS")}return r}async function ri(e,t){let r=t?.extensions??[".ts",".tsx"],s=[],n=0;async function i(c){let o=await Rc(c,{withFileTypes:!0}).catch(()=>[]);for(let a of o){let d=Dc(c,a.name);if(a.isDirectory())a.name!=="node_modules"&&a.name!==".git"&&a.name!=="dist"&&await i(d);else if(a.isFile()&&r.includes(Pc(a.name))){n++;try{s.push(...sr(d))}catch{}}}}return await i(e),{opportunities:s,fileCount:n}}function ir(e){let t=[];t.push("Migration Opportunities Found:"),t.push("");for(let r of e.opportunities)t.push(` ${r.filePath}:${r.line}:${r.column} ${r.pattern}`),t.push(` \u2192 ${r.suggestion}`),r.codeSnippet&&t.push(` Snippet: ${r.codeSnippet.slice(0,60)}...`),t.push("");return t.push(`Total: ${e.opportunities.length} opportunities in ${e.fileCount} files`),t.join(`
|
|
43
|
-
`)}import{createHash as
|
|
44
|
-
${E}`)){u=r.get(E);break}}if(!u)continue;let g=[],p=/Layer\.provide\s*\(([^)]+)\)/.exec(a);if(p?.[1]){let E=p[1].trim();for(let[$,S]of r.entries())S!==u&&E.includes($)&&!g.includes(S)&&g.push(S)}let m=a.matchAll(/yield\*\s+(\w+)/g);for(let E of m){let $=E[1],S=$?r.get($):void 0;S&&S!==u&&!g.includes(S)&&g.push(S)}let h=a.matchAll(/yield\s*\*\s*(\w+)/g);for(let E of h){let $=E[1],S=$?r.get($):void 0;S&&S!==u&&!g.includes(S)&&g.push(S)}let y=c.getStart(),N=e.getLineAndColumnAtPos(y);n.push({providesServiceId:u,implementation:{name:f,filePath:t,location:{filePath:t,line:N.line,column:N.column-1},kind:l,requires:g}})}return n}function zc(e){let t=new Map;for(let[r,s]of e)for(let n of s){let i=n.root.programName;if(n.root.requiredServices)for(let c of n.root.requiredServices){let o=t.get(c.serviceId)??[];o.push({programName:i,filePath:r,location:c.requiredAt}),t.set(c.serviceId,o)}fi(n.root.children,i,r,t)}return t}function fi(e,t,r,s){for(let n of e){if(n.type==="effect"&&n.serviceCall){let c=n.serviceCall.serviceType;if(c){let o=s.get(c)??[];o.some(a=>a.programName===t&&a.filePath===r)||(o.push({programName:t,filePath:r,location:n.location}),s.set(c,o))}}let i=ui.getOrElse(P(n),()=>[]);i.length>0&&fi(i,t,r,s)}}function _c(e){let t=[],r=new Set,s=new Set;function n(i){if(r.has(i)||s.has(i))return;s.add(i);let c=e.get(i);if(c)for(let o of c.dependencies)n(o);s.delete(i),r.add(i),t.push(i)}for(let i of e.keys())n(i);return t}function pi(e,t,r,s=new Set){let n=[];if(s.has(e))return n;s.add(e);for(let i of t)for(let c of i.requires){n.includes(c)||n.push(c);let o=r.get(c);if(o)for(let a of pi(c,o,r,s))n.includes(a)||n.push(a)}return n}function or(e,t){let r=new Map;if(t)for(let[u,g]of t){let p=Bc(g,u);for(let m of p)r.has(m.tagId)||r.set(m.tagId,m)}for(let[u,g]of e)for(let p of g)if(p.metadata.serviceDefinitions)for(let m of p.metadata.serviceDefinitions)r.has(m.tagId)||r.set(m.tagId,{tagId:m.tagId,className:m.tagId,filePath:u,location:{filePath:u,line:1,column:0},definition:m});let s=new Set(r.keys()),n=new Map;for(let[u,g]of r)n.has(u)||n.set(u,u),n.has(g.className)||n.set(g.className,u);let i=new Set;for(let u of e.values())for(let g of u)if(g.root.requiredServices)for(let p of g.root.requiredServices)i.add(p.serviceId);let c=new Map;if(t)for(let[u,g]of t){let p=qc(g,u,n);for(let m of p){if(!s.has(m.providesServiceId))continue;let h=c.get(m.providesServiceId)??[];h.push(m.implementation),c.set(m.providesServiceId,h)}}for(let[u,g]of e)for(let p of g)gi(p.root.children,u,s,n,c,p);let o=zc(e),a=new Map,d=[];for(let[u,g]of r){let p=c.get(u)??[],m=o.get(u)??[],h=pi(u,p,c);a.set(u,{serviceId:u,className:g.className,definitionFilePath:g.filePath,definitionLocation:g.location,definition:g.definition,interfaceTypeText:g.interfaceTypeText,layerImplementations:p,consumers:m,dependencies:h})}let l=new Set(i);for(let u of o.keys())l.add(u);for(let u of l)a.has(u)||d.push(u);let f=_c(a);return{services:a,unresolvedServices:d,topologicalOrder:f}}function gi(e,t,r,s,n,i){for(let c of e){if(c.type==="layer"&&c.provides)for(let a of c.provides){let d=s.get(a)??(r.has(a)?a:void 0);if(d&&r.has(d)){let l=n.get(d)??[],f=c.requires?c.requires.map(u=>s.get(u)??u).filter(u=>r.has(u)):[];l.some(u=>u.name===(c.name??i.root.programName)&&u.filePath===t)||(l.push({name:c.name??i.root.programName,filePath:t,location:c.location??{filePath:t,line:1,column:0},kind:"other",requires:f}),n.set(d,l))}}let o=ui.getOrElse(P(c),()=>[]);o.length>0&&gi(o,t,r,s,n,i)}}var Jt={extensions:[".ts",".tsx"],maxDepth:10,knownEffectInternalsRoot:void 0,includePerFileTiming:!1,excludeFromSuspiciousZeros:[],buildServiceMap:!1};function Vc(e){let t=0,r=0,s=n=>{for(let i of n){t++,i.type==="unknown"&&r++;let c=yi.getOrElse(P(i),()=>[]);c.length>0&&s(c)}};return s(e),{total:t,unknown:r}}function Jc(e){let t=new Map,r=s=>{for(let n of s){if(Er(n)){let c=n.reason;t.set(c,(t.get(c)??0)+1)}let i=yi.getOrElse(P(n),()=>[]);i.length>0&&r(i)}};return r(e),t}function Qc(e){try{let t=Si(e,"utf-8");return/from\s+["'](?:effect|effect\/|@effect\/)/.test(t)}catch{return!1}}function Zc(e){try{let t=Si(e,"utf-8");return/\bEffect\./.test(t)||/\bLayer\./.test(t)||/\bStream\./.test(t)||/\bSchema\./.test(t)||/\byield\*/.test(t)||/\bpipe\(/.test(t)||/\brunPromise\b/.test(t)||/\brunSync\b/.test(t)||/\brunFork\b/.test(t)||/\bacquireRelease\b/.test(t)?!1:/\binterface\b/.test(t)||/\btype\b/.test(t)||/\bdeclare\b/.test(t)||/^\s*import\s+type\b/m.test(t)||/^\s*export\s+type\b/m.test(t)}catch{return!1}}function Yc(e){let t=e.replace(/\\/g,"/"),r=Gc(t).toLowerCase();if(r==="index.ts"||r==="index.tsx"||/\/index\.[jt]sx?$/.test(t))return"barrel_or_index";if(/(^|\/)(__tests__|test|tests|dtslint)(\/|$)/.test(t)||/\.(test|spec|tst)\.[jt]sx?$/.test(t))return"test_or_dtslint";if(/(^|\/)(vitest|vite|jest|webpack|rollup|tsup|esbuild|eslint|prettier|babel|playwright|typedoc|karma)\.config\.[jt]s$/.test(t)||/(^|\/)vitest\.workspace\.[jt]s$/.test(t))return"config_or_build";if(Zc(e))return"type_only"}async function ar(e,t,r,s){if(s>=r)return[];let n=[];try{let i=await hi(e,{withFileTypes:!0});for(let c of i){let o=Qt(e,c.name);c.isDirectory()?c.name!=="node_modules"&&c.name!==".git"&&n.push(...await ar(o,t,r,s+1)):c.isFile()&&t.includes(xi(c.name))&&n.push(o)}}catch{}return n}async function Ei(e,t,r){if(r>=t)return[];let s=[];try{let n=await hi(e,{withFileTypes:!0});n.some(c=>c.isFile()&&c.name==="package.json")&&s.push(e);for(let c of n)c.isDirectory()&&c.name!=="node_modules"&&c.name!==".git"&&s.push(...await Ei(Qt(e,c.name),t,r+1))}catch{}return s}function Vt(e,t,r){if(!t||typeof t!="string")return[];let s=t.replace(/^\.\//,""),n=Qt(e,s);return xi(s)?[mi(n)]:r.map(c=>mi(n+c))}async function Xc(e){try{let{Project:t,SyntaxKind:r}=w(),i=new t({skipAddingFilesFromTsConfig:!0}).addSourceFileAtPath(e).getDescendantsOfKind(r.CallExpression),c=[r.FunctionDeclaration,r.FunctionExpression,r.ArrowFunction,r.MethodDeclaration];for(let o of i){let a=o.getParent();if(a?.getKind()!==r.ExpressionStatement)continue;let d=a;for(;d;){let f=d.getKind();if(f===r.SourceFile||c.includes(f))break;d=d.getParent()}if(d?.getKind()!==r.SourceFile)continue;let l=o.getExpression().getText();if(l.includes(".runPromise")||l.includes(".runSync")||l.includes(".runFork")||l.includes(".runCallback")||l.includes("NodeRuntime.runMain")||l.includes("BunRuntime.runMain")||l.includes("DenoRuntime.runMain")||l.includes("Runtime.runPromise")||l.includes("Runtime.runSync")||l.includes("Runtime.runFork"))return!0}}catch{}return!1}async function el(e,t){let r=await Ei(e,10,0),s=[];for(let n of r)try{let i=await Hc(Qt(n,"package.json"),"utf-8"),c=JSON.parse(i),o=[Vt(n,c.main,t),Vt(n,c.module,t)];if(typeof c.bin=="string")o.push(Vt(n,c.bin,t));else if(c.bin&&typeof c.bin=="object")for(let a of Object.values(c.bin))o.push(Vt(n,typeof a=="string"?a:void 0,t));for(let a of o)for(let d of a)try{(await Uc(d).catch(()=>null))?.isFile()&&s.push(d)}catch{}}catch{}return[...new Set(s)]}function bi(e,t={}){let r=t.extensions??Jt.extensions,s=t.maxDepth??Jt.maxDepth;return be.gen(function*(){let n=yield*be.promise(()=>ar(e,r,s,0)),i=new Map,c=[],o=[],a=[],d=[];for(let u of n){let g=yield*We(u,{tsConfigPath:t.tsconfig,knownEffectInternalsRoot:t.knownEffectInternalsRoot}).all().pipe(be.map(m=>({_tag:"ok",programs:m})),be.catchAll(m=>be.succeed({_tag:"fail",error:m instanceof Error?m.message:String(m)})));if(g._tag==="fail"){a.push({file:u,error:g.error});continue}let p=g.programs;if(p.length===0){d.push(u);continue}i.set(u,p),c.push(...p);for(let m of p){let h=m.root.programName==="main"||m.root.programName.includes("run"),y=m.root.source==="run";(h||y)&&(o.includes(u)||o.push(u))}}let l=yield*be.promise(()=>el(e,r));for(let u of l)n.includes(u)&&!o.includes(u)&&o.push(u);for(let u of i.keys()){if(o.includes(u))continue;(yield*be.promise(()=>Xc(u)))&&o.push(u)}let f;if(t.buildServiceMap)try{let{Project:u}=w(),g=new u({skipAddingFilesFromTsConfig:!0,compilerOptions:{allowJs:!0}}),p=new Map;for(let m of i.keys())try{let h=g.addSourceFileAtPath(m);p.set(m,h)}catch{}f=or(i,p)}catch{f=or(i)}return{byFile:i,allPrograms:c,entryPointFiles:o,fileCount:n.length,failedFiles:a,zeroProgramFiles:d,serviceMap:f}})}function Ni(e,t={}){let r=t.extensions??Jt.extensions,s=t.maxDepth??Jt.maxDepth;return be.gen(function*(){let n=Date.now(),i=yield*be.promise(()=>ar(e,r,s,0)),c=[],o=0,a=0,d=[],l=new Map,f=t.includePerFileTiming===!0;for(let I of i){let q=f?Date.now():0,z=yield*We(I,{tsConfigPath:t.tsconfig,knownEffectInternalsRoot:t.knownEffectInternalsRoot}).all().pipe(be.map(Z=>({_tag:"ok",programs:Z})),be.catchAll(Z=>be.succeed({_tag:"fail",error:Z instanceof Error?Z.message:String(Z)}))),Y=f?Date.now()-q:void 0;if(z._tag==="ok"){let Z=z.programs.length,L=0,H=0;for(let ge of z.programs){let de=Vc(ge.root.children);o+=de.total,a+=de.unknown,L+=de.total,H+=de.unknown;let ne=Jc(ge.root.children);for(let[we,ve]of ne)l.set(we,(l.get(we)??0)+ve)}L>0&&d.push({file:I,total:L,unknown:H}),c.push(Z>0?{file:I,status:"ok",programCount:Z,...Y!==void 0?{durationMs:Y}:{}}:{file:I,status:"zero",programCount:0,...Y!==void 0?{durationMs:Y}:{}})}else{let Z=z.error??"",L=Z.includes("No Effect programs found")||Z.includes("NO_EFFECTS_FOUND");c.push(L?{file:I,status:"zero",programCount:0,...Y!==void 0?{durationMs:Y}:{}}:{file:I,status:"fail",error:z.error,...Y!==void 0?{durationMs:Y}:{}})}}let u=i.length,g=c.filter(I=>I.status==="ok").length,p=c.filter(I=>I.status==="zero").length,m=c.filter(I=>I.status==="fail").length,h=u>0?g/u*100:0,y=g+m>0?g/(g+m)*100:100,N=t.excludeFromSuspiciousZeros??[],E=I=>{let q=I.replace(/\\/g,"/");return N.some(z=>q.includes(z.replace(/\\/g,"/"))||q.endsWith(z.replace(/\\/g,"/")))},$={barrel_or_index:0,config_or_build:0,test_or_dtslint:0,type_only:0,suspicious:0,other:0},S=[],b=[],T=c.filter(I=>I.status==="zero");for(let I of T){let q=Qc(I.file),z=Yc(I.file),Y=q&&!E(I.file)&&z===void 0?"suspicious":z??"other";$[Y]++,b.push({file:I.file,category:Y,importsEffect:q}),Y==="suspicious"&&S.push(I.file)}let v=o>0?a/o:0,x=d.filter(I=>I.total>0).sort((I,q)=>q.unknown/q.total-I.unknown/I.total).slice(0,10).map(I=>I.file),K={};for(let[I,q]of l)K[I]=q;let F=[...l.entries()].sort((I,q)=>q[1]-I[1]).slice(0,20).map(([I,q])=>({reason:I,count:q})),j=Date.now()-n;return{discovered:u,analyzed:g,zeroPrograms:p,failed:m,outcomes:c,percentage:h,analyzableCoverage:y,unknownNodeRate:v,totalNodes:o,unknownNodes:a,suspiciousZeros:S,zeroProgramCategoryCounts:$,zeroProgramClassifications:b,topUnknownFiles:x,unknownReasonCounts:K,topUnknownReasons:F,durationMs:j}})}import*as ke from"path";import*as dr from"fs/promises";import{Effect as dt}from"effect";var tl=e=>" ".repeat(e);function Ci(e){switch(e.type){case"effect":return e.serviceCall?`${e.serviceCall.serviceType}.${e.serviceCall.methodName}`:e.displayName??e.callee;case"generator":return"Effect.gen block";case"pipe":return`pipe(${Ci(e.initial)})`;case"parallel":return`${e.callee}(${e.children.length} effects)`;case"race":return`${e.callee}(${e.children.length} effects)`;case"error-handler":return e.handlerType;case"retry":return"retry";case"timeout":return e.duration?`timeout(${e.duration})`:"timeout";case"resource":return"acquireRelease";case"conditional":return`if ${e.conditionLabel??e.condition}`;case"loop":return`${e.loopType}${e.iterSource?`(${e.iterSource})`:""}`;case"layer":return e.provides?`Layer(${e.provides.join(", ")})`:"Layer";case"stream":return"Stream";case"fiber":return`Fiber.${e.operation}`;case"concurrency-primitive":return`${e.primitive}.${e.operation}`;case"decision":return`if ${e.condition}`;case"switch":return`switch(${e.expression})`;case"try-catch":return"try/catch";case"terminal":return e.terminalKind;case"match":return e.matchedTags?`Match(${e.matchedTags.join(", ")})`:"Match";case"transform":return e.transformType;case"channel":return"Channel";case"sink":return"Sink";case"cause":return`Cause.${e.causeOp}`;case"exit":return`Exit.${e.exitOp}`;case"schedule":return`Schedule.${e.scheduleOp}`;case"interruption":return e.interruptionType;case"opaque":return`(opaque: ${e.reason})`;case"unknown":return`(unknown: ${e.reason})`}}function U(e,t,r={hasParallelism:!1,serviceCallsSeen:new Set}){let s=tl(t),n=[];switch(e.type){case"effect":{if(e.serviceCall)if(r.serviceCallsSeen.add(e.serviceCall.serviceType),e.callee.includes("Tag")||e.callee.includes("Context")||e.callee===e.serviceCall.serviceType)n.push(`${s}Acquires ${e.serviceCall.serviceType} service`);else{let i=e.description?` \u2014 ${e.description}`:"";n.push(`${s}Calls ${e.serviceCall.serviceType}.${e.serviceCall.methodName}${i}`)}else{let i=e.displayName??e.callee,c=e.description?` \u2014 ${e.description}`:"";i.includes(" <- ")?n.push(`${s}Yields ${i}`):n.push(`${s}Calls ${i}${c}`)}break}case"generator":{for(let i of e.yields){let c=U(i.effect,t,r),o=c[0];if(i.variableName&&o!==void 0){let a=o.trimStart();a.includes(`${i.variableName} <-`)||a.includes(`${i.variableName} =`)||(c[0]=`${s}${i.variableName} = ${a.replace(/^Calls /,"")}`)}n.push(...c)}if(e.returnNode){let i=U(e.returnNode,t,r),c=i[0];if(c!==void 0){let o=c.trimStart();i[0]=`${s}Returns ${o.replace(/^Calls /,"")}`,n.push(...i)}}break}case"pipe":{n.push(`${s}Pipes ${Ci(e.initial)} through:`);let i=U(e.initial,t+1,r);n.push(...i);for(let c of e.transformations){let o=U(c,t+1,r);n.push(...o)}break}case"parallel":{r.hasParallelism=!0;let i=e.concurrency!==void 0&&e.concurrency!=="sequential"?` (concurrency: ${e.concurrency})`:"";n.push(`${s}Runs ${e.children.length} effects in ${e.mode}${i}:`);for(let c of e.children)n.push(...U(c,t+1,r));break}case"race":{r.hasParallelism=!0,n.push(`${s}Races ${e.children.length} effects:`);for(let i of e.children)n.push(...U(i,t+1,r));break}case"error-handler":{let i=e.errorTag?` "${e.errorTag}"`:e.errorTags&&e.errorTags.length>0?` [${e.errorTags.join(", ")}]`:"";switch(e.handlerType){case"catchAll":n.push(`${s}Catches all errors on:`);break;case"catchTag":n.push(`${s}Catches tag${i} on:`);break;case"catchTags":n.push(`${s}Catches tags${i} on:`);break;case"orElse":n.push(`${s}Falls back (orElse) on error:`);break;case"orDie":n.push(`${s}Converts errors to defects (orDie):`);break;case"mapError":n.push(`${s}Maps error on:`);break;case"ignore":n.push(`${s}Ignores errors on:`);break;default:n.push(`${s}Handles errors (${e.handlerType})${i}:`)}n.push(...U(e.source,t+1,r)),e.handler&&(n.push(`${s} Handler:`),n.push(...U(e.handler,t+2,r)));break}case"retry":{if(e.scheduleInfo){let i=e.scheduleInfo.maxRetries!==void 0?`max ${e.scheduleInfo.maxRetries}`:"",c=e.scheduleInfo.baseStrategy,o=[i,c].filter(Boolean).join(", ");n.push(`${s}Retries (${o}):`)}else e.schedule?n.push(`${s}Retries with ${e.schedule}:`):n.push(`${s}Retries:`);n.push(...U(e.source,t+1,r)),e.hasFallback&&n.push(`${s} (with fallback on exhaustion)`);break}case"timeout":{let i=e.duration?` after ${e.duration}`:"";n.push(`${s}Times out${i}:`),n.push(...U(e.source,t+1,r)),e.hasFallback&&n.push(`${s} (with fallback on timeout)`);break}case"resource":{n.push(`${s}Acquires resource:`),n.push(...U(e.acquire,t+1,r)),e.use&&(n.push(`${s} Uses:`),n.push(...U(e.use,t+2,r))),n.push(`${s} Then releases:`),n.push(...U(e.release,t+2,r));break}case"conditional":{let i=e.conditionLabel??e.condition;n.push(`${s}If ${i}:`),n.push(...U(e.onTrue,t+1,r)),e.onFalse&&(n.push(`${s}Else:`),n.push(...U(e.onFalse,t+1,r)));break}case"decision":{n.push(`${s}If ${e.condition}:`);for(let i of e.onTrue)n.push(...U(i,t+1,r));if(e.onFalse&&e.onFalse.length>0){n.push(`${s}Else:`);for(let i of e.onFalse)n.push(...U(i,t+1,r))}break}case"switch":{n.push(`${s}Switch on ${e.expression}:`);for(let i of e.cases){let c=i.isDefault?"default":i.labels.join(", ");n.push(`${s} Case ${c}:`);for(let o of i.body)n.push(...U(o,t+2,r))}break}case"try-catch":{n.push(`${s}Try:`);for(let i of e.tryBody)n.push(...U(i,t+1,r));if(e.catchBody&&e.catchBody.length>0){n.push(`${s}Catch:`);for(let i of e.catchBody)n.push(...U(i,t+1,r))}if(e.finallyBody&&e.finallyBody.length>0){n.push(`${s}Finally:`);for(let i of e.finallyBody)n.push(...U(i,t+1,r))}break}case"terminal":{switch(e.terminalKind){case"return":{if(e.value&&e.value.length>0){n.push(`${s}Returns:`);for(let i of e.value)n.push(...U(i,t+1,r))}else n.push(`${s}Returns`);break}case"throw":n.push(`${s}Throws`);break;case"break":n.push(`${s}Breaks`);break;case"continue":n.push(`${s}Continues`);break}break}case"loop":{let i=e.iterSource?` over ${e.iterSource}`:"";n.push(`${s}Iterates (${e.loopType})${i}:`),n.push(...U(e.body,t+1,r));break}case"layer":{let i=e.provides&&e.provides.length>0?` providing ${e.provides.join(", ")}`:"",c=e.requires&&e.requires.length>0?` (requires ${e.requires.join(", ")})`:"";n.push(`${s}Provides layer${i}${c}:`);for(let o of e.operations)n.push(...U(o,t+1,r));break}case"stream":{let i=e.pipeline.map(o=>o.operation).join(" -> "),c=e.sink?` -> ${e.sink}`:"";n.push(`${s}Stream: ${i}${c}`),n.push(...U(e.source,t+1,r));break}case"fiber":{let i=e.isDaemon?" (daemon)":e.isScoped?" (scoped)":"";n.push(`${s}Fiber ${e.operation}${i}:`),e.fiberSource&&n.push(...U(e.fiberSource,t+1,r));break}case"concurrency-primitive":{let i=e.capacity!==void 0?` (capacity: ${e.capacity})`:"";n.push(`${s}${e.primitive}.${e.operation}${i}`),e.source&&n.push(...U(e.source,t+1,r));break}case"match":{e.matchedTags&&e.matchedTags.length>0?n.push(`${s}Matches tags: ${e.matchedTags.join(", ")}`):n.push(`${s}Match (${e.matchOp})`);break}case"transform":{n.push(`${s}Transforms via ${e.transformType}`),e.source&&n.push(...U(e.source,t+1,r));break}case"cause":{if(n.push(`${s}Cause.${e.causeOp}`),e.children)for(let i of e.children)n.push(...U(i,t+1,r));break}case"exit":{n.push(`${s}Exit.${e.exitOp}`);break}case"schedule":{n.push(`${s}Schedule.${e.scheduleOp}`);break}case"channel":{let i=e.pipeline.map(c=>c.operation).join(" -> ");n.push(`${s}Channel${i?`: ${i}`:""}`),e.source&&n.push(...U(e.source,t+1,r));break}case"sink":{let i=e.pipeline.map(c=>c.operation).join(" -> ");n.push(`${s}Sink${i?`: ${i}`:""}`),e.source&&n.push(...U(e.source,t+1,r));break}case"interruption":{n.push(`${s}${e.interruptionType}`),e.source&&n.push(...U(e.source,t+1,r)),e.handler&&(n.push(`${s} On interrupt:`),n.push(...U(e.handler,t+2,r)));break}case"opaque":{n.push(`${s}(opaque: ${e.reason})`);break}case"unknown":{n.push(`${s}(unknown: ${e.reason})`);break}}return n}function nl(e,t){let r={hasParallelism:!1,serviceCallsSeen:new Set},s=[];for(let d of e.children)s.push(...U(d,1,r));let n=rl(s),i=`${e.programName} (${e.source}):`,c=[],o=new Set;for(let d of e.dependencies)o.add(d.name);Array.from(r.serviceCallsSeen).forEach(d=>{o.add(d)}),o.size>0&&c.push(` Services required: ${Array.from(o).join(", ")}`),e.errorTypes.length>0&&c.push(` Error paths: ${e.errorTypes.join(", ")}`),r.hasParallelism?c.push(" Concurrency: uses parallelism / racing"):c.push(" Concurrency: sequential (no parallelism)");let a=[i,n.join(`
|
|
42
|
+
`}import{execSync as si}from"child_process";function vt(e){if(/^https?:\/\/github\.com\/.+\/pull\/\d+/.test(e))return{kind:"github-pr",prUrl:e};let t=/^([^:]+):(.+)$/.exec(e);return t?.[1]&&t[2]&&!e.startsWith("/")&&!e.startsWith(".")&&!(/^[A-Za-z]$/.test(t[1])&&t[2].startsWith("\\"))?{kind:"git-ref",ref:t[1],filePath:t[2]}:{kind:"file",filePath:e}}function gt(e,t,r){try{return si(`git show ${e}:${t}`,{cwd:r??process.cwd(),encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(s){let n=s instanceof Error?s.message:String(s);throw new Error(`Failed to resolve git source ${e}:${t}: ${n}`,{cause:s})}}function dr(e){try{let t=si(`gh pr view "${e}" --json baseRefName,headRefName,baseRefOid,headRefOid`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),r=JSON.parse(t);return{baseRef:r.baseRefOid,headRef:r.headRefOid,baseBranch:r.baseRefName,headBranch:r.headRefName}}catch(t){let r=t instanceof Error?t.message:String(t);throw new Error(`Failed to resolve GitHub PR ${e}: ${r}`,{cause:t})}}var dc={maxPaths:1e3,expandLoops:!1,maxLoopIterations:3};function mt(e,t={}){return uc(e,t).paths}function uc(e,t={}){let s={opts:{...dc,...t},pathCount:0,hasHitLimit:!1,controlStack:[]},n={steps:[],conditions:[],hasLoops:!1,hasUnresolvedRefs:!1};return{paths:he(e.root.children,n,s).map((o,a)=>({id:`path-${a+1}`,description:Oc(o),steps:o.steps,conditions:o.conditions,hasLoops:o.hasLoops,hasUnresolvedRefs:o.hasUnresolvedRefs})),limitHit:s.hasHitLimit}}function he(e,t,r){if(e.length===0)return[t];let s=[t];for(let n of e){let i=[];for(let c of s)i.push(...ue(n,c,r));if(s=i,n.type==="terminal"){let c=n;if(c.terminalKind==="return"||c.terminalKind==="throw")return s}}return s}function ue(e,t,r){switch(e.type){case"effect":return fc(e,t);case"generator":return pc(e,t,r);case"pipe":return gc(e,t,r);case"parallel":return mc(e,t,r);case"race":return yc(e,t,r);case"error-handler":return hc(e,t,r);case"retry":case"timeout":return Sc(e,t,r);case"resource":return xc(e,t,r);case"conditional":return Ec(e,t,r);case"loop":return bc(e,t,r);case"layer":return Nc(e,t,r);case"stream":return Cc(e,t,r);case"concurrency-primitive":case"fiber":return wc(e,t,r);case"decision":return Tc(e,t,r);case"switch":return kc(e,t,r);case"try-catch":return vc(e,t,r);case"terminal":return Ic(e,t,r);case"cause":return Fc(e,t,r);case"exit":case"schedule":return $c(e,t);case"match":return Ac(e,t,r);case"transform":return Rc(e,t,r);case"channel":return Dc(e,t,r);case"sink":return Pc(e,t,r);case"interruption":return Mc(e,t,r);case"opaque":return[t];case"unknown":return[t];default:return[t]}}function fc(e,t){let r={nodeId:e.id,name:e.name??e.callee,repeated:!1};return[{...t,steps:[...t.steps,r]}]}function pc(e,t,r){let s=e.yields.map(n=>n.effect);return he(s,t,r)}function gc(e,t,r){let s=[e.initial,...e.transformations];return he(s,t,r)}function mc(e,t,r){let s=[t];for(let n of e.children){let i=[];for(let c of s){let o=ue(n,c,r);for(let a of o)i.push({steps:a.steps,conditions:a.conditions,hasLoops:c.hasLoops||a.hasLoops,hasUnresolvedRefs:c.hasUnresolvedRefs||a.hasUnresolvedRefs})}s=i}return s}function yc(e,t,r){if(e.children.length===0)return[t];if(r.hasHitLimit||r.pathCount+e.children.length>=r.opts.maxPaths){r.hasHitLimit=!0;let c=e.children[0];return c?ue(c,t,r):[t]}let n=[],i=r.opts.maxPaths;for(let c of e.children){if(n.length>=i){r.hasHitLimit=!0;break}let o=ue(c,t,r),a=i-n.length,d=o.slice(0,a);n.push(...d),d.length<o.length&&(r.hasHitLimit=!0)}return r.pathCount+=Math.max(0,n.length-1),n.length>0?n:[t]}function hc(e,t,r){let s=ue(e.source,t,r);if(!e.handler)return s;let n=ue(e.handler,t,r);return[...s,...n]}function Sc(e,t,r){return ue(e.source,t,r)}function xc(e,t,r){let s=[e.acquire,e.release];return e.use&&s.push(e.use),he(s,t,r)}function Ec(e,t,r){let s={expression:e.condition,mustBe:e.conditionalType!=="unless",location:e.location},n={...t,conditions:[...t.conditions,s]},i=ue(e.onTrue,n,r),c={expression:e.condition,mustBe:e.conditionalType==="unless",location:e.location},o={...t,conditions:[...t.conditions,c]};if(e.onFalse){let a=ue(e.onFalse,o,r);return[...i,...a]}return[...i,o]}function bc(e,t,r){return ue(e.body,t,r).map(n=>({...n,steps:n.steps.map((i,c)=>c>=t.steps.length?{...i,repeated:!0}:i),hasLoops:!0}))}function Nc(e,t,r){return he(e.operations,t,r)}function Cc(e,t,r){let s={nodeId:e.id,name:e.pipeline.length>0?`Stream.${e.pipeline.map(i=>i.operation).join(" \u2192 ")}`:"Stream",repeated:!1},n={...t,steps:[...t.steps,s]};return ue(e.source,n,r)}function wc(e,t,r){let s={nodeId:e.id,name:e.type==="concurrency-primitive"?`${e.primitive}.${e.operation}`:e.operation,repeated:!1},n={...t,steps:[...t.steps,s]},i=e.type==="concurrency-primitive"?e.source:e.fiberSource;return i?ue(i,n,r):[n]}function Tc(e,t,r){let s={expression:e.condition,mustBe:!0,location:e.location},n={...t,conditions:[...t.conditions,s]},i=he(e.onTrue,n,r);if(e.onFalse&&e.onFalse.length>0){let a={expression:e.condition,mustBe:!1,location:e.location},d={...t,conditions:[...t.conditions,a]},l=he(e.onFalse,d,r);return[...i,...l]}let c={expression:e.condition,mustBe:!1,location:e.location},o={...t,conditions:[...t.conditions,c]};return[...i,o]}function kc(e,t,r){let s=[];for(let n of e.cases){let i=n.labels.join(" / "),c={expression:`${e.expression} === ${i}`,mustBe:!0,location:e.location},o={...t,conditions:[...t.conditions,c]},a=he(n.body,o,r);s.push(...a)}return s.length>0?s:[t]}function vc(e,t,r){let s=he(e.tryBody,t,r),n=[];if(e.catchBody&&e.catchBody.length>0){let c={expression:"throws",mustBe:!0,location:e.location},o={...t,conditions:[...t.conditions,c]};n.push(...he(e.catchBody,o,r))}let i=[...s,...n];if(e.finallyBody&&e.finallyBody.length>0){let c=[];for(let o of i)c.push(...he(e.finallyBody,o,r));return c}return i}function Ic(e,t,r){let s=t;switch(e.value&&e.value.length>0&&(s=he(e.value,t,r)[0]??t),e.terminalKind){case"return":case"throw":return[{...s,steps:[...s.steps,{nodeId:e.id,name:e.terminalKind,repeated:!1}]}];case"break":case"continue":return[s]}}function $c(e,t){let r={nodeId:e.id,name:e.name??e.type,repeated:!1};return[{...t,steps:[...t.steps,r]}]}function Fc(e,t,r){let s={nodeId:e.id,name:e.name??`Cause.${e.causeOp}`,repeated:!1},n={...t,steps:[...t.steps,s]};return e.children&&e.children.length>0?he([...e.children],n,r):[n]}function Ac(e,t,r){let s={nodeId:e.id,name:e.name??`Match.${e.matchOp}`,repeated:!1};return[{...t,steps:[...t.steps,s]}]}function Rc(e,t,r){let s=t;e.source&&(s=ue(e.source,t,r)[0]??t);let n={nodeId:e.id,name:e.name??e.transformType,repeated:!1};return[{...s,steps:[...s.steps,n]}]}function Dc(e,t,r){let s=t;e.source&&(s=ue(e.source,t,r)[0]??t);let n={nodeId:e.id,name:e.name??`Channel${e.pipeline.length>0?`.${e.pipeline.map(i=>i.operation).join(".")}`:""}`,repeated:!1};return[{...s,steps:[...s.steps,n]}]}function Pc(e,t,r){let s=t;e.source&&(s=ue(e.source,t,r)[0]??t);let n={nodeId:e.id,name:e.name??`Sink${e.pipeline.length>0?`.${e.pipeline.map(i=>i.operation).join(".")}`:""}`,repeated:!1};return[{...s,steps:[...s.steps,n]}]}function Mc(e,t,r){let s={nodeId:e.id,name:e.name??e.interruptionType,repeated:!1},n={...t,steps:[...t.steps,s]};if(e.source){let i=ue(e.source,n,r);if(e.handler){let c=ue(e.handler,n,r);return[...i,...c]}return i}return[n]}function Oc(e){let t=[];if(e.conditions.length>0){let s=e.conditions.map(n=>{let i=n.mustBe?"is true":"is false";return`${n.expression.length>30?n.expression.slice(0,30)+"...":n.expression} ${i}`});t.push(`When ${s.join(" AND ")}`)}let r=e.steps.map(s=>{let n=s.name??s.nodeId;return s.repeated?`${n} (repeated)`:n}).join(" \u2192 ");return r&&t.push(`Steps: ${r}`),e.hasLoops&&t.push("[contains loops]"),e.hasUnresolvedRefs&&t.push("[has unresolved refs]"),t.join(". ")||"Empty path"}import{Effect as ii}from"effect";var oi={pretty:!0,includeMetadata:!0,compact:!1},ai=(e,t)=>ii.gen(function*(){let r={...oi,...t},s=r.pretty?2:void 0,n=r.includeMetadata?{root:e.root,metadata:e.metadata,references:e.references instanceof Map?Object.fromEntries(e.references):e.references}:{root:e.root};return JSON.stringify(n,li,s)}),ci=(e,t)=>ii.gen(function*(){let r={...oi,...t},s=r.pretty?2:void 0,n=e.map(i=>r.includeMetadata?{root:i.root,metadata:i.metadata,references:i.references instanceof Map?Object.fromEntries(i.references):i.references}:{root:i.root});return JSON.stringify(n,li,s)}),li=(e,t)=>t instanceof Map?Object.fromEntries(t):t instanceof Set?Array.from(t):typeof t=="bigint"?t.toString():(t&&typeof t=="object"&&"_tag"in t,t);import{Option as Lc}from"effect";function Wc(e){return e?e.typeConfidence:"unknown"}function Kc(e){return!e||e==="never"?"never":e}function Bc(e){return!e||e==="never"?[]:De(e).filter(t=>t!=="never")}function ur(e){switch(e.type){case"effect":return e.displayName??e.callee;case"generator":return e.name??"generator";case"pipe":return e.name??"pipe";default:return e.name??e.type}}function We(e,t,r){for(let s of e){let n=jc(s,r);n&&t.push(n);let i=r;if(s.type==="loop"){i={...i,inLoop:!0,loopType:s.loopType,iterationSource:s.iterSource},We([s.body],t,i);continue}if(s.type==="retry"){let o=s.scheduleInfo?{attempts:s.scheduleInfo.maxRetries??"unlimited",backoff:s.scheduleInfo.baseStrategy}:{attempts:"unlimited",backoff:s.schedule??"unknown"};i={...i,inRetry:o},We([s.source],t,i);continue}if(s.type==="timeout"){i={...i,inTimeout:{ms:s.duration??"unknown"}},We([s.source],t,i);continue}if(s.type==="resource"){s.use&&We([s.use],t,r);continue}if(s.type==="error-handler"){We([s.source],t,r),s.handler&&We([s.handler],t,r);continue}if(s.type==="generator"){let o=s.yields.map(a=>a.effect);We(o,t,i);continue}let c=Lc.getOrElse(P(s),()=>[]);c.length>0&&We(c,t,i)}}function jc(e,t){switch(e.type){case"effect":{let r=e.typeSignature,s=r?.successType??"unknown",n=r?.errorType??"never";return{stepId:e.id,name:e.displayName??e.callee,callee:e.callee,outputType:s,outputTypeKind:Wc(r),outputTypeDisplay:s,outputTypeText:r?`Effect<${r.successType}, ${r.errorType}, ${r.requirementsType}>`:`Effect<${s}>`,errorTypeDisplay:Kc(n),errors:Bc(n),depSource:e.serviceCall?.serviceType,stepKind:"effect",...t.inRetry?{retry:t.inRetry}:{},...t.inTimeout?{timeout:t.inTimeout}:{},...t.inLoop?{repeats:"loop",loopType:t.loopType,iterationSource:t.iterationSource}:{}}}case"retry":{let r=e.scheduleInfo?{attempts:e.scheduleInfo.maxRetries??"unlimited",backoff:e.scheduleInfo.baseStrategy}:{attempts:"unlimited",backoff:e.schedule??"unknown"};return{stepId:e.id,name:e.name??"Retry",callee:"Effect.retry",outputType:"void",outputTypeKind:"unknown",outputTypeDisplay:"void",outputTypeText:"retry wrapper",errorTypeDisplay:"never",errors:[],stepKind:"retry",retry:r}}case"timeout":return{stepId:e.id,name:e.name??"Timeout",callee:"Effect.timeout",outputType:"void",outputTypeKind:"unknown",outputTypeDisplay:"void",outputTypeText:"timeout wrapper",errorTypeDisplay:"TimeoutException",errors:["TimeoutException"],stepKind:"timeout",timeout:{ms:e.duration??"unknown"}};case"resource":return{stepId:e.id,name:e.name??"Resource",callee:"Effect.acquireRelease",outputType:"void",outputTypeKind:"unknown",outputTypeDisplay:"void",outputTypeText:"resource lifecycle",errorTypeDisplay:"never",errors:[],stepKind:"resource",kind:"resource",acquire:ur(e.acquire),use:e.use?ur(e.use):void 0,release:ur(e.release)};case"error-handler":{if(e.handlerType==="catchTag"||e.handlerType==="catchTags"){let r=e.errorTags?[...e.errorTags]:e.errorTag?[e.errorTag]:[];return{stepId:e.id,name:e.name??e.handlerType,callee:`Effect.${e.handlerType}`,outputType:"void",outputTypeKind:"unknown",outputTypeDisplay:"void",outputTypeText:`error handler (${e.handlerType})`,errorTypeDisplay:r.join(" | ")||"unknown",errors:r,stepKind:"error-handler"}}return null}default:return null}}function qc(e,t,r){let s=nt(e,{direction:t?.direction??"TB"}),n=[];return We(e.root.children,n,{}),{title:e.root.programName,code:r??"",mermaid:s,stepDetails:n}}function di(e,t,r){return e.map(s=>qc(s,t,r))}import{readdir as _c}from"fs/promises";import{join as zc,extname as Uc}from"path";import{Project as Hc,SyntaxKind as O}from"ts-morph";function R(e,t,r,s,n,i,c){let{line:o,column:a}=s.getLineAndColumnAtPos(r.getStart());e.push({filePath:t,line:o+1,column:a,pattern:n,suggestion:i,codeSnippet:c??s.getText().slice(r.getStart(),r.getStart()+80).replace(/\n/g," ")})}function fr(e,t){let r=[],s=new Hc({skipAddingFilesFromTsConfig:!0}),n=t?s.createSourceFile(e,t):s.addSourceFileAtPath(e);for(let l of n.getDescendantsOfKind(O.TryStatement))R(r,e,l,n,"try/catch","Effect.try or Effect.tryPromise with catch handler");for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u==="Promise.all"||u.endsWith(".all")&&u.includes("Promise"))&&R(r,e,l,n,"Promise.all",'Effect.all([...], { concurrency: "unbounded" })'),(u==="Promise.race"||u.endsWith(".race")&&u.includes("Promise"))&&R(r,e,l,n,"Promise.race","Effect.race(first, second)")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u==="setTimeout"||u==="setInterval")&&R(r,e,l,n,u,u==="setTimeout"?"Effect.sleep(Duration.millis(n))":"Schedule.spaced(Duration.millis(n))"),(u==="setImmediate"||u==="process.setImmediate")&&R(r,e,l,n,"setImmediate","Effect.sync + queueMicrotask or Effect.async")}for(let l of n.getDescendantsOfKind(O.NewExpression)){let u=l.getExpression().getText();(u==="XMLHttpRequest"||u.includes("XMLHttpRequest"))&&R(r,e,l,n,"new XMLHttpRequest()","HttpClient.request or @effect/platform HttpClient")}for(let l of n.getDescendantsOfKind(O.NewExpression)){let u=l.getExpression().getText();(u==="Worker"||u.includes("Worker"))&&R(r,e,l,n,"new Worker()","Worker.make or @effect/platform Worker")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u==="fs.exists"||u.endsWith(".exists")&&u.startsWith("fs."))&&l.getArguments().length>=2&&R(r,e,l,n,"fs.exists (callback)","Effect.promise or fs.promises.access")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u.endsWith(".request")&&(u.includes("http")||u.includes("https"))||u==="request"&&n.getText().includes("http"))&&R(r,e,l,n,"http.request / https.request","HttpClient.request or @effect/platform HttpClient")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u.startsWith("dns.")||u.includes("dns."))&&(u.includes("lookup")||u.includes("resolve")||u.includes("reverse"))&&R(r,e,l,n,"dns (callback)","Effect.promise or dns.promises")}for(let l of n.getDescendantsOfKind(O.CallExpression))l.getExpression().getText()==="fetch"&&R(r,e,l,n,"fetch()","HttpClient.request or @effect/platform HttpClient");for(let l of n.getDescendantsOfKind(O.NewExpression)){let u=l.getExpression().getText();(u==="EventEmitter"||u.includes("EventEmitter"))&&R(r,e,l,n,"new EventEmitter()","PubSub.bounded<EventType>() or PubSub.unbounded<EventType>()")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u.endsWith(".on(")||u.endsWith(".addListener("))&&(u.includes("Emitter")||u.includes("emitter"))&&R(r,e,l,n,"EventEmitter.on / addListener","PubSub.subscribe for PubSub"),u.endsWith(".emit(")&&(u.includes("Emitter")||u.includes("emitter"))&&R(r,e,l,n,"EventEmitter.emit","PubSub.publish for PubSub")}for(let l of n.getDescendantsOfKind(O.ClassDeclaration)){let f=l.getName(),u=l.getText();f&&(u.includes("new ")||u.includes("constructor"))&&(f.endsWith("Service")||f.endsWith("Repository")||f.endsWith("Client"))&&R(r,e,l,n,`class ${f} (manual DI)`,`Context.Tag<${f}>() + Layer.effect or Layer.succeed`)}for(let l of n.getDescendantsOfKind(O.NewExpression)){let u=l.getExpression().getText();(u.endsWith("Service")||u.endsWith("Repository")||u.endsWith("Client"))&&!u.includes("Context")&&!u.includes("Layer")&&R(r,e,l,n,`new ${u}()`,"Context.Tag + Layer.effect for dependency injection")}for(let l of n.getDescendantsOfKind(O.FunctionDeclaration))(l.getModifiers().some(f=>f.getText()==="async")||l.getText().startsWith("async"))&&R(r,e,l,n,"async function","Effect.gen or Effect.pipe with flatMap");for(let l of n.getDescendantsOfKind(O.ArrowFunction))l.getText().startsWith("async")&&R(r,e,l,n,"async arrow function","Effect.gen or Effect.pipe with flatMap");for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();u.endsWith(".then")&&u.includes("Promise")&&R(r,e,l,n,"Promise.then","Effect.flatMap for sequential composition"),(u==="Promise.allSettled"||u.endsWith(".allSettled")&&u.includes("Promise"))&&R(r,e,l,n,"Promise.allSettled","Effect.all with merge or separate error handling"),u.endsWith(".catch")&&(u.includes("Promise")||u.includes(".then"))&&R(r,e,l,n,"Promise.catch","Effect.catchAll or Effect.catchTag for typed error handling"),u.endsWith(".finally")&&(u.includes("Promise")||u.includes(".then"))&&R(r,e,l,n,"Promise.finally","Effect.ensuring for cleanup")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u==="addEventListener"||u.endsWith(".addEventListener"))&&R(r,e,l,n,"addEventListener","Effect.async or EventTarget + Effect.asyncInterrupt")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u==="fs.readFile"||u==="fs.writeFile"||u==="readFile"||u==="writeFile"||u.endsWith(".readFile")&&u.startsWith("fs.")||u.endsWith(".writeFile")&&u.startsWith("fs."))&&l.getArguments().length>=2&&R(r,e,l,n,u.includes("write")?"fs.writeFile (callback)":"fs.readFile (callback)","Effect.promise or fs.promises + Effect.tryPromise")}for(let l of n.getDescendantsOfKind(O.ThrowStatement))R(r,e,l,n,"throw","Effect.fail(error) for typed error channel");for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u==="promisify"||u.endsWith(".promisify"))&&R(r,e,l,n,"util.promisify","Effect.tryPromise or Effect.async for callback-style APIs")}for(let l of n.getDescendantsOfKind(O.NewExpression))l.getExpression().getText()==="Promise"&&R(r,e,l,n,"new Promise(...)","Effect.async or Effect.promise for callback-style");for(let l of n.getDescendantsOfKind(O.ForOfStatement))l.getAwaitKeyword()&&R(r,e,l,n,"for await...of","Stream.iterate or Effect.asyncIterable for async iteration");for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u==="readFileSync"||u==="writeFileSync"||u==="existsSync"||u.endsWith(".readFileSync")||u.endsWith(".writeFileSync")||u.endsWith(".existsSync"))&&R(r,e,l,n,u,"Effect.promise or fs/promises + Effect.tryPromise")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u==="process.nextTick"||u.endsWith(".nextTick")&&u.includes("process"))&&R(r,e,l,n,"process.nextTick","Effect.sync + queueMicrotask or Effect.async")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u==="queueMicrotask"||u.endsWith(".queueMicrotask"))&&R(r,e,l,n,"queueMicrotask","Effect.sync for deferred execution")}for(let l of n.getDescendantsOfKind(O.NewExpression)){let u=l.getExpression().getText();(u==="WebSocket"||u.includes("WebSocket"))&&R(r,e,l,n,"new WebSocket()","Effect.async or @effect/platform WebSocket")}for(let l of n.getDescendantsOfKind(O.NewExpression)){let u=l.getExpression().getText();(u==="MessageChannel"||u.includes("MessageChannel"))&&R(r,e,l,n,"new MessageChannel()","Effect.async or Queue for cross-context messaging")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u==="fs.appendFile"||u.endsWith(".appendFile")&&u.startsWith("fs."))&&l.getArguments().length>=2&&R(r,e,l,n,"fs.appendFile (callback)","Effect.promise or fs.promises.appendFile")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();if((u==="fs.mkdir"||u==="fs.stat"||u==="fs.unlink"||u.endsWith(".mkdir")&&u.startsWith("fs.")||u.endsWith(".stat")&&u.startsWith("fs.")||u.endsWith(".unlink")&&u.startsWith("fs."))&&l.getArguments().length>=2){let p=u.includes("mkdir")?"fs.mkdir":u.includes("stat")?"fs.stat":"fs.unlink";R(r,e,l,n,`${p} (callback)`,"Effect.promise or fs.promises")}}for(let l of n.getDescendantsOfKind(O.NewExpression)){let u=l.getExpression().getText();(u==="MutationObserver"||u.includes("MutationObserver"))&&R(r,e,l,n,"new MutationObserver()","Effect.async or Effect.asyncInterrupt for DOM observation")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u==="requestIdleCallback"||u.endsWith(".requestIdleCallback"))&&R(r,e,l,n,"requestIdleCallback","Effect.async or Effect.sync for idle-time work")}for(let l of n.getDescendantsOfKind(O.NewExpression)){let u=l.getExpression().getText();(u==="BroadcastChannel"||u.includes("BroadcastChannel"))&&R(r,e,l,n,"new BroadcastChannel()","PubSub or Effect.async for cross-tab messaging")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();if((u==="fs.rename"||u==="fs.realpath"||u.endsWith(".rename")&&u.startsWith("fs.")||u.endsWith(".realpath")&&u.startsWith("fs."))&&l.getArguments().length>=2){let p=u.includes("realpath")?"fs.realpath":"fs.rename";R(r,e,l,n,`${p} (callback)`,"Effect.promise or fs.promises")}}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText(),g=(u==="fs.readdir"||u.endsWith(".readdir")&&u.startsWith("fs."))&&l.getArguments().length>=2,p=(u==="fs.copyFile"||u.endsWith(".copyFile")&&u.startsWith("fs."))&&l.getArguments().length>=2;g&&R(r,e,l,n,"fs.readdir (callback)","Effect.promise or fs.promises.readdir"),p&&R(r,e,l,n,"fs.copyFile (callback)","Effect.promise or fs.promises.copyFile")}for(let l of n.getDescendantsOfKind(O.NewExpression)){let u=l.getExpression().getText();(u==="FileReader"||u.includes("FileReader"))&&R(r,e,l,n,"new FileReader()","Effect.async or FileReader + Effect.asyncInterrupt")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText(),g=(u==="fs.mkdtemp"||u.endsWith(".mkdtemp")&&u.startsWith("fs."))&&l.getArguments().length>=2,p=(u==="fs.symlink"||u.endsWith(".symlink")&&u.startsWith("fs."))&&l.getArguments().length>=2;g&&R(r,e,l,n,"fs.mkdtemp (callback)","Effect.promise or fs.promises.mkdtemp"),p&&R(r,e,l,n,"fs.symlink (callback)","Effect.promise or fs.promises.symlink")}for(let l of n.getDescendantsOfKind(O.NewExpression)){let u=l.getExpression().getText();(u==="ResizeObserver"||u==="IntersectionObserver"||u.includes("ResizeObserver")||u.includes("IntersectionObserver"))&&R(r,e,l,n,`new ${u}()`,"Effect.async or Effect.asyncInterrupt for DOM observation")}let i=n.getText().includes("child_process");for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u.includes("child_process")&&u.endsWith(".fork")||i&&u==="fork")&&R(r,e,l,n,"child_process.fork","Worker.make or @effect/platform Worker")}for(let l of n.getDescendantsOfKind(O.NewExpression)){let u=l.getExpression().getText();(u==="AbortController"||u.includes("AbortController"))&&R(r,e,l,n,"new AbortController()","Effect.Scoped or Effect.interruptible for cancellation")}let c=n.getText(),o=c.includes("child_process");for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();((u.endsWith(".exec")||u.endsWith(".execSync")||u.endsWith(".spawn"))&&u.includes("child_process")||o&&(u==="exec"||u==="execSync"||u==="spawn"))&&R(r,e,l,n,"child_process.exec/spawn","@effect/platform CommandExecutor or Effect.promise")}for(let l of n.getDescendantsOfKind(O.PropertyAccessExpression))l.getExpression().getText()==="process"&&l.getName()==="env"&&R(r,e,l,n,"process.env","Config.string or Config.forEffect for typed config");if(c.includes("rxjs")||c.includes("Observable"))for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u.includes("Observable")||u.includes("of")&&u.includes("rxjs"))&&R(r,e,l,n,"RxJS Observable","Stream from @effect/platform or Effect Stream")}for(let l of n.getDescendantsOfKind(O.NewExpression)){let u=l.getExpression().getText();(u.includes("Observable")||u.includes("Subject"))&&R(r,e,l,n,"RxJS Observable/Subject","Stream or PubSub for Effect")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u==="requestAnimationFrame"||u.endsWith(".requestAnimationFrame"))&&R(r,e,l,n,"requestAnimationFrame","Effect.async or Effect.sync + queueMicrotask for scheduling")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u.includes("crypto.")||u.includes("randomBytes")||u.includes("scrypt")||u.includes("pbkdf2"))&&l.getArguments().length>=2&&R(r,e,l,n,"crypto (callback)","Effect.promise or crypto.webcrypto / node:crypto promises")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u==="createReadStream"||u==="createWriteStream"||u.endsWith(".createReadStream")||u.endsWith(".createWriteStream"))&&R(r,e,l,n,u,"Stream.fromReadable or @effect/platform FileSystem/Stream")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();u.includes("cluster")&&u.endsWith(".fork")&&R(r,e,l,n,"cluster.fork","Worker.make or @effect/platform Worker pool")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let f=l.getExpression(),u=f.getText();if(u==="createServer"||u==="connect"||u.endsWith(".createServer")||u.endsWith(".connect")){let g=f.getText();(g.includes("net")||g.includes("tls"))&&R(r,e,l,n,g,"Effect.async or @effect/platform Socket/Server")}}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();u.includes("zlib.")&&(u.includes("deflate")||u.includes("inflate")||u.includes("gzip")||u.includes("gunzip"))&&R(r,e,l,n,"zlib (callback)","Effect.promise or zlib.promises")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u==="createInterface"||u.endsWith(".createInterface"))&&u.includes("readline")&&R(r,e,l,n,"readline.createInterface","Effect.async or Stream for line-by-line reading")}let d=n.getText().includes("stream");for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u.endsWith(".pipeline")&&u.includes("stream")||d&&u==="pipeline")&&R(r,e,l,n,"stream.pipeline (callback)","Effect.promise or stream.promises.pipeline")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u==="once"||u.endsWith(".once"))&&(u.includes("events")||n.getText().includes("from 'events'"))&&R(r,e,l,n,"events.once","Effect.async for one-shot event")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let f=l.getExpression(),u=f.getText();(u==="watch"||u==="watchFile"||u.endsWith(".watch")||u.endsWith(".watchFile"))&&(u.includes("fs")||f.getText().includes("fs."))&&R(r,e,l,n,"fs.watch / fs.watchFile","Effect.async or fs.watch with EventEmitter")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u.includes("runInNewContext")||u.includes("runInContext")||u.includes("runInThisContext"))&&u.includes("vm")&&R(r,e,l,n,"vm.runIn*","Effect.sync for isolated code execution")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u==="parse"||u.endsWith(".parse"))&&u.includes("url")&&R(r,e,l,n,"url.parse (deprecated)","new URL() or URL.parse for standard parsing")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u.endsWith(".spawnSync")&&u.includes("child_process")||n.getText().includes("child_process")&&u==="spawnSync")&&R(r,e,l,n,"child_process.spawnSync","@effect/platform CommandExecutor or Effect.promise")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();(u==="glob"||u.endsWith(".glob"))&&n.getText().includes("glob")&&l.getArguments().length>=2&&R(r,e,l,n,"glob (callback)","Effect.promise or glob promise API")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText(),g=u.includes("assert")&&u.endsWith(".throws"),p=u.endsWith(".rejects")&&u.includes("expect");(g||p)&&R(r,e,l,n,p?"expect().rejects":"assert.throws","Effect.runPromiseExit + Exit.match for testing Effect failures")}for(let l of n.getDescendantsOfKind(O.CallExpression)){let u=l.getExpression().getText();u.includes("tls")&&(u.endsWith(".connect")||u.endsWith(".createServer"))&&R(r,e,l,n,"tls.connect / tls.createServer","Effect.async or @effect/platform Socket/TLS")}return r}async function ui(e,t){let r=t?.extensions??[".ts",".tsx"],s=[],n=0;async function i(c){let o=await _c(c,{withFileTypes:!0}).catch(()=>[]);for(let a of o){let d=zc(c,a.name);if(a.isDirectory())a.name!=="node_modules"&&a.name!==".git"&&a.name!=="dist"&&await i(d);else if(a.isFile()&&r.includes(Uc(a.name))){n++;try{s.push(...fr(d))}catch{}}}}return await i(e),{opportunities:s,fileCount:n}}function pr(e){let t=[];t.push("Migration Opportunities Found:"),t.push("");for(let r of e.opportunities)t.push(` ${r.filePath}:${r.line}:${r.column} ${r.pattern}`),t.push(` \u2192 ${r.suggestion}`),r.codeSnippet&&t.push(` Snippet: ${r.codeSnippet.slice(0,60)}...`),t.push("");return t.push(`Total: ${e.opportunities.length} opportunities in ${e.fileCount} files`),t.join(`
|
|
43
|
+
`)}import{createHash as Gc}from"crypto";import{readFile as Vc,writeFile as Jc,mkdir as Qc}from"fs/promises";import{stat as Zc}from"fs/promises";import{join as fi}from"path";var pi=".effect-analyzer-cache",gi=1;function mi(e){return Gc("sha256").update(e,"utf-8").digest("hex").slice(0,16)}function yi(e,t){let r=t.replace(/[^a-zA-Z0-9._-]/g,"_");return fi(e,pi,`${r}.json`)}async function hi(e,t,r=process.cwd()){try{let s=yi(r,e),n=mi(t),i=await Vc(s,"utf-8"),c=JSON.parse(i);if(c.version===gi&&c.contentHash===n)return c.irs}catch{}return null}async function Si(e,t,r,s=process.cwd()){try{let n=fi(s,pi);await Qc(n,{recursive:!0});let i=await Zc(e).catch(()=>null),c={version:gi,contentHash:mi(t),mtimeMs:i?.mtimeMs??0,irs:r};await Jc(yi(s,e),JSON.stringify(c),"utf-8")}catch{}}import{Effect as Ne,Option as wi}from"effect";import{readdir as Ti,readFile as nl,stat as rl}from"fs/promises";import{readFileSync as ki}from"fs";import{join as on,extname as vi,resolve as Ci,basename as sl}from"path";import{Option as xi}from"effect";function Yc(e,t){let{SyntaxKind:r}=T(),s=[],n=e.getProject().getTypeChecker(),i=e.getDescendantsOfKind(r.ClassDeclaration);for(let c of i){let o=c.getName();if(!o)continue;let a=c.getExtends();if(!a)continue;let d=a.getText();if(!d.includes("Context.Tag")&&!d.includes("Effect.Service"))continue;let l=o,f=/Context\.Tag\s*\(\s*['"]([^'"]+)['"]\s*\)/.exec(d);f?.[1]&&(l=f[1]);let u=a.getTypeArguments();if(u.length<2){let h=a.getExpression();h&&"getTypeArguments"in h&&typeof h.getTypeArguments=="function"&&(u=h.getTypeArguments())}let g={tagId:l,methods:[],properties:[]},p;if(u.length>=2){let h=u[1];if(h)try{p=h.getText();let N=n.getTypeAtLocation(h),x=[],F=[];for(let E of N.getProperties()){let b=E.getName();if(b.startsWith("_")||b==="constructor")continue;n.getTypeOfSymbolAtLocation(E,h).getCallSignatures().length>0?x.push(b):F.push(b)}g={tagId:l,methods:x,properties:F}}catch{}}let m=c.getStart(),y=e.getLineAndColumnAtPos(m);s.push({tagId:l,className:o,filePath:t,location:{filePath:t,line:y.line,column:y.column-1},definition:g,interfaceTypeText:p})}return s}function Xc(e,t,r){let{SyntaxKind:s}=T(),n=[],i=e.getDescendantsOfKind(s.VariableDeclaration);for(let c of i){let o=c.getInitializer();if(!o)continue;let a=o.getText(),d=/Layer\.(effect|succeed|sync|scoped)\s*\(\s*/.exec(a);if(!d)continue;let l=d[1],f=c.getName(),u;if(o.getKind()===s.CallExpression){let x=o.getArguments?.();if(x&&x.length>0){let F=x[0];if(!F)continue;let E=F.getText().trim();u=r.get(E)}}if(!u){for(let x of r.keys())if(a.includes(`Layer.${l}(${x}`)||a.includes(`Layer.${l}(
|
|
44
|
+
${x}`)){u=r.get(x);break}}if(!u)continue;let g=[],p=/Layer\.provide\s*\(([^)]+)\)/.exec(a);if(p?.[1]){let x=p[1].trim();for(let[F,E]of r.entries())E!==u&&x.includes(F)&&!g.includes(E)&&g.push(E)}let m=a.matchAll(/yield\*\s+(\w+)/g);for(let x of m){let F=x[1],E=F?r.get(F):void 0;E&&E!==u&&!g.includes(E)&&g.push(E)}let y=a.matchAll(/yield\s*\*\s*(\w+)/g);for(let x of y){let F=x[1],E=F?r.get(F):void 0;E&&E!==u&&!g.includes(E)&&g.push(E)}let h=c.getStart(),N=e.getLineAndColumnAtPos(h);n.push({providesServiceId:u,implementation:{name:f,filePath:t,location:{filePath:t,line:N.line,column:N.column-1},kind:l,requires:g}})}return n}function el(e){let t=new Map;for(let[r,s]of e)for(let n of s){let i=n.root.programName;if(n.root.requiredServices)for(let c of n.root.requiredServices){let o=t.get(c.serviceId)??[];o.push({programName:i,filePath:r,location:c.requiredAt}),t.set(c.serviceId,o)}Ei(n.root.children,i,r,t)}return t}function Ei(e,t,r,s){for(let n of e){if(n.type==="effect"&&n.serviceCall){let c=n.serviceCall.serviceType;if(c){let o=s.get(c)??[];o.some(a=>a.programName===t&&a.filePath===r)||(o.push({programName:t,filePath:r,location:n.location}),s.set(c,o))}}let i=xi.getOrElse(P(n),()=>[]);i.length>0&&Ei(i,t,r,s)}}function tl(e){let t=[],r=new Set,s=new Set;function n(i){if(r.has(i)||s.has(i))return;s.add(i);let c=e.get(i);if(c)for(let o of c.dependencies)n(o);s.delete(i),r.add(i),t.push(i)}for(let i of e.keys())n(i);return t}function bi(e,t,r,s=new Set){let n=[];if(s.has(e))return n;s.add(e);for(let i of t)for(let c of i.requires){n.includes(c)||n.push(c);let o=r.get(c);if(o)for(let a of bi(c,o,r,s))n.includes(a)||n.push(a)}return n}function gr(e,t){let r=new Map;if(t)for(let[u,g]of t){let p=Yc(g,u);for(let m of p)r.has(m.tagId)||r.set(m.tagId,m)}for(let[u,g]of e)for(let p of g)if(p.metadata.serviceDefinitions)for(let m of p.metadata.serviceDefinitions)r.has(m.tagId)||r.set(m.tagId,{tagId:m.tagId,className:m.tagId,filePath:u,location:{filePath:u,line:1,column:0},definition:m});let s=new Set(r.keys()),n=new Map;for(let[u,g]of r)n.has(u)||n.set(u,u),n.has(g.className)||n.set(g.className,u);let i=new Set;for(let u of e.values())for(let g of u)if(g.root.requiredServices)for(let p of g.root.requiredServices)i.add(p.serviceId);let c=new Map;if(t)for(let[u,g]of t){let p=Xc(g,u,n);for(let m of p){if(!s.has(m.providesServiceId))continue;let y=c.get(m.providesServiceId)??[];y.push(m.implementation),c.set(m.providesServiceId,y)}}for(let[u,g]of e)for(let p of g)Ni(p.root.children,u,s,n,c,p);let o=el(e),a=new Map,d=[];for(let[u,g]of r){let p=c.get(u)??[],m=o.get(u)??[],y=bi(u,p,c);a.set(u,{serviceId:u,className:g.className,definitionFilePath:g.filePath,definitionLocation:g.location,definition:g.definition,interfaceTypeText:g.interfaceTypeText,layerImplementations:p,consumers:m,dependencies:y})}let l=new Set(i);for(let u of o.keys())l.add(u);for(let u of l)a.has(u)||d.push(u);let f=tl(a);return{services:a,unresolvedServices:d,topologicalOrder:f}}function Ni(e,t,r,s,n,i){for(let c of e){if(c.type==="layer"&&c.provides)for(let a of c.provides){let d=s.get(a)??(r.has(a)?a:void 0);if(d&&r.has(d)){let l=n.get(d)??[],f=c.requires?c.requires.map(u=>s.get(u)??u).filter(u=>r.has(u)):[];l.some(u=>u.name===(c.name??i.root.programName)&&u.filePath===t)||(l.push({name:c.name??i.root.programName,filePath:t,location:c.location??{filePath:t,line:1,column:0},kind:"other",requires:f}),n.set(d,l))}}let o=xi.getOrElse(P(c),()=>[]);o.length>0&&Ni(o,t,r,s,n,i)}}var sn={extensions:[".ts",".tsx"],maxDepth:10,knownEffectInternalsRoot:void 0,includePerFileTiming:!1,excludeFromSuspiciousZeros:[],buildServiceMap:!1};function il(e){let t=0,r=0,s=n=>{for(let i of n){t++,i.type==="unknown"&&r++;let c=wi.getOrElse(P(i),()=>[]);c.length>0&&s(c)}};return s(e),{total:t,unknown:r}}function ol(e){let t=new Map,r=s=>{for(let n of s){if(Ir(n)){let c=n.reason;t.set(c,(t.get(c)??0)+1)}let i=wi.getOrElse(P(n),()=>[]);i.length>0&&r(i)}};return r(e),t}function al(e){try{let t=ki(e,"utf-8");return/from\s+["'](?:effect|effect\/|@effect\/)/.test(t)}catch{return!1}}function cl(e){try{let t=ki(e,"utf-8");return/\bEffect\./.test(t)||/\bLayer\./.test(t)||/\bStream\./.test(t)||/\bSchema\./.test(t)||/\byield\*/.test(t)||/\bpipe\(/.test(t)||/\brunPromise\b/.test(t)||/\brunSync\b/.test(t)||/\brunFork\b/.test(t)||/\bacquireRelease\b/.test(t)?!1:/\binterface\b/.test(t)||/\btype\b/.test(t)||/\bdeclare\b/.test(t)||/^\s*import\s+type\b/m.test(t)||/^\s*export\s+type\b/m.test(t)}catch{return!1}}function ll(e){let t=e.replace(/\\/g,"/"),r=sl(t).toLowerCase();if(r==="index.ts"||r==="index.tsx"||/\/index\.[jt]sx?$/.test(t))return"barrel_or_index";if(/(^|\/)(__tests__|test|tests|dtslint)(\/|$)/.test(t)||/\.(test|spec|tst)\.[jt]sx?$/.test(t))return"test_or_dtslint";if(/(^|\/)(vitest|vite|jest|webpack|rollup|tsup|esbuild|eslint|prettier|babel|playwright|typedoc|karma)\.config\.[jt]s$/.test(t)||/(^|\/)vitest\.workspace\.[jt]s$/.test(t))return"config_or_build";if(cl(e))return"type_only"}async function mr(e,t,r,s){if(s>=r)return[];let n=[];try{let i=await Ti(e,{withFileTypes:!0});for(let c of i){let o=on(e,c.name);c.isDirectory()?c.name!=="node_modules"&&c.name!==".git"&&n.push(...await mr(o,t,r,s+1)):c.isFile()&&t.includes(vi(c.name))&&n.push(o)}}catch{}return n}async function Ii(e,t,r){if(r>=t)return[];let s=[];try{let n=await Ti(e,{withFileTypes:!0});n.some(c=>c.isFile()&&c.name==="package.json")&&s.push(e);for(let c of n)c.isDirectory()&&c.name!=="node_modules"&&c.name!==".git"&&s.push(...await Ii(on(e,c.name),t,r+1))}catch{}return s}function rn(e,t,r){if(!t||typeof t!="string")return[];let s=t.replace(/^\.\//,""),n=on(e,s);return vi(s)?[Ci(n)]:r.map(c=>Ci(n+c))}async function dl(e){try{let{Project:t,SyntaxKind:r}=T(),i=new t({skipAddingFilesFromTsConfig:!0}).addSourceFileAtPath(e).getDescendantsOfKind(r.CallExpression),c=[r.FunctionDeclaration,r.FunctionExpression,r.ArrowFunction,r.MethodDeclaration];for(let o of i){let a=o.getParent();if(a?.getKind()!==r.ExpressionStatement)continue;let d=a;for(;d;){let f=d.getKind();if(f===r.SourceFile||c.includes(f))break;d=d.getParent()}if(d?.getKind()!==r.SourceFile)continue;let l=o.getExpression().getText();if(l.includes(".runPromise")||l.includes(".runSync")||l.includes(".runFork")||l.includes(".runCallback")||l.includes("NodeRuntime.runMain")||l.includes("BunRuntime.runMain")||l.includes("DenoRuntime.runMain")||l.includes("Runtime.runPromise")||l.includes("Runtime.runSync")||l.includes("Runtime.runFork"))return!0}}catch{}return!1}async function ul(e,t){let r=await Ii(e,10,0),s=[];for(let n of r)try{let i=await nl(on(n,"package.json"),"utf-8"),c=JSON.parse(i),o=[rn(n,c.main,t),rn(n,c.module,t)];if(typeof c.bin=="string")o.push(rn(n,c.bin,t));else if(c.bin&&typeof c.bin=="object")for(let a of Object.values(c.bin))o.push(rn(n,typeof a=="string"?a:void 0,t));for(let a of o)for(let d of a)try{(await rl(d).catch(()=>null))?.isFile()&&s.push(d)}catch{}}catch{}return[...new Set(s)]}function $i(e,t={}){let r=t.extensions??sn.extensions,s=t.maxDepth??sn.maxDepth;return Ne.gen(function*(){let n=yield*Ne.promise(()=>mr(e,r,s,0)),i=new Map,c=[],o=[],a=[],d=[];for(let u of n){let g=yield*_e(u,{tsConfigPath:t.tsconfig,knownEffectInternalsRoot:t.knownEffectInternalsRoot}).all().pipe(Ne.map(m=>({_tag:"ok",programs:m})),Ne.catchAll(m=>Ne.succeed({_tag:"fail",error:m instanceof Error?m.message:String(m)})));if(g._tag==="fail"){a.push({file:u,error:g.error});continue}let p=g.programs;if(p.length===0){d.push(u);continue}i.set(u,p),c.push(...p);for(let m of p){let y=m.root.programName==="main"||m.root.programName.includes("run"),h=m.root.source==="run";(y||h)&&(o.includes(u)||o.push(u))}}let l=yield*Ne.promise(()=>ul(e,r));for(let u of l)n.includes(u)&&!o.includes(u)&&o.push(u);for(let u of i.keys()){if(o.includes(u))continue;(yield*Ne.promise(()=>dl(u)))&&o.push(u)}let f;if(t.buildServiceMap)try{let{Project:u}=T(),g=new u({skipAddingFilesFromTsConfig:!0,compilerOptions:{allowJs:!0}}),p=new Map;for(let m of i.keys())try{let y=g.addSourceFileAtPath(m);p.set(m,y)}catch{}f=gr(i,p)}catch{f=gr(i)}return{byFile:i,allPrograms:c,entryPointFiles:o,fileCount:n.length,failedFiles:a,zeroProgramFiles:d,serviceMap:f}})}function Fi(e,t={}){let r=t.extensions??sn.extensions,s=t.maxDepth??sn.maxDepth;return Ne.gen(function*(){let n=Date.now(),i=yield*Ne.promise(()=>mr(e,r,s,0)),c=[],o=0,a=0,d=[],l=new Map,f=t.includePerFileTiming===!0;for(let $ of i){let q=f?Date.now():0,B=yield*_e($,{tsConfigPath:t.tsconfig,knownEffectInternalsRoot:t.knownEffectInternalsRoot}).all().pipe(Ne.map(Z=>({_tag:"ok",programs:Z})),Ne.catchAll(Z=>Ne.succeed({_tag:"fail",error:Z instanceof Error?Z.message:String(Z)}))),H=f?Date.now()-q:void 0;if(B._tag==="ok"){let Z=B.programs.length,ae=0,ke=0;for(let Re of B.programs){let Ke=il(Re.root.children);o+=Ke.total,a+=Ke.unknown,ae+=Ke.total,ke+=Ke.unknown;let L=ol(Re.root.children);for(let[G,Se]of L)l.set(G,(l.get(G)??0)+Se)}ae>0&&d.push({file:$,total:ae,unknown:ke}),c.push(Z>0?{file:$,status:"ok",programCount:Z,...H!==void 0?{durationMs:H}:{}}:{file:$,status:"zero",programCount:0,...H!==void 0?{durationMs:H}:{}})}else{let Z=B.error??"",ae=Z.includes("No Effect programs found")||Z.includes("NO_EFFECTS_FOUND");c.push(ae?{file:$,status:"zero",programCount:0,...H!==void 0?{durationMs:H}:{}}:{file:$,status:"fail",error:B.error,...H!==void 0?{durationMs:H}:{}})}}let u=i.length,g=c.filter($=>$.status==="ok").length,p=c.filter($=>$.status==="zero").length,m=c.filter($=>$.status==="fail").length,y=u>0?g/u*100:0,h=g+m>0?g/(g+m)*100:100,N=t.excludeFromSuspiciousZeros??[],x=$=>{let q=$.replace(/\\/g,"/");return N.some(B=>q.includes(B.replace(/\\/g,"/"))||q.endsWith(B.replace(/\\/g,"/")))},F={barrel_or_index:0,config_or_build:0,test_or_dtslint:0,type_only:0,suspicious:0,other:0},E=[],b=[],C=c.filter($=>$.status==="zero");for(let $ of C){let q=al($.file),B=ll($.file),H=q&&!x($.file)&&B===void 0?"suspicious":B??"other";F[H]++,b.push({file:$.file,category:H,importsEffect:q}),H==="suspicious"&&E.push($.file)}let k=o>0?a/o:0,S=d.filter($=>$.total>0).sort(($,q)=>q.unknown/q.total-$.unknown/$.total).slice(0,10).map($=>$.file),W={};for(let[$,q]of l)W[$]=q;let A=[...l.entries()].sort(($,q)=>q[1]-$[1]).slice(0,20).map(([$,q])=>({reason:$,count:q})),z=Date.now()-n;return{discovered:u,analyzed:g,zeroPrograms:p,failed:m,outcomes:c,percentage:y,analyzableCoverage:h,unknownNodeRate:k,totalNodes:o,unknownNodes:a,suspiciousZeros:E,zeroProgramCategoryCounts:F,zeroProgramClassifications:b,topUnknownFiles:S,unknownReasonCounts:W,topUnknownReasons:A,durationMs:z}})}import*as Ae from"path";import*as Sr from"fs/promises";import{Effect as yt}from"effect";var fl=e=>" ".repeat(e);function Ai(e){let t=(r,s=X)=>ee(r,s);switch(e.type){case"effect":return e.serviceCall?t(`${e.serviceCall.serviceType}.${e.serviceCall.methodName}`):t(e.displayName??e.callee);case"generator":return"Effect.gen block";case"pipe":return t(`pipe(${Ai(e.initial)})`);case"parallel":return t(`${e.callee}(${e.children.length} effects)`);case"race":return t(`${e.callee}(${e.children.length} effects)`);case"error-handler":return e.handlerType;case"retry":return"retry";case"timeout":return e.duration?`timeout(${e.duration})`:"timeout";case"resource":return"acquireRelease";case"conditional":return`if ${e.conditionLabel??e.condition}`;case"loop":return t(`${e.loopType}${e.iterSource?`(${e.iterSource})`:""}`);case"layer":return e.provides?`Layer(${e.provides.join(", ")})`:"Layer";case"stream":return"Stream";case"fiber":return`Fiber.${e.operation}`;case"concurrency-primitive":return`${e.primitive}.${e.operation}`;case"decision":return`if ${e.condition}`;case"switch":return`switch(${e.expression})`;case"try-catch":return"try/catch";case"terminal":return e.terminalKind;case"match":return e.matchedTags?`Match(${e.matchedTags.join(", ")})`:"Match";case"transform":return e.transformType;case"channel":return"Channel";case"sink":return"Sink";case"cause":return`Cause.${e.causeOp}`;case"exit":return`Exit.${e.exitOp}`;case"schedule":return`Schedule.${e.scheduleOp}`;case"interruption":return e.interruptionType;case"opaque":return`(opaque: ${e.reason})`;case"unknown":return`(unknown: ${e.reason})`}}function U(e,t,r={hasParallelism:!1,serviceCallsSeen:new Set}){let s=fl(t),n=[];switch(e.type){case"effect":{if(e.serviceCall)if(r.serviceCallsSeen.add(e.serviceCall.serviceType),e.callee.includes("Tag")||e.callee.includes("Context")||e.callee===e.serviceCall.serviceType)n.push(`${s}Acquires ${e.serviceCall.serviceType} service`);else{let i=e.description?` \u2014 ${e.description}`:"";n.push(`${s}Calls ${e.serviceCall.serviceType}.${e.serviceCall.methodName}${i}`)}else{let i=ee(e.displayName??e.callee,X),c=e.description?` \u2014 ${e.description}`:"";i.includes(" <- ")?n.push(`${s}Yields ${i}`):n.push(`${s}Calls ${i}${c}`)}break}case"generator":{for(let i of e.yields){let c=U(i.effect,t,r),o=c[0];if(i.variableName&&o!==void 0){let a=o.trimStart();a.includes(`${i.variableName} <-`)||a.includes(`${i.variableName} =`)||(c[0]=`${s}${i.variableName} = ${a.replace(/^Calls /,"")}`)}n.push(...c)}if(e.returnNode){let i=U(e.returnNode,t,r),c=i[0];if(c!==void 0){let o=c.trimStart();i[0]=`${s}Returns ${o.replace(/^Calls /,"")}`,n.push(...i)}}break}case"pipe":{n.push(`${s}Pipes ${Ai(e.initial)} through:`);let i=U(e.initial,t+1,r);n.push(...i);for(let c of e.transformations){let o=U(c,t+1,r);n.push(...o)}break}case"parallel":{r.hasParallelism=!0;let i=e.concurrency!==void 0&&e.concurrency!=="sequential"?` (concurrency: ${e.concurrency})`:"";n.push(`${s}Runs ${e.children.length} effects in ${e.mode}${i}:`);for(let c of e.children)n.push(...U(c,t+1,r));break}case"race":{r.hasParallelism=!0,n.push(`${s}Races ${e.children.length} effects:`);for(let i of e.children)n.push(...U(i,t+1,r));break}case"error-handler":{let i=e.errorTag?` "${e.errorTag}"`:e.errorTags&&e.errorTags.length>0?` [${e.errorTags.join(", ")}]`:"";switch(e.handlerType){case"catchAll":n.push(`${s}Catches all errors on:`);break;case"catchTag":n.push(`${s}Catches tag${i} on:`);break;case"catchTags":n.push(`${s}Catches tags${i} on:`);break;case"orElse":n.push(`${s}Falls back (orElse) on error:`);break;case"orDie":n.push(`${s}Converts errors to defects (orDie):`);break;case"mapError":n.push(`${s}Maps error on:`);break;case"ignore":n.push(`${s}Ignores errors on:`);break;default:n.push(`${s}Handles errors (${e.handlerType})${i}:`)}n.push(...U(e.source,t+1,r)),e.handler&&(n.push(`${s} Handler:`),n.push(...U(e.handler,t+2,r)));break}case"retry":{if(e.scheduleInfo){let i=e.scheduleInfo.maxRetries!==void 0?`max ${e.scheduleInfo.maxRetries}`:"",c=e.scheduleInfo.baseStrategy,o=[i,c].filter(Boolean).join(", ");n.push(`${s}Retries (${o}):`)}else e.schedule?n.push(`${s}Retries with ${e.schedule}:`):n.push(`${s}Retries:`);n.push(...U(e.source,t+1,r)),e.hasFallback&&n.push(`${s} (with fallback on exhaustion)`);break}case"timeout":{let i=e.duration?` after ${e.duration}`:"";n.push(`${s}Times out${i}:`),n.push(...U(e.source,t+1,r)),e.hasFallback&&n.push(`${s} (with fallback on timeout)`);break}case"resource":{n.push(`${s}Acquires resource:`),n.push(...U(e.acquire,t+1,r)),e.use&&(n.push(`${s} Uses:`),n.push(...U(e.use,t+2,r))),n.push(`${s} Then releases:`),n.push(...U(e.release,t+2,r));break}case"conditional":{let i=e.conditionLabel??e.condition;n.push(`${s}If ${i}:`),n.push(...U(e.onTrue,t+1,r)),e.onFalse&&(n.push(`${s}Else:`),n.push(...U(e.onFalse,t+1,r)));break}case"decision":{n.push(`${s}If ${e.condition}:`);for(let i of e.onTrue)n.push(...U(i,t+1,r));if(e.onFalse&&e.onFalse.length>0){n.push(`${s}Else:`);for(let i of e.onFalse)n.push(...U(i,t+1,r))}break}case"switch":{n.push(`${s}Switch on ${e.expression}:`);for(let i of e.cases){let c=i.isDefault?"default":i.labels.join(", ");n.push(`${s} Case ${c}:`);for(let o of i.body)n.push(...U(o,t+2,r))}break}case"try-catch":{n.push(`${s}Try:`);for(let i of e.tryBody)n.push(...U(i,t+1,r));if(e.catchBody&&e.catchBody.length>0){n.push(`${s}Catch:`);for(let i of e.catchBody)n.push(...U(i,t+1,r))}if(e.finallyBody&&e.finallyBody.length>0){n.push(`${s}Finally:`);for(let i of e.finallyBody)n.push(...U(i,t+1,r))}break}case"terminal":{switch(e.terminalKind){case"return":{if(e.value&&e.value.length>0){n.push(`${s}Returns:`);for(let i of e.value)n.push(...U(i,t+1,r))}else n.push(`${s}Returns`);break}case"throw":n.push(`${s}Throws`);break;case"break":n.push(`${s}Breaks`);break;case"continue":n.push(`${s}Continues`);break}break}case"loop":{let i=e.iterSource?` over ${ee(e.iterSource,X)}`:"";n.push(`${s}Iterates (${e.loopType})${i}:`),n.push(...U(e.body,t+1,r));break}case"layer":{let i=e.provides&&e.provides.length>0?` providing ${e.provides.join(", ")}`:"",c=e.requires&&e.requires.length>0?` (requires ${e.requires.join(", ")})`:"";n.push(`${s}Provides layer${i}${c}:`);for(let o of e.operations)n.push(...U(o,t+1,r));break}case"stream":{let i=e.pipeline.map(o=>o.operation).join(" -> "),c=e.sink?` -> ${e.sink}`:"";n.push(`${s}Stream: ${i}${c}`),n.push(...U(e.source,t+1,r));break}case"fiber":{let i=e.isDaemon?" (daemon)":e.isScoped?" (scoped)":"";n.push(`${s}Fiber ${e.operation}${i}:`),e.fiberSource&&n.push(...U(e.fiberSource,t+1,r));break}case"concurrency-primitive":{let i=e.capacity!==void 0?` (capacity: ${e.capacity})`:"";n.push(`${s}${e.primitive}.${e.operation}${i}`),e.source&&n.push(...U(e.source,t+1,r));break}case"match":{e.matchedTags&&e.matchedTags.length>0?n.push(`${s}Matches tags: ${e.matchedTags.join(", ")}`):n.push(`${s}Match (${e.matchOp})`);break}case"transform":{n.push(`${s}Transforms via ${e.transformType}`),e.source&&n.push(...U(e.source,t+1,r));break}case"cause":{if(n.push(`${s}Cause.${e.causeOp}`),e.children)for(let i of e.children)n.push(...U(i,t+1,r));break}case"exit":{n.push(`${s}Exit.${e.exitOp}`);break}case"schedule":{n.push(`${s}Schedule.${e.scheduleOp}`);break}case"channel":{let i=e.pipeline.map(c=>c.operation).join(" -> ");n.push(`${s}Channel${i?`: ${i}`:""}`),e.source&&n.push(...U(e.source,t+1,r));break}case"sink":{let i=e.pipeline.map(c=>c.operation).join(" -> ");n.push(`${s}Sink${i?`: ${i}`:""}`),e.source&&n.push(...U(e.source,t+1,r));break}case"interruption":{n.push(`${s}${e.interruptionType}`),e.source&&n.push(...U(e.source,t+1,r)),e.handler&&(n.push(`${s} On interrupt:`),n.push(...U(e.handler,t+2,r)));break}case"opaque":{n.push(`${s}(opaque: ${e.reason})`);break}case"unknown":{n.push(`${s}(unknown: ${e.reason})`);break}}return n}function pl(e,t){let r={hasParallelism:!1,serviceCallsSeen:new Set},s=[];for(let d of e.children)s.push(...U(d,1,r));let n=gl(s),i=`${e.programName} (${e.source}):`,c=[],o=new Set;for(let d of e.dependencies)o.add(d.name);Array.from(r.serviceCallsSeen).forEach(d=>{o.add(d)}),o.size>0&&c.push(` Services required: ${Array.from(o).join(", ")}`),e.errorTypes.length>0&&c.push(` Error paths: ${e.errorTypes.join(", ")}`),r.hasParallelism?c.push(" Concurrency: uses parallelism / racing"):c.push(" Concurrency: sequential (no parallelism)");let a=[i,n.join(`
|
|
45
45
|
`)];return c.length>0&&(a.push(""),a.push(c.join(`
|
|
46
46
|
`))),a.join(`
|
|
47
|
-
`)}function
|
|
47
|
+
`)}function gl(e){let t=0;return e.map(r=>/^ {2}\S/.test(r)?(t++,` ${t}. ${r.trimStart()}`):r)}function yr(e){return pl(e.root,e)}function hr(e){return e.map(t=>yr(t)).join(`
|
|
48
48
|
|
|
49
49
|
---
|
|
50
50
|
|
|
51
|
-
`)}var
|
|
52
|
-
`):"- No operations found"};var
|
|
53
|
-
`)}),
|
|
54
|
-
`)},
|
|
55
|
-
`)}function
|
|
51
|
+
`)}var ml=(e,t)=>{let r=Ae.dirname(e),s=Ae.basename(e,Ae.extname(e));return Ae.join(r,`${s}.${t}.md`)},yl=e=>{let t=[];return e.totalEffects>0&&t.push(`- **Total Effects**: ${e.totalEffects}`),e.parallelCount>0&&t.push(`- **Parallel Operations**: ${e.parallelCount}`),e.raceCount>0&&t.push(`- **Race Operations**: ${e.raceCount}`),e.errorHandlerCount>0&&t.push(`- **Error Handlers**: ${e.errorHandlerCount}`),e.retryCount>0&&t.push(`- **Retry Operations**: ${e.retryCount}`),e.timeoutCount>0&&t.push(`- **Timeout Operations**: ${e.timeoutCount}`),e.resourceCount>0&&t.push(`- **Resources**: ${e.resourceCount}`),e.loopCount>0&&t.push(`- **Loops**: ${e.loopCount}`),e.conditionalCount>0&&t.push(`- **Conditionals**: ${e.conditionalCount}`),e.layerCount>0&&t.push(`- **Layers**: ${e.layerCount}`),e.unknownCount>0&&t.push(`- **Unknown Nodes**: ${e.unknownCount}`),t.length>0?t.join(`
|
|
52
|
+
`):"- No operations found"};var hl=(e,t="TB",r=!0,s,n=!1)=>yt.gen(function*(){let i=[];for(let c=0;c<e.length;c++){let o=e[c];if(!o)continue;c>0&&i.push("","---",""),i.push(`# Effect Analysis: ${o.root.programName}`,""),i.push("## Metadata",""),i.push(`- **File**: \`${o.metadata.filePath}\``),i.push(`- **Analyzed**: ${new Date(o.metadata.analyzedAt).toISOString()}`),i.push(`- **Source Type**: ${o.root.source}`),o.metadata.tsVersion&&i.push(`- **TypeScript Version**: ${o.metadata.tsVersion}`),i.push("",""),i.push("## Effect Flow","","```mermaid");let a=r?Jt(o,{direction:t}):yield*Gt(o,{direction:t});if(i.push(a.trim()),i.push("```","",""),n){let f=mt(o);f.length>0&&(i.push("## Summary Flow (Style Guide)","","```mermaid"),i.push(Vt(f,{direction:t,styleGuide:!0}).trim()),i.push("```","",""))}let d=s?.get(o.root.id);if(d){if(i.push("## Diagram Quality",""),i.push(`- **Readability score**: ${d.score} (${d.band})`),i.push(`- **Detailed steps**: ${d.metrics.stepCountDetailed} | **Summary steps**: ${d.metrics.stepCountSummary}`),i.push(`- **Unknown nodes**: ${d.metrics.unknownNodeCount} | **Anonymous nodes**: ${d.metrics.anonymousNodeCount}`),i.push(""),d.reasons.length>0){i.push("### Reasons","");for(let f of d.reasons)i.push(`- ${f}`);i.push("")}if(d.tips.length>0){i.push("### Tips","");for(let f of d.tips)i.push(`- ${f}`);i.push("")}i.push("")}i.push("## Statistics","",yl(o.metadata.stats),"","");let l=yr(o);if(i.push("## Explanation","","```",l,"```","",""),o.root.dependencies.length>0){i.push("## Dependencies","");for(let f of o.root.dependencies){let u=f.typeSignature?`: ${f.typeSignature}`:"",g=f.isLayer?" (Layer)":"";i.push(`- \`${f.name}\`${u}${g}`)}i.push("","")}if(o.root.errorTypes.length>0){i.push("## Error Types","");for(let f of o.root.errorTypes)i.push(`- \`${f}\``);i.push("","")}if(o.metadata.warnings.length>0){i.push("## Warnings","");for(let f of o.metadata.warnings){let u=f.location?` (${f.location.filePath}:${f.location.line})`:"";i.push(`- **${f.code}**: ${f.message}${u}`)}i.push("","")}}return i.join(`
|
|
53
|
+
`)}),xr=(e,t,r,s="TB",n=!0,i,c=!1)=>yt.gen(function*(){let o=ml(e,r),a=yield*hl(t,s,n,i,c);return yield*yt.tryPromise({try:()=>Sr.writeFile(o,a,"utf-8"),catch:d=>new Error(`Failed to write ${o}: ${String(d)}`)}),o});var Sl=e=>{let t=[];if(t.push(`# Service: ${e.serviceId}`),t.push(""),t.push("## Definition"),t.push(""),t.push(`- **Class**: \`${e.className}\``),t.push(`- **File**: \`${e.definitionFilePath}:${e.definitionLocation.line}\``),t.push(`- **Tag**: \`'${e.serviceId}'\``),e.interfaceTypeText&&t.push(`- **Type**: \`${e.interfaceTypeText}\``),t.push(""),e.definition.methods.length>0||e.definition.properties.length>0){if(t.push("## Interface"),t.push(""),e.definition.methods.length>0){t.push("**Methods:**");for(let r of e.definition.methods)t.push(`- \`${r}\``);t.push("")}if(e.definition.properties.length>0){t.push("**Properties:**");for(let r of e.definition.properties)t.push(`- \`${r}\``);t.push("")}}if(e.layerImplementations.length>0){t.push("## Layer Implementations"),t.push("");for(let r of e.layerImplementations)t.push(`### ${r.name} (\`${r.filePath}:${r.location.line}\`)`),t.push(""),t.push(`- **Kind**: Layer.${r.kind}`),r.requires.length>0?t.push(`- **Requires**: ${r.requires.join(", ")}`):t.push("- **Requires**: (none)"),t.push("")}if(e.consumers.length>0){t.push(`## Consumers (${e.consumers.length} program${e.consumers.length===1?"":"s"})`),t.push("");for(let r of e.consumers){let s=r.location?`:${r.location.line}`:"";t.push(`- \`${r.programName}\` in \`${r.filePath}${s}\``)}t.push("")}if(e.dependencies.length>0){t.push("## Dependencies"),t.push("");for(let r of e.dependencies)t.push(`- ${r}`);t.push("")}return t.join(`
|
|
54
|
+
`)},xl=(e,t)=>{let r=Ae.dirname(e),s=t.replace(/[^a-zA-Z0-9_-]/g,"_").toLowerCase();return Ae.join(r,`${s}.service-analysis.md`)},El=e=>yt.gen(function*(){let t=xl(e.definitionFilePath,e.serviceId),r=Sl(e);return yield*yt.tryPromise({try:()=>Sr.writeFile(t,r,"utf-8"),catch:s=>new Error(`Failed to write ${t}: ${String(s)}`)}),t}),Ri=e=>yt.gen(function*(){let t=[];for(let r of e.services.values()){let s=yield*El(r);t.push(s)}return t});var bl={generator:"gen",direct:"direct",pipe:"pipe",run:"run","workflow-execute":"wf-exec",class:"class",classProperty:"classProp",classMethod:"classMeth"};function Nl(e){return bl[e]}function Cl(e){return{program:e.root.programName,kind:Nl(e.root.source),steps:e.metadata.stats.totalEffects,services:e.root.dependencies.length,errors:e.root.errorTypes.length,handlers:e.metadata.stats.errorHandlerCount,complexity:nn(e).cyclomaticComplexity}}function Er(e){if(e.length===0)return"(no programs)";let t=e.map(Cl),r={program:"Program",kind:"Kind",steps:"Steps",services:"Services",errors:"Errors",handlers:"Handlers",complexity:"Complexity"},s={program:Math.max(r.program.length,...t.map(d=>d.program.length)),kind:Math.max(r.kind.length,...t.map(d=>d.kind.length)),steps:Math.max(r.steps.length,...t.map(d=>String(d.steps).length)),services:Math.max(r.services.length,...t.map(d=>String(d.services).length)),errors:Math.max(r.errors.length,...t.map(d=>String(d.errors).length)),handlers:Math.max(r.handlers.length,...t.map(d=>String(d.handlers).length)),complexity:Math.max(r.complexity.length,...t.map(d=>String(d.complexity).length))},n=(d,l)=>d+" ".repeat(Math.max(0,l-d.length)),i=(d,l)=>" ".repeat(Math.max(0,l-d.length))+d,c=[n(r.program,s.program),n(r.kind,s.kind),n(r.steps,s.steps),n(r.services,s.services),n(r.errors,s.errors),n(r.handlers,s.handlers),n(r.complexity,s.complexity)].join(" | "),o=["-".repeat(s.program),"-".repeat(s.kind),"-".repeat(s.steps),"-".repeat(s.services),"-".repeat(s.errors),"-".repeat(s.handlers),"-".repeat(s.complexity)].join("-+-"),a=t.map(d=>[n(d.program,s.program),n(d.kind,s.kind),i(String(d.steps),s.steps),i(String(d.services),s.services),i(String(d.errors),s.errors),i(String(d.handlers),s.handlers),i(String(d.complexity),s.complexity)].join(" | "));return[c,o,...a].join(`
|
|
55
|
+
`)}function br(e){let t=new Set,r=new Map;for(let i of e){let c=i.root.programName,o=r.get(c)??new Set;for(let a of i.root.dependencies)t.add(a.name),o.add(a.name);r.set(c,o)}let s=[...t].sort((i,c)=>i.localeCompare(c)),n=[...r.keys()].sort((i,c)=>i.localeCompare(c));return Pi(n,s,(i,c)=>{let o=r.get(i);return o?o.has(c):!1},{programs:e.length,services:s.length})}function Di(e){let t=[],r=new Set,s=new Set,n=new Map;for(let[c,o]of e.services){t.push(c);let a=new Set;for(let d of o.consumers)a.add(d.programName),r.add(d.programName),s.add(`${d.filePath}::${d.programName}`);n.set(c,a)}t.sort((c,o)=>c.localeCompare(o));let i=[...r].sort((c,o)=>c.localeCompare(o));return Pi(i,t,(c,o)=>{let a=n.get(o);return a?a.has(c):!1},{programs:s.size,services:t.length})}function Pi(e,t,r,s){let n=s?.programs??e.length,i=s?.services??t.length;if(e.length===0||t.length===0)return`_No dependencies found._
|
|
56
56
|
|
|
57
57
|
${n} programs \xD7 ${i} services`;let c=[];c.push(`| Program | ${t.join(" | ")} |`);let o=t.map(a=>`:${"-".repeat(Math.max(a.length-2,1))}:`);c.push(`|${"-".repeat(9)}|${o.join("|")}|`);for(let a of e){let d=t.map(l=>r(a,l)?"\u2713":"");c.push(`| ${a} | ${d.join(" | ")} |`)}return c.push(""),c.push(`${n} programs \xD7 ${i} services`),c.join(`
|
|
58
|
-
`)}function
|
|
59
|
-
`).trim()}function vi(e){let t={};for(let r of e){let s=r.prefix??"";for(let n of r.groups){let i=n.prefix??"";for(let c of n.endpoints){let o=s+i+c.path;t[o]??={};let a=c.method.toLowerCase(),d={operationId:`${n.name}.${c.name}`,...c.summary?{summary:c.summary}:{},...c.deprecated?{deprecated:!0}:{}};if(c.requestSchema&&(d.requestBody={content:{"application/json":{schema:c.requestSchema}}}),c.responseSchema&&(d.responses={200:{description:c.summary??c.description??"Success",content:{"application/json":{schema:c.responseSchema}}}}),c.urlParamsSchema?.properties){let l=Object.entries(c.urlParamsSchema.properties).map(([f,u])=>({name:f,in:"path",schema:u}));l.length&&(d.parameters=l)}t[o][a]=d}}}return{paths:t}}import{SyntaxKind as J}from"ts-morph";import{SyntaxKind as re}from"ts-morph";function pl(e,t,r){if(e.getText().includes("Schema."))return e;if(e.getKind()===re.Identifier){let n=e,i=n.getSymbol(),o=(i?.getAliasedSymbol()??i)?.getDeclarations()??[];for(let l of o){if(l.getKind()===re.VariableDeclaration){let f=l.getInitializer();if(f?.getText().includes("Schema."))return f}if(l.getKind()===re.ImportSpecifier){let f=l.getName(),u=l.getFirstAncestorByKind(re.ImportDeclaration);if(u){let g=u.getModuleSpecifierValue(),p=t.getFilePath(),m=g.startsWith(".")?mt(p,g):void 0,h=m?r.getSourceFile(m):void 0;if(h){let y=h.getExportedDeclarations().get(f)??[];for(let N of y)if(N.getKind()===re.VariableDeclaration){let E=N.getInitializer();if(E?.getText().includes("Schema."))return E}}}}}let a=n.getText(),d=t.getVariableDeclarations();for(let l of d)if(l.getName()===a){let f=l.getInitializer();if(f?.getText().includes("Schema."))return f}}return e.getText().includes("Schema.")?e:void 0}function Zt(e,t,r,s){let n=pl(e,t,r);if(n)return qe(n,t,r,s??new Map)}function qe(e,t,r,s){let n=e.getText();if(n.includes("Schema.Array")){let a=e.getKind()===re.CallExpression?e:e.getFirstDescendantByKind(re.CallExpression);if(a){let d=a.getArguments();return{type:"array",items:(d[0]?qe(d[0],t,r,s):void 0)??{}}}}if(n.includes("Schema.Struct")){let a=e.getKind()===re.CallExpression?e:e.getFirstDescendantByKind(re.CallExpression);if(!a)return{type:"object"};let l=a.getArguments()[0];if(l?.getKind()!==re.ObjectLiteralExpression)return{type:"object"};let f=l,u={},g=[];for(let m of f.getProperties()){if(m.getKind()!==re.PropertyAssignment)continue;let h=m,y=h.getNameNode().getText(),N=h.getInitializer();if(!N)continue;let E=N.getText();E.includes("Schema.optional")||E.includes(".optional")||g.push(y);let S=qe(N,t,r,s);S&&(u[y]=S)}let p={type:"object",properties:Object.keys(u).length?u:void 0,additionalProperties:!1};return g.length&&(p.required=g),p}if(n.includes("Schema.Union")){let a=e.getKind()===re.CallExpression?e:e.getFirstDescendantByKind(re.CallExpression);if(a){let l=a.getArguments().map(f=>qe(f,t,r,s)).filter(f=>f!==void 0);if(l.length)return{oneOf:l}}}if(n.includes("Schema.optional")||n.includes(".pipe(Schema.optional")){let a=e.getKind()===re.CallExpression?e:e.getFirstDescendantByKind(re.CallExpression);if(a){let d=a.getArguments(),l=d[0]?qe(d[0],t,r,s):void 0;if(l)return{...l,nullable:!0}}}if(n.includes("Schema.Record")){let a=e.getKind()===re.CallExpression?e:e.getFirstDescendantByKind(re.CallExpression);if(a){let d=a.getArguments();return{type:"object",additionalProperties:(d[1]?qe(d[1],t,r,s):void 0)??!0}}}if(n.includes("Schema.Tuple")){let a=e.getKind()===re.CallExpression?e:e.getFirstDescendantByKind(re.CallExpression);if(a)return{type:"array",items:a.getArguments().map(f=>qe(f,t,r,s)).filter(Boolean)}}if(n.includes("Schema.Date")||n.includes("Schema.DateTimeUtc")||n.includes("Schema.Instant"))return{type:"string",format:"date-time"};if(n.includes("Schema.String")&&!n.includes("Schema.Struct"))return{type:"string"};if(n.includes("Schema.Number")||n.includes("Schema.Int")||n.includes("Schema.Positive")||n.includes("Schema.NonNegative")||n.includes("Schema.Finite"))return{type:"number"};if(n.includes("Schema.Boolean"))return{type:"boolean"};if(n.includes("Schema.Null"))return{type:"null"};let i=/Schema\.Literal\s*\(\s*(["'])([^"']*)\1\s*\)/.exec(n);if(i)return{type:"string",enum:[i[2]]};let c=/Schema\.Literal\s*\(\s*(\d+)\s*\)/.exec(n);if(c)return{type:"number",enum:[Number(c[1])]};let o=/Schema\.Literal\s*\(\s*(true|false)\s*\)/.exec(n);if(o)return{type:"boolean",enum:[o[1]==="true"]};if(e.getKind()===re.Identifier){let l=(e.getSymbol()?.getDeclarations()[0]).getInitializer();if(l)return qe(l,t,r,s)}}function gl(e,t,r){let{line:s,column:n}=r.getLineAndColumnAtPos(t.getStart());return{filePath:e,line:s+1,column:n}}function ml(e){let s=e.getText().replace(/\$\{HttpApiSchema\.param\s*\(\s*["'](\w+)["'][^}]*\)\}/g,":$1").replace(/\$\{[^}]*\}/g,":param").replace(/^`|`$/g,"").trim();return s.startsWith("/")?s:`/${s}`}function Ii(e,t,r){let s={},n=e;for(let i=0;i<30&&n;i++){let c=n.getParent();if(c?.getKind()!==J.CallExpression){n=c;continue}let o=c,a=o.getExpression().getText(),d=o.getArguments();if(d.length<2){n=c;continue}let l=d[0]?.getText(),f=d[1]?.getText();if(a.endsWith(".annotate")||a.endsWith(".annotateContext"))if(l?.includes("OpenApi.Description")||l?.includes("Description")){let u=f?.replace(/^["']|["']$/g,"");u&&(s.description=u)}else if(l?.includes("OpenApi.Summary")||l?.includes("Summary")){let u=f?.replace(/^["']|["']$/g,"");u&&(s.summary=u)}else l?.includes("OpenApi.Deprecated")||l?.includes("Deprecated")?s.deprecated=f==="true":(l?.includes("OpenApi.Exclude")||l?.includes("Exclude"))&&(s.excluded=f==="true");n=c}return s}function yl(e,t){let r={},s=t.getProject(),n=e;for(let i=0;i<40&&n;i++){let c=n.getParent();if(c?.getKind()!==J.CallExpression){n=c;continue}let o=c,a=o.getExpression().getText(),d=o.getArguments();if(d.length<1){n=c;continue}let l=d[0];if(a.endsWith(".addSuccess")&&l&&!r.responseSchema){let f=Zt(l,t,s);f&&(r.responseSchema=f)}else if(a.endsWith(".setPayload")&&l&&!r.requestSchema){let f=Zt(l,t,s);f&&(r.requestSchema=f)}else if((a.endsWith(".setUrlParams")||a.endsWith(".setQueryParams"))&&l&&!r.urlParamsSchema){let f=Zt(l,t,s);f&&(r.urlParamsSchema=f)}n=c}return r}function hl(e,t,r,s){let n=e.getArguments(),c=(n.length>0?n[0]?.getText().replace(/["'`]/g,""):"unnamed")??"unnamed",o="/";if(n.length>=2)o=n[1]?.getText().replace(/["'`]/g,"")??"/";else{let l=e.getParent();if(l?.getKind()===J.TaggedTemplateExpression){let f=l.getTemplate();o=ml(f)}}let a=Ii(e,r,s);if(a.excluded)return null;let d=yl(e,r);return{name:c,method:t.toUpperCase(),path:o||"/",location:gl(s,e,r),...a.description?{description:a.description}:{},...a.summary?{summary:a.summary}:{},...a.deprecated?{deprecated:!0}:{},...d.requestSchema?{requestSchema:d.requestSchema}:{},...d.responseSchema?{responseSchema:d.responseSchema}:{},...d.urlParamsSchema?{urlParamsSchema:d.urlParamsSchema}:{}}}function Sl(e,t,r){let s=[],n=["get","post","put","delete","patch","head","options"],i=new Set,c=mr(e);function o(l){let f=l,u=[".annotate",".addSuccess",".setPayload",".setUrlParams",".setQueryParams",".addFailure"];for(let g=0;g<15;g++){if(f.getKind()!==J.CallExpression)return;let p=f,m=p.getExpression().getText();for(let y of n){let N=m.includes(`HttpApiEndpoint.${y}`)||m.includes(`HttpApiEndpoint.${y}(`),E=!u.some($=>m.endsWith($)||m.includes($));if(N&&!m.includes(".annotate")&&E)return p}if(u.some(y=>m.endsWith(y)||m.includes(y))){let y=p.getExpression();y.getKind()===J.CallExpression?f=y:f=y.getExpression();continue}return}}function a(l){if(l.getKind()===J.CallExpression)return l;if(l.getKind()===J.Identifier){let f=l.getText(),u=l.getSymbol(),g=u?.getDeclarations()??u?.getAliasedSymbol()?.getDeclarations()??[];for(let m of g)if(m.getKind()===J.VariableDeclaration){let h=m.getInitializer();if(h)return h}let p=t.getVariableDeclarations();for(let m of p)if(m.getName()===f){let h=m.getInitializer();if(h)return h}}}function d(l){let f=a(l);if(f?.getKind()!==J.CallExpression)return;let u=f,g=o(u);if(g){let m=g.getExpression().getText();for(let h of n)if(m.includes(`HttpApiEndpoint.${h}`)){let y=hl(g,h,t,r);y&&!i.has(`${y.method}:${y.path}:${y.name}`)&&(i.add(`${y.method}:${y.path}:${y.name}`),s.push(y));return}}if(u.getExpression().getText().endsWith(".add"))for(let m of u.getArguments())d(m)}for(let l of c)d(l);return s}function xl(e,t,r,s){let n=e.getArguments(),c=(n.length>0?n[0]?.getText().replace(/["'`]/g,""):"group")??"group",o=n[1],a=!1;if(o?.getKind()===J.ObjectLiteralExpression){let u=o.getProperty("topLevel");u?.getKind()===J.PropertyAssignment&&(a=u.getInitializer()?.getText()==="true")}let d=Sl(e,t,r),l=Ii(e,t,r);return{name:c,endpoints:d,...l.description?{description:l.description}:{},...a?{topLevel:!0}:{},...s?{prefix:s}:{}}}function El(e){let t=e;for(let r=0;r<25&&t.getKind()===J.CallExpression;r++){let s=t;if(s.getExpression().getText().endsWith(".prefix")){let c=s.getArguments();if(c.length>=1){let o=c[0]?.getText().replace(/["'`]/g,"");if(o)return o.startsWith("/")?o:`/${o}`}break}let i=s.getExpression();if(i.getKind()===J.PropertyAccessExpression)t=i.getExpression();else break}}function mr(e){let t=[],r,s=e,n=e.getExpression().getText(),i=n.includes("HttpApi.make"),c=n.includes("HttpApiGroup.make");for(let o=0;o<20;o++){let a=s.getParent();if(!a||(a.getKind()===J.PropertyAccessExpression&&(a=a.getParent()),a?.getKind()!==J.CallExpression))break;let d=a,l=d.getExpression().getText();if(l.endsWith(".add")){if(i&&l.includes("HttpApiGroup.make")||c&&l.includes("HttpApi.make")&&!l.includes("HttpApiGroup"))break;r=d,s=a;continue}break}if(!r)return t;s=r;for(let o=0;o<50;o++){if(s.getKind()===J.CallExpression){let a=s;if(a.getExpression().getText().endsWith(".add")){for(let f of a.getArguments())t.push(f);let l=a.getExpression();if(l.getKind()===J.CallExpression){s=l;continue}if(l.getKind()===J.PropertyAccessExpression){let f=l.getExpression();if(f.getKind()===J.CallExpression){s=f;continue}}}}break}return t}function bl(e,t,r){let s=[],n=new Set,i=mr(e),c=[".add",".prefix",".annotate"];function o(l){let f=l;for(let u=0;u<20;u++){if(f.getKind()!==J.CallExpression)return;let g=f,p=g.getExpression().getText();if(p.includes("HttpApiGroup.make")&&!c.some(m=>p.endsWith(m))||p.includes("HttpApi.make")&&!c.some(m=>p.endsWith(m)))return g;if(c.some(m=>p.endsWith(m))){let m=g.getExpression();if(m.getKind()===J.CallExpression){f=m;continue}if(m.getKind()===J.PropertyAccessExpression){let h=m.getExpression();if(h.getKind()===J.CallExpression){f=h;continue}}return}return}}function a(l){if(l.getKind()===J.CallExpression)return l;if(l.getKind()===J.Identifier){let f=l.getText(),u=l.getSymbol(),g=u?.getDeclarations()??u?.getAliasedSymbol()?.getDeclarations()??[];for(let m of g)if(m.getKind()===J.VariableDeclaration){let h=m.getInitializer();if(h?.getKind()===J.CallExpression)return h}let p=t.getVariableDeclarations();for(let m of p)if(m.getName()===f){let h=m.getInitializer();if(h?.getKind()===J.CallExpression)return h}}}function d(l){let f=a(l);if(!f)return;let u=f.getExpression().getText();if(u.includes("HttpApiGroup.make")){let g=o(f);if(g){let p=El(f),m=xl(g,t,r,p);m&&!n.has(m.name)&&(n.add(m.name),s.push(m))}return}if(u.includes("HttpApi.make")){let g=o(f);if(g)for(let p of mr(g))d(p)}}for(let l of i)d(l);return s}function Nl(e){let t=e;for(let r=0;r<50;r++){let s=t.getParent();if(s?.getKind()!==J.CallExpression)return e;let n=s;if(n.getExpression().getText().endsWith(".add")){let c=n.getExpression();if(c.getKind()===J.CallExpression){let o=c;if(o.getExpression().getText().includes("HttpApi.make")){t=o;continue}}}break}return t}function yr(e,t){let r=[],s=t||e.getFilePath(),n=new Set;for(let i of e.getDescendantsOfKind(J.CallExpression)){let c=i.getExpression().getText();if(!c.includes("HttpApi.make")||c.includes("HttpApiBuilder")||c.includes(".add"))continue;let o=i.getArguments(),a=o.length>0?o[0]?.getText().replace(/["'`]/g,""):void 0;if(!a||n.has(a))continue;let d=Nl(i),l=bl(d,e,s);n.add(a),r.push({apiId:a,filePath:s,groups:l})}return r}import{Option as Cl}from"effect";var $i=3,wl=5;function Fi(e,t,r){return Math.max(t,Math.min(r,e))}function bt(e,t){return[...new Set(e)].slice(0,t)}function Ai(e){return e.startsWith("Consider")||e.startsWith("If you want clearer diagrams")||e.startsWith("For larger programs")}function Xt(e){return Ai(e)?e:`Consider ${e.charAt(0).toLowerCase()}${e.slice(1)}`}function Tl(e){let t=[],r=s=>{for(let n of s){t.push(n);let i=Cl.getOrElse(P(n),()=>[]);i.length>0&&r(i)}};return r(e),t}function kl(e){let t=e.toLowerCase();return t.includes("log")||t.includes("logger")||t.includes("taperror")}function vl(e){let t=e.callee.trim();return!!(t===""||t==="_"||t==="Effect"||/call expression/i.test(t)||/^program-\d+$/i.test(e.name??""))}function Il(e){return e.type==="effect"&&(e.semanticRole==="service-call"||e.serviceCall!==void 0||e.serviceMethod!==void 0)}function $l(e){let t=e.callee.trim();return!(t===""||t==="_"||t==="Effect"||/unknown/i.test(t)||/call expression/i.test(t))}function Fl(e,t={}){let r=Tl(e.root.children),s=r.length,n=r.filter(E=>E.type==="effect"),i=n.filter(E=>E.semanticRole==="side-effect"),c=n.filter(E=>kl(E.displayName??E.name??E.callee)),o=r.filter(E=>E.type==="unknown").length,a=r.filter(E=>E.type==="unknown"||E.type==="pipe"?!0:E.type==="effect"?vl(E):!1).length,d=r.filter(E=>Il(E)),l=d.filter(E=>$l(E)),f=r.filter(E=>E.type==="pipe"),u=f.length,g=f.length>0?Math.max(...f.map(E=>1+E.transformations.length)):0,m=[...lt(e)].sort((E,$)=>$.steps.length-E.steps.length)[0],h=m?Dn(m,{collapseRepeatedLogs:!0,collapsePureTransforms:!0,styleGuide:t.styleGuideSummary??!1}):{steps:[],collapsedGroups:0},y=s>0?s:1,N=d.length>0?d.length:1;return{stepCountDetailed:s,stepCountSummary:h.steps.length,collapsedGroupsSummary:h.collapsedGroups,logRatio:c.length/y,sideEffectRatio:i.length/y,anonymousNodeCount:a,anonymousRatio:a/y,unknownNodeCount:o,serviceCallCount:d.length,namedServiceCallRatio:l.length/N,pipeChainCount:u,maxPipeChainLength:g}}function Al(e){let t=Math.min(35,e.unknownNodeCount*8),r=Math.min(25,Math.round(e.anonymousRatio*40)),s=e.stepCountDetailed>24?Math.min(22,Math.round((e.stepCountDetailed-24)*.6)):0,n=Math.min(12,Math.round(e.logRatio*30)),i=e.sideEffectRatio>.75?Math.min(8,Math.round((e.sideEffectRatio-.75)*40)):0,c=Fi(Math.round(100-t-r-s-n-i),0,100),o=c>=75?"good":c>=50?"ok":"noisy";return{score:c,band:o}}function Ri(e){let t=[],r=Math.round(e.logRatio*Math.max(e.stepCountDetailed,1));return e.stepCountDetailed>=60?t.push(`High step count (${String(e.stepCountDetailed)}). Consider summary mode.`):e.stepCountDetailed>=35&&t.push(`Moderate step count (${String(e.stepCountDetailed)}). Summary mode may improve readability.`),(r>=12||e.logRatio>=.35)&&t.push(`Many log steps (${String(r)}). Consider collapsing logs or summary mode.`),e.anonymousNodeCount>=5&&t.push(`${String(e.anonymousNodeCount)} anonymous nodes from pipe chains or unnamed calls.`),e.unknownNodeCount>0&&t.push(`${String(e.unknownNodeCount)} unresolved nodes may reduce diagram clarity.`),e.serviceCallCount>=3&&e.namedServiceCallRatio<.7&&t.push(`Service call naming clarity is ${(e.namedServiceCallRatio*100).toFixed(0)}% (${String(e.serviceCallCount)} calls).`),t}function Di(e){let t=[],r=Math.round(e.logRatio*Math.max(e.stepCountDetailed,1));return e.stepCountDetailed>=35&&t.push("For larger programs, consider summary mode."),(r>=12||e.logRatio>=.35)&&t.push("For larger programs, consider grouping logs or using summary mode."),e.anonymousNodeCount>=5&&t.push("Consider naming intermediate values or extracting named helpers."),(e.pipeChainCount>=4||e.maxPipeChainLength>=6)&&t.push("If you want clearer diagrams, consider splitting long pipe chains into named steps."),e.serviceCallCount>=3&&e.namedServiceCallRatio<.7&&t.push("Consider naming service-call intermediates to make boundaries explicit."),bt(t.map(Xt),$i)}function hr(e,t={}){let r=Fl(e,t),{score:s,band:n}=Al(r),i=Ri(r),c=Di(r),o=t.hints?.reasons??[],a=(t.hints?.tips??[]).map(Xt);return{score:s,band:n,metrics:r,reasons:bt([...i,...o],8),tips:bt([...c,...a],$i)}}function Rl(e){if(e.length===0)return{stepCountDetailed:0,stepCountSummary:0,collapsedGroupsSummary:0,logRatio:0,sideEffectRatio:0,anonymousNodeCount:0,anonymousRatio:0,unknownNodeCount:0,serviceCallCount:0,namedServiceCallRatio:0,pipeChainCount:0,maxPipeChainLength:0};let t=e.map(i=>Math.max(1,i.metrics.stepCountDetailed)),r=t.reduce((i,c)=>i+c,0),s=i=>e.reduce((c,o,a)=>c+i(o)*(t[a]??1),0)/r,n=i=>e.reduce((c,o)=>c+i(o),0);return{stepCountDetailed:Math.round(s(i=>i.metrics.stepCountDetailed)),stepCountSummary:Math.round(s(i=>i.metrics.stepCountSummary)),collapsedGroupsSummary:Math.round(s(i=>i.metrics.collapsedGroupsSummary)),logRatio:s(i=>i.metrics.logRatio),sideEffectRatio:s(i=>i.metrics.sideEffectRatio),anonymousNodeCount:Math.round(n(i=>i.metrics.anonymousNodeCount)),anonymousRatio:s(i=>i.metrics.anonymousRatio),unknownNodeCount:Math.round(n(i=>i.metrics.unknownNodeCount)),serviceCallCount:Math.round(n(i=>i.metrics.serviceCallCount)),namedServiceCallRatio:s(i=>i.metrics.namedServiceCallRatio),pipeChainCount:Math.round(n(i=>i.metrics.pipeChainCount)),maxPipeChainLength:Math.max(...e.map(i=>i.metrics.maxPipeChainLength))}}function Pi(e,t,r={}){let s=t.map(d=>hr(d,r)),n=Rl(s),i=s.length>0?Math.round(s.reduce((d,l)=>d+l.score*Math.max(1,l.metrics.stepCountDetailed),0)/s.reduce((d,l)=>d+Math.max(1,l.metrics.stepCountDetailed),0)):100,c=i>=75?"good":i>=50?"ok":"noisy",o=bt([...Ri(n),...r.hints?.reasons??[]],10),a=bt([...Di(n),...(r.hints?.tips??[]).map(Xt)].filter(Ai),wl);return{filePath:e,quality:{score:i,band:c,metrics:n,reasons:o,tips:a}}}function Dl(e,t,r){return{filePath:e,metricValue:t,tip:Xt(r)}}function Yt(e,t,r,s){return[...e].sort((n,i)=>{let c=t(i)-t(n);return c!==0?c:n.filePath.localeCompare(i.filePath)}).slice(0,s).map(n=>Dl(n.filePath,t(n),r(n)))}function Mi(e,t=10){let r=Fi(t,1,50);return{largestPrograms:Yt(e,s=>s.quality.metrics.stepCountDetailed,()=>"For larger programs, consider summary mode.",r),mostAnonymousNodes:Yt(e,s=>s.quality.metrics.anonymousNodeCount,()=>"Consider naming intermediate values or extracting named helpers.",r),mostUnknownNodes:Yt(e,s=>s.quality.metrics.unknownNodeCount,()=>"If you want clearer diagrams, consider extracting helpers to reduce unresolved nodes.",r),highestLogRatio:Yt(e,s=>s.quality.metrics.logRatio,()=>"For larger programs, consider grouping logs or using summary mode.",r)}}import{readFile as Pl}from"fs/promises";import{resolve as Ml}from"path";function Ol(e){return e?/effect/i.test(e):!1}function Ll(e){let t=`${e.ruleId??""} ${e.message??""}`.toLowerCase();if(t.includes("yield")||t.includes("untagged"))return"Consider binding yielded values with meaningful names.";if(t.includes("error")||t.includes("catch")||t.includes("handle"))return"If you want clearer diagrams, consider making error boundaries explicit.";if(t.includes("service")||t.includes("layer")||t.includes("provide"))return"Consider acquiring services near the top of the workflow.";if(t.includes("pipe")||t.includes("nested")||t.includes("lambda"))return"If you want clearer diagrams, consider extracting nested pipe lambdas into named helpers."}function Wl(e){let t=e.ruleId??"eslint",r=(e.message??"").trim();if(r)return`ESLint (${t}): ${r}`}function Kl(e){if(Array.isArray(e))return e;if(e&&typeof e=="object"&&"results"in e){let t=e.results;if(Array.isArray(t))return t}return[]}async function Oi(e){let t=await Pl(e,"utf-8"),r=JSON.parse(t),s=Kl(r),n=new Map;for(let c of s){let o=c.filePath?Ml(c.filePath):void 0;if(!o)continue;let a=c.messages??[];for(let d of a){if(!Ol(d.ruleId))continue;let l=n.get(o)??{reasons:[],tips:[]},f=Wl(d);f&&l.reasons.push(f);let u=Ll(d);u&&l.tips.push(u),n.set(o,l)}}let i=new Map;for(let[c,o]of n)i.set(c,{reasons:[...new Set(o.reasons)].slice(0,8),tips:[...new Set(o.tips)].slice(0,5)});return i}function Wi(e){let t=r=>s=>e?`\x1B[${r}m${s}\x1B[0m`:s;return{dim:t(2),green:t(32),cyan:t(36),yellow:t(33),red:t(31),bold:t(1)}}function Ul(e){let t,r="auto",s,n=!0,i=!0,c="TB",o,a=!1,d=!1,l="effect-analysis",f=!0,u=!1,g=!1,p=!1,m=!1,h=!1,y=!1,N=!1,E=!1,$=!1,S=!1,b=!1,T=!1,v,x=[],K,F=!1,j=!0,I=!1,q,z=!1,Y=!1,Z=!0,L,H=!1,ge=!1,de=!1,ne=[];for(let te=0;te<e.length;te++){let A=e[te];if(A!==void 0){if((A==="--help"||A==="-h")&&(Gl(),process.exit(0)),!A.startsWith("-")){ne.push(A),t??=A;continue}if(A==="--format"||A==="-f"){let W=e[++te];(W==="auto"||W==="json"||W==="mermaid"||W==="mermaid-paths"||W==="mermaid-enhanced"||W==="mermaid-railway"||W==="mermaid-services"||W==="mermaid-errors"||W==="mermaid-decisions"||W==="mermaid-causes"||W==="mermaid-concurrency"||W==="mermaid-timeline"||W==="mermaid-layers"||W==="mermaid-retry"||W==="mermaid-testability"||W==="mermaid-dataflow"||W==="stats"||W==="migration"||W==="showcase"||W==="explain"||W==="summary"||W==="matrix"||W==="api-docs"||W==="openapi-paths"||W==="openapi-runtime")&&(r=W)}else if(A==="--export")L=e[++te];else if(A==="--output"||A==="-o")s=e[++te];else if(A==="--compact"||A==="-c")n=!1;else if(A==="--pretty")n=!0;else if(A==="--no-metadata")i=!1;else if(A==="--direction"||A==="-d"){let W=e[++te];(W==="TB"||W==="LR"||W==="BT"||W==="RL")&&(c=W)}else if(A==="--tsconfig")o=e[++te];else if(A.startsWith("--tsconfig="))o=A.slice(11);else if(A==="--colocate")a=!0;else if(A==="--no-colocate")d=!0;else if(A==="--no-colocate-enhanced")f=!1;else if(A==="--colocate-suffix"){let W=e[++te];W&&(l=W)}else if(A.startsWith("--colocate-suffix="))l=A.slice(18);else if(A==="--watch"||A==="-w")u=!0;else if(A==="--migration"||A==="-m")g=!0;else if(A==="--cache")p=!0;else if(A==="--coverage-audit")m=!0;else if(A==="--show-suspicious-zeros")h=!0;else if(A==="--show-top-unknown")y=!0;else if(A==="--no-show-top-unknown")y=!1,N=!0;else if(A==="--show-top-unknown-reasons")E=!0;else if(A==="--no-show-top-unknown-reasons")E=!1,$=!0;else if(A==="--show-by-folder")S=!0;else if(A==="--per-file-timing")T=!0;else if(A==="--min-meaningful-nodes"){let W=e[++te];if(W!==void 0){let Ie=Number.parseInt(W,10);Number.isFinite(Ie)&&Ie>=0&&(v=Ie)}}else if(A==="--exclude-from-suspicious-zero"){let W=e[++te];W!==void 0&&x.push(W)}else A==="--known-effect-internals-root"?K=e[++te]:A==="--json-summary"?b=!0:A==="--quiet"||A==="-q"?F=!0:A==="--no-color"?j=!1:A==="--quality"?I=!0:A==="--quality-eslint"?q=e[++te]:A.startsWith("--quality-eslint=")?q=A.slice(17):A==="--style-guide"?z=!0:A==="--no-style-guide"?(z=!1,Y=!0):A==="--service-map"?Z=!0:A==="--no-service-map"?Z=!1:A==="--diff"?H=!0:A==="--regression"?ge=!0:A==="--include-trivial"&&(de=!0)}}let we=H?ne:[];return g&&(r="migration"),r==="mermaid-paths"&&!Y&&!z&&(z=!0),m&&(N||(y=!0),$||(E=!0)),{pathArg:t,options:{format:r,output:s,pretty:n,includeMetadata:i,direction:c,tsconfig:o,colocate:a,noColocate:d,colocateSuffix:l,colocateEnhanced:f,watch:u,migration:g,cache:p,coverageAudit:m,showSuspiciousZeros:h,showTopUnknown:y,showTopUnknownReasons:E,showOkZeroFailByFolder:S,jsonSummary:b,perFileTiming:T,minMeaningfulNodes:v,excludeFromSuspiciousZeros:x,knownEffectInternalsRoot:K,quiet:F,color:j,quality:I,qualityEslint:q,styleGuide:z,serviceMap:Z,openapiExport:L,diff:H,diffSources:we,regression:ge,includeTrivial:de}}}var Gl=()=>{process.stdout.write(`
|
|
58
|
+
`)}function Nr(e){let t=[];for(let r of e){t.push(`# API: ${r.apiId}`),t.push("");let s=r.prefix??"";for(let n of r.groups){t.push(`## ${n.name}`),n.description&&(t.push(""),t.push(n.description),t.push("")),t.push(""),t.push("| Method | Path | Name | Description |"),t.push("|--------|------|------|-------------|");let i=n.prefix??"";for(let c of n.endpoints){let o=s+i+c.path,a=c.description??c.summary??"-",d=c.deprecated?" (deprecated)":"";t.push(`| ${c.method} | ${o} | ${c.name}${d} | ${a} |`)}t.push("")}t.push("")}return t.join(`
|
|
59
|
+
`).trim()}function Mi(e){let t={};for(let r of e){let s=r.prefix??"";for(let n of r.groups){let i=n.prefix??"";for(let c of n.endpoints){let o=s+i+c.path;t[o]??={};let a=c.method.toLowerCase(),d={operationId:`${n.name}.${c.name}`,...c.summary?{summary:c.summary}:{},...c.deprecated?{deprecated:!0}:{}};if(c.requestSchema&&(d.requestBody={content:{"application/json":{schema:c.requestSchema}}}),c.responseSchema&&(d.responses={200:{description:c.summary??c.description??"Success",content:{"application/json":{schema:c.responseSchema}}}}),c.urlParamsSchema?.properties){let l=Object.entries(c.urlParamsSchema.properties).map(([f,u])=>({name:f,in:"path",schema:u}));l.length&&(d.parameters=l)}t[o][a]=d}}}return{paths:t}}import{SyntaxKind as Q}from"ts-morph";import{SyntaxKind as se}from"ts-morph";function wl(e,t,r){if(e.getText().includes("Schema."))return e;if(e.getKind()===se.Identifier){let n=e,i=n.getSymbol(),o=(i?.getAliasedSymbol()??i)?.getDeclarations()??[];for(let l of o){if(l.getKind()===se.VariableDeclaration){let f=l.getInitializer();if(f?.getText().includes("Schema."))return f}if(l.getKind()===se.ImportSpecifier){let f=l.getName(),u=l.getFirstAncestorByKind(se.ImportDeclaration);if(u){let g=u.getModuleSpecifierValue(),p=t.getFilePath(),m=g.startsWith(".")?Nt(p,g):void 0,y=m?r.getSourceFile(m):void 0;if(y){let h=y.getExportedDeclarations().get(f)??[];for(let N of h)if(N.getKind()===se.VariableDeclaration){let x=N.getInitializer();if(x?.getText().includes("Schema."))return x}}}}}let a=n.getText(),d=t.getVariableDeclarations();for(let l of d)if(l.getName()===a){let f=l.getInitializer();if(f?.getText().includes("Schema."))return f}}return e.getText().includes("Schema.")?e:void 0}function an(e,t,r,s){let n=wl(e,t,r);if(n)return Ge(n,t,r,s??new Map)}function Ge(e,t,r,s){let n=e.getText();if(n.includes("Schema.Array")){let a=e.getKind()===se.CallExpression?e:e.getFirstDescendantByKind(se.CallExpression);if(a){let d=a.getArguments();return{type:"array",items:(d[0]?Ge(d[0],t,r,s):void 0)??{}}}}if(n.includes("Schema.Struct")){let a=e.getKind()===se.CallExpression?e:e.getFirstDescendantByKind(se.CallExpression);if(!a)return{type:"object"};let l=a.getArguments()[0];if(l?.getKind()!==se.ObjectLiteralExpression)return{type:"object"};let f=l,u={},g=[];for(let m of f.getProperties()){if(m.getKind()!==se.PropertyAssignment)continue;let y=m,h=y.getNameNode().getText(),N=y.getInitializer();if(!N)continue;let x=N.getText();x.includes("Schema.optional")||x.includes(".optional")||g.push(h);let E=Ge(N,t,r,s);E&&(u[h]=E)}let p={type:"object",properties:Object.keys(u).length?u:void 0,additionalProperties:!1};return g.length&&(p.required=g),p}if(n.includes("Schema.Union")){let a=e.getKind()===se.CallExpression?e:e.getFirstDescendantByKind(se.CallExpression);if(a){let l=a.getArguments().map(f=>Ge(f,t,r,s)).filter(f=>f!==void 0);if(l.length)return{oneOf:l}}}if(n.includes("Schema.optional")||n.includes(".pipe(Schema.optional")){let a=e.getKind()===se.CallExpression?e:e.getFirstDescendantByKind(se.CallExpression);if(a){let d=a.getArguments(),l=d[0]?Ge(d[0],t,r,s):void 0;if(l)return{...l,nullable:!0}}}if(n.includes("Schema.Record")){let a=e.getKind()===se.CallExpression?e:e.getFirstDescendantByKind(se.CallExpression);if(a){let d=a.getArguments();return{type:"object",additionalProperties:(d[1]?Ge(d[1],t,r,s):void 0)??!0}}}if(n.includes("Schema.Tuple")){let a=e.getKind()===se.CallExpression?e:e.getFirstDescendantByKind(se.CallExpression);if(a)return{type:"array",items:a.getArguments().map(f=>Ge(f,t,r,s)).filter(Boolean)}}if(n.includes("Schema.Date")||n.includes("Schema.DateTimeUtc")||n.includes("Schema.Instant"))return{type:"string",format:"date-time"};if(n.includes("Schema.String")&&!n.includes("Schema.Struct"))return{type:"string"};if(n.includes("Schema.Number")||n.includes("Schema.Int")||n.includes("Schema.Positive")||n.includes("Schema.NonNegative")||n.includes("Schema.Finite"))return{type:"number"};if(n.includes("Schema.Boolean"))return{type:"boolean"};if(n.includes("Schema.Null"))return{type:"null"};let i=/Schema\.Literal\s*\(\s*(["'])([^"']*)\1\s*\)/.exec(n);if(i)return{type:"string",enum:[i[2]]};let c=/Schema\.Literal\s*\(\s*(\d+)\s*\)/.exec(n);if(c)return{type:"number",enum:[Number(c[1])]};let o=/Schema\.Literal\s*\(\s*(true|false)\s*\)/.exec(n);if(o)return{type:"boolean",enum:[o[1]==="true"]};if(e.getKind()===se.Identifier){let l=(e.getSymbol()?.getDeclarations()[0]).getInitializer();if(l)return Ge(l,t,r,s)}}function Tl(e,t,r){let{line:s,column:n}=r.getLineAndColumnAtPos(t.getStart());return{filePath:e,line:s+1,column:n}}function kl(e){let s=e.getText().replace(/\$\{HttpApiSchema\.param\s*\(\s*["'](\w+)["'][^}]*\)\}/g,":$1").replace(/\$\{[^}]*\}/g,":param").replace(/^`|`$/g,"").trim();return s.startsWith("/")?s:`/${s}`}function Oi(e,t,r){let s={},n=e;for(let i=0;i<30&&n;i++){let c=n.getParent();if(c?.getKind()!==Q.CallExpression){n=c;continue}let o=c,a=o.getExpression().getText(),d=o.getArguments();if(d.length<2){n=c;continue}let l=d[0]?.getText(),f=d[1]?.getText();if(a.endsWith(".annotate")||a.endsWith(".annotateContext"))if(l?.includes("OpenApi.Description")||l?.includes("Description")){let u=f?.replace(/^["']|["']$/g,"");u&&(s.description=u)}else if(l?.includes("OpenApi.Summary")||l?.includes("Summary")){let u=f?.replace(/^["']|["']$/g,"");u&&(s.summary=u)}else l?.includes("OpenApi.Deprecated")||l?.includes("Deprecated")?s.deprecated=f==="true":(l?.includes("OpenApi.Exclude")||l?.includes("Exclude"))&&(s.excluded=f==="true");n=c}return s}function vl(e,t){let r={},s=t.getProject(),n=e;for(let i=0;i<40&&n;i++){let c=n.getParent();if(c?.getKind()!==Q.CallExpression){n=c;continue}let o=c,a=o.getExpression().getText(),d=o.getArguments();if(d.length<1){n=c;continue}let l=d[0];if(a.endsWith(".addSuccess")&&l&&!r.responseSchema){let f=an(l,t,s);f&&(r.responseSchema=f)}else if(a.endsWith(".setPayload")&&l&&!r.requestSchema){let f=an(l,t,s);f&&(r.requestSchema=f)}else if((a.endsWith(".setUrlParams")||a.endsWith(".setQueryParams"))&&l&&!r.urlParamsSchema){let f=an(l,t,s);f&&(r.urlParamsSchema=f)}n=c}return r}function Il(e,t,r,s){let n=e.getArguments(),c=(n.length>0?n[0]?.getText().replace(/["'`]/g,""):"unnamed")??"unnamed",o="/";if(n.length>=2)o=n[1]?.getText().replace(/["'`]/g,"")??"/";else{let l=e.getParent();if(l?.getKind()===Q.TaggedTemplateExpression){let f=l.getTemplate();o=kl(f)}}let a=Oi(e,r,s);if(a.excluded)return null;let d=vl(e,r);return{name:c,method:t.toUpperCase(),path:o||"/",location:Tl(s,e,r),...a.description?{description:a.description}:{},...a.summary?{summary:a.summary}:{},...a.deprecated?{deprecated:!0}:{},...d.requestSchema?{requestSchema:d.requestSchema}:{},...d.responseSchema?{responseSchema:d.responseSchema}:{},...d.urlParamsSchema?{urlParamsSchema:d.urlParamsSchema}:{}}}function $l(e,t,r){let s=[],n=["get","post","put","delete","patch","head","options"],i=new Set,c=Cr(e);function o(l){let f=l,u=[".annotate",".addSuccess",".setPayload",".setUrlParams",".setQueryParams",".addFailure"];for(let g=0;g<15;g++){if(f.getKind()!==Q.CallExpression)return;let p=f,m=p.getExpression().getText();for(let h of n){let N=m.includes(`HttpApiEndpoint.${h}`)||m.includes(`HttpApiEndpoint.${h}(`),x=!u.some(F=>m.endsWith(F)||m.includes(F));if(N&&!m.includes(".annotate")&&x)return p}if(u.some(h=>m.endsWith(h)||m.includes(h))){let h=p.getExpression();h.getKind()===Q.CallExpression?f=h:f=h.getExpression();continue}return}}function a(l){if(l.getKind()===Q.CallExpression)return l;if(l.getKind()===Q.Identifier){let f=l.getText(),u=l.getSymbol(),g=u?.getDeclarations()??u?.getAliasedSymbol()?.getDeclarations()??[];for(let m of g)if(m.getKind()===Q.VariableDeclaration){let y=m.getInitializer();if(y)return y}let p=t.getVariableDeclarations();for(let m of p)if(m.getName()===f){let y=m.getInitializer();if(y)return y}}}function d(l){let f=a(l);if(f?.getKind()!==Q.CallExpression)return;let u=f,g=o(u);if(g){let m=g.getExpression().getText();for(let y of n)if(m.includes(`HttpApiEndpoint.${y}`)){let h=Il(g,y,t,r);h&&!i.has(`${h.method}:${h.path}:${h.name}`)&&(i.add(`${h.method}:${h.path}:${h.name}`),s.push(h));return}}if(u.getExpression().getText().endsWith(".add"))for(let m of u.getArguments())d(m)}for(let l of c)d(l);return s}function Fl(e,t,r,s){let n=e.getArguments(),c=(n.length>0?n[0]?.getText().replace(/["'`]/g,""):"group")??"group",o=n[1],a=!1;if(o?.getKind()===Q.ObjectLiteralExpression){let u=o.getProperty("topLevel");u?.getKind()===Q.PropertyAssignment&&(a=u.getInitializer()?.getText()==="true")}let d=$l(e,t,r),l=Oi(e,t,r);return{name:c,endpoints:d,...l.description?{description:l.description}:{},...a?{topLevel:!0}:{},...s?{prefix:s}:{}}}function Al(e){let t=e;for(let r=0;r<25&&t.getKind()===Q.CallExpression;r++){let s=t;if(s.getExpression().getText().endsWith(".prefix")){let c=s.getArguments();if(c.length>=1){let o=c[0]?.getText().replace(/["'`]/g,"");if(o)return o.startsWith("/")?o:`/${o}`}break}let i=s.getExpression();if(i.getKind()===Q.PropertyAccessExpression)t=i.getExpression();else break}}function Cr(e){let t=[],r,s=e,n=e.getExpression().getText(),i=n.includes("HttpApi.make"),c=n.includes("HttpApiGroup.make");for(let o=0;o<20;o++){let a=s.getParent();if(!a||(a.getKind()===Q.PropertyAccessExpression&&(a=a.getParent()),a?.getKind()!==Q.CallExpression))break;let d=a,l=d.getExpression().getText();if(l.endsWith(".add")){if(i&&l.includes("HttpApiGroup.make")||c&&l.includes("HttpApi.make")&&!l.includes("HttpApiGroup"))break;r=d,s=a;continue}break}if(!r)return t;s=r;for(let o=0;o<50;o++){if(s.getKind()===Q.CallExpression){let a=s;if(a.getExpression().getText().endsWith(".add")){for(let f of a.getArguments())t.push(f);let l=a.getExpression();if(l.getKind()===Q.CallExpression){s=l;continue}if(l.getKind()===Q.PropertyAccessExpression){let f=l.getExpression();if(f.getKind()===Q.CallExpression){s=f;continue}}}}break}return t}function Rl(e,t,r){let s=[],n=new Set,i=Cr(e),c=[".add",".prefix",".annotate"];function o(l){let f=l;for(let u=0;u<20;u++){if(f.getKind()!==Q.CallExpression)return;let g=f,p=g.getExpression().getText();if(p.includes("HttpApiGroup.make")&&!c.some(m=>p.endsWith(m))||p.includes("HttpApi.make")&&!c.some(m=>p.endsWith(m)))return g;if(c.some(m=>p.endsWith(m))){let m=g.getExpression();if(m.getKind()===Q.CallExpression){f=m;continue}if(m.getKind()===Q.PropertyAccessExpression){let y=m.getExpression();if(y.getKind()===Q.CallExpression){f=y;continue}}return}return}}function a(l){if(l.getKind()===Q.CallExpression)return l;if(l.getKind()===Q.Identifier){let f=l.getText(),u=l.getSymbol(),g=u?.getDeclarations()??u?.getAliasedSymbol()?.getDeclarations()??[];for(let m of g)if(m.getKind()===Q.VariableDeclaration){let y=m.getInitializer();if(y?.getKind()===Q.CallExpression)return y}let p=t.getVariableDeclarations();for(let m of p)if(m.getName()===f){let y=m.getInitializer();if(y?.getKind()===Q.CallExpression)return y}}}function d(l){let f=a(l);if(!f)return;let u=f.getExpression().getText();if(u.includes("HttpApiGroup.make")){let g=o(f);if(g){let p=Al(f),m=Fl(g,t,r,p);m&&!n.has(m.name)&&(n.add(m.name),s.push(m))}return}if(u.includes("HttpApi.make")){let g=o(f);if(g)for(let p of Cr(g))d(p)}}for(let l of i)d(l);return s}function Dl(e){let t=e;for(let r=0;r<50;r++){let s=t.getParent();if(s?.getKind()!==Q.CallExpression)return e;let n=s;if(n.getExpression().getText().endsWith(".add")){let c=n.getExpression();if(c.getKind()===Q.CallExpression){let o=c;if(o.getExpression().getText().includes("HttpApi.make")){t=o;continue}}}break}return t}function wr(e,t){let r=[],s=t||e.getFilePath(),n=new Set;for(let i of e.getDescendantsOfKind(Q.CallExpression)){let c=i.getExpression().getText();if(!c.includes("HttpApi.make")||c.includes("HttpApiBuilder")||c.includes(".add"))continue;let o=i.getArguments(),a=o.length>0?o[0]?.getText().replace(/["'`]/g,""):void 0;if(!a||n.has(a))continue;let d=Dl(i),l=Rl(d,e,s);n.add(a),r.push({apiId:a,filePath:s,groups:l})}return r}import{Option as Pl}from"effect";var Li=3,Ml=5;function Wi(e,t,r){return Math.max(t,Math.min(r,e))}function It(e,t){return[...new Set(e)].slice(0,t)}function Ki(e){return e.startsWith("Consider")||e.startsWith("If you want clearer diagrams")||e.startsWith("For larger programs")}function ln(e){return Ki(e)?e:`Consider ${e.charAt(0).toLowerCase()}${e.slice(1)}`}function Ol(e){let t=[],r=s=>{for(let n of s){t.push(n);let i=Pl.getOrElse(P(n),()=>[]);i.length>0&&r(i)}};return r(e),t}function Ll(e){let t=e.toLowerCase();return t.includes("log")||t.includes("logger")||t.includes("taperror")}function Wl(e){let t=e.callee.trim();return!!(t===""||t==="_"||t==="Effect"||/call expression/i.test(t)||/^program-\d+$/i.test(e.name??""))}function Kl(e){return e.type==="effect"&&(e.semanticRole==="service-call"||e.serviceCall!==void 0||e.serviceMethod!==void 0)}function Bl(e){let t=e.callee.trim();return!(t===""||t==="_"||t==="Effect"||/unknown/i.test(t)||/call expression/i.test(t))}function jl(e,t={}){let r=Ol(e.root.children),s=r.length,n=r.filter(x=>x.type==="effect"),i=n.filter(x=>x.semanticRole==="side-effect"),c=n.filter(x=>Ll(x.displayName??x.name??x.callee)),o=r.filter(x=>x.type==="unknown").length,a=r.filter(x=>x.type==="unknown"||x.type==="pipe"?!0:x.type==="effect"?Wl(x):!1).length,d=r.filter(x=>Kl(x)),l=d.filter(x=>Bl(x)),f=r.filter(x=>x.type==="pipe"),u=f.length,g=f.length>0?Math.max(...f.map(x=>1+x.transformations.length)):0,m=[...mt(e)].sort((x,F)=>F.steps.length-x.steps.length)[0],y=m?jn(m,{collapseRepeatedLogs:!0,collapsePureTransforms:!0,styleGuide:t.styleGuideSummary??!1}):{steps:[],collapsedGroups:0},h=s>0?s:1,N=d.length>0?d.length:1;return{stepCountDetailed:s,stepCountSummary:y.steps.length,collapsedGroupsSummary:y.collapsedGroups,logRatio:c.length/h,sideEffectRatio:i.length/h,anonymousNodeCount:a,anonymousRatio:a/h,unknownNodeCount:o,serviceCallCount:d.length,namedServiceCallRatio:l.length/N,pipeChainCount:u,maxPipeChainLength:g}}function ql(e){let t=Math.min(35,e.unknownNodeCount*8),r=Math.min(25,Math.round(e.anonymousRatio*40)),s=e.stepCountDetailed>24?Math.min(22,Math.round((e.stepCountDetailed-24)*.6)):0,n=Math.min(12,Math.round(e.logRatio*30)),i=e.sideEffectRatio>.75?Math.min(8,Math.round((e.sideEffectRatio-.75)*40)):0,c=Wi(Math.round(100-t-r-s-n-i),0,100),o=c>=75?"good":c>=50?"ok":"noisy";return{score:c,band:o}}function Bi(e){let t=[],r=Math.round(e.logRatio*Math.max(e.stepCountDetailed,1));return e.stepCountDetailed>=60?t.push(`High step count (${String(e.stepCountDetailed)}). Consider summary mode.`):e.stepCountDetailed>=35&&t.push(`Moderate step count (${String(e.stepCountDetailed)}). Summary mode may improve readability.`),(r>=12||e.logRatio>=.35)&&t.push(`Many log steps (${String(r)}). Consider collapsing logs or summary mode.`),e.anonymousNodeCount>=5&&t.push(`${String(e.anonymousNodeCount)} anonymous nodes from pipe chains or unnamed calls.`),e.unknownNodeCount>0&&t.push(`${String(e.unknownNodeCount)} unresolved nodes may reduce diagram clarity.`),e.serviceCallCount>=3&&e.namedServiceCallRatio<.7&&t.push(`Service call naming clarity is ${(e.namedServiceCallRatio*100).toFixed(0)}% (${String(e.serviceCallCount)} calls).`),t}function ji(e){let t=[],r=Math.round(e.logRatio*Math.max(e.stepCountDetailed,1));return e.stepCountDetailed>=35&&t.push("For larger programs, consider summary mode."),(r>=12||e.logRatio>=.35)&&t.push("For larger programs, consider grouping logs or using summary mode."),e.anonymousNodeCount>=5&&t.push("Consider naming intermediate values or extracting named helpers."),(e.pipeChainCount>=4||e.maxPipeChainLength>=6)&&t.push("If you want clearer diagrams, consider splitting long pipe chains into named steps."),e.serviceCallCount>=3&&e.namedServiceCallRatio<.7&&t.push("Consider naming service-call intermediates to make boundaries explicit."),It(t.map(ln),Li)}function Tr(e,t={}){let r=jl(e,t),{score:s,band:n}=ql(r),i=Bi(r),c=ji(r),o=t.hints?.reasons??[],a=(t.hints?.tips??[]).map(ln);return{score:s,band:n,metrics:r,reasons:It([...i,...o],8),tips:It([...c,...a],Li)}}function _l(e){if(e.length===0)return{stepCountDetailed:0,stepCountSummary:0,collapsedGroupsSummary:0,logRatio:0,sideEffectRatio:0,anonymousNodeCount:0,anonymousRatio:0,unknownNodeCount:0,serviceCallCount:0,namedServiceCallRatio:0,pipeChainCount:0,maxPipeChainLength:0};let t=e.map(i=>Math.max(1,i.metrics.stepCountDetailed)),r=t.reduce((i,c)=>i+c,0),s=i=>e.reduce((c,o,a)=>c+i(o)*(t[a]??1),0)/r,n=i=>e.reduce((c,o)=>c+i(o),0);return{stepCountDetailed:Math.round(s(i=>i.metrics.stepCountDetailed)),stepCountSummary:Math.round(s(i=>i.metrics.stepCountSummary)),collapsedGroupsSummary:Math.round(s(i=>i.metrics.collapsedGroupsSummary)),logRatio:s(i=>i.metrics.logRatio),sideEffectRatio:s(i=>i.metrics.sideEffectRatio),anonymousNodeCount:Math.round(n(i=>i.metrics.anonymousNodeCount)),anonymousRatio:s(i=>i.metrics.anonymousRatio),unknownNodeCount:Math.round(n(i=>i.metrics.unknownNodeCount)),serviceCallCount:Math.round(n(i=>i.metrics.serviceCallCount)),namedServiceCallRatio:s(i=>i.metrics.namedServiceCallRatio),pipeChainCount:Math.round(n(i=>i.metrics.pipeChainCount)),maxPipeChainLength:Math.max(...e.map(i=>i.metrics.maxPipeChainLength))}}function qi(e,t,r={}){let s=t.map(d=>Tr(d,r)),n=_l(s),i=s.length>0?Math.round(s.reduce((d,l)=>d+l.score*Math.max(1,l.metrics.stepCountDetailed),0)/s.reduce((d,l)=>d+Math.max(1,l.metrics.stepCountDetailed),0)):100,c=i>=75?"good":i>=50?"ok":"noisy",o=It([...Bi(n),...r.hints?.reasons??[]],10),a=It([...ji(n),...(r.hints?.tips??[]).map(ln)].filter(Ki),Ml);return{filePath:e,quality:{score:i,band:c,metrics:n,reasons:o,tips:a}}}function zl(e,t,r){return{filePath:e,metricValue:t,tip:ln(r)}}function cn(e,t,r,s){return[...e].sort((n,i)=>{let c=t(i)-t(n);return c!==0?c:n.filePath.localeCompare(i.filePath)}).slice(0,s).map(n=>zl(n.filePath,t(n),r(n)))}function _i(e,t=10){let r=Wi(t,1,50);return{largestPrograms:cn(e,s=>s.quality.metrics.stepCountDetailed,()=>"For larger programs, consider summary mode.",r),mostAnonymousNodes:cn(e,s=>s.quality.metrics.anonymousNodeCount,()=>"Consider naming intermediate values or extracting named helpers.",r),mostUnknownNodes:cn(e,s=>s.quality.metrics.unknownNodeCount,()=>"If you want clearer diagrams, consider extracting helpers to reduce unresolved nodes.",r),highestLogRatio:cn(e,s=>s.quality.metrics.logRatio,()=>"For larger programs, consider grouping logs or using summary mode.",r)}}import{readFile as Ul}from"fs/promises";import{resolve as Hl}from"path";function Gl(e){return e?/effect/i.test(e):!1}function Vl(e){let t=`${e.ruleId??""} ${e.message??""}`.toLowerCase();if(t.includes("yield")||t.includes("untagged"))return"Consider binding yielded values with meaningful names.";if(t.includes("error")||t.includes("catch")||t.includes("handle"))return"If you want clearer diagrams, consider making error boundaries explicit.";if(t.includes("service")||t.includes("layer")||t.includes("provide"))return"Consider acquiring services near the top of the workflow.";if(t.includes("pipe")||t.includes("nested")||t.includes("lambda"))return"If you want clearer diagrams, consider extracting nested pipe lambdas into named helpers."}function Jl(e){let t=e.ruleId??"eslint",r=(e.message??"").trim();if(r)return`ESLint (${t}): ${r}`}function Ql(e){if(Array.isArray(e))return e;if(e&&typeof e=="object"&&"results"in e){let t=e.results;if(Array.isArray(t))return t}return[]}async function zi(e){let t=await Ul(e,"utf-8"),r=JSON.parse(t),s=Ql(r),n=new Map;for(let c of s){let o=c.filePath?Hl(c.filePath):void 0;if(!o)continue;let a=c.messages??[];for(let d of a){if(!Gl(d.ruleId))continue;let l=n.get(o)??{reasons:[],tips:[]},f=Jl(d);f&&l.reasons.push(f);let u=Vl(d);u&&l.tips.push(u),n.set(o,l)}}let i=new Map;for(let[c,o]of n)i.set(c,{reasons:[...new Set(o.reasons)].slice(0,8),tips:[...new Set(o.tips)].slice(0,5)});return i}function Hi(e){let t=r=>s=>e?`\x1B[${r}m${s}\x1B[0m`:s;return{dim:t(2),green:t(32),cyan:t(36),yellow:t(33),red:t(31),bold:t(1)}}function rd(e){let t,r="auto",s,n=!0,i=!0,c="TB",o,a=!1,d=!1,l="effect-analysis",f=!0,u=!1,g=!1,p=!1,m=!1,y=!1,h=!1,N=!1,x=!1,F=!1,E=!1,b=!1,C=!1,k,S=[],W,A=!1,z=!0,$=!1,q,B=!1,H=!1,Z=!0,ae,ke=!1,Re=!1,Ke=!1,L=[];for(let ne=0;ne<e.length;ne++){let I=e[ne];if(I!==void 0){if((I==="--help"||I==="-h")&&(sd(),process.exit(0)),!I.startsWith("-")){L.push(I),t??=I;continue}if(I==="--format"||I==="-f"){let K=e[++ne];(K==="auto"||K==="json"||K==="mermaid"||K==="mermaid-paths"||K==="mermaid-enhanced"||K==="mermaid-railway"||K==="mermaid-services"||K==="mermaid-errors"||K==="mermaid-decisions"||K==="mermaid-causes"||K==="mermaid-concurrency"||K==="mermaid-timeline"||K==="mermaid-layers"||K==="mermaid-retry"||K==="mermaid-testability"||K==="mermaid-dataflow"||K==="stats"||K==="migration"||K==="showcase"||K==="explain"||K==="summary"||K==="matrix"||K==="api-docs"||K==="openapi-paths"||K==="openapi-runtime")&&(r=K)}else if(I==="--export")ae=e[++ne];else if(I==="--output"||I==="-o")s=e[++ne];else if(I==="--compact"||I==="-c")n=!1;else if(I==="--pretty")n=!0;else if(I==="--no-metadata")i=!1;else if(I==="--direction"||I==="-d"){let K=e[++ne];(K==="TB"||K==="LR"||K==="BT"||K==="RL")&&(c=K)}else if(I==="--tsconfig")o=e[++ne];else if(I.startsWith("--tsconfig="))o=I.slice(11);else if(I==="--colocate")a=!0;else if(I==="--no-colocate")d=!0;else if(I==="--no-colocate-enhanced")f=!1;else if(I==="--colocate-suffix"){let K=e[++ne];K&&(l=K)}else if(I.startsWith("--colocate-suffix="))l=I.slice(18);else if(I==="--watch"||I==="-w")u=!0;else if(I==="--migration"||I==="-m")g=!0;else if(I==="--cache")p=!0;else if(I==="--coverage-audit")m=!0;else if(I==="--show-suspicious-zeros")y=!0;else if(I==="--show-top-unknown")h=!0;else if(I==="--no-show-top-unknown")h=!1,N=!0;else if(I==="--show-top-unknown-reasons")x=!0;else if(I==="--no-show-top-unknown-reasons")x=!1,F=!0;else if(I==="--show-by-folder")E=!0;else if(I==="--per-file-timing")C=!0;else if(I==="--min-meaningful-nodes"){let K=e[++ne];if(K!==void 0){let ve=Number.parseInt(K,10);Number.isFinite(ve)&&ve>=0&&(k=ve)}}else if(I==="--exclude-from-suspicious-zero"){let K=e[++ne];K!==void 0&&S.push(K)}else I==="--known-effect-internals-root"?W=e[++ne]:I==="--json-summary"?b=!0:I==="--quiet"||I==="-q"?A=!0:I==="--no-color"?z=!1:I==="--quality"?$=!0:I==="--quality-eslint"?q=e[++ne]:I.startsWith("--quality-eslint=")?q=I.slice(17):I==="--style-guide"?B=!0:I==="--no-style-guide"?(B=!1,H=!0):I==="--service-map"?Z=!0:I==="--no-service-map"?Z=!1:I==="--diff"?ke=!0:I==="--regression"?Re=!0:I==="--include-trivial"&&(Ke=!0)}}let G=ke?L:[];return g&&(r="migration"),r==="mermaid-paths"&&!H&&!B&&(B=!0),m&&(N||(h=!0),F||(x=!0)),{pathArg:t,options:{format:r,output:s,pretty:n,includeMetadata:i,direction:c,tsconfig:o,colocate:a,noColocate:d,colocateSuffix:l,colocateEnhanced:f,watch:u,migration:g,cache:p,coverageAudit:m,showSuspiciousZeros:y,showTopUnknown:h,showTopUnknownReasons:x,showOkZeroFailByFolder:E,jsonSummary:b,perFileTiming:C,minMeaningfulNodes:k,excludeFromSuspiciousZeros:S,knownEffectInternalsRoot:W,quiet:A,color:z,quality:$,qualityEslint:q,styleGuide:B,serviceMap:Z,openapiExport:ae,diff:ke,diffSources:G,regression:Re,includeTrivial:Ke}}}var sd=()=>{process.stdout.write(`
|
|
60
60
|
effect-analyzer - Static analysis for Effect-TS
|
|
61
61
|
|
|
62
62
|
Usage: effect-analyze [PATH] [options]
|
|
@@ -120,8 +120,8 @@ Examples:
|
|
|
120
120
|
effect-analyze ./src --format openapi-paths -o paths.json # Emit OpenAPI paths JSON
|
|
121
121
|
effect-analyze ./src/api.ts --format openapi-runtime --export TodoApi -o openapi.json # Runtime OpenApi.fromApi
|
|
122
122
|
|
|
123
|
-
`)},
|
|
124
|
-
${
|
|
123
|
+
`)},Gi=(e,t)=>v.gen(function*(){if(!e.quality||!e.qualityEslint)return new Map;let r=Ve(e.qualityEslint);return yield*v.tryPromise(()=>zi(r)).pipe(v.catchAll(n=>v.gen(function*(){return yield*D.error(t.yellow(`Warning: could not load --quality-eslint file (${String(n)}). Continuing without ESLint hints.`)),new Map})))}),Vi=(e,t,r)=>{let s=new Map;for(let n of e){let i=t.get(Ve(n.metadata.filePath)),c=Tr(n,{styleGuideSummary:r,hints:i});s.set(n.root.id,c)}return s},id=e=>v.gen(function*(){let t=e.diffSources;if(t.length===0){yield*D.error("--diff requires at least one source argument");return}let r=u=>{if(u.kind==="git-ref"&&u.ref&&u.filePath){let{ref:g,filePath:p}=u;return v.gen(function*(){let m=yield*v.try(()=>gt(g,p));return yield*tt(m,p)})}if(u.kind==="github-pr"&&u.prUrl){let{prUrl:g}=u;return v.gen(function*(){return yield*D.error("GitHub PR diff requires two resolved refs. Use: --diff <base-ref>:<path> <head-ref>:<path>"),yield*D.error(`To resolve PR refs: gh pr view "${g}" --json baseRefName,headRefName`),[]})}return u.filePath?Tt(u.filePath):v.gen(function*(){return yield*D.error(`Cannot resolve source: ${JSON.stringify(u)}`),[]})},s,n,i=t[0];if(!i){yield*D.error("No sources specified for diff");return}let c=vt(i);if(c.kind==="github-pr"&&c.prUrl){let u=c.prUrl,g=yield*v.try(()=>dr(u));if(t.length<2){yield*D.error("GitHub PR diff requires a file path: --diff <pr-url> <file-path>");return}let p=t[1]??"",m=yield*v.try(()=>gt(g.baseRef,p)),y=yield*v.try(()=>gt(g.headRef,p));s=yield*tt(m,p),n=yield*tt(y,p)}else if(t.length===1){let u=i,g=yield*v.try(()=>gt("HEAD",u));s=yield*tt(g,u),n=yield*Tt(u)}else s=yield*r(vt(i)),n=yield*r(vt(t[1]??""));let o=[],a=new Set;for(let u of n){let g=s.find(p=>p.root.programName===u.root.programName);if(g){a.add(g.root.programName);let p=or(g,u,{regressionMode:e.regression});e.format==="json"?o.push(cr(p,{pretty:e.pretty})):e.format==="mermaid"||e.format==="mermaid-enhanced"?o.push(`%% diff: ${u.root.programName}
|
|
124
|
+
${lr(u,p,{direction:e.direction})}`):o.push(ar(p))}else{let p=u.root.children.map(m=>(m.type==="effect"?m.callee:m.displayName??m.name??m.type)??m.type);e.format==="json"?o.push(JSON.stringify({added:u.root.programName,steps:p})):o.push(`## Added program: \`${u.root.programName}\`
|
|
125
125
|
|
|
126
126
|
Steps: ${p.map(m=>`\`${m}\``).join(", ")}`)}}for(let u of s)if(!a.has(u.root.programName)){let g=u.root.children.map(p=>(p.type==="effect"?p.callee:p.displayName??p.name??p.type)??p.type);if(e.format==="json")o.push(JSON.stringify({removed:u.root.programName,steps:g}));else{let p=e.regression?"\u26A0\uFE0F ":"";o.push(`## ${p}Removed program: \`${u.root.programName}\`
|
|
127
127
|
|
|
@@ -132,67 +132,67 @@ Steps: ${g.map(m=>`\`${m}\``).join(", ")}`)}}let d=e.format==="mermaid"||e.forma
|
|
|
132
132
|
|
|
133
133
|
---
|
|
134
134
|
|
|
135
|
-
`,f=e.format==="json"?`[${o.join(l)}]`:o.join(l);if(e.output){let u=e.output;yield*
|
|
136
|
-
${
|
|
135
|
+
`,f=e.format==="json"?`[${o.join(l)}]`:o.join(l);if(e.output){let u=e.output;yield*v.tryPromise(()=>ge.writeFile(u,f,"utf-8")),yield*D.log(`Diff output written to ${u}`)}else yield*D.log(f)}),Ui=(e,t)=>v.gen(function*(){let r=Hi(t.color&&process.stdout.isTTY),s=p=>{let m=0,y=h=>{for(let N of h){N.type!=="unknown"&&m++;let x=un.getOrElse(P(N),()=>[]);x.length>0&&y(x)}};return y(p),m},n=t.tsconfig!==void 0?{tsConfigPath:t.tsconfig}:void 0,i;if(t.cache&&!e.includes("*")){let p=yield*v.tryPromise(()=>ge.readFile(e,"utf-8")).pipe(v.catchAll(()=>v.succeed(null)));if(p!==null){let m=yield*v.tryPromise(()=>hi(e,p)).pipe(v.catchAll(()=>v.succeed(null)));m!==null&&m.length>0?(i=m,yield*D.log(`(cache hit) Found ${String(i.length)} program(s)`)):(i=yield*_e(e,n).all().pipe(v.tapError(y=>D.error(`Error: ${y.message}`))),yield*v.tryPromise(()=>Si(e,p,i)).pipe(v.ignore),yield*D.log(`Found ${String(i.length)} program(s)`))}else i=yield*_e(e,n).all().pipe(v.tapError(m=>D.error(`Error: ${m.message}`))),yield*D.log(`Found ${String(i.length)} program(s)`)}else i=yield*_e(e,n).all().pipe(v.tapError(p=>D.error(`Error: ${p.message}`))),yield*D.log(`Found ${String(i.length)} program(s)`);let o=t.minMeaningfulNodes,a=o!==void 0?i.filter(p=>s(p.root.children)>=o):i;if(o!==void 0&&a.length!==i.length&&(yield*D.log(`Filtered ${String(i.length-a.length)} low-signal program(s) with --min-meaningful-nodes=${String(o)}`)),!t.includeTrivial){let p=a.length;a=a.filter(y=>{let{source:h,children:N}=y.root;if(h==="class"||h==="classProperty"||h==="classMethod")return!1;if(h==="direct"&&N.length===1&&N[0]?.type==="effect"){let x=N[0].callee??"";if(x.startsWith("Schema.")||x.startsWith("Data.")||x==="Service")return!1}return!(h==="direct"&&N.length<=1)});let m=p-a.length;m>0&&!t.quiet&&(yield*D.log(`Filtered ${String(m)} trivial program(s) (use --include-trivial to see all)`))}let d=yield*Gi(t,r),l=t.quality?Vi(a,d,t.styleGuide):new Map;if(t.colocate){let p=yield*xr(e,a,t.colocateSuffix,t.direction,t.colocateEnhanced,t.quality?l:void 0,t.styleGuide);yield*D.log(`Written: ${p}`);return}let f="",u={mermaid:p=>nt(p,{direction:t.direction}),"mermaid-railway":p=>qn(p,{direction:t.direction==="TB"?"LR":t.direction}),"mermaid-services":p=>Yt(p,{direction:t.direction==="TB"?"LR":t.direction}),"mermaid-errors":p=>Un(p,{direction:t.direction==="TB"?"LR":t.direction}),"mermaid-decisions":p=>Vn(p,{direction:t.direction}),"mermaid-causes":p=>Qn(p,{direction:t.direction}),"mermaid-concurrency":p=>Zn(p,{direction:t.direction}),"mermaid-timeline":p=>Xn(p),"mermaid-layers":p=>er(p,{direction:t.direction}),"mermaid-retry":p=>nr(p,{direction:t.direction==="TB"?"LR":t.direction}),"mermaid-testability":p=>rr(p,{direction:t.direction==="TB"?"LR":t.direction}),"mermaid-dataflow":p=>sr(p,{direction:t.direction==="TB"?"LR":t.direction})};switch(t.format){case"auto":{let p=[],m=new Set;for(let y of a){let h=ei(y);for(let N of h){let x=u[N];if(x){let F=x(y);if(F.includes("((No steps))")||F.includes("((No errors))")||F.includes("((No ")||m.has(F))continue;m.add(F);let E=a.length>1?` [${y.root.programName}]`:"";p.push(`%% ${N}${E}
|
|
136
|
+
${F}`)}}}f=p.join(`
|
|
137
137
|
|
|
138
|
-
`);break}case"json":{if(t.quality){let p=a.map(m=>{let
|
|
138
|
+
`);break}case"json":{if(t.quality){let p=a.map(m=>{let y=t.includeMetadata?{root:m.root,metadata:m.metadata,references:m.references instanceof Map?Object.fromEntries(m.references):m.references}:{root:m.root},h=l.get(m.root.id);return{...y,diagramQuality:h}});f=JSON.stringify(p.length===1?p[0]:p,null,t.pretty?2:void 0)}else{let p=a[0];a.length===1&&p?f=yield*ai(p,{pretty:t.pretty,includeMetadata:t.includeMetadata}):f=yield*ci(a,{pretty:t.pretty,includeMetadata:t.includeMetadata})}break}case"mermaid":{let p=[];for(let m of a){let y=yield*Gt(m,{direction:t.direction});p.push(y)}f=p.join(`
|
|
139
139
|
|
|
140
|
-
`);break}case"mermaid-paths":{let p=[];for(let m of a){let
|
|
140
|
+
`);break}case"mermaid-paths":{let p=[];for(let m of a){let y=mt(m);p.push(Vt(y,{direction:t.direction,styleGuide:t.styleGuide}))}f=p.join(`
|
|
141
141
|
|
|
142
|
-
`);break}case"mermaid-enhanced":{let p=[];for(let m of a)p.push(
|
|
142
|
+
`);break}case"mermaid-enhanced":{let p=[];for(let m of a)p.push(Jt(m,{direction:t.direction}));f=p.join(`
|
|
143
143
|
|
|
144
|
-
`);break}case"mermaid-railway":{let p=t.direction==="TB"?"LR":t.direction;f=a.map(
|
|
144
|
+
`);break}case"mermaid-railway":{let p=t.direction==="TB"?"LR":t.direction;f=a.map(y=>qn(y,{direction:p})).join(`
|
|
145
145
|
|
|
146
|
-
`);break}case"mermaid-services":{let p=t.direction==="TB"?"LR":t.direction;f=a.map(
|
|
146
|
+
`);break}case"mermaid-services":{let p=t.direction==="TB"?"LR":t.direction;f=a.map(y=>Yt(y,{direction:p})).join(`
|
|
147
147
|
|
|
148
|
-
`);break}case"mermaid-errors":{let p=t.direction==="TB"?"LR":t.direction;f=a.map(
|
|
148
|
+
`);break}case"mermaid-errors":{let p=t.direction==="TB"?"LR":t.direction;f=a.map(y=>Un(y,{direction:p})).join(`
|
|
149
149
|
|
|
150
|
-
`);break}case"mermaid-decisions":{f=a.map(m=>
|
|
150
|
+
`);break}case"mermaid-decisions":{f=a.map(m=>Vn(m,{direction:t.direction})).join(`
|
|
151
151
|
|
|
152
|
-
`);break}case"mermaid-causes":{f=a.map(m=>
|
|
152
|
+
`);break}case"mermaid-causes":{f=a.map(m=>Qn(m,{direction:t.direction})).join(`
|
|
153
153
|
|
|
154
|
-
`);break}case"mermaid-concurrency":{f=a.map(m=>
|
|
154
|
+
`);break}case"mermaid-concurrency":{f=a.map(m=>Zn(m,{direction:t.direction})).join(`
|
|
155
155
|
|
|
156
|
-
`);break}case"mermaid-timeline":{f=a.map(m=>
|
|
156
|
+
`);break}case"mermaid-timeline":{f=a.map(m=>Xn(m)).join(`
|
|
157
157
|
|
|
158
|
-
`);break}case"mermaid-layers":{f=a.map(m=>
|
|
158
|
+
`);break}case"mermaid-layers":{f=a.map(m=>er(m,{direction:t.direction})).join(`
|
|
159
159
|
|
|
160
|
-
`);break}case"mermaid-retry":{let p=t.direction==="TB"?"LR":t.direction;f=a.map(
|
|
160
|
+
`);break}case"mermaid-retry":{let p=t.direction==="TB"?"LR":t.direction;f=a.map(y=>nr(y,{direction:p})).join(`
|
|
161
161
|
|
|
162
|
-
`);break}case"mermaid-testability":{let p=t.direction==="TB"?"LR":t.direction;f=a.map(
|
|
162
|
+
`);break}case"mermaid-testability":{let p=t.direction==="TB"?"LR":t.direction;f=a.map(y=>rr(y,{direction:p})).join(`
|
|
163
163
|
|
|
164
|
-
`);break}case"mermaid-dataflow":{let p=t.direction==="TB"?"LR":t.direction;f=a.map(
|
|
164
|
+
`);break}case"mermaid-dataflow":{let p=t.direction==="TB"?"LR":t.direction;f=a.map(y=>sr(y,{direction:p})).join(`
|
|
165
165
|
|
|
166
|
-
`);break}case"stats":{let p=a.map(m=>({program:m.root.programName,stats:m.metadata.stats,...t.quality?{diagramQuality:l.get(m.root.id)}:{}}));f=JSON.stringify(p,null,t.pretty?2:void 0);break}case"showcase":{let p=yield*
|
|
167
|
-
`)),yield*D.log(`Zero categories: barrel/index=${r.zeroProgramCategoryCounts.barrel_or_index}, config/build=${r.zeroProgramCategoryCounts.config_or_build}, test/dtslint=${r.zeroProgramCategoryCounts.test_or_dtslint}, type-only=${r.zeroProgramCategoryCounts.type_only}, suspicious=${r.zeroProgramCategoryCounts.suspicious}, other=${r.zeroProgramCategoryCounts.other}`),t.showOkZeroFailByFolder&&r.outcomes.length>0){let o=new Map;for(let a of r.outcomes){let l=(e?a.file.replace(e,"").replace(/^[/\\]+/,""):a.file).split(
|
|
166
|
+
`);break}case"stats":{let p=a.map(m=>({program:m.root.programName,stats:m.metadata.stats,...t.quality?{diagramQuality:l.get(m.root.id)}:{}}));f=JSON.stringify(p,null,t.pretty?2:void 0);break}case"showcase":{let p=yield*v.tryPromise(()=>ge.readFile(e,"utf-8")).pipe(v.catchAll(()=>v.succeed(""))),m=di(a,{direction:t.direction},p),y=m.length===1?m[0]:m;f=JSON.stringify(y,null,t.pretty?2:void 0);break}case"explain":{f=hr(a);break}case"summary":{f=Er(a);break}case"matrix":{f=br(a);break}}let g=t.output;g?(yield*v.tryPromise(()=>ge.writeFile(g,f,"utf-8")),yield*D.log(`Output written to ${g}`)):yield*D.log(f)}),od=(e,t)=>v.gen(function*(){let r=yield*Fi(e,{tsconfig:t.tsconfig,includePerFileTiming:t.perFileTiming,excludeFromSuspiciousZeros:t.excludeFromSuspiciousZeros,knownEffectInternalsRoot:t.knownEffectInternalsRoot});if(t.jsonSummary){yield*D.log(JSON.stringify({...r,timestamp:new Date().toISOString(),dirPath:e},null,t.pretty?2:void 0));return}yield*D.log(`Coverage audit for ${e}...`);let s=[`Discovered: ${r.discovered}`,`Analyzed: ${r.analyzed}`,`Zero programs: ${r.zeroPrograms}`,`Suspicious zeros: ${r.suspiciousZeros.length}`,`Failed: ${r.failed}`,`Coverage: ${r.percentage.toFixed(1)}%`,`Analyzable coverage: ${r.analyzableCoverage.toFixed(1)}%`,`Unknown node rate: ${(r.unknownNodeRate*100).toFixed(2)}%`,...r.durationMs!==void 0?[`Duration: ${r.durationMs}ms`]:[]];if(yield*D.log(s.join(`
|
|
167
|
+
`)),yield*D.log(`Zero categories: barrel/index=${r.zeroProgramCategoryCounts.barrel_or_index}, config/build=${r.zeroProgramCategoryCounts.config_or_build}, test/dtslint=${r.zeroProgramCategoryCounts.test_or_dtslint}, type-only=${r.zeroProgramCategoryCounts.type_only}, suspicious=${r.zeroProgramCategoryCounts.suspicious}, other=${r.zeroProgramCategoryCounts.other}`),t.showOkZeroFailByFolder&&r.outcomes.length>0){let o=new Map;for(let a of r.outcomes){let l=(e?a.file.replace(e,"").replace(/^[/\\]+/,""):a.file).split(Zl)[0]??"(root)",f=o.get(l)??{ok:0,zero:0,fail:0};a.status==="ok"?f.ok++:a.status==="zero"?f.zero++:f.fail++,o.set(l,f)}yield*D.log(`
|
|
168
168
|
By top-level folder:`);for(let[a,d]of[...o.entries()].sort((l,f)=>l[0].localeCompare(f[0])))yield*D.log(` ${a}: ok=${d.ok} zero=${d.zero} fail=${d.fail}`)}if(yield*D.log("(Detection is heuristic; re-exports and some aliases may be under-detected.)"),t.showSuspiciousZeros&&r.suspiciousZeros.length>0){yield*D.log(`
|
|
169
169
|
Suspicious zeros (Effect import but 0 programs):`);for(let o of r.suspiciousZeros)yield*D.log(` ${o}`)}else if(r.suspiciousZeros.length>0){let o=r.suspiciousZeros.slice(0,10);yield*D.log(`
|
|
170
170
|
Suspicious zeros (sample):`);for(let a of o)yield*D.log(` ${a}`);r.suspiciousZeros.length>o.length&&(yield*D.log(` ... and ${r.suspiciousZeros.length-o.length} more (use --show-suspicious-zeros for full list)`))}if(t.showTopUnknown&&r.topUnknownFiles&&r.topUnknownFiles.length>0){yield*D.log(`
|
|
171
171
|
Top files by unknown node rate:`);for(let o of r.topUnknownFiles)yield*D.log(` ${o}`)}if(t.showTopUnknownReasons&&r.topUnknownReasons&&r.topUnknownReasons.length>0){yield*D.log(`
|
|
172
172
|
Top unknown node reasons (by count):`);for(let{reason:o,count:a}of r.topUnknownReasons)yield*D.log(` ${a} ${o}`)}let n=r.outcomes.filter(o=>o.status==="fail"||o.status==="zero");if(n.length>0){yield*D.log(`
|
|
173
|
-
Failed or zero programs:`);for(let o of n){let a=o.status==="fail"?` error: ${o.error??""}`:" (0 programs)";yield*D.log(` ${o.file}${a}`)}}let i={...r,timestamp:new Date().toISOString(),dirPath:e},c=t.output;if(c){let o=JSON.stringify(i,null,t.pretty?2:void 0);yield*
|
|
174
|
-
Audit written to ${c}`)}}),
|
|
173
|
+
Failed or zero programs:`);for(let o of n){let a=o.status==="fail"?` error: ${o.error??""}`:" (0 programs)";yield*D.log(` ${o.file}${a}`)}}let i={...r,timestamp:new Date().toISOString(),dirPath:e},c=t.output;if(c){let o=JSON.stringify(i,null,t.pretty?2:void 0);yield*v.tryPromise(()=>ge.writeFile(c,o,"utf-8")),yield*D.log(`
|
|
174
|
+
Audit written to ${c}`)}}),ad=(e,t)=>v.gen(function*(){let r=t.color&&process.stdout.isTTY,s=Hi(r);t.quiet||(yield*D.log(s.bold(`Analyzing ${e}...`)));let n=yield*$i(e,{tsconfig:t.tsconfig,knownEffectInternalsRoot:t.knownEffectInternalsRoot,buildServiceMap:t.serviceMap}),i=n.byFile,c=yield*Gi(t,s),o=t.quality?[...i.entries()].map(([p,m])=>qi(p,m,{styleGuideSummary:t.styleGuide,hints:c.get(Ve(p))})):[],a=new Map;if(t.quality)for(let[p,m]of i){let y=c.get(Ve(p)),h=Vi(m,new Map(y?[[Ve(p),y]]:[]),t.styleGuide);a.set(p,h)}let d=i.size;if(d===0){yield*D.log(s.yellow("No Effect programs found in discovered TypeScript files."));return}let l=!t.noColocate,f=0;if(l)for(let[p,m]of i){let y=yield*xr(p,m,t.colocateSuffix,t.direction,t.colocateEnhanced,a.get(p),t.styleGuide);f++,t.quiet||(yield*D.log(s.green(" Written: ")+s.cyan(y)))}if(t.serviceMap&&n.serviceMap){let p=n.serviceMap,m=p.services.size;if(m>0){if(l){let y=yield*Ri(p).pipe(v.catchAll(()=>v.succeed([])));for(let F of y)t.quiet||(yield*D.log(s.green(" Service: ")+s.cyan(F)));let h=Rs(p,{direction:t.direction}),N=$t(e,"service-graph.md"),x=`# Service Dependency Graph
|
|
175
175
|
|
|
176
176
|
\`\`\`mermaid
|
|
177
|
-
${
|
|
177
|
+
${h}
|
|
178
178
|
\`\`\`
|
|
179
|
-
`;yield*
|
|
180
|
-
`+p)}else if(t.format==="mermaid-services"){let p=t.direction==="TB"?"LR":t.direction,m=t.serviceMap&&n.serviceMap?
|
|
179
|
+
`;yield*v.tryPromise(()=>ge.writeFile(N,x,"utf-8")).pipe(v.catchAll(()=>v.succeed(void 0))),t.quiet||(yield*D.log(s.green(" Service graph: ")+s.cyan(N)))}yield*D.log(s.green(`Found ${String(m)} service(s)${p.unresolvedServices.length>0?`, ${String(p.unresolvedServices.length)} unresolved`:""}.`))}}if(l){let p=yield*v.tryPromise(()=>{let m=t.tsconfig?new dn({tsConfigFilePath:t.tsconfig}):new dn({skipAddingFilesFromTsConfig:!0}),y=[];for(let h of i.keys())try{let N=m.addSourceFileAtPath(h);y.push(...wr(N,h))}catch{}return Promise.resolve(y)}).pipe(v.catchAll(()=>v.succeed([])));if(p.length>0){let m=$t(e,"api-docs.md"),y=Nr(p);yield*v.tryPromise(()=>ge.writeFile(m,y,"utf-8")).pipe(v.catchAll(()=>v.succeed(void 0))),t.quiet||(yield*D.log(s.green(" API docs: ")+s.cyan(m)))}}if(t.format==="matrix"){let p=t.serviceMap&&n.serviceMap?Di(n.serviceMap):br(n.allPrograms);yield*D.log(`
|
|
180
|
+
`+p)}else if(t.format==="mermaid-services"){let p=t.direction==="TB"?"LR":t.direction,m=t.serviceMap&&n.serviceMap?Ws(n.serviceMap,{direction:p}):n.allPrograms.map(y=>Yt(y,{direction:p})).join(`
|
|
181
181
|
|
|
182
182
|
---
|
|
183
183
|
|
|
184
184
|
`);yield*D.log(`
|
|
185
185
|
`+m)}else t.format==="explain"?yield*D.log(`
|
|
186
|
-
`+
|
|
187
|
-
`+
|
|
188
|
-
${s.bold(
|
|
189
|
-
`)})}else{let s=yield*
|
|
190
|
-
`)})}}).pipe(
|
|
186
|
+
`+hr(n.allPrograms)):t.format==="summary"&&(yield*D.log(`
|
|
187
|
+
`+Er(n.allPrograms)));let u=n.allPrograms.length,g=l?s.green(`Analyzed ${String(d)} file(s) with Effect programs, wrote ${String(f)} colocated .${t.colocateSuffix}.md file(s) (${String(u)} program(s) total).`):s.dim(`Analyzed ${String(d)} file(s), ${String(u)} program(s). Use without --no-colocate to write .${t.colocateSuffix}.md files.`);if(yield*D.log(g),t.quality&&o.length>0){let p=_i(o,10),m=h=>Number.isInteger(h)?String(h):h.toFixed(2),y=(h,N)=>v.gen(function*(){yield*D.log(`
|
|
188
|
+
${s.bold(h)}`);for(let x of N)yield*D.log(` ${x.filePath} (${m(x.metricValue)})`),yield*D.log(` ${s.dim(x.tip)}`)});yield*y("Top offenders: largest programs",p.largestPrograms),yield*y("Top offenders: most anonymous nodes",p.mostAnonymousNodes),yield*y("Top offenders: most unknown nodes",p.mostUnknownNodes),yield*y("Top offenders: highest log ratio",p.highestLogRatio)}}),cd=(e,t)=>v.async(r=>{let s=kr(nd(import.meta.url)),n=$t(s,"..","scripts","openapi-runtime-runner.mjs"),i=Ve(process.cwd(),e),c=kr(i),a=(f=>{let u=f;for(let g=0;g<20;g++){if(ed($t(u,"package.json")))return u;let p=kr(u);if(p===u)break;u=p}return c})(c),d=[i,t.openapiExport??"default",...t.output?["--output",Ve(process.cwd(),t.output)]:[]],l=td("npx",["tsx",n,...d],{stdio:t.output?["inherit","pipe","inherit"]:"inherit",shell:!1,cwd:a});t.output&&l.stdout?.on("data",f=>process.stdout.write(f)),l.on("close",f=>{r(f===0?v.succeed(void 0):v.fail(new Error(`OpenAPI runtime exited with code ${f}`)))}),l.on("error",f=>{r(v.fail(f))})}),ld=(e,t)=>v.gen(function*(){let r=t.tsconfig?new dn({tsConfigFilePath:t.tsconfig}):new dn({skipAddingFilesFromTsConfig:!0}),s,n=yield*v.tryPromise(()=>ge.stat(e)).pipe(v.option);if(un.isSome(n)&&n.value.isDirectory()){let a=[".ts",".tsx"],d=async(l,f)=>{if(f>10)return[];let u=[],g=await ge.readdir(l,{withFileTypes:!0});for(let p of g){let m=$t(l,p.name);p.isDirectory()&&p.name!=="node_modules"&&p.name!==".git"?u.push(...await d(m,f+1)):p.isFile()&&a.includes(Yl(p.name))&&u.push(m)}return u};s=yield*v.tryPromise(()=>d(e,0))}else s=[e];let i=[];for(let a of s)try{let d=r.addSourceFileAtPath(a),l=wr(d,a);i.push(...l)}catch{}let c=t.format==="openapi-paths"?JSON.stringify(Mi(i),null,t.pretty?2:void 0):Nr(i),o=t.output;o?(yield*v.tryPromise(()=>ge.writeFile(o,c,"utf-8")),yield*D.log(`Output written to ${o}`)):yield*D.log(c)}),dd=e=>v.gen(function*(){let t=yield*v.tryPromise(()=>ge.stat(e)).pipe(v.option);if(un.isSome(t)&&t.value.isDirectory()){let s=yield*v.tryPromise(()=>ui(e)).pipe(v.catchAll(n=>v.fail(new Error(n instanceof Error?n.message:String(n)))));yield*v.sync(()=>{process.stdout.write(pr(s)+`
|
|
189
|
+
`)})}else{let s=yield*v.try({try:()=>fr(e),catch:n=>new Error(n instanceof Error?n.message:String(n))});yield*v.sync(()=>{process.stdout.write(pr({opportunities:s,fileCount:1})+`
|
|
190
|
+
`)})}}).pipe(v.catchAll(t=>v.sync(()=>{console.error("Migration failed:",t instanceof Error?t.message:t)}))),ud=v.gen(function*(){let e=process.argv.slice(2),{pathArg:t,options:r}=rd(e);if(r.diff)return yield*id(r),Te.succeed(void 0);let s=Ve(t??"."),n=yield*v.tryPromise(()=>ge.stat(s)).pipe(v.option);if(un.isNone(n))return yield*D.error(`Error: Path not found: ${s}`),yield*v.fail(Te.fail("Path not found"));let i=n.value.isDirectory();if(r.coverageAudit)return i?(yield*od(s,r),Te.succeed(void 0)):(yield*D.error("Error: --coverage-audit requires a directory path"),yield*v.fail(Te.fail("Coverage audit requires directory")));if(r.format==="migration")return yield*D.log(`Migration report for ${s}...`),yield*dd(s),Te.succeed(void 0);if(r.format==="api-docs"||r.format==="openapi-paths")return yield*ld(s,r),Te.succeed(void 0);if(r.format==="openapi-runtime")return i?(yield*D.error("openapi-runtime requires a file path (entrypoint), not a directory."),Te.fail(new Error("openapi-runtime needs entrypoint file"))):(yield*cd(s,r),Te.succeed(void 0));if(i)return yield*ad(s,r),Te.succeed(void 0);if(r.quiet||(yield*D.log(`Analyzing ${s}...`)),yield*Ui(s,r),r.watch){let c={...r,quiet:!0};yield*D.log(`\x1B[2m\u{1F441} Watching ${s} for changes... (Ctrl+C to stop)\x1B[0m`),yield*v.sync(()=>{let o,a=0,d=Xl(s,{persistent:!0},(l,f)=>{o&&clearTimeout(o),o=setTimeout(()=>{a++,process.stdout.write("\x1Bc");let u=new Date().toLocaleTimeString();process.stdout.write(`\x1B[2m\u{1F441} ${s} \u2014 ${u} (#${a})\x1B[0m
|
|
191
191
|
|
|
192
|
-
`),
|
|
192
|
+
`),v.runPromise(Ui(s,c).pipe(v.tap(()=>v.sync(()=>{process.stdout.write(`
|
|
193
193
|
\x1B[2m\u2713 Updated. Waiting for changes...\x1B[0m
|
|
194
|
-
`)})),
|
|
194
|
+
`)})),v.catchAll(g=>v.sync(()=>{process.stdout.write(`
|
|
195
195
|
\x1B[31m\u2717 Error: ${g instanceof Error?g.message:String(g)}\x1B[0m
|
|
196
196
|
`),process.stdout.write(`\x1B[2mWaiting for changes...\x1B[0m
|
|
197
197
|
`)})))).catch(()=>{})},300)});process.on("SIGINT",()=>{d.close(),process.stdout.write(`
|
|
198
|
-
`),process.exit(0)})}),yield*
|
|
198
|
+
`),process.exit(0)})}),yield*v.never}return Te.succeed(void 0)}).pipe(v.catchAll(e=>v.gen(function*(){return yield*D.error(`Fatal error: ${String(e)}`),Te.fail(e)})));v.runPromise(ud).then(()=>{process.exit(0)},e=>{let t=e instanceof Error?e.message:String(e);t&&console.error(`Error: ${t}`),process.exit(1)});
|