@callbag-recharge/callbag-recharge 0.9.0 → 0.11.0
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/adapters/http.cjs +4 -4
- package/dist/adapters/http.d.cts +12 -29
- package/dist/adapters/http.d.ts +12 -29
- package/dist/adapters/http.js +1 -1
- package/dist/adapters/index.cjs +12 -12
- package/dist/adapters/index.d.cts +5 -4
- package/dist/adapters/index.d.ts +5 -4
- package/dist/adapters/index.js +1 -1
- package/dist/adapters/llm.cjs +5 -5
- package/dist/adapters/llm.d.cts +7 -7
- package/dist/adapters/llm.d.ts +7 -7
- package/dist/adapters/llm.js +1 -1
- package/dist/adapters/mcp.cjs +5 -5
- package/dist/adapters/mcp.d.cts +3 -3
- package/dist/adapters/mcp.d.ts +3 -3
- package/dist/adapters/mcp.js +1 -1
- package/dist/adapters/webhook.cjs +4 -4
- package/dist/adapters/webhook.d.cts +39 -33
- package/dist/adapters/webhook.d.ts +39 -33
- package/dist/adapters/webhook.js +1 -1
- package/dist/adapters/websocket.cjs +4 -4
- package/dist/adapters/websocket.d.cts +13 -33
- package/dist/adapters/websocket.d.ts +13 -33
- package/dist/adapters/websocket.js +1 -1
- package/dist/chunk-6M3P6NXX.js +1 -0
- package/dist/chunk-CXF5XC6M.js +1 -0
- package/dist/chunk-EEKTY7JA.js +1 -0
- package/dist/chunk-OHNEQFSD.js +1 -0
- package/dist/chunk-OXIEM5ZP.js +2 -0
- package/dist/chunk-RX5LWE4X.js +1 -0
- package/dist/chunk-W74KQTWL.js +2 -0
- package/dist/orchestrate/index.cjs +6 -4
- package/dist/orchestrate/index.d.cts +187 -10
- package/dist/orchestrate/index.d.ts +187 -10
- package/dist/orchestrate/index.js +3 -1
- package/dist/utils/index.cjs +4 -4
- package/dist/utils/index.d.cts +2 -42
- package/dist/utils/index.d.ts +2 -42
- package/dist/utils/index.js +1 -1
- package/dist/withStatus-BJI4TOZV.d.ts +44 -0
- package/dist/withStatus-BQCWdfrH.d.cts +44 -0
- package/package.json +1 -1
- package/dist/chunk-437ZAXJ7.js +0 -2
- package/dist/chunk-6DEMLAB5.js +0 -2
- package/dist/chunk-EHKXHATG.js +0 -1
- package/dist/chunk-KNWJHTOJ.js +0 -1
- package/dist/chunk-TATS3PIH.js +0 -1
package/dist/adapters/http.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`)}static _observe(e,i,n){let s=null,r=i??t.getName(e),o={values:[],signals:[],events:[],ended:!1,endError:void 0,dirtyCount:0,resolvedCount:0,name:r,dispose:()=>s?.(
|
|
3
|
-
`)}static toD2(e){let i=e?.direction??"down",n=t.snapshot(),s=[`direction: ${i}`,""],r={state:"rectangle",derived:"hexagon",effect:"oval",producer:"rectangle",operator:"parallelogram","pipeline-step":"rectangle","pipeline-status":"diamond",checkpoint:"cylinder"},o=new Map;function a
|
|
4
|
-
`)}static annotate(e,i){if(!t.enabled)return;t._annotations.set(e,i);let n={node:t._resolveKey(e),reason:i,timestamp:Date.now()},s=t.maxTraceEntries;s<=0||(t._traceLog.length<s?t._traceLog.push(n):(t._traceLog[t._traceHead]=n,t._traceFull=!0),t._traceHead=(t._traceHead+1)%s)}static getAnnotation(e){return t._annotations.get(e)}static traceLog(){return t._traceFull?[...t._traceLog.slice(t._traceHead),...t._traceLog.slice(0,t._traceHead)]:t._traceLog.slice(0,t._traceHead||t._traceLog.length)}static clearTrace(){t._traceLog=[],t._traceHead=0,t._traceFull=!1}static _reset(){t._names=new WeakMap,t._kinds=new WeakMap,t._keys=new WeakMap,t._stores=new Set,t._edges=new Map,t._usedKeys=new Set,t._nextId=0,t._explicitEnabled=null,t._cachedDefault=null,t._annotations=new WeakMap,t._traceLog=[],t._traceHead=0,t._traceFull=!1,t.maxTraceEntries=1e3}};var
|
|
1
|
+
"use strict";var Q=Object.defineProperty;var yt=Object.getOwnPropertyDescriptor;var vt=Object.getOwnPropertyNames;var Et=Object.prototype.hasOwnProperty;var Dt=(t,e)=>{for(var i in e)Q(t,i,{get:e[i],enumerable:!0})},kt=(t,e,i,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of vt(e))!Et.call(t,s)&&s!==i&&Q(t,s,{get:()=>e[s],enumerable:!(n=yt(e,s))||n.enumerable});return t};var xt=t=>kt(Q({},"__esModule",{value:!0}),t);var At={};Dt(At,{fromHTTP:()=>$t});module.exports=xt(At);var k=Symbol("DIRTY"),Y=Symbol("RESOLVED"),st=Symbol("SINGLE_DEP"),it=0,rt=1,ot=2,at=3,ut=4,lt=5,x=7,tt=7<<x,Rt=["DISCONNECTED","DIRTY","SETTLED","RESOLVED","COMPLETED","ERRORED"];function ct(t){return Rt[(t&tt)>>>x]}var _=0,b=1,g=2,y=3,F=0,K=[],X=!1;function P(t){F++;try{return t()}finally{if(F--,F===0&&!X){X=!0;for(let e=0;e<K.length;e++)K[e]();K.length=0,X=!1}}}function V(){return F>0}function q(t){K.push(t)}var H=0,W=[];function ft(){H++}function dt(){if(H--,H===0){for(let t=0;t<W.length;t++)W[t]();W.length=0}}function pt(t){H>0?W.push(t):t()}var O=class t{static _names=new WeakMap;static _kinds=new WeakMap;static _keys=new WeakMap;static _stores=new Set;static _edges=new Map;static _nextId=0;static _usedKeys=new Set;static _explicitEnabled=null;static _cachedDefault=null;static _annotations=new WeakMap;static _traceLog=[];static _traceHead=0;static _traceFull=!1;static maxTraceEntries=1e3;static get enabled(){if(t._explicitEnabled!==null)return t._explicitEnabled;if(t._cachedDefault!==null)return t._cachedDefault;try{t._cachedDefault=globalThis.process?.env?.NODE_ENV!=="production"}catch{t._cachedDefault=!0}return t._cachedDefault}static set enabled(e){t._explicitEnabled=e}static _depSuffix(e){if(!e?.length)return;let n=e.map(s=>t._names.get(s)??"?").join(",");return n.length>40?`${n.slice(0,37)}...`:n}static _resolveKey(e){let i=t._keys.get(e)??t._names.get(e);if(i)return i;let n=`anonymous_${t._nextId++}`;return t._keys.set(e,n),n}static register(e,i){if(!t.enabled)return;i?.name&&t._names.set(e,i.name),i?.kind&&t._kinds.set(e,i.kind);let n=t._nextId++,s=i?.name;if(!(s&&!t._usedKeys.has(s)))if(s){let r=t._depSuffix(i?.deps);s=r?`${s}(${r})`:`${s}_${n}`,t._usedKeys.has(s)&&(s=`${s}_${n}`)}else{let r=i?.kind??"store",o=t._depSuffix(i?.deps);s=o?`${r}(${o})`:`${r}_${n}`,t._usedKeys.has(s)&&(s=`${s}_${n}`)}t._usedKeys.add(s),t._keys.set(e,s),t._stores.add(new WeakRef(e))}static registerEdge(e,i){if(!t.enabled)return;let n=t._resolveKey(e),s=t._resolveKey(i),r=t._edges.get(n);r?r.includes(s)||r.push(s):t._edges.set(n,[s])}static getEdges(){return new Map(t._edges)}static getName(e){if(t.enabled)return t._names.get(e)}static getKind(e){return t._kinds.get(e)}static inspect(e){return{name:t._names.get(e),kind:t._kinds.get(e)??"unknown",value:typeof e.get=="function"?e.get():void 0,status:e._status}}static graph(){let e=new Map,i=new Set;for(let n of t._stores){let s=n.deref();if(!s){t._stores.delete(n);continue}let r=t._resolveKey(s);i.add(r),e.set(r,t.inspect(s))}for(let[n,s]of t._edges){if(!i.has(n)){t._edges.delete(n),t._usedKeys.delete(n);continue}let r=s.filter(o=>i.has(o));r.length===0?t._edges.delete(n):r.length!==s.length&&t._edges.set(n,r)}return e}static trace(e,i){let n=null,s=e.get();return e.source(_,(r,o)=>{if(r===_&&(n=o),r===g){n=null;return}if(r===1){let u=o;if(!Object.is(u,s)){let l=s;s=u,i(u,l)}}}),()=>n?.(g)}static dumpGraph(){let e=t.graph(),i=t.getEdges(),n=new Map;for(let[o,u]of i)for(let l of u){let d=n.get(l);d?d.includes(o)||d.push(o):n.set(l,[o])}let s=[];for(let[o,u]of e){let l=n.get(o),d=i.get(o),a=l?.length?` \u2190 [${l.join(", ")}]`:"",c=d?.length?` \u2192 [${d.join(", ")}]`:"";s.push(` ${o} (${u.kind}) = ${JSON.stringify(u.value)} [${u.status??"?"}]${a}${c}`)}return[`Store Graph (${e.size} nodes):`,...s].join(`
|
|
2
|
+
`)}static _observe(e,i,n){let s=null,r=i??t.getName(e),o={values:[],signals:[],events:[],ended:!1,endError:void 0,dirtyCount:0,resolvedCount:0,name:r,dispose:()=>s?.(g)};return e.source(_,(u,l)=>{if(u===_){s=l;return}u===b?(o.values.push(l),o.events.push({type:"data",data:l}),n&&n(`[${r}] DATA:`,l)):u===y?(o.signals.push(l),o.events.push({type:"signal",data:l}),l===k?o.dirtyCount++:l===Y&&o.resolvedCount++,n&&n(`[${r}] STATE:`,l)):u===g&&(o.ended=!0,o.endError=l,o.events.push({type:"end",data:l}),n&&n(`[${r}] END`,l!==void 0?l:""),s=null)}),o}static observe(e){return t._observe(e)}static tap(e,i){let n=i??`tap(${t.getName(e)??"anon"})`,s={get:()=>e.get(),source:e.source};return t.register(s,{name:n,kind:"tap"}),t.registerEdge(e,s),s}static spy(e,i){let n=i?.name??t.getName(e)??"spy",s=i?.log??console.log;return t._observe(e,n,s)}static snapshot(){let e=t.graph(),i=t.getEdges(),n=new Map;for(let o of t._stores){let u=o.deref();if(!u)continue;let l=t._annotations.get(u);l!==void 0&&n.set(t._resolveKey(u),l)}let s=[];for(let[o,u]of e){let l={name:o,kind:u.kind,value:u.value,status:u.status},d=n.get(o);d!==void 0&&(l.annotation=d),s.push(l)}let r=[];for(let[o,u]of i)for(let l of u)r.push({from:o,to:l});return{nodes:s,edges:r,trace:t.traceLog()}}static toMermaid(e){let i=e?.direction??"TD",n=t.snapshot(),s=[`graph ${i}`],r={SETTLED:":::settled",DIRTY:":::dirty",ERRORED:":::errored",COMPLETED:":::completed"},o=new Map;function u(a){let c=a.replace(/[^a-zA-Z0-9_]/g,"_"),f=o.get(c);return f===void 0?(o.set(c,1),c):(o.set(c,f+1),`${c}__${f}`)}let l=new Map;function d(a){let c=JSON.stringify(a);return c&&c.length>30?`${c.slice(0,27)}...`:c??"undefined"}for(let a of n.nodes){let c=u(a.name);l.set(a.name,c);let f=`${a.name} (${a.kind}) = ${d(a.value)}`,h=r[a.status??""]??"";s.push(` ${c}["${f}"]${h}`)}for(let a of n.edges){let c=l.get(a.from)??u(a.from),f=l.get(a.to)??u(a.to);s.push(` ${c} --> ${f}`)}return s.push(""),s.push(" classDef settled fill:#d4edda,stroke:#28a745"),s.push(" classDef dirty fill:#fff3cd,stroke:#ffc107"),s.push(" classDef errored fill:#f8d7da,stroke:#dc3545"),s.push(" classDef completed fill:#cce5ff,stroke:#007bff"),s.join(`
|
|
3
|
+
`)}static toD2(e){let i=e?.direction??"down",n=t.snapshot(),s=[`direction: ${i}`,""],r={state:"rectangle",derived:"hexagon",effect:"oval",producer:"rectangle",operator:"parallelogram","pipeline-step":"rectangle","pipeline-status":"diamond",checkpoint:"cylinder"},o=new Map;function u(a){let c=a.replace(/[^a-zA-Z0-9_]/g,"_"),f=o.get(c);return f===void 0?(o.set(c,1),c):(o.set(c,f+1),`${c}__${f}`)}let l=new Map;function d(a){let c=JSON.stringify(a);return c&&c.length>30?`${c.slice(0,27)}...`:c??"undefined"}for(let a of n.nodes){let c=u(a.name);l.set(a.name,c);let f=r[a.kind]??"rectangle",h=`${a.name} (${a.kind}) = ${d(a.value)}`,E=a.status?` [${a.status}]`:"";s.push(`${c}: "${h}${E}" { shape: ${f} }`)}n.edges.length>0&&s.push("");for(let a of n.edges){let c=l.get(a.from)??u(a.from),f=l.get(a.to)??u(a.to);s.push(`${c} -> ${f}`)}return s.join(`
|
|
4
|
+
`)}static annotate(e,i){if(!t.enabled)return;t._annotations.set(e,i);let n={node:t._resolveKey(e),reason:i,timestamp:Date.now()},s=t.maxTraceEntries;s<=0||(t._traceLog.length<s?t._traceLog.push(n):(t._traceLog[t._traceHead]=n,t._traceFull=!0),t._traceHead=(t._traceHead+1)%s)}static getAnnotation(e){return t._annotations.get(e)}static traceLog(){return t._traceFull?[...t._traceLog.slice(t._traceHead),...t._traceLog.slice(0,t._traceHead)]:t._traceLog.slice(0,t._traceHead||t._traceLog.length)}static clearTrace(){t._traceLog=[],t._traceHead=0,t._traceFull=!1}static _reset(){t._names=new WeakMap,t._kinds=new WeakMap,t._keys=new WeakMap,t._stores=new Set,t._edges=new Map,t._usedKeys=new Set,t._nextId=0,t._explicitEnabled=null,t._cachedDefault=null,t._annotations=new WeakMap,t._traceLog=[],t._traceHead=0,t._traceFull=!1,t.maxTraceEntries=1e3}};var U=1,T=64,S=2,$=4,gt=8,ht=16,I=32,v=1024,p=tt,A=rt<<x,L=ot<<x,G=it<<x,wt=ut<<x,Ot=lt<<x,It=at<<x,N=class{_value;_output=null;_flags;get _status(){return ct(this._flags)}_cleanup;_fn;_eqFn;_getterFn;_initial;_singleDepCount=0;constructor(e,i){this._value=i?.initial,this._fn=e,this._eqFn=i?.equals,this._getterFn=i?.getter,this._initial=i?.initial;let n=0;i?.autoDirty!==!1&&(n|=$),i?.resetOnTeardown&&(n|=gt),i?.resubscribable&&(n|=ht),this._flags=n,this.source=this.source.bind(this),this.emit=this.emit.bind(this),i?._skipInspect||O.register(this,{kind:"producer",...i})}get(){return this._getterFn?this._getterFn(this._value):this._value}_dispatch(e,i){let n=this._output;if(n)if(this._flags&T)for(let s of n)s(e,i);else n(e,i)}emit(e){this._flags&S||this._eqFn&&this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(V()?this._flags&I||(this._flags|=I,this._flags&$&&(this._flags=this._flags&~p|A,this._dispatch(y,k)),q(()=>{this._flags&=~I,this._flags=this._flags&~p|L,this._dispatch(b,this._value)})):(this._flags&$&&!(this._flags&v)&&(this._flags=this._flags&~p|A,this._dispatch(y,k)),this._flags=this._flags&~p|L,this._dispatch(b,this._value))))}signal(e){this._flags&S||!this._output||(e===k?this._flags=this._flags&~p|A:e===Y&&(this._flags=this._flags&~p|It),this._dispatch(y,e))}complete(){if(this._flags&S)return;this._flags=(this._flags|S)&~p|wt;let e=this._output,i=this._flags&T;if(this._output=null,this._flags&=~(T|v),this._singleDepCount=0,this._stop(),e)if(i)for(let n of e)n(g);else e(g)}error(e){if(this._flags&S)return;this._flags=(this._flags|S)&~p|Ot;let i=this._output,n=this._flags&T;if(this._output=null,this._flags&=~(T|v),this._singleDepCount=0,this._stop(),i)if(n)for(let s of i)s(g,e);else i(g,e)}_start(){if(this._flags&U||!this._fn)return;this._flags|=U;let e=this._fn({emit:this.emit,signal:i=>this.signal(i),complete:()=>this.complete(),error:i=>this.error(i)});this._cleanup=typeof e=="function"?e:void 0}_stop(){this._flags&U&&(this._flags&=~U,this._cleanup&&this._cleanup(),this._cleanup=void 0,this._flags>&&(this._value=this._initial),this._flags&S||(this._flags=this._flags&~p|G))}source(e,i){if(e===_){let n=i;if(this._flags&S)if(this._flags&ht&&this._output===null)this._flags=this._flags&~(S|p)|G;else{n(_,r=>{}),n(g);return}if(this._output===null)this._output=n;else if(this._flags&T)this._output.add(n);else{let r=new Set;r.add(this._output),r.add(n),this._output=r,this._flags=(this._flags|T)&~v}let s=!1;n(_,(r,o)=>{if(r===b&&n(b,this._value),r===y&&o===st&&!s&&(s=!0,this._singleDepCount++,this._flags&T||(this._flags|=v)),r===g){if(s&&(s=!1,this._singleDepCount--),this._output===null)return;if(this._flags&T){let u=this._output;u.delete(n),u.size===1?(this._output=u.values().next().value,this._flags&=~T,this._singleDepCount>0&&(this._flags|=v)):u.size===0&&(this._output=null,this._flags&=~(T|v),this._singleDepCount=0,this._flags=this._flags&~p|G,this._stop())}else this._output===n&&(this._output=null,this._flags&=~v,this._singleDepCount=0,this._flags=this._flags&~p|G,this._stop())}}),pt(()=>this._start())}}};function z(t,e){return new N(t,e)}var et=class extends N{constructor(e,i){super(void 0,{initial:e,autoDirty:!0,equals:i?.equals??Object.is,_skipInspect:!0}),this.set=this.set.bind(this),O.register(this,{kind:"state",...i})}get(){return this._value}set(e){this._flags&S||this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(V()?this._flags&I||(this._flags|=I,this._flags&$&&(this._flags=this._flags&~p|A,this._dispatch(y,k)),q(()=>{this._flags&=~I,this._flags=this._flags&~p|L,this._dispatch(b,this._value)})):(this._flags&$&&!(this._flags&v)&&(this._flags=this._flags&~p|A,this._dispatch(y,k)),this._flags=this._flags&~p|L,this._dispatch(b,this._value))))}update(e){this.set(e(this._value))}};function C(t,e){return new et(t,e)}function _t(t,e,i){let n=null;ft(),t.source(_,(r,o)=>{if(r===_&&(n=o),r===g){n=null,i?.onEnd?.(o);return}if(r===1){let u=o,l=s;s=u,e(u,l)}});let s;try{s=t.get()}catch{}return dt(),()=>n?.(g)}function Tt(t,e){let i=e?.initialStatus??"pending",n=C(i,{name:"withStatus:status",equals:Object.is}),s=C(void 0,{name:"withStatus:error",equals:Object.is}),r=z(({emit:o,complete:u,error:l})=>{n.set(i),s.set(void 0);let d=_t(t,a=>{n.get()==="errored"?P(()=>{s.set(void 0),n.set("active")}):n.set("active"),o(a)},{onEnd:a=>{if(a!==void 0){let c=a instanceof Error?a:new Error(String(a));P(()=>{s.set(c),n.set("errored")}),l(a)}else n.set("completed"),u()}});return()=>{d()}},{initial:t.get(),resubscribable:!0});return O.register(r,{kind:"withStatus"}),{get:()=>t.get(),source:(o,u)=>r.source(o,u),status:n,error:s}}function $t(t,e){let i=e?.name??"http",n=e?.method??"GET",s=e?.headers,r=e?.body,o=e?.poll??0,u=e?.transform??(R=>R.json()),l=e?.timeout??3e4,d=C(0,{name:`${i}:fetchCount`}),a=null,c=null,f=null,h=null,E=null,m=!1;async function B(){if(!m||!a)return;E=new AbortController;let R=[E.signal];e?.signal&&R.push(e.signal);let w=new AbortController;for(let D of R){if(D.aborted){w.abort(D.reason);break}D.addEventListener("abort",()=>w.abort(D.reason),{once:!0})}let Z=setTimeout(()=>w.abort(new Error("Request timeout")),l);try{let D=r!==void 0?typeof r=="string"?r:JSON.stringify(r):void 0,j=await fetch(t,{method:n,headers:s,body:D,signal:w.signal});if(!m)return;if(!j.ok)throw new Error(`HTTP ${j.status}: ${j.statusText}`);let mt=await u(j);if(!m)return;P(()=>{d.update(bt=>bt+1),a?.(mt)})}catch(D){if(!m||D?.name==="AbortError")return;c?.(D)}finally{clearTimeout(Z),E=null}}function nt(){!m||o<=0||(h=setTimeout(()=>{h=null,B().then(()=>{m&&nt()}).catch(()=>{})},o))}let J=null,St=z(({emit:R,error:w,complete:Z})=>(a=R,c=w,f=Z,m=!0,J=()=>{B()},B().then(()=>{m&&nt()}),()=>{m=!1,a=null,c=null,f=null,J=null,E?.abort(),E=null,h!==null&&(clearTimeout(h),h=null)}),{name:i,kind:"http"}),M=Tt(St);return{get:()=>M.get(),source:(R,w)=>M.source(R,w),status:M.status,error:M.error,fetchCount:d,refetch(){J?.()},stop(){m=!1,E?.abort(),E=null,h!==null&&(clearTimeout(h),h=null),f?.()}}}0&&(module.exports={fromHTTP});
|
package/dist/adapters/http.d.cts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { S as Store } from '../types-BwU0Zcuz.cjs';
|
|
2
|
+
import { W as WithStatusStatus } from '../withStatus-BQCWdfrH.cjs';
|
|
2
3
|
import '../protocol-BVxRx57r.cjs';
|
|
3
4
|
|
|
4
|
-
type HTTPStatus = "idle" | "fetching" | "success" | "error";
|
|
5
5
|
interface FromHTTPOptions {
|
|
6
6
|
/** HTTP method. Default: "GET". */
|
|
7
7
|
method?: string;
|
|
@@ -20,11 +20,11 @@ interface FromHTTPOptions {
|
|
|
20
20
|
/** Timeout per request in ms. Default: 30000. */
|
|
21
21
|
timeout?: number;
|
|
22
22
|
}
|
|
23
|
-
interface HTTPStore<T = unknown> {
|
|
24
|
-
/**
|
|
25
|
-
|
|
26
|
-
/**
|
|
27
|
-
|
|
23
|
+
interface HTTPStore<T = unknown> extends Store<T | undefined> {
|
|
24
|
+
/** Lifecycle status: pending → active → completed/errored. */
|
|
25
|
+
status: Store<WithStatusStatus>;
|
|
26
|
+
/** Last error, if any. */
|
|
27
|
+
error: Store<Error | undefined>;
|
|
28
28
|
/** Number of completed fetches. */
|
|
29
29
|
fetchCount: Store<number>;
|
|
30
30
|
/** Manually trigger a fetch (useful with polling disabled). */
|
|
@@ -38,44 +38,27 @@ interface HTTPStore<T = unknown> {
|
|
|
38
38
|
* @param url - The URL to fetch.
|
|
39
39
|
* @param opts - Optional configuration.
|
|
40
40
|
*
|
|
41
|
-
* @returns `HTTPStore<T>` — reactive store with status, fetch count, and manual refetch.
|
|
42
|
-
*
|
|
43
|
-
* @returnsTable store | Store\<T \| undefined\> | Reactive store emitting fetched values.
|
|
44
|
-
* status | Store\<HTTPStatus\> | Fetch status: "idle", "fetching", "success", "error".
|
|
45
|
-
* fetchCount | Store\<number\> | Number of completed fetches.
|
|
46
|
-
* refetch() | () => void | Manually trigger a fetch.
|
|
47
|
-
* stop() | () => void | Stop polling and cancel in-flight request.
|
|
41
|
+
* @returns `HTTPStore<T>` — reactive store with status, error, fetch count, and manual refetch.
|
|
48
42
|
*
|
|
49
43
|
* @remarks **Tier 2:** Cycle boundary — each fetch result starts a new reactive update cycle.
|
|
50
44
|
* @remarks **Polling:** Set `poll` interval for periodic refetch. Omit for one-shot.
|
|
51
45
|
* @remarks **Transform:** Default extracts JSON. Override with `transform` for text, blob, etc.
|
|
52
46
|
* @remarks **Timeout:** Default 30s per request. Uses AbortController internally.
|
|
47
|
+
* @remarks **Status:** Uses withStatus() for lifecycle tracking (pending → active → completed/errored).
|
|
53
48
|
*
|
|
54
49
|
* @example
|
|
55
50
|
* ```ts
|
|
56
|
-
* import { fromHTTP } from 'callbag-recharge/adapters
|
|
51
|
+
* import { fromHTTP } from 'callbag-recharge/adapters';
|
|
57
52
|
* import { subscribe } from 'callbag-recharge';
|
|
58
53
|
*
|
|
59
54
|
* const api = fromHTTP("https://api.example.com/status", { poll: 5000 });
|
|
60
|
-
* subscribe(api
|
|
61
|
-
*
|
|
55
|
+
* subscribe(api, data => console.log("status:", data));
|
|
56
|
+
* subscribe(api.status, s => console.log("lifecycle:", s));
|
|
62
57
|
* api.stop();
|
|
63
58
|
* ```
|
|
64
59
|
*
|
|
65
|
-
* @example One-shot POST
|
|
66
|
-
* ```ts
|
|
67
|
-
* const result = fromHTTP("https://api.example.com/submit", {
|
|
68
|
-
* method: "POST",
|
|
69
|
-
* headers: { "Content-Type": "application/json" },
|
|
70
|
-
* body: { name: "test" },
|
|
71
|
-
* });
|
|
72
|
-
* subscribe(result.store, v => console.log(v));
|
|
73
|
-
* ```
|
|
74
|
-
*
|
|
75
|
-
* @seeAlso [fromWebhook](./webhook) — HTTP trigger (server-side), [fromWebSocket](./websocket) — WebSocket source
|
|
76
|
-
*
|
|
77
60
|
* @category adapters
|
|
78
61
|
*/
|
|
79
62
|
declare function fromHTTP<T = unknown>(url: string, opts?: FromHTTPOptions): HTTPStore<T>;
|
|
80
63
|
|
|
81
|
-
export { type FromHTTPOptions, type
|
|
64
|
+
export { type FromHTTPOptions, type HTTPStore, fromHTTP };
|
package/dist/adapters/http.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { S as Store } from '../types-DGII6w5S.js';
|
|
2
|
+
import { W as WithStatusStatus } from '../withStatus-BJI4TOZV.js';
|
|
2
3
|
import '../protocol-BVxRx57r.js';
|
|
3
4
|
|
|
4
|
-
type HTTPStatus = "idle" | "fetching" | "success" | "error";
|
|
5
5
|
interface FromHTTPOptions {
|
|
6
6
|
/** HTTP method. Default: "GET". */
|
|
7
7
|
method?: string;
|
|
@@ -20,11 +20,11 @@ interface FromHTTPOptions {
|
|
|
20
20
|
/** Timeout per request in ms. Default: 30000. */
|
|
21
21
|
timeout?: number;
|
|
22
22
|
}
|
|
23
|
-
interface HTTPStore<T = unknown> {
|
|
24
|
-
/**
|
|
25
|
-
|
|
26
|
-
/**
|
|
27
|
-
|
|
23
|
+
interface HTTPStore<T = unknown> extends Store<T | undefined> {
|
|
24
|
+
/** Lifecycle status: pending → active → completed/errored. */
|
|
25
|
+
status: Store<WithStatusStatus>;
|
|
26
|
+
/** Last error, if any. */
|
|
27
|
+
error: Store<Error | undefined>;
|
|
28
28
|
/** Number of completed fetches. */
|
|
29
29
|
fetchCount: Store<number>;
|
|
30
30
|
/** Manually trigger a fetch (useful with polling disabled). */
|
|
@@ -38,44 +38,27 @@ interface HTTPStore<T = unknown> {
|
|
|
38
38
|
* @param url - The URL to fetch.
|
|
39
39
|
* @param opts - Optional configuration.
|
|
40
40
|
*
|
|
41
|
-
* @returns `HTTPStore<T>` — reactive store with status, fetch count, and manual refetch.
|
|
42
|
-
*
|
|
43
|
-
* @returnsTable store | Store\<T \| undefined\> | Reactive store emitting fetched values.
|
|
44
|
-
* status | Store\<HTTPStatus\> | Fetch status: "idle", "fetching", "success", "error".
|
|
45
|
-
* fetchCount | Store\<number\> | Number of completed fetches.
|
|
46
|
-
* refetch() | () => void | Manually trigger a fetch.
|
|
47
|
-
* stop() | () => void | Stop polling and cancel in-flight request.
|
|
41
|
+
* @returns `HTTPStore<T>` — reactive store with status, error, fetch count, and manual refetch.
|
|
48
42
|
*
|
|
49
43
|
* @remarks **Tier 2:** Cycle boundary — each fetch result starts a new reactive update cycle.
|
|
50
44
|
* @remarks **Polling:** Set `poll` interval for periodic refetch. Omit for one-shot.
|
|
51
45
|
* @remarks **Transform:** Default extracts JSON. Override with `transform` for text, blob, etc.
|
|
52
46
|
* @remarks **Timeout:** Default 30s per request. Uses AbortController internally.
|
|
47
|
+
* @remarks **Status:** Uses withStatus() for lifecycle tracking (pending → active → completed/errored).
|
|
53
48
|
*
|
|
54
49
|
* @example
|
|
55
50
|
* ```ts
|
|
56
|
-
* import { fromHTTP } from 'callbag-recharge/adapters
|
|
51
|
+
* import { fromHTTP } from 'callbag-recharge/adapters';
|
|
57
52
|
* import { subscribe } from 'callbag-recharge';
|
|
58
53
|
*
|
|
59
54
|
* const api = fromHTTP("https://api.example.com/status", { poll: 5000 });
|
|
60
|
-
* subscribe(api
|
|
61
|
-
*
|
|
55
|
+
* subscribe(api, data => console.log("status:", data));
|
|
56
|
+
* subscribe(api.status, s => console.log("lifecycle:", s));
|
|
62
57
|
* api.stop();
|
|
63
58
|
* ```
|
|
64
59
|
*
|
|
65
|
-
* @example One-shot POST
|
|
66
|
-
* ```ts
|
|
67
|
-
* const result = fromHTTP("https://api.example.com/submit", {
|
|
68
|
-
* method: "POST",
|
|
69
|
-
* headers: { "Content-Type": "application/json" },
|
|
70
|
-
* body: { name: "test" },
|
|
71
|
-
* });
|
|
72
|
-
* subscribe(result.store, v => console.log(v));
|
|
73
|
-
* ```
|
|
74
|
-
*
|
|
75
|
-
* @seeAlso [fromWebhook](./webhook) — HTTP trigger (server-side), [fromWebSocket](./websocket) — WebSocket source
|
|
76
|
-
*
|
|
77
60
|
* @category adapters
|
|
78
61
|
*/
|
|
79
62
|
declare function fromHTTP<T = unknown>(url: string, opts?: FromHTTPOptions): HTTPStore<T>;
|
|
80
63
|
|
|
81
|
-
export { type FromHTTPOptions, type
|
|
64
|
+
export { type FromHTTPOptions, type HTTPStore, fromHTTP };
|
package/dist/adapters/http.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a}from"../chunk-
|
|
1
|
+
import{a}from"../chunk-EEKTY7JA.js";import"../chunk-RX5LWE4X.js";import"../chunk-YJXCVG35.js";import"../chunk-P5MXN4AF.js";import"../chunk-YN4VWXAF.js";import"../chunk-M76W372U.js";import"../chunk-CWP55MPE.js";import"../chunk-I7AUKTXE.js";export{a as fromHTTP};
|
package/dist/adapters/index.cjs
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
"use strict";var Ae=Object.create;var
|
|
2
|
-
`)}static _observe(t,n,r){let o=null,
|
|
3
|
-
`)}static toD2(t){let n=t?.direction??"down",r=e.snapshot(),o=[`direction: ${n}`,""],
|
|
4
|
-
`)}static annotate(t,n){if(!e.enabled)return;e._annotations.set(t,n);let r={node:e._resolveKey(t),reason:n,timestamp:Date.now()},o=e.maxTraceEntries;o<=0||(e._traceLog.length<o?e._traceLog.push(r):(e._traceLog[e._traceHead]=r,e._traceFull=!0),e._traceHead=(e._traceHead+1)%o)}static getAnnotation(t){return e._annotations.get(t)}static traceLog(){return e._traceFull?[...e._traceLog.slice(e._traceHead),...e._traceLog.slice(0,e._traceHead)]:e._traceLog.slice(0,e._traceHead||e._traceLog.length)}static clearTrace(){e._traceLog=[],e._traceHead=0,e._traceFull=!1}static _reset(){e._names=new WeakMap,e._kinds=new WeakMap,e._keys=new WeakMap,e._stores=new Set,e._edges=new Map,e._usedKeys=new Set,e._nextId=0,e._explicitEnabled=null,e._cachedDefault=null,e._annotations=new WeakMap,e._traceLog=[],e._traceHead=0,e._traceFull=!1,e.maxTraceEntries=1e3}};var
|
|
5
|
-
`);
|
|
6
|
-
`),
|
|
7
|
-
data: ${
|
|
1
|
+
"use strict";var Ae=Object.create;var Z=Object.defineProperty;var Me=Object.getOwnPropertyDescriptor;var $e=Object.getOwnPropertyNames;var We=Object.getPrototypeOf,Ie=Object.prototype.hasOwnProperty;var Ne=(e,t)=>{for(var n in t)Z(e,n,{get:t[n],enumerable:!0})},de=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of $e(t))!Ie.call(e,o)&&o!==n&&Z(e,o,{get:()=>t[o],enumerable:!(r=Me(t,o))||r.enumerable});return e};var je=(e,t,n)=>(n=e!=null?Ae(We(e)):{},de(t||!e||!e.__esModule?Z(n,"default",{value:e,enumerable:!0}):n,e)),He=e=>de(Z({},"__esModule",{value:!0}),e);var Ze={};Ne(Ze,{fromHTTP:()=>xe,fromLLM:()=>Re,fromMCP:()=>De,fromWebSocket:()=>Oe,fromWebhook:()=>Pe,toSSE:()=>Ce,toWebSocket:()=>Le});module.exports=He(Ze);var j=Symbol("DIRTY"),re=Symbol("RESOLVED"),pe=Symbol("SINGLE_DEP"),ge=0,me=1,he=2,Se=3,Te=4,be=5,H=7,ce=7<<H,Fe=["DISCONNECTED","DIRTY","SETTLED","RESOLVED","COMPLETED","ERRORED"];function ye(e){return Fe[(e&ce)>>>H]}var L=0,W=1,D=2,I=3,X=0,ee=[],ue=!1;function O(e){X++;try{return e()}finally{if(X--,X===0&&!ue){ue=!0;for(let t=0;t<ee.length;t++)ee[t]();ee.length=0,ue=!1}}}function oe(){return X>0}function se(e){ee.push(e)}var ne=0,te=[];function _e(){ne++}function ke(){if(ne--,ne===0){for(let e=0;e<te.length;e++)te[e]();te.length=0}}function ve(e){ne>0?te.push(e):e()}var C=class e{static _names=new WeakMap;static _kinds=new WeakMap;static _keys=new WeakMap;static _stores=new Set;static _edges=new Map;static _nextId=0;static _usedKeys=new Set;static _explicitEnabled=null;static _cachedDefault=null;static _annotations=new WeakMap;static _traceLog=[];static _traceHead=0;static _traceFull=!1;static maxTraceEntries=1e3;static get enabled(){if(e._explicitEnabled!==null)return e._explicitEnabled;if(e._cachedDefault!==null)return e._cachedDefault;try{e._cachedDefault=globalThis.process?.env?.NODE_ENV!=="production"}catch{e._cachedDefault=!0}return e._cachedDefault}static set enabled(t){e._explicitEnabled=t}static _depSuffix(t){if(!t?.length)return;let r=t.map(o=>e._names.get(o)??"?").join(",");return r.length>40?`${r.slice(0,37)}...`:r}static _resolveKey(t){let n=e._keys.get(t)??e._names.get(t);if(n)return n;let r=`anonymous_${e._nextId++}`;return e._keys.set(t,r),r}static register(t,n){if(!e.enabled)return;n?.name&&e._names.set(t,n.name),n?.kind&&e._kinds.set(t,n.kind);let r=e._nextId++,o=n?.name;if(!(o&&!e._usedKeys.has(o)))if(o){let u=e._depSuffix(n?.deps);o=u?`${o}(${u})`:`${o}_${r}`,e._usedKeys.has(o)&&(o=`${o}_${r}`)}else{let u=n?.kind??"store",a=e._depSuffix(n?.deps);o=a?`${u}(${a})`:`${u}_${r}`,e._usedKeys.has(o)&&(o=`${o}_${r}`)}e._usedKeys.add(o),e._keys.set(t,o),e._stores.add(new WeakRef(t))}static registerEdge(t,n){if(!e.enabled)return;let r=e._resolveKey(t),o=e._resolveKey(n),u=e._edges.get(r);u?u.includes(o)||u.push(o):e._edges.set(r,[o])}static getEdges(){return new Map(e._edges)}static getName(t){if(e.enabled)return e._names.get(t)}static getKind(t){return e._kinds.get(t)}static inspect(t){return{name:e._names.get(t),kind:e._kinds.get(t)??"unknown",value:typeof t.get=="function"?t.get():void 0,status:t._status}}static graph(){let t=new Map,n=new Set;for(let r of e._stores){let o=r.deref();if(!o){e._stores.delete(r);continue}let u=e._resolveKey(o);n.add(u),t.set(u,e.inspect(o))}for(let[r,o]of e._edges){if(!n.has(r)){e._edges.delete(r),e._usedKeys.delete(r);continue}let u=o.filter(a=>n.has(a));u.length===0?e._edges.delete(r):u.length!==o.length&&e._edges.set(r,u)}return t}static trace(t,n){let r=null,o=t.get();return t.source(L,(u,a)=>{if(u===L&&(r=a),u===D){r=null;return}if(u===1){let i=a;if(!Object.is(i,o)){let l=o;o=i,n(i,l)}}}),()=>r?.(D)}static dumpGraph(){let t=e.graph(),n=e.getEdges(),r=new Map;for(let[a,i]of n)for(let l of i){let f=r.get(l);f?f.includes(a)||f.push(a):r.set(l,[a])}let o=[];for(let[a,i]of t){let l=r.get(a),f=n.get(a),s=l?.length?` \u2190 [${l.join(", ")}]`:"",c=f?.length?` \u2192 [${f.join(", ")}]`:"";o.push(` ${a} (${i.kind}) = ${JSON.stringify(i.value)} [${i.status??"?"}]${s}${c}`)}return[`Store Graph (${t.size} nodes):`,...o].join(`
|
|
2
|
+
`)}static _observe(t,n,r){let o=null,u=n??e.getName(t),a={values:[],signals:[],events:[],ended:!1,endError:void 0,dirtyCount:0,resolvedCount:0,name:u,dispose:()=>o?.(D)};return t.source(L,(i,l)=>{if(i===L){o=l;return}i===W?(a.values.push(l),a.events.push({type:"data",data:l}),r&&r(`[${u}] DATA:`,l)):i===I?(a.signals.push(l),a.events.push({type:"signal",data:l}),l===j?a.dirtyCount++:l===re&&a.resolvedCount++,r&&r(`[${u}] STATE:`,l)):i===D&&(a.ended=!0,a.endError=l,a.events.push({type:"end",data:l}),r&&r(`[${u}] END`,l!==void 0?l:""),o=null)}),a}static observe(t){return e._observe(t)}static tap(t,n){let r=n??`tap(${e.getName(t)??"anon"})`,o={get:()=>t.get(),source:t.source};return e.register(o,{name:r,kind:"tap"}),e.registerEdge(t,o),o}static spy(t,n){let r=n?.name??e.getName(t)??"spy",o=n?.log??console.log;return e._observe(t,r,o)}static snapshot(){let t=e.graph(),n=e.getEdges(),r=new Map;for(let a of e._stores){let i=a.deref();if(!i)continue;let l=e._annotations.get(i);l!==void 0&&r.set(e._resolveKey(i),l)}let o=[];for(let[a,i]of t){let l={name:a,kind:i.kind,value:i.value,status:i.status},f=r.get(a);f!==void 0&&(l.annotation=f),o.push(l)}let u=[];for(let[a,i]of n)for(let l of i)u.push({from:a,to:l});return{nodes:o,edges:u,trace:e.traceLog()}}static toMermaid(t){let n=t?.direction??"TD",r=e.snapshot(),o=[`graph ${n}`],u={SETTLED:":::settled",DIRTY:":::dirty",ERRORED:":::errored",COMPLETED:":::completed"},a=new Map;function i(s){let c=s.replace(/[^a-zA-Z0-9_]/g,"_"),p=a.get(c);return p===void 0?(a.set(c,1),c):(a.set(c,p+1),`${c}__${p}`)}let l=new Map;function f(s){let c=JSON.stringify(s);return c&&c.length>30?`${c.slice(0,27)}...`:c??"undefined"}for(let s of r.nodes){let c=i(s.name);l.set(s.name,c);let p=`${s.name} (${s.kind}) = ${f(s.value)}`,y=u[s.status??""]??"";o.push(` ${c}["${p}"]${y}`)}for(let s of r.edges){let c=l.get(s.from)??i(s.from),p=l.get(s.to)??i(s.to);o.push(` ${c} --> ${p}`)}return o.push(""),o.push(" classDef settled fill:#d4edda,stroke:#28a745"),o.push(" classDef dirty fill:#fff3cd,stroke:#ffc107"),o.push(" classDef errored fill:#f8d7da,stroke:#dc3545"),o.push(" classDef completed fill:#cce5ff,stroke:#007bff"),o.join(`
|
|
3
|
+
`)}static toD2(t){let n=t?.direction??"down",r=e.snapshot(),o=[`direction: ${n}`,""],u={state:"rectangle",derived:"hexagon",effect:"oval",producer:"rectangle",operator:"parallelogram","pipeline-step":"rectangle","pipeline-status":"diamond",checkpoint:"cylinder"},a=new Map;function i(s){let c=s.replace(/[^a-zA-Z0-9_]/g,"_"),p=a.get(c);return p===void 0?(a.set(c,1),c):(a.set(c,p+1),`${c}__${p}`)}let l=new Map;function f(s){let c=JSON.stringify(s);return c&&c.length>30?`${c.slice(0,27)}...`:c??"undefined"}for(let s of r.nodes){let c=i(s.name);l.set(s.name,c);let p=u[s.kind]??"rectangle",y=`${s.name} (${s.kind}) = ${f(s.value)}`,_=s.status?` [${s.status}]`:"";o.push(`${c}: "${y}${_}" { shape: ${p} }`)}r.edges.length>0&&o.push("");for(let s of r.edges){let c=l.get(s.from)??i(s.from),p=l.get(s.to)??i(s.to);o.push(`${c} -> ${p}`)}return o.join(`
|
|
4
|
+
`)}static annotate(t,n){if(!e.enabled)return;e._annotations.set(t,n);let r={node:e._resolveKey(t),reason:n,timestamp:Date.now()},o=e.maxTraceEntries;o<=0||(e._traceLog.length<o?e._traceLog.push(r):(e._traceLog[e._traceHead]=r,e._traceFull=!0),e._traceHead=(e._traceHead+1)%o)}static getAnnotation(t){return e._annotations.get(t)}static traceLog(){return e._traceFull?[...e._traceLog.slice(e._traceHead),...e._traceLog.slice(0,e._traceHead)]:e._traceLog.slice(0,e._traceHead||e._traceLog.length)}static clearTrace(){e._traceLog=[],e._traceHead=0,e._traceFull=!1}static _reset(){e._names=new WeakMap,e._kinds=new WeakMap,e._keys=new WeakMap,e._stores=new Set,e._edges=new Map,e._usedKeys=new Set,e._nextId=0,e._explicitEnabled=null,e._cachedDefault=null,e._annotations=new WeakMap,e._traceLog=[],e._traceHead=0,e._traceFull=!1,e.maxTraceEntries=1e3}};var ie=1,M=64,$=2,K=4,we=8,Ee=16,q=32,N=1024,x=ce,U=me<<H,Y=he<<H,ae=ge<<H,qe=Te<<H,Be=be<<H,Ke=Se<<H,G=class{_value;_output=null;_flags;get _status(){return ye(this._flags)}_cleanup;_fn;_eqFn;_getterFn;_initial;_singleDepCount=0;constructor(t,n){this._value=n?.initial,this._fn=t,this._eqFn=n?.equals,this._getterFn=n?.getter,this._initial=n?.initial;let r=0;n?.autoDirty!==!1&&(r|=K),n?.resetOnTeardown&&(r|=we),n?.resubscribable&&(r|=Ee),this._flags=r,this.source=this.source.bind(this),this.emit=this.emit.bind(this),n?._skipInspect||C.register(this,{kind:"producer",...n})}get(){return this._getterFn?this._getterFn(this._value):this._value}_dispatch(t,n){let r=this._output;if(r)if(this._flags&M)for(let o of r)o(t,n);else r(t,n)}emit(t){this._flags&$||this._eqFn&&this._value!==void 0&&this._eqFn(this._value,t)||(this._value=t,this._output&&(oe()?this._flags&q||(this._flags|=q,this._flags&K&&(this._flags=this._flags&~x|U,this._dispatch(I,j)),se(()=>{this._flags&=~q,this._flags=this._flags&~x|Y,this._dispatch(W,this._value)})):(this._flags&K&&!(this._flags&N)&&(this._flags=this._flags&~x|U,this._dispatch(I,j)),this._flags=this._flags&~x|Y,this._dispatch(W,this._value))))}signal(t){this._flags&$||!this._output||(t===j?this._flags=this._flags&~x|U:t===re&&(this._flags=this._flags&~x|Ke),this._dispatch(I,t))}complete(){if(this._flags&$)return;this._flags=(this._flags|$)&~x|qe;let t=this._output,n=this._flags&M;if(this._output=null,this._flags&=~(M|N),this._singleDepCount=0,this._stop(),t)if(n)for(let r of t)r(D);else t(D)}error(t){if(this._flags&$)return;this._flags=(this._flags|$)&~x|Be;let n=this._output,r=this._flags&M;if(this._output=null,this._flags&=~(M|N),this._singleDepCount=0,this._stop(),n)if(r)for(let o of n)o(D,t);else n(D,t)}_start(){if(this._flags&ie||!this._fn)return;this._flags|=ie;let t=this._fn({emit:this.emit,signal:n=>this.signal(n),complete:()=>this.complete(),error:n=>this.error(n)});this._cleanup=typeof t=="function"?t:void 0}_stop(){this._flags&ie&&(this._flags&=~ie,this._cleanup&&this._cleanup(),this._cleanup=void 0,this._flags&we&&(this._value=this._initial),this._flags&$||(this._flags=this._flags&~x|ae))}source(t,n){if(t===L){let r=n;if(this._flags&$)if(this._flags&Ee&&this._output===null)this._flags=this._flags&~($|x)|ae;else{r(L,u=>{}),r(D);return}if(this._output===null)this._output=r;else if(this._flags&M)this._output.add(r);else{let u=new Set;u.add(this._output),u.add(r),this._output=u,this._flags=(this._flags|M)&~N}let o=!1;r(L,(u,a)=>{if(u===W&&r(W,this._value),u===I&&a===pe&&!o&&(o=!0,this._singleDepCount++,this._flags&M||(this._flags|=N)),u===D){if(o&&(o=!1,this._singleDepCount--),this._output===null)return;if(this._flags&M){let i=this._output;i.delete(r),i.size===1?(this._output=i.values().next().value,this._flags&=~M,this._singleDepCount>0&&(this._flags|=N)):i.size===0&&(this._output=null,this._flags&=~(M|N),this._singleDepCount=0,this._flags=this._flags&~x|ae,this._stop())}else this._output===r&&(this._output=null,this._flags&=~N,this._singleDepCount=0,this._flags=this._flags&~x|ae,this._stop())}}),ve(()=>this._start())}}};function F(e,t){return new G(e,t)}var le=class extends G{constructor(t,n){super(void 0,{initial:t,autoDirty:!0,equals:n?.equals??Object.is,_skipInspect:!0}),this.set=this.set.bind(this),C.register(this,{kind:"state",...n})}get(){return this._value}set(t){this._flags&$||this._value!==void 0&&this._eqFn(this._value,t)||(this._value=t,this._output&&(oe()?this._flags&q||(this._flags|=q,this._flags&K&&(this._flags=this._flags&~x|U,this._dispatch(I,j)),se(()=>{this._flags&=~q,this._flags=this._flags&~x|Y,this._dispatch(W,this._value)})):(this._flags&K&&!(this._flags&N)&&(this._flags=this._flags&~x|U,this._dispatch(I,j)),this._flags=this._flags&~x|Y,this._dispatch(W,this._value))))}update(t){this.set(t(this._value))}};function v(e,t){return new le(e,t)}function z(e,t,n){let r=null;_e(),e.source(L,(u,a)=>{if(u===L&&(r=a),u===D){r=null,n?.onEnd?.(a);return}if(u===1){let i=a,l=o;o=i,t(i,l)}});let o;try{o=e.get()}catch{}return ke(),()=>r?.(D)}function V(e,t){let n=t?.initialStatus??"pending",r=v(n,{name:"withStatus:status",equals:Object.is}),o=v(void 0,{name:"withStatus:error",equals:Object.is}),u=F(({emit:a,complete:i,error:l})=>{r.set(n),o.set(void 0);let f=z(e,s=>{r.get()==="errored"?O(()=>{o.set(void 0),r.set("active")}):r.set("active"),a(s)},{onEnd:s=>{if(s!==void 0){let c=s instanceof Error?s:new Error(String(s));O(()=>{o.set(c),r.set("errored")}),l(s)}else r.set("completed"),i()}});return()=>{f()}},{initial:e.get(),resubscribable:!0});return C.register(u,{kind:"withStatus"}),{get:()=>e.get(),source:(a,i)=>u.source(a,i),status:r,error:o}}function xe(e,t){let n=t?.name??"http",r=t?.method??"GET",o=t?.headers,u=t?.body,a=t?.poll??0,i=t?.transform??(k=>k.json()),l=t?.timeout??3e4,f=v(0,{name:`${n}:fetchCount`}),s=null,c=null,p=null,y=null,_=null,h=!1;async function T(){if(!h||!s)return;_=new AbortController;let k=[_.signal];t?.signal&&k.push(t.signal);let E=new AbortController;for(let b of k){if(b.aborted){E.abort(b.reason);break}b.addEventListener("abort",()=>E.abort(b.reason),{once:!0})}let w=setTimeout(()=>E.abort(new Error("Request timeout")),l);try{let b=u!==void 0?typeof u=="string"?u:JSON.stringify(u):void 0,A=await fetch(e,{method:r,headers:o,body:b,signal:E.signal});if(!h)return;if(!A.ok)throw new Error(`HTTP ${A.status}: ${A.statusText}`);let P=await i(A);if(!h)return;O(()=>{f.update(R=>R+1),s?.(P)})}catch(b){if(!h||b?.name==="AbortError")return;c?.(b)}finally{clearTimeout(w),_=null}}function m(){!h||a<=0||(y=setTimeout(()=>{y=null,T().then(()=>{h&&m()}).catch(()=>{})},a))}let g=null,d=F(({emit:k,error:E,complete:w})=>(s=k,c=E,p=w,h=!0,g=()=>{T()},T().then(()=>{h&&m()}),()=>{h=!1,s=null,c=null,p=null,g=null,_?.abort(),_=null,y!==null&&(clearTimeout(y),y=null)}),{name:n,kind:"http"}),S=V(d);return{get:()=>S.get(),source:(k,E)=>S.source(k,E),status:S.status,error:S.error,fetchCount:f,refetch(){g?.()},stop(){h=!1,_?.abort(),_=null,y!==null&&(clearTimeout(y),y=null),p?.()}}}function Ue(e){switch(e){case"openai":return"https://api.openai.com/v1";case"ollama":return"http://localhost:11434";default:return""}}function ze(e,t){switch(e){case"openai":case"custom":return`${t}/chat/completions`;case"ollama":return`${t}/api/chat`;default:return`${t}/chat/completions`}}function Ve(e,t,n,r){let o={model:t,messages:n,stream:!0};return r?.temperature!==void 0&&(o.temperature=r.temperature),r?.maxTokens!==void 0&&(e==="ollama"?o.options={num_predict:r.maxTokens}:o.max_tokens=r.maxTokens),r?.stop&&(o.stop=r.stop),o}function Ye(e,t){let n={"Content-Type":"application/json"};return t&&(n.Authorization=`Bearer ${t}`),n}function Re(e){let t=e.name??"llm",n=e.provider,r=e.baseURL??Ue(n),o=e.model??"",u=e.fetch??globalThis.fetch,a=v("",{name:`${t}.store`}),i=v({},{name:`${t}.tokens`}),l=v("pending",{name:`${t}.status`}),f=v(void 0,{name:`${t}.error`}),s=null;function c(){s&&(s.abort(),s=null),l.get()==="active"&&l.set("pending")}function p(_,h){c(),s=new AbortController;let T=h?.signal?Qe(s.signal,h.signal):s.signal;O(()=>{a.set(""),i.set({}),f.set(void 0),l.set("active")});let m=ze(n,r),g=Ve(n,o,_,h),d=Ye(n,e.apiKey);y(m,d,g,T).catch(()=>{})}async function y(_,h,T,m){try{let g=await u(_,{method:"POST",headers:h,body:JSON.stringify(T),signal:m});if(!g.ok){let w=await g.text().catch(()=>"");throw new Error(`LLM API error ${g.status}: ${w}`)}let d=g.body?.getReader();if(!d)throw new Error("No response body");let S=new TextDecoder,k="",E="";for(;;){if(m.aborted)return;let{done:w,value:b}=await d.read();if(w)break;E+=S.decode(b,{stream:!0});let A=E.split(`
|
|
5
|
+
`);E=A.pop()??"";for(let P of A){if(m.aborted)return;let R=P.trim();if(!R||R.startsWith(":")||!R.startsWith("data: "))continue;let J=R.slice(6);if(J!=="[DONE]")try{let B=JSON.parse(J),Q=Ge(n,B);Q&&(k+=Q,a.set(k));let fe=Je(n,B);fe&&i.set(fe)}catch{}}}if(S.decode(),m.aborted)return;l.set("completed"),s=null}catch(g){if(m.aborted)return;O(()=>{f.set(g),l.set("errored")}),s=null}finally{m._cleanup?.()}}return{store:a,tokens:i,status:l,error:f,generate:p,abort:c}}function Ge(e,t){return e==="ollama"?t?.message?.content:t?.choices?.[0]?.delta?.content}function Je(e,t){let n=e==="ollama"?t:t?.usage;if(n){if(e==="ollama")return t.eval_count!==void 0||t.prompt_eval_count!==void 0?{promptTokens:t.prompt_eval_count,completionTokens:t.eval_count,totalTokens:(t.prompt_eval_count??0)+(t.eval_count??0)}:void 0;if(n.prompt_tokens!==void 0||n.completion_tokens!==void 0)return{promptTokens:n.prompt_tokens,completionTokens:n.completion_tokens,totalTokens:n.total_tokens}}}function Qe(e,t){let n=new AbortController,r=()=>{e.removeEventListener("abort",o),t.removeEventListener("abort",o)},o=()=>{n.abort(),r()};e.addEventListener("abort",o,{once:!0}),t.addEventListener("abort",o,{once:!0});let u=n.signal;return u._cleanup=r,u}function De(e){let t=e.name??"mcp",n=e.client,r=v([],{name:`${t}.tools`}),o=v([],{name:`${t}.resources`}),u=v(void 0,{name:`${t}.refreshError`});function a(f){u.set(f);let s=e.onRefreshError;if(s==="warn")console.warn(`[${t}] refresh error:`,f);else{if(s==="error")throw f;typeof s=="function"&&s(f)}}async function i(){if(u.set(void 0),n.listTools)try{let f=await n.listTools();r.set(f.tools)}catch(f){a(f)}if(n.listResources)try{let f=await n.listResources();o.set(f.resources)}catch(f){a(f)}}function l(f){let s=`${t}:${f}`,c=v(void 0,{name:`${s}.result`}),p=v("idle",{name:`${s}.status`}),y=v(void 0,{name:`${s}.error`}),_=v(void 0,{name:`${s}.lastArgs`}),h=v(void 0,{name:`${s}.duration`}),T=!1;async function m(g){if(T)return;T=!0,O(()=>{_.set(g),y.set(void 0),p.set("active")});let d=Date.now();try{let S=await n.callTool({name:f,arguments:g}),k=Date.now()-d;if(S.isError){let b=S.content.filter(P=>P.type==="text").map(P=>P.text??"").join(`
|
|
6
|
+
`),A=new Error(b||"MCP tool returned error");O(()=>{h.set(k),y.set(A),p.set("errored")});return}let E=S.content.filter(b=>b.type==="text"),w;if(E.length===1){let b=E[0].text;if(b!==void 0)try{w=JSON.parse(b)}catch{w=b}}else E.length>1?w=E.map(b=>b.text??""):w=S.content;O(()=>{h.set(k),c.set(w),p.set("completed")})}catch(S){let k=Date.now()-d;O(()=>{h.set(k),y.set(S),p.set("errored")})}finally{T=!1}}return{store:c,status:p,error:y,call:m,lastArgs:_,duration:h}}return{tool:l,tools:r,resources:o,refresh:i,refreshError:u}}function Ce(e,t){let n=t?.path??"/",r=t?.name??"sse",o=t?.hostname??"0.0.0.0",u=t?.serialize??JSON.stringify,a=t?.eventName??"message",i=t?.pingInterval??3e4,l=v(0,{name:`${r}:connections`}),f=new Set,s=new Map,c=null;function p(){c||(c=z(e,g=>{let d=u(g),S=`event: ${a}
|
|
7
|
+
data: ${d}
|
|
8
8
|
|
|
9
|
-
`;for(let
|
|
9
|
+
`;for(let k of f)try{k.write(S)}catch{y(k)}}))}function y(g){f.delete(g);let d=s.get(g);d&&(clearInterval(d),s.delete(g)),l.set(f.size),f.size===0&&c&&(c(),c=null)}function _(g,d){let S=g.method?.toUpperCase();if((g.url??"/").split("?")[0]!==n){d.writeHead(404,{"Content-Type":"text/plain"}),d.end("Not found");return}if(S==="OPTIONS"){d.writeHead(204,{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET","Access-Control-Allow-Headers":"Cache-Control"}),d.end();return}if(S!=="GET"){d.writeHead(405,{"Content-Type":"text/plain"}),d.end("Method not allowed");return}d.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","Access-Control-Allow-Origin":"*"}),d.write(`:ok
|
|
10
10
|
|
|
11
|
-
`),
|
|
12
|
-
data: ${
|
|
11
|
+
`),f.add(d),l.set(f.size);try{let w=e.get();if(w!==void 0){let b=u(w);d.write(`event: ${a}
|
|
12
|
+
data: ${b}
|
|
13
13
|
|
|
14
|
-
`)}}catch{}if(
|
|
14
|
+
`)}}catch{}if(i>0){let w=setInterval(()=>{try{d.write(`:ping
|
|
15
15
|
|
|
16
|
-
`)}catch{
|
|
16
|
+
`)}catch{y(d)}},i);s.set(d,w)}g.on("close",()=>y(d)),p()}let h=null;async function T(){if(!t?.port)throw new Error("toSSE: port is required for listen()");if(h)throw new Error("toSSE: already listening. Call close() first.");let g=await import("http");return new Promise((d,S)=>{h=g.createServer(_),h.once("listening",()=>d()),h.once("error",k=>{h=null,S(k)}),h.listen(t.port,o)})}function m(){for(let g of f)try{g.end()}catch{}f.clear();for(let g of s.values())clearInterval(g);s.clear(),l.set(0),c?.(),c=null,h?.close(),h=null}return C.register(l,{kind:"sse"}),{connectionCount:l,handler:_,listen:T,close:m}}function Pe(e){let t=e?.path??"/",n=e?.parse??JSON.parse,r=e?.name??"webhook",o=e?.hostname??"0.0.0.0",u=e?.maxBodySize??1024*1024,a=e?.responseTimeout??3e4,i=v(0,{name:`${r}:count`}),l=null,f=F(({emit:T})=>(l=T,()=>{l=null}),{name:r,kind:"webhook"});C.register(f,{kind:"webhook"});let s=V(f),c=null,p=new Set;function y(T,m){let g=T.method?.toUpperCase(),S=(T.url??"/").split("?")[0];if(g!=="POST"||S!==t){m.writeHead(404,{"Content-Type":"application/json"}),m.end(JSON.stringify({error:"Not found"}));return}let k=[],E=0,w=!1;T.on("error",()=>{w=!0,m.headersSent||(m.writeHead(400,{"Content-Type":"application/json"}),m.end(JSON.stringify({error:"Request aborted"})))}),T.on("data",b=>{if(!w){if(E+=b.length,E>u){w=!0,m.writeHead(413,{"Content-Type":"application/json"}),m.end(JSON.stringify({error:"Payload too large"})),T.destroy?.();return}k.push(b)}}),T.on("end",()=>{if(!w)try{let b=Buffer.concat(k).toString("utf-8"),A=b.length>0?n(b):void 0;i.update(B=>B+1);let P=!1,R=null,J={body:A,get responded(){return P},respond(B,Q=200){P||(P=!0,R!==null&&(clearTimeout(R),p.delete(R),R=null),m.writeHead(Q,{"Content-Type":"application/json"}),m.end(JSON.stringify(B)))}};R=setTimeout(()=>{p.delete(R),R=null,P||(P=!0,m.writeHead(504,{"Content-Type":"application/json"}),m.end(JSON.stringify({error:"Response timeout"})))},a),p.add(R),l?.(J)}catch(b){m.writeHead(400,{"Content-Type":"application/json"}),m.end(JSON.stringify({error:b?.message??"Parse error"}))}})}function _(){return e?.port?c?Promise.reject(new Error("fromWebhook: already listening. Call close() first.")):new Promise((T,m)=>{try{c=require("http").createServer(y),c.once("listening",()=>T()),c.once("error",d=>{c=null,m(d)}),c.listen(e.port,o)}catch(g){m(g)}}):Promise.reject(new Error("fromWebhook: port is required for listen()"))}function h(){for(let T of p)clearTimeout(T);p.clear(),c?.close(),c=null}return{get:()=>s.get(),source:(T,m)=>s.source(T,m),status:s.status,error:s.error,requestCount:i,handler:y,listen:_,close:h}}function Oe(e,t){let n=t?.name??"websocket",r=t?.parse??(d=>d),o=t?.reconnect??!1,u=t?.onParseError??"warn",a=v("connecting",{name:`${n}:connectionState`,equals:()=>!1}),i=null,l=null,f=null,s=null,c=null,p=!1,y=null,_=[];function h(){for(;_.length>0&&i?.readyState===WebSocket.OPEN;)i.send(_.shift())}function T(){p=!1,a.set("connecting");try{i=new WebSocket(e,t?.protocols)}catch(d){a.set("closed"),f?.(d);return}i.onopen=()=>{a.set("open"),h()},i.onmessage=d=>{try{let S=r(d.data);l?.(S)}catch(S){u==="error"?f?.(S):u==="warn"&&console.warn(`[${n}] parse error:`,S)}},i.onerror=()=>{y=new Error(`WebSocket error on ${e}`)},i.onclose=()=>{a.set("closed"),i=null;let d=y;y=null,!p&&o!==!1?c=setTimeout(()=>{c=null,l&&T()},o):d&&!p?f?.(d):s?.()}}let m=F(({emit:d,error:S,complete:k})=>(l=d,f=S,s=k,T(),()=>{l=null,f=null,s=null,p=!0,_.length=0,c!==null&&(clearTimeout(c),c=null),i&&(i.onopen=null,i.onmessage=null,i.onerror=null,i.onclose=null,i.close(),i=null),a.set("closed")}),{name:n,kind:"websocket"});C.register(m,{kind:"websocket"});let g=V(m);return{get:()=>g.get(),source:(d,S)=>g.source(d,S),status:g.status,error:g.error,connectionState:a,send(d){i?.readyState===WebSocket.OPEN?i.send(d):_.push(d)},close(d,S){p=!0,_.length=0,c!==null&&(clearTimeout(c),c=null),i?.close(d,S)}}}function Le(e,t,n){let r=a=>typeof a=="string"?a:JSON.stringify(a),o=n?.serialize??r,u="send"in e&&typeof e.send=="function"?e.send.bind(e):null;if(!u)throw new Error("toWebSocket: invalid WebSocket target");return z(t,a=>{try{let i=o(a);u(i)}catch{}})}0&&(module.exports={fromHTTP,fromLLM,fromMCP,fromWebSocket,fromWebhook,toSSE,toWebSocket});
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
export { FromHTTPOptions,
|
|
1
|
+
export { FromHTTPOptions, HTTPStore, fromHTTP } from './http.cjs';
|
|
2
2
|
export { GenerateOptions, LLMMessage, LLMOptions, LLMStore, LLMTokenUsage, fromLLM } from './llm.cjs';
|
|
3
|
-
export { MCPClientLike, MCPOptions, MCPResource, MCPResult, MCPToolInfo,
|
|
3
|
+
export { MCPClientLike, MCPOptions, MCPResource, MCPResult, MCPToolInfo, MCPToolStore, fromMCP } from './mcp.cjs';
|
|
4
4
|
export { SSEOptions, SSEStore, toSSE } from './sse.cjs';
|
|
5
|
-
export { WebhookOptions, WebhookStore, fromWebhook } from './webhook.cjs';
|
|
6
|
-
export { FromWebSocketOptions, ToWebSocketOptions,
|
|
5
|
+
export { WebhookOptions, WebhookRequest, WebhookStore, fromWebhook } from './webhook.cjs';
|
|
6
|
+
export { FromWebSocketOptions, ToWebSocketOptions, WebSocketConnectionState, WebSocketStore, fromWebSocket, toWebSocket } from './websocket.cjs';
|
|
7
7
|
import '../types-BwU0Zcuz.cjs';
|
|
8
8
|
import '../protocol-BVxRx57r.cjs';
|
|
9
|
+
import '../withStatus-BQCWdfrH.cjs';
|
package/dist/adapters/index.d.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
export { FromHTTPOptions,
|
|
1
|
+
export { FromHTTPOptions, HTTPStore, fromHTTP } from './http.js';
|
|
2
2
|
export { GenerateOptions, LLMMessage, LLMOptions, LLMStore, LLMTokenUsage, fromLLM } from './llm.js';
|
|
3
|
-
export { MCPClientLike, MCPOptions, MCPResource, MCPResult, MCPToolInfo,
|
|
3
|
+
export { MCPClientLike, MCPOptions, MCPResource, MCPResult, MCPToolInfo, MCPToolStore, fromMCP } from './mcp.js';
|
|
4
4
|
export { SSEOptions, SSEStore, toSSE } from './sse.js';
|
|
5
|
-
export { WebhookOptions, WebhookStore, fromWebhook } from './webhook.js';
|
|
6
|
-
export { FromWebSocketOptions, ToWebSocketOptions,
|
|
5
|
+
export { WebhookOptions, WebhookRequest, WebhookStore, fromWebhook } from './webhook.js';
|
|
6
|
+
export { FromWebSocketOptions, ToWebSocketOptions, WebSocketConnectionState, WebSocketStore, fromWebSocket, toWebSocket } from './websocket.js';
|
|
7
7
|
import '../types-DGII6w5S.js';
|
|
8
8
|
import '../protocol-BVxRx57r.js';
|
|
9
|
+
import '../withStatus-BJI4TOZV.js';
|
package/dist/adapters/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as o}from"../chunk-
|
|
1
|
+
import{a as o}from"../chunk-EEKTY7JA.js";import{a as e}from"../chunk-OXIEM5ZP.js";import{a as t}from"../chunk-W74KQTWL.js";import{a as r}from"../chunk-X6RLUCXO.js";import{a as p}from"../chunk-6M3P6NXX.js";import{a as m,b as S}from"../chunk-OHNEQFSD.js";import"../chunk-RX5LWE4X.js";import"../chunk-YJXCVG35.js";import"../chunk-P5MXN4AF.js";import"../chunk-YN4VWXAF.js";import"../chunk-M76W372U.js";import"../chunk-CWP55MPE.js";import"../chunk-I7AUKTXE.js";export{o as fromHTTP,e as fromLLM,t as fromMCP,m as fromWebSocket,p as fromWebhook,r as toSSE,S as toWebSocket};
|
package/dist/adapters/llm.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var q=Object.defineProperty;var mt=Object.getOwnPropertyDescriptor;var St=Object.getOwnPropertyNames;var vt=Object.prototype.hasOwnProperty;var
|
|
2
|
-
`)}static _observe(e,n,s){let i=null,
|
|
3
|
-
`)}static toD2(e){let n=e?.direction??"down",s=t.snapshot(),i=[`direction: ${n}`,""],
|
|
4
|
-
`)}static annotate(e,n){if(!t.enabled)return;t._annotations.set(e,n);let s={node:t._resolveKey(e),reason:n,timestamp:Date.now()},i=t.maxTraceEntries;i<=0||(t._traceLog.length<i?t._traceLog.push(s):(t._traceLog[t._traceHead]=s,t._traceFull=!0),t._traceHead=(t._traceHead+1)%i)}static getAnnotation(e){return t._annotations.get(e)}static traceLog(){return t._traceFull?[...t._traceLog.slice(t._traceHead),...t._traceLog.slice(0,t._traceHead)]:t._traceLog.slice(0,t._traceHead||t._traceLog.length)}static clearTrace(){t._traceLog=[],t._traceHead=0,t._traceFull=!1}static _reset(){t._names=new WeakMap,t._kinds=new WeakMap,t._keys=new WeakMap,t._stores=new Set,t._edges=new Map,t._usedKeys=new Set,t._nextId=0,t._explicitEnabled=null,t._cachedDefault=null,t._annotations=new WeakMap,t._traceLog=[],t._traceHead=0,t._traceFull=!1,t.maxTraceEntries=1e3}};var U=1,h=64,_=2,L=4,pt=8,ht=16,D=32,S=1024,g=B,R=at<<
|
|
5
|
-
`);G=tt.pop()??"";for(let Tt of tt){if(
|
|
1
|
+
"use strict";var q=Object.defineProperty;var mt=Object.getOwnPropertyDescriptor;var St=Object.getOwnPropertyNames;var vt=Object.prototype.hasOwnProperty;var yt=(t,e)=>{for(var n in e)q(t,n,{get:e[n],enumerable:!0})},bt=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of St(e))!vt.call(t,i)&&i!==n&&q(t,i,{get:()=>e[i],enumerable:!(s=mt(e,i))||s.enumerable});return t};var Et=t=>bt(q({},"__esModule",{value:!0}),t);var jt={};yt(jt,{fromLLM:()=>At});module.exports=Et(jt);var v=Symbol("DIRTY"),j=Symbol("RESOLVED"),rt=Symbol("SINGLE_DEP"),ot=0,at=1,ct=2,ut=3,lt=4,dt=5,y=7,B=7<<y,kt=["DISCONNECTED","DIRTY","SETTLED","RESOLVED","COMPLETED","ERRORED"];function ft(t){return kt[(t&B)>>>y]}var b=0,T=1,p=2,m=3,N=0,C=[],z=!1;function J(t){N++;try{return t()}finally{if(N--,N===0&&!z){z=!0;for(let e=0;e<C.length;e++)C[e]();C.length=0,z=!1}}}function K(){return N>0}function F(t){C.push(t)}var Dt=0,xt=[];function gt(t){Dt>0?xt.push(t):t()}var x=class t{static _names=new WeakMap;static _kinds=new WeakMap;static _keys=new WeakMap;static _stores=new Set;static _edges=new Map;static _nextId=0;static _usedKeys=new Set;static _explicitEnabled=null;static _cachedDefault=null;static _annotations=new WeakMap;static _traceLog=[];static _traceHead=0;static _traceFull=!1;static maxTraceEntries=1e3;static get enabled(){if(t._explicitEnabled!==null)return t._explicitEnabled;if(t._cachedDefault!==null)return t._cachedDefault;try{t._cachedDefault=globalThis.process?.env?.NODE_ENV!=="production"}catch{t._cachedDefault=!0}return t._cachedDefault}static set enabled(e){t._explicitEnabled=e}static _depSuffix(e){if(!e?.length)return;let s=e.map(i=>t._names.get(i)??"?").join(",");return s.length>40?`${s.slice(0,37)}...`:s}static _resolveKey(e){let n=t._keys.get(e)??t._names.get(e);if(n)return n;let s=`anonymous_${t._nextId++}`;return t._keys.set(e,s),s}static register(e,n){if(!t.enabled)return;n?.name&&t._names.set(e,n.name),n?.kind&&t._kinds.set(e,n.kind);let s=t._nextId++,i=n?.name;if(!(i&&!t._usedKeys.has(i)))if(i){let r=t._depSuffix(n?.deps);i=r?`${i}(${r})`:`${i}_${s}`,t._usedKeys.has(i)&&(i=`${i}_${s}`)}else{let r=n?.kind??"store",o=t._depSuffix(n?.deps);i=o?`${r}(${o})`:`${r}_${s}`,t._usedKeys.has(i)&&(i=`${i}_${s}`)}t._usedKeys.add(i),t._keys.set(e,i),t._stores.add(new WeakRef(e))}static registerEdge(e,n){if(!t.enabled)return;let s=t._resolveKey(e),i=t._resolveKey(n),r=t._edges.get(s);r?r.includes(i)||r.push(i):t._edges.set(s,[i])}static getEdges(){return new Map(t._edges)}static getName(e){if(t.enabled)return t._names.get(e)}static getKind(e){return t._kinds.get(e)}static inspect(e){return{name:t._names.get(e),kind:t._kinds.get(e)??"unknown",value:typeof e.get=="function"?e.get():void 0,status:e._status}}static graph(){let e=new Map,n=new Set;for(let s of t._stores){let i=s.deref();if(!i){t._stores.delete(s);continue}let r=t._resolveKey(i);n.add(r),e.set(r,t.inspect(i))}for(let[s,i]of t._edges){if(!n.has(s)){t._edges.delete(s),t._usedKeys.delete(s);continue}let r=i.filter(o=>n.has(o));r.length===0?t._edges.delete(s):r.length!==i.length&&t._edges.set(s,r)}return e}static trace(e,n){let s=null,i=e.get();return e.source(b,(r,o)=>{if(r===b&&(s=o),r===p){s=null;return}if(r===1){let u=o;if(!Object.is(u,i)){let a=i;i=u,n(u,a)}}}),()=>s?.(p)}static dumpGraph(){let e=t.graph(),n=t.getEdges(),s=new Map;for(let[o,u]of n)for(let a of u){let d=s.get(a);d?d.includes(o)||d.push(o):s.set(a,[o])}let i=[];for(let[o,u]of e){let a=s.get(o),d=n.get(o),c=a?.length?` \u2190 [${a.join(", ")}]`:"",l=d?.length?` \u2192 [${d.join(", ")}]`:"";i.push(` ${o} (${u.kind}) = ${JSON.stringify(u.value)} [${u.status??"?"}]${c}${l}`)}return[`Store Graph (${e.size} nodes):`,...i].join(`
|
|
2
|
+
`)}static _observe(e,n,s){let i=null,r=n??t.getName(e),o={values:[],signals:[],events:[],ended:!1,endError:void 0,dirtyCount:0,resolvedCount:0,name:r,dispose:()=>i?.(p)};return e.source(b,(u,a)=>{if(u===b){i=a;return}u===T?(o.values.push(a),o.events.push({type:"data",data:a}),s&&s(`[${r}] DATA:`,a)):u===m?(o.signals.push(a),o.events.push({type:"signal",data:a}),a===v?o.dirtyCount++:a===j&&o.resolvedCount++,s&&s(`[${r}] STATE:`,a)):u===p&&(o.ended=!0,o.endError=a,o.events.push({type:"end",data:a}),s&&s(`[${r}] END`,a!==void 0?a:""),i=null)}),o}static observe(e){return t._observe(e)}static tap(e,n){let s=n??`tap(${t.getName(e)??"anon"})`,i={get:()=>e.get(),source:e.source};return t.register(i,{name:s,kind:"tap"}),t.registerEdge(e,i),i}static spy(e,n){let s=n?.name??t.getName(e)??"spy",i=n?.log??console.log;return t._observe(e,s,i)}static snapshot(){let e=t.graph(),n=t.getEdges(),s=new Map;for(let o of t._stores){let u=o.deref();if(!u)continue;let a=t._annotations.get(u);a!==void 0&&s.set(t._resolveKey(u),a)}let i=[];for(let[o,u]of e){let a={name:o,kind:u.kind,value:u.value,status:u.status},d=s.get(o);d!==void 0&&(a.annotation=d),i.push(a)}let r=[];for(let[o,u]of n)for(let a of u)r.push({from:o,to:a});return{nodes:i,edges:r,trace:t.traceLog()}}static toMermaid(e){let n=e?.direction??"TD",s=t.snapshot(),i=[`graph ${n}`],r={SETTLED:":::settled",DIRTY:":::dirty",ERRORED:":::errored",COMPLETED:":::completed"},o=new Map;function u(c){let l=c.replace(/[^a-zA-Z0-9_]/g,"_"),f=o.get(l);return f===void 0?(o.set(l,1),l):(o.set(l,f+1),`${l}__${f}`)}let a=new Map;function d(c){let l=JSON.stringify(c);return l&&l.length>30?`${l.slice(0,27)}...`:l??"undefined"}for(let c of s.nodes){let l=u(c.name);a.set(c.name,l);let f=`${c.name} (${c.kind}) = ${d(c.value)}`,w=r[c.status??""]??"";i.push(` ${l}["${f}"]${w}`)}for(let c of s.edges){let l=a.get(c.from)??u(c.from),f=a.get(c.to)??u(c.to);i.push(` ${l} --> ${f}`)}return i.push(""),i.push(" classDef settled fill:#d4edda,stroke:#28a745"),i.push(" classDef dirty fill:#fff3cd,stroke:#ffc107"),i.push(" classDef errored fill:#f8d7da,stroke:#dc3545"),i.push(" classDef completed fill:#cce5ff,stroke:#007bff"),i.join(`
|
|
3
|
+
`)}static toD2(e){let n=e?.direction??"down",s=t.snapshot(),i=[`direction: ${n}`,""],r={state:"rectangle",derived:"hexagon",effect:"oval",producer:"rectangle",operator:"parallelogram","pipeline-step":"rectangle","pipeline-status":"diamond",checkpoint:"cylinder"},o=new Map;function u(c){let l=c.replace(/[^a-zA-Z0-9_]/g,"_"),f=o.get(l);return f===void 0?(o.set(l,1),l):(o.set(l,f+1),`${l}__${f}`)}let a=new Map;function d(c){let l=JSON.stringify(c);return l&&l.length>30?`${l.slice(0,27)}...`:l??"undefined"}for(let c of s.nodes){let l=u(c.name);a.set(c.name,l);let f=r[c.kind]??"rectangle",w=`${c.name} (${c.kind}) = ${d(c.value)}`,$=c.status?` [${c.status}]`:"";i.push(`${l}: "${w}${$}" { shape: ${f} }`)}s.edges.length>0&&i.push("");for(let c of s.edges){let l=a.get(c.from)??u(c.from),f=a.get(c.to)??u(c.to);i.push(`${l} -> ${f}`)}return i.join(`
|
|
4
|
+
`)}static annotate(e,n){if(!t.enabled)return;t._annotations.set(e,n);let s={node:t._resolveKey(e),reason:n,timestamp:Date.now()},i=t.maxTraceEntries;i<=0||(t._traceLog.length<i?t._traceLog.push(s):(t._traceLog[t._traceHead]=s,t._traceFull=!0),t._traceHead=(t._traceHead+1)%i)}static getAnnotation(e){return t._annotations.get(e)}static traceLog(){return t._traceFull?[...t._traceLog.slice(t._traceHead),...t._traceLog.slice(0,t._traceHead)]:t._traceLog.slice(0,t._traceHead||t._traceLog.length)}static clearTrace(){t._traceLog=[],t._traceHead=0,t._traceFull=!1}static _reset(){t._names=new WeakMap,t._kinds=new WeakMap,t._keys=new WeakMap,t._stores=new Set,t._edges=new Map,t._usedKeys=new Set,t._nextId=0,t._explicitEnabled=null,t._cachedDefault=null,t._annotations=new WeakMap,t._traceLog=[],t._traceHead=0,t._traceFull=!1,t.maxTraceEntries=1e3}};var U=1,h=64,_=2,L=4,pt=8,ht=16,D=32,S=1024,g=B,R=at<<y,I=ct<<y,W=ot<<y,Lt=lt<<y,Rt=dt<<y,wt=ut<<y,Y=class{_value;_output=null;_flags;get _status(){return ft(this._flags)}_cleanup;_fn;_eqFn;_getterFn;_initial;_singleDepCount=0;constructor(e,n){this._value=n?.initial,this._fn=e,this._eqFn=n?.equals,this._getterFn=n?.getter,this._initial=n?.initial;let s=0;n?.autoDirty!==!1&&(s|=L),n?.resetOnTeardown&&(s|=pt),n?.resubscribable&&(s|=ht),this._flags=s,this.source=this.source.bind(this),this.emit=this.emit.bind(this),n?._skipInspect||x.register(this,{kind:"producer",...n})}get(){return this._getterFn?this._getterFn(this._value):this._value}_dispatch(e,n){let s=this._output;if(s)if(this._flags&h)for(let i of s)i(e,n);else s(e,n)}emit(e){this._flags&_||this._eqFn&&this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(K()?this._flags&D||(this._flags|=D,this._flags&L&&(this._flags=this._flags&~g|R,this._dispatch(m,v)),F(()=>{this._flags&=~D,this._flags=this._flags&~g|I,this._dispatch(T,this._value)})):(this._flags&L&&!(this._flags&S)&&(this._flags=this._flags&~g|R,this._dispatch(m,v)),this._flags=this._flags&~g|I,this._dispatch(T,this._value))))}signal(e){this._flags&_||!this._output||(e===v?this._flags=this._flags&~g|R:e===j&&(this._flags=this._flags&~g|wt),this._dispatch(m,e))}complete(){if(this._flags&_)return;this._flags=(this._flags|_)&~g|Lt;let e=this._output,n=this._flags&h;if(this._output=null,this._flags&=~(h|S),this._singleDepCount=0,this._stop(),e)if(n)for(let s of e)s(p);else e(p)}error(e){if(this._flags&_)return;this._flags=(this._flags|_)&~g|Rt;let n=this._output,s=this._flags&h;if(this._output=null,this._flags&=~(h|S),this._singleDepCount=0,this._stop(),n)if(s)for(let i of n)i(p,e);else n(p,e)}_start(){if(this._flags&U||!this._fn)return;this._flags|=U;let e=this._fn({emit:this.emit,signal:n=>this.signal(n),complete:()=>this.complete(),error:n=>this.error(n)});this._cleanup=typeof e=="function"?e:void 0}_stop(){this._flags&U&&(this._flags&=~U,this._cleanup&&this._cleanup(),this._cleanup=void 0,this._flags&pt&&(this._value=this._initial),this._flags&_||(this._flags=this._flags&~g|W))}source(e,n){if(e===b){let s=n;if(this._flags&_)if(this._flags&ht&&this._output===null)this._flags=this._flags&~(_|g)|W;else{s(b,r=>{}),s(p);return}if(this._output===null)this._output=s;else if(this._flags&h)this._output.add(s);else{let r=new Set;r.add(this._output),r.add(s),this._output=r,this._flags=(this._flags|h)&~S}let i=!1;s(b,(r,o)=>{if(r===T&&s(T,this._value),r===m&&o===rt&&!i&&(i=!0,this._singleDepCount++,this._flags&h||(this._flags|=S)),r===p){if(i&&(i=!1,this._singleDepCount--),this._output===null)return;if(this._flags&h){let u=this._output;u.delete(s),u.size===1?(this._output=u.values().next().value,this._flags&=~h,this._singleDepCount>0&&(this._flags|=S)):u.size===0&&(this._output=null,this._flags&=~(h|S),this._singleDepCount=0,this._flags=this._flags&~g|W,this._stop())}else this._output===s&&(this._output=null,this._flags&=~S,this._singleDepCount=0,this._flags=this._flags&~g|W,this._stop())}}),gt(()=>this._start())}}};var Z=class extends Y{constructor(e,n){super(void 0,{initial:e,autoDirty:!0,equals:n?.equals??Object.is,_skipInspect:!0}),this.set=this.set.bind(this),x.register(this,{kind:"state",...n})}get(){return this._value}set(e){this._flags&_||this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(K()?this._flags&D||(this._flags|=D,this._flags&L&&(this._flags=this._flags&~g|R,this._dispatch(m,v)),F(()=>{this._flags&=~D,this._flags=this._flags&~g|I,this._dispatch(T,this._value)})):(this._flags&L&&!(this._flags&S)&&(this._flags=this._flags&~g|R,this._dispatch(m,v)),this._flags=this._flags&~g|I,this._dispatch(T,this._value))))}update(e){this.set(e(this._value))}};function O(t,e){return new Z(t,e)}function $t(t){switch(t){case"openai":return"https://api.openai.com/v1";case"ollama":return"http://localhost:11434";default:return""}}function Mt(t,e){switch(t){case"openai":case"custom":return`${e}/chat/completions`;case"ollama":return`${e}/api/chat`;default:return`${e}/chat/completions`}}function It(t,e,n,s){let i={model:e,messages:n,stream:!0};return s?.temperature!==void 0&&(i.temperature=s.temperature),s?.maxTokens!==void 0&&(t==="ollama"?i.options={num_predict:s.maxTokens}:i.max_tokens=s.maxTokens),s?.stop&&(i.stop=s.stop),i}function Ot(t,e){let n={"Content-Type":"application/json"};return e&&(n.Authorization=`Bearer ${e}`),n}function At(t){let e=t.name??"llm",n=t.provider,s=t.baseURL??$t(n),i=t.model??"",r=t.fetch??globalThis.fetch,o=O("",{name:`${e}.store`}),u=O({},{name:`${e}.tokens`}),a=O("pending",{name:`${e}.status`}),d=O(void 0,{name:`${e}.error`}),c=null;function l(){c&&(c.abort(),c=null),a.get()==="active"&&a.set("pending")}function f($,M){l(),c=new AbortController;let V=M?.signal?Ct(c.signal,M.signal):c.signal;J(()=>{o.set(""),u.set({}),d.set(void 0),a.set("active")});let E=Mt(n,s),k=It(n,i,$,M),A=Ot(n,t.apiKey);w(E,A,k,V).catch(()=>{})}async function w($,M,V,E){try{let k=await r($,{method:"POST",headers:M,body:JSON.stringify(V),signal:E});if(!k.ok){let H=await k.text().catch(()=>"");throw new Error(`LLM API error ${k.status}: ${H}`)}let A=k.body?.getReader();if(!A)throw new Error("No response body");let Q=new TextDecoder,X="",G="";for(;;){if(E.aborted)return;let{done:H,value:_t}=await A.read();if(H)break;G+=Q.decode(_t,{stream:!0});let tt=G.split(`
|
|
5
|
+
`);G=tt.pop()??"";for(let Tt of tt){if(E.aborted)return;let P=Tt.trim();if(!P||P.startsWith(":")||!P.startsWith("data: "))continue;let et=P.slice(6);if(et!=="[DONE]")try{let nt=JSON.parse(et),st=Pt(n,nt);st&&(X+=st,o.set(X));let it=Nt(n,nt);it&&u.set(it)}catch{}}}if(Q.decode(),E.aborted)return;a.set("completed"),c=null}catch(k){if(E.aborted)return;J(()=>{d.set(k),a.set("errored")}),c=null}finally{E._cleanup?.()}}return{store:o,tokens:u,status:a,error:d,generate:f,abort:l}}function Pt(t,e){return t==="ollama"?e?.message?.content:e?.choices?.[0]?.delta?.content}function Nt(t,e){let n=t==="ollama"?e:e?.usage;if(n){if(t==="ollama")return e.eval_count!==void 0||e.prompt_eval_count!==void 0?{promptTokens:e.prompt_eval_count,completionTokens:e.eval_count,totalTokens:(e.prompt_eval_count??0)+(e.eval_count??0)}:void 0;if(n.prompt_tokens!==void 0||n.completion_tokens!==void 0)return{promptTokens:n.prompt_tokens,completionTokens:n.completion_tokens,totalTokens:n.total_tokens}}}function Ct(t,e){let n=new AbortController,s=()=>{t.removeEventListener("abort",i),e.removeEventListener("abort",i)},i=()=>{n.abort(),s()};t.addEventListener("abort",i,{once:!0}),e.addEventListener("abort",i,{once:!0});let r=n.signal;return r._cleanup=s,r}0&&(module.exports={fromLLM});
|