brass-runtime 1.4.6 → 1.5.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/README.md CHANGED
@@ -1,227 +1,139 @@
1
1
  # 🛠️ brass-runtime — Mini ZIO-like runtime in TypeScript
2
2
 
3
- A small experimental runtime inspired by ZIO 2, implemented in vanilla TypeScript and intentionally built without using `Promise` / `async`/`await` as the primary semantic primitive.
3
+ A small experimental runtime inspired by **ZIO 2**, implemented in vanilla TypeScript and intentionally built without using `Promise` / `async`/`await` as the primary semantic primitive.
4
4
 
5
- Goals: explore typed effects, structured concurrency, fibers, cooperative scheduling, resource safety and streams with backpressure — in a deterministic, pure-FP friendly way.
5
+ `brass-runtime` is the **foundation**: it provides the effect system, fibers, scheduler, scopes and streams.
6
+ Higher-level modules (HTTP, streaming utilities, integrations) are built **on top of this runtime**, not baked into it.
6
7
 
7
8
  ---
8
9
 
9
- ## Key ideas
10
-
11
- - Pure, sync core effect: `Effect<R, E, A>` and `Exit<E, A>`.
12
- - An algebraic representation for async work: `Async<R, E, A>` with an explicit interpreter (no `Promise` as runtime primitive).
13
- - A cooperative `Scheduler` for deterministic task interleaving and fairness.
14
- - Lightweight `Fiber`s with cooperative interruption, `join`, and LIFO finalizers.
15
- - Structured `Scope`s that manage child fibers, sub-scopes and finalizers; closing a scope cleans up children deterministically.
16
- - Resource-safe `acquireRelease` semantics (acquire + release tied to scope finalizers).
17
- - Structured concurrency combinators: `race`, `zipPar`, `collectAllPar`.
18
- - ZStream-style streams with backpressure, `Pull` semantics and resource safety.
10
+ ## Philosophy
19
11
 
12
+ - **Effects are values** — lazy, composable, referentially transparent
13
+ - **Async is explicit** — no hidden Promise semantics
14
+ - **Concurrency is structured** — fibers, scopes, finalizers
15
+ - **Side effects are interpreted** — not executed eagerly
16
+ - **Higher-level APIs are libraries, not magic**
20
17
 
18
+ If you like ZIO’s separation between `zio-core`, `zio-streams`, and `zio-http`, this project follows the same spirit.
21
19
 
22
20
  ---
23
21
 
24
- ## Getting Started
22
+ ## Core concepts (this package)
25
23
 
26
- 👉 [Read the Getting Started guide](./docs/getting-started.md)
24
+ - Pure, sync core effect: `Effect<R, E, A>` and `Exit<E, A>`
25
+ - Algebraic async representation: `Async<R, E, A>`
26
+ - Cooperative `Scheduler` for deterministic execution
27
+ - Lightweight `Fiber`s with interruption and finalizers
28
+ - Structured `Scope`s for resource safety
29
+ - ZStream-style streams with backpressure
27
30
 
28
31
  ---
29
32
 
30
- ## What's new (recent changes)
33
+ ## Modules built on top of brass-runtime
31
34
 
32
- - Implemented stream buffering primitives: `buffer` supports bounded buffering with backpressure semantics.
33
- - Added `fromPromiseAbortable` helper to integrate callback/Promise APIs that support `AbortSignal`, preserving cooperative cancellation.
34
- - Added `toPromise` for interop convenience (tests/examples use it to await results from the runtime).
35
- - New example: `src/examples/fromPromise.ts` — demonstrates creating a stream from abortable Promises and using `buffer` + `collectStream`.
36
- - Misc: tests and examples updated to exercise buffer modes and abortable integration.
35
+ These are **optional layers**, implemented using the runtime primitives.
37
36
 
38
- Branch containing recent work: `feature/buffer-pipes`.
37
+ ### 🌐 brass-http (HTTP client)
39
38
 
40
- ---
39
+ A ZIO-style HTTP client built on top of fibers and `Async`.
41
40
 
42
- ## Features (status)
41
+ - Lazy & cancelable HTTP requests
42
+ - No Promise-based semantics
43
+ - Explicit wire / content / metadata separation
44
+ - Middleware-friendly (logging, retry, timeout, etc.)
45
+ - Integrated with fiber interruption via `AbortController`
43
46
 
44
- - [x] Sync core: `Effect` (pure FP core)
45
- - [x] Async algebra: `Async` (no Promises in semantics)
46
- - [x] Cooperative `Scheduler`
47
- - [x] Fibers with LIFO finalizers and interruption
48
- - [x] `Scope` (structured concurrency and finalizers)
49
- - [x] `acquireRelease` / resource safety
50
- - [x] Structured concurrency: `race`, `zipPar`, `collectAllPar`
51
- - [x] ZStream-like core (pull-based, resource-aware)
52
- - [x] Buffering in streams (bounded/backpressure modes)
53
- - [x] Merge / zipPar of streams
54
- - [ ] Hubs / Broadcast / Multicast
55
- - [ ] Pipelines (`ZPipeline`-style)
56
- - [ ] Advanced Channels / Sinks
47
+ 👉 **Read the HTTP module docs:**
48
+ ➡️ [`src/http/README.md`](./src/http/README.md)
57
49
 
58
- ---
50
+ Example:
51
+ ```ts
52
+ const http = httpClient({
53
+ baseUrl: "https://jsonplaceholder.typicode.com",
54
+ });
59
55
 
60
- ## API highlights
56
+ const post = await toPromise(
57
+ http.getJson<Post>("/posts/1"),
58
+ {}
59
+ );
60
+ ```
61
61
 
62
- Core types
63
- - `type Exit<E, A> = Success | Failure`
64
- - `type Effect<R, E, A> = (env: R) => Exit<E, A>`
65
- - `type Async<R, E, A> = Succeed | Fail | Sync | Async | FlatMap`
62
+ ---
66
63
 
67
- Async constructors
68
- - `asyncSucceed`, `asyncFail`, `asyncSync`, `asyncTotal`
69
- - `async` primitive for callback integration
70
- - `asyncMap`, `asyncFlatMap`
71
- - `fromPromiseAbortable` — integrate APIs that accept `AbortSignal` and support cooperative cancellation
64
+ ### 🌊 Streams (ZStream-like)
72
65
 
73
- Fibers / Concurrency
74
- - `Fiber<E, A>`: `id`, `status()`, `join(cb)`, `interrupt()`, `addFinalizer(...)`
75
- - `Scheduler.schedule(task: () => void)`
76
- - `race`, `zipPar`, `collectAllPar` — structured concurrency semantics
66
+ Pull-based, resource-aware streams with backpressure.
77
67
 
78
- Scopes & Resource safety
79
- - `class Scope<R>`: `fork`, `subScope`, `addFinalizer`, `close`, `isClosed`
80
- - `acquireRelease(acquire, release, scope)`
68
+ - `ZStream<R, E, A>`
69
+ - `Pull` semantics
70
+ - Bounded buffers
71
+ - Deterministic resource cleanup
81
72
 
82
- Streams (ZStream-like)
83
- - `type Pull<R, E, A> = Async<R, Option<E>, A>`
84
- - `type ZStream<R, E, A> = { open: (scope: Scope<R>) => Pull<R, E, A> }`
85
- - Constructors: `empty`, `streamOf`, `fromArray`, `fromPull`
86
- - Transformations: `map`, `filter`, `fromResource`
87
- - Buffering: `buffer(stream, capacity, mode)` — bounded buffer with backpressure or dropping modes
88
- - Interop: `collectStream`, `runCollect`, `toPromise` for awaiting results in examples
73
+ Examples:
74
+ - `src/examples/fromPromise.ts`
75
+ - `src/examples/mergeStreamSync.ts`
89
76
 
90
77
  ---
91
78
 
92
- ## Example (what to look at)
93
-
94
- See `src/examples/fromPromise.ts`:
95
- - Shows `fromPromiseAbortable` producing stream elements with cooperative cancellation.
96
- - Demonstrates `buffer` with a bounded capacity and backpressure semantics.
97
- - Uses `collectStream` + `toPromise` to gather stream output in an example-run friendly way.
79
+ ## Getting Started
98
80
 
99
- Do not copy the example here — open `src/examples/fromPromise.ts` for details.
81
+ 👉 **Start here:**
82
+ ➡️ [Getting Started](./docs/getting-started.md)
100
83
 
101
84
  ---
102
85
 
103
- ## Running examples and tests
104
-
105
- - Use your editor's run configuration (WebStorm 2025.3.1 recommended) or run with `ts-node` for quick iteration.
106
- - Typical flow:
107
- - Install deps: `npm install`
108
- - Run an example directly: `npx ts-node src/examples/fromPromise.ts` (or configure a Node run config that compiles first)
109
- - Build: `npm run build` → run compiled files from `dist/`
110
-
111
- Adjust the commands to your preferred setup. The project intentionally leaves runtime execution flexible (ts-node, esbuild, tsc + node, etc.).
112
-
113
-
114
- ## Examples — abortable Promises (DX)
115
-
116
- Below are small, copy-pasteable examples showing how to use the abortable helpers: `tryPromiseAbortable` and `fromPromiseAbortable`. Use these snippets in examples or docs to demonstrate typical flows: plain signal, env+signal, custom error mapping and cancellation.
117
-
118
- ### 1) Signal-only thunk (uses `tryPromiseAbortable`)
119
- ```typescript
120
- import { tryPromiseAbortable, toPromise, fork } from './src/asyncEffect';
121
-
122
- // A thunk that only expects an AbortSignal
123
- const fetchUser = tryPromiseAbortable(async (signal: AbortSignal) => {
124
- const res = await fetch('https://jsonplaceholder.typicode.com/users/1', { signal });
125
- if (!res.ok) throw new Error('HTTP ' + res.status);
126
- return await res.json();
127
- });
128
-
129
- async function example() {
130
- // Await via runtime helper toPromise (env = {})
131
- try {
132
- const user = await toPromise(fetchUser, {});
133
- console.log('user', user);
134
- } catch (err) {
135
- console.error('failed', err);
136
- }
137
- }
138
-
139
- // Cancellation example using fork + interrupt
140
- function cancelExample() {
141
- const fiber = fork(fetchUser as any, {}); // fork returns a Fiber
142
- setTimeout(() => {
143
- fiber.interrupt(); // will abort the underlying fetch via AbortController
144
- console.log('interrupt requested');
145
- }, 50);
146
- }
147
- ```
86
+ ## What’s new (recent changes)
148
87
 
88
+ - Stream buffering with backpressure (`buffer`)
89
+ - Abortable async integration (`fromPromiseAbortable`)
90
+ - Fiber-safe `toPromise` for examples & DX
91
+ - New HTTP module (`brass-http`) built on top of the runtime
149
92
 
150
- ### 2) Env + signal thunk (uses `fromPromiseAbortable`)
151
- ```typescript
152
- import { tryPromiseAbortable, toPromise } from './src/asyncEffect';
153
-
154
- type Env = { baseUrl: string };
155
-
156
- const fetchWithEnv = tryPromiseAbortable<Env, any>((env, signal) =>
157
- fetch(`${env.baseUrl}/users/1`, { signal }).then((r) => {
158
- if (!r.ok) throw new Error('HTTP ' + r.status);
159
- return r.json();
160
- })
161
- );
162
-
163
- async function runEnv() {
164
- const env: Env = { baseUrl: 'https://jsonplaceholder.typicode.com' };
165
- try {
166
- const user = await toPromise(fetchWithEnv, env);
167
- console.log('user with env', user);
168
- } catch (e) {
169
- console.error('error', e);
170
- }
171
- }
172
-
173
- ```
174
-
175
- ### 3) Custom error mapping with fromPromiseAbortable
176
- ```typescript
177
- import { fromPromiseAbortable, toPromise } from './src/asyncEffect';
93
+ ---
178
94
 
179
- // Map any rejection (including non-abort) to a custom error shape
180
- const safeFetch = fromPromiseAbortable(
181
- (signal: AbortSignal) => fetch('https://example.com/data', { signal }).then((r) => r.json()),
182
- (e) => ({ kind: 'FetchError', detail: String(e) })
183
- );
95
+ ## Features (status)
184
96
 
185
- async function runSafe() {
186
- try {
187
- const data = await toPromise(safeFetch, {});
188
- console.log('data', data);
189
- } catch (err) {
190
- console.error('mapped error', err);
191
- }
192
- }
193
- ```
194
- ---
97
+ ### Runtime (core)
98
+ - [x] Sync core: `Effect`
99
+ - [x] Async algebra: `Async`
100
+ - [x] Cooperative `Scheduler`
101
+ - [x] Fibers with interruption & finalizers
102
+ - [x] Structured `Scope`
103
+ - [x] Resource safety (`acquireRelease`)
104
+
105
+ ### Concurrency & Streams
106
+ - [x] `race`, `zipPar`, `collectAllPar`
107
+ - [x] ZStream-like core
108
+ - [x] Bounded buffers & backpressure
109
+ - [x] Stream merge / zip
110
+ - [ ] Hubs / Broadcast
111
+ - [ ] Pipelines (`ZPipeline`-style)
195
112
 
196
- ## Project structure (recommended)
197
- Examples:
198
- - `src/examples/fromPromise.ts` (abortable promise -> stream + buffer)
199
- - `src/examples/resourceExample.ts` (acquire/release + scope)
200
- - `src/examples/fiberFinalizer.ts` (fiber finalizer LIFO semantics)
113
+ ### Libraries
114
+ - [x] HTTP client (`brass-http`)
115
+ - [ ] Retry / timeout middleware
116
+ - [ ] Logging / metrics layers
201
117
 
202
118
  ---
203
119
 
204
120
  ## Design notes
205
121
 
206
- - Determinism: scheduling is explicit and testable via the cooperative `Scheduler`.
207
- - No hidden `Promise` semantics: the runtime models async as an algebraic datatype with an explicit interpreter.
208
- - Resource safety is structural scopes tie resource lifetimes to lexical structure, ensuring deterministic cleanup.
209
- - Streaming model uses pull-based backpressure; buffering is explicit and configurable.
122
+ - **No hidden Promises**: async is always modeled explicitly
123
+ - **Deterministic execution**: scheduler is observable & testable
124
+ - **Resource safety is structural**: scopes guarantee cleanup
125
+ - **Libraries compose via functions**: middleware, not inheritance
210
126
 
211
127
  ---
212
128
 
213
129
  ## Contributing
214
130
 
215
- - Branch for current work: `feature/buffer-pipes`.
216
- - Open issues / PRs welcome. Aim for small, focused PRs that preserve the runtime invariants (no hidden Promise semantics).
217
- - Tests should exercise scheduling determinism, interruption guarantees and resource cleanup.
131
+ - Runtime invariants matter avoid sneaking Promises into semantics
132
+ - Prefer libraries on top of the runtime over changes in the core
133
+ - Small, focused PRs are welcome
218
134
 
219
135
  ---
220
136
 
221
137
  ## License
222
138
 
223
139
  MIT License © 2025
224
-
225
- ---
226
-
227
- If you need the README translated to Spanish or a trimmed/expanded version for npm package metadata, a shorter project landing page, or a CHANGELOG entry for the branch `feature/buffer-pipes`, provide the preference and a target audience.
@@ -1 +1 @@
1
- function p(n,e,t){return {_tag:"Fold",first:n,onFailure:e,onSuccess:t}}function x(n,e){return p(n,t=>e(t),t=>d(t))}function F(n,e){return p(n,t=>R(e(t)),t=>d(t))}function k(){return y(()=>{})}var d=n=>({_tag:"Succeed",value:n}),R=n=>({_tag:"Fail",error:n}),y=n=>({_tag:"Sync",thunk:n}),_=n=>y(()=>n()),l=n=>({_tag:"Async",register:n});function N(n,e){return E(n,t=>d(e(t)))}function E(n,e){return {_tag:"FlatMap",first:n,andThen:e}}function q(n,e,t){return E(n,r=>(t.addFinalizer(o=>e(r,o)),d(r)))}function D(n){return l(n)}var f=class{queue=[];flushing=false;requested=false;schedule(e,t="anonymous"){if(console.log("[Scheduler.schedule] typeof task =",typeof e,"tag=",t),typeof e!="function"){console.error("[Scheduler.schedule] NON-FUNCTION TASK!",{tag:t,task:e});return}this.queue.push({tag:t,task:e}),this.requestFlush(),console.log("SCHEDULER",{flushing:this.flushing,q:this.queue.length,next:this.queue[0]?.tag,head:this.queue.slice(0,5).map(r=>r.tag)});}requestFlush(){console.log("requestFlush",{flushing:this.flushing,requested:this.requested,q:this.queue.length}),!this.flushing&&(this.requested||(this.requested=true,queueMicrotask(()=>{console.log(">> microtask fired",{flushing:this.flushing,requested:this.requested,q:this.queue.length}),this.flush();})));}flush(){if(console.log("FLUSH enter",{flushing:this.flushing,requested:this.requested,q:this.queue.length}),!this.flushing){this.flushing=true,this.requested=false;try{for(;this.queue.length>0;){let e=this.queue.shift();console.log("[flush] dequeued",{tag:e.tag,typeofTask:typeof e.task});try{console.log("TASK typeof",typeof e.task),e.task();}catch(t){console.error("[flush] task threw",t);}}}finally{this.flushing=false,console.log("FLUSH exit",{requested:this.requested,q:this.queue.length}),this.queue.length>0&&this.requestFlush();}}}},g=new f;var u={CONTINUE:"Continue",SUSPEND:"Suspend",DONE:"Done"},c={QUEUED:"Queued",RUNNING:"Running",SUSPENDED:"Suspended",DONE:"Done"},S=1,A=class{constructor(e,t,r){this.scheduler=r;this.id=S++,this.current=e,this.env=t;}id;closing=null;finishing=false;runState=c.RUNNING;interrupted=false;result=null;joiners=[];current;env;stack=[];fiberFinalizers=[];finalizersDrained=false;addFinalizer(e){this.fiberFinalizers.push(e);}status(){return this.result==null?"Running":this.interrupted?"Interrupted":"Done"}join(e){this.result!=null?e(this.result):this.joiners.push(e);}interrupt(){this.result==null&&(this.interrupted||(this.interrupted=true,this.schedule("interrupt-step")));}schedule(e="step"){console.log("[fiber.schedule]",{fiber:this.id,tag:e,runState:this.runState,schedulerCtor:this.scheduler?.constructor?.name,schedulerScheduleType:typeof this.scheduler?.schedule}),!(this.runState===c.DONE||this.runState===c.QUEUED)&&(this.runState=c.QUEUED,this.scheduler.schedule(()=>{if(console.log("[fiber.task] running",this.id),this.runState===c.DONE)return;switch(this.runState=c.RUNNING,this.step()){case u.CONTINUE:this.schedule("continue");return;case u.SUSPEND:this.runState=c.SUSPENDED;return;case u.DONE:this.runState=c.DONE;return}},`fiber#${this.id}.${e}`));}runFinalizersOnce(e){if(!this.finalizersDrained)for(this.finalizersDrained=true;this.fiberFinalizers.length>0;){let t=this.fiberFinalizers.pop();try{t(e);}catch{}}}notify(e){if(this.result==null&&this.closing==null){this.finishing=true,this.closing=e,this.runFinalizersOnce(e),this.result=e;for(let t of this.joiners)t(e);this.joiners.length=0;}}onSuccess(e){let t=this.stack.pop();if(!t){this.notify({_tag:"Success",value:e});return}this.current=t._tag==="SuccessCont"?t.k(e):t.onSuccess(e);}onFailure(e){for(;this.stack.length>0;){let t=this.stack.pop();if(t._tag==="FoldCont"){this.current=t.onFailure(e);return}}this.notify({_tag:"Failure",error:e});}step(){console.log("[fiber.step] enter",{fiber:this.id,current:this.current?._tag,result:this.result!=null,interrupted:this.interrupted,closing:this.closing!=null,finishing:this.finishing,stack:this.stack.length});let e=u.CONTINUE;if(this.result!=null)return e=u.DONE,e;if(this.interrupted&&this.closing==null)return console.log("[fiber.step] interrupted: failing now",{fiber:this.id}),this.notify({_tag:"Failure",error:{_tag:"Interrupted"}}),e=u.DONE,e;let t=this.current;switch(t._tag){case "Succeed":{console.log("[fiber.step] Succeed",{fiber:this.id}),this.onSuccess(t.value);break}case "Fail":{console.log("[fiber.step] Fail",{fiber:this.id}),this.onFailure(t.error);break}case "Sync":{console.log("[fiber.step] Sync",{fiber:this.id});try{let r=t.thunk(this.env);console.log("[fiber.step] Sync success",{fiber:this.id}),this.onSuccess(r);}catch(r){console.log("[fiber.step] Sync threw",{fiber:this.id,e:r}),this.onFailure(r);}break}case "FlatMap":{console.log("[fiber.step] FlatMap push cont",{fiber:this.id}),this.stack.push({_tag:"SuccessCont",k:t.andThen}),this.current=t.first;break}case "Fold":{console.log("[fiber.step] Fold push cont",{fiber:this.id}),this.stack.push({_tag:"FoldCont",onFailure:t.onFailure,onSuccess:t.onSuccess}),this.current=t.first;break}case "Async":{if(this.finishing)break;let r=false,o=s=>{if(!(this.result!=null||this.closing!=null)){if(this.interrupted){this.onFailure({_tag:"Interrupted"});return}s._tag==="Success"?this.onSuccess(s.value):this.onFailure(s.error),this.schedule("async-resume");}},i=s=>{r||(r=true,this.scheduler.schedule(()=>o(s),`fiber#${this.id}.async-resume`));},a=t.register(this.env,i);typeof a=="function"&&this.addFinalizer(()=>{r=true;try{a();}catch{}}),e=u.SUSPEND;break}}return this.result!=null&&(e=u.DONE),e}};function M(n){return l((e,t)=>{let r=false,o=s=>{r||(r=true,t(s));},i=s=>o({_tag:"Failure",error:s instanceof Error?s:new Error(String(s))}),a=s=>o({_tag:"Success",value:s});try{typeof n=="function"&&n.length>=1?n((s,h)=>s?i(s):a(h)):n().then(a,i);}catch(s){i(s);}})}function b(n,e,t=g){let r=new A(n,e,t);return r.schedule("initial-step"),r}function Q(n,e,t){b(n,e).join(t);}function G(n,e){return new Promise((t,r)=>{b(n,e).join(i=>{let a=i;a._tag==="Success"?t(a.value):r(a.error);});})}function H(n,e){return l((t,r)=>{n(t).then(o=>r({_tag:"Success",value:o})).catch(o=>r({_tag:"Failure",error:e(o)}));})}function L(n){return l((e,t)=>{let r=false,o=i=>{r||(r=true,t(i));};try{n((i,a)=>{o(i?{_tag:"Failure",error:i}:{_tag:"Success",value:a});});}catch(i){o({_tag:"Failure",error:i instanceof Error?i:new Error(String(i))});}})}function $(n){return v((t,r)=>n.length===1?n(r):n(t,r),t=>m(t)?{_tag:"Abort"}:{_tag:"PromiseRejected",reason:t})}function v(n,e){return l((t,r)=>{let o=new AbortController,i=false,a=s=>{i||(i=true,r(s));};try{(n.length===1?n(o.signal):n(t,o.signal)).then(h=>a({_tag:"Success",value:h})).catch(h=>a({_tag:"Failure",error:e(h)}));}catch(s){a({_tag:"Failure",error:e(s)});}return ()=>{i=true,o.abort();}})}var m=n=>typeof n=="object"&&n!==null&&"name"in n&&n.name==="AbortError";export{p as a,x as b,F as c,k as d,d as e,R as f,y as g,_ as h,l as i,N as j,E as k,q as l,D as m,f as n,g as o,A as p,M as q,b as r,Q as s,G as t,H as u,L as v,$ as w,v as x};
1
+ function p(n,e,t){return {_tag:"Fold",first:n,onFailure:e,onSuccess:t}}function x(n,e){return p(n,t=>e(t),t=>d(t))}function F(n,e){return p(n,t=>S(e(t)),t=>d(t))}function k(){return y(()=>{})}var d=n=>({_tag:"Succeed",value:n}),S=n=>({_tag:"Fail",error:n}),y=n=>({_tag:"Sync",thunk:n}),_=n=>y(()=>n()),l=n=>({_tag:"Async",register:n});function N(n,e){return E(n,t=>d(e(t)))}function E(n,e){return {_tag:"FlatMap",first:n,andThen:e}}function q(n,e,t){return E(n,r=>(t.addFinalizer(o=>e(r,o)),d(r)))}function w(n){return l(n)}var f=class{queue=[];flushing=false;requested=false;schedule(e,t="anonymous"){if(console.log("[Scheduler.schedule] typeof task =",typeof e,"tag=",t),typeof e!="function"){console.error("[Scheduler.schedule] NON-FUNCTION TASK!",{tag:t,task:e});return}this.queue.push({tag:t,task:e}),this.requestFlush(),console.log("SCHEDULER",{flushing:this.flushing,q:this.queue.length,next:this.queue[0]?.tag,head:this.queue.slice(0,5).map(r=>r.tag)});}requestFlush(){console.log("requestFlush",{flushing:this.flushing,requested:this.requested,q:this.queue.length}),!this.flushing&&(this.requested||(this.requested=true,queueMicrotask(()=>{console.log(">> microtask fired",{flushing:this.flushing,requested:this.requested,q:this.queue.length}),this.flush();})));}flush(){if(console.log("FLUSH enter",{flushing:this.flushing,requested:this.requested,q:this.queue.length}),!this.flushing){this.flushing=true,this.requested=false;try{for(;this.queue.length>0;){let e=this.queue.shift();console.log("[flush] dequeued",{tag:e.tag,typeofTask:typeof e.task});try{console.log("TASK typeof",typeof e.task),e.task();}catch(t){console.error("[flush] task threw",t);}}}finally{this.flushing=false,console.log("FLUSH exit",{requested:this.requested,q:this.queue.length}),this.queue.length>0&&this.requestFlush();}}}},g=new f;var u={CONTINUE:"Continue",SUSPEND:"Suspend",DONE:"Done"},c={QUEUED:"Queued",RUNNING:"Running",SUSPENDED:"Suspended",DONE:"Done"},R=1,A=class{constructor(e,t,r){this.scheduler=r;this.id=R++,this.current=e,this.env=t;}id;closing=null;finishing=false;runState=c.RUNNING;interrupted=false;result=null;joiners=[];current;env;stack=[];fiberFinalizers=[];finalizersDrained=false;addFinalizer(e){this.fiberFinalizers.push(e);}status(){return this.result==null?"Running":this.interrupted?"Interrupted":"Done"}join(e){this.result!=null?e(this.result):this.joiners.push(e);}interrupt(){this.result==null&&(this.interrupted||(this.interrupted=true,this.schedule("interrupt-step")));}schedule(e="step"){console.log("[fiber.schedule]",{fiber:this.id,tag:e,runState:this.runState,schedulerCtor:this.scheduler?.constructor?.name,schedulerScheduleType:typeof this.scheduler?.schedule}),!(this.runState===c.DONE||this.runState===c.QUEUED)&&(this.runState=c.QUEUED,this.scheduler.schedule(()=>{if(console.log("[fiber.task] running",this.id),this.runState===c.DONE)return;switch(this.runState=c.RUNNING,this.step()){case u.CONTINUE:this.schedule("continue");return;case u.SUSPEND:this.runState=c.SUSPENDED;return;case u.DONE:this.runState=c.DONE;return}},`fiber#${this.id}.${e}`));}runFinalizersOnce(e){if(!this.finalizersDrained)for(this.finalizersDrained=true;this.fiberFinalizers.length>0;){let t=this.fiberFinalizers.pop();try{t(e);}catch{}}}notify(e){if(this.result==null&&this.closing==null){this.finishing=true,this.closing=e,this.runFinalizersOnce(e),this.result=e;for(let t of this.joiners)t(e);this.joiners.length=0;}}onSuccess(e){let t=this.stack.pop();if(!t){this.notify({_tag:"Success",value:e});return}this.current=t._tag==="SuccessCont"?t.k(e):t.onSuccess(e);}onFailure(e){for(;this.stack.length>0;){let t=this.stack.pop();if(t._tag==="FoldCont"){this.current=t.onFailure(e);return}}this.notify({_tag:"Failure",error:e});}step(){console.log("[fiber.step] enter",{fiber:this.id,current:this.current?._tag,result:this.result!=null,interrupted:this.interrupted,closing:this.closing!=null,finishing:this.finishing,stack:this.stack.length});let e=u.CONTINUE;if(this.result!=null)return e=u.DONE,e;if(this.interrupted&&this.closing==null)return console.log("[fiber.step] interrupted: failing now",{fiber:this.id}),this.notify({_tag:"Failure",error:{_tag:"Interrupted"}}),e=u.DONE,e;let t=this.current;switch(t._tag){case "Succeed":{console.log("[fiber.step] Succeed",{fiber:this.id}),this.onSuccess(t.value);break}case "Fail":{console.log("[fiber.step] Fail",{fiber:this.id}),this.onFailure(t.error);break}case "Sync":{console.log("[fiber.step] Sync",{fiber:this.id});try{let r=t.thunk(this.env);console.log("[fiber.step] Sync success",{fiber:this.id}),this.onSuccess(r);}catch(r){console.log("[fiber.step] Sync threw",{fiber:this.id,e:r}),this.onFailure(r);}break}case "FlatMap":{console.log("[fiber.step] FlatMap push cont",{fiber:this.id}),this.stack.push({_tag:"SuccessCont",k:t.andThen}),this.current=t.first;break}case "Fold":{console.log("[fiber.step] Fold push cont",{fiber:this.id}),this.stack.push({_tag:"FoldCont",onFailure:t.onFailure,onSuccess:t.onSuccess}),this.current=t.first;break}case "Async":{if(this.finishing)break;let r=false,i=s=>{r||(r=true,this.scheduler.schedule(()=>{this.result!=null||this.closing!=null||(this.current=s._tag==="Success"?{_tag:"Succeed",value:s.value}:{_tag:"Fail",error:s.error},this.schedule("async-resume"));},`fiber#${this.id}.async-wakeup`));},a=t.register(this.env,i);typeof a=="function"&&this.addFinalizer(()=>{r=true;try{a();}catch{}}),e=u.SUSPEND;break}}return this.result!=null&&(e=u.DONE),e}};function M(n){return l((e,t)=>{let r=false,o=s=>{r||(r=true,t(s));},i=s=>o({_tag:"Failure",error:s instanceof Error?s:new Error(String(s))}),a=s=>o({_tag:"Success",value:s});try{typeof n=="function"&&n.length>=1?n((s,h)=>s?i(s):a(h)):n().then(a,i);}catch(s){i(s);}})}function b(n,e,t=g){let r=new A(n,e,t);return r.schedule("initial-step"),r}function Q(n,e,t){b(n,e).join(t);}function G(n,e){return new Promise((t,r)=>{b(n,e).join(i=>{let a=i;a._tag==="Success"?t(a.value):r(a.error);});})}function H(n,e){return l((t,r)=>{n(t).then(o=>r({_tag:"Success",value:o})).catch(o=>r({_tag:"Failure",error:e(o)}));})}function L(n){return l((e,t)=>{let r=false,o=i=>{r||(r=true,t(i));};try{n((i,a)=>{o(i?{_tag:"Failure",error:i}:{_tag:"Success",value:a});});}catch(i){o({_tag:"Failure",error:i instanceof Error?i:new Error(String(i))});}})}function $(n){return v((t,r)=>n.length===1?n(r):n(t,r),t=>m(t)?{_tag:"Abort"}:{_tag:"PromiseRejected",reason:t})}function v(n,e){return l((t,r)=>{let o=new AbortController,i=false,a=s=>{i||(i=true,r(s));};try{(n.length===1?n(o.signal):n(t,o.signal)).then(h=>a({_tag:"Success",value:h})).catch(h=>a({_tag:"Failure",error:e(h)}));}catch(s){a({_tag:"Failure",error:e(s)});}return ()=>{i=true,o.abort();}})}var m=n=>typeof n=="object"&&n!==null&&"name"in n&&n.name==="AbortError";export{p as a,x as b,F as c,k as d,d as e,S as f,y as g,_ as h,l as i,N as j,E as k,q as l,w as m,f as n,g as o,A as p,M as q,b as r,Q as s,G as t,H as u,L as v,$ as w,v as x};
@@ -1 +1 @@
1
- 'use strict';function p(n,e,t){return {_tag:"Fold",first:n,onFailure:e,onSuccess:t}}function x(n,e){return p(n,t=>e(t),t=>d(t))}function F(n,e){return p(n,t=>R(e(t)),t=>d(t))}function k(){return y(()=>{})}var d=n=>({_tag:"Succeed",value:n}),R=n=>({_tag:"Fail",error:n}),y=n=>({_tag:"Sync",thunk:n}),_=n=>y(()=>n()),l=n=>({_tag:"Async",register:n});function N(n,e){return E(n,t=>d(e(t)))}function E(n,e){return {_tag:"FlatMap",first:n,andThen:e}}function q(n,e,t){return E(n,r=>(t.addFinalizer(o=>e(r,o)),d(r)))}function D(n){return l(n)}var f=class{queue=[];flushing=false;requested=false;schedule(e,t="anonymous"){if(console.log("[Scheduler.schedule] typeof task =",typeof e,"tag=",t),typeof e!="function"){console.error("[Scheduler.schedule] NON-FUNCTION TASK!",{tag:t,task:e});return}this.queue.push({tag:t,task:e}),this.requestFlush(),console.log("SCHEDULER",{flushing:this.flushing,q:this.queue.length,next:this.queue[0]?.tag,head:this.queue.slice(0,5).map(r=>r.tag)});}requestFlush(){console.log("requestFlush",{flushing:this.flushing,requested:this.requested,q:this.queue.length}),!this.flushing&&(this.requested||(this.requested=true,queueMicrotask(()=>{console.log(">> microtask fired",{flushing:this.flushing,requested:this.requested,q:this.queue.length}),this.flush();})));}flush(){if(console.log("FLUSH enter",{flushing:this.flushing,requested:this.requested,q:this.queue.length}),!this.flushing){this.flushing=true,this.requested=false;try{for(;this.queue.length>0;){let e=this.queue.shift();console.log("[flush] dequeued",{tag:e.tag,typeofTask:typeof e.task});try{console.log("TASK typeof",typeof e.task),e.task();}catch(t){console.error("[flush] task threw",t);}}}finally{this.flushing=false,console.log("FLUSH exit",{requested:this.requested,q:this.queue.length}),this.queue.length>0&&this.requestFlush();}}}},g=new f;var u={CONTINUE:"Continue",SUSPEND:"Suspend",DONE:"Done"},c={QUEUED:"Queued",RUNNING:"Running",SUSPENDED:"Suspended",DONE:"Done"},S=1,A=class{constructor(e,t,r){this.scheduler=r;this.id=S++,this.current=e,this.env=t;}id;closing=null;finishing=false;runState=c.RUNNING;interrupted=false;result=null;joiners=[];current;env;stack=[];fiberFinalizers=[];finalizersDrained=false;addFinalizer(e){this.fiberFinalizers.push(e);}status(){return this.result==null?"Running":this.interrupted?"Interrupted":"Done"}join(e){this.result!=null?e(this.result):this.joiners.push(e);}interrupt(){this.result==null&&(this.interrupted||(this.interrupted=true,this.schedule("interrupt-step")));}schedule(e="step"){console.log("[fiber.schedule]",{fiber:this.id,tag:e,runState:this.runState,schedulerCtor:this.scheduler?.constructor?.name,schedulerScheduleType:typeof this.scheduler?.schedule}),!(this.runState===c.DONE||this.runState===c.QUEUED)&&(this.runState=c.QUEUED,this.scheduler.schedule(()=>{if(console.log("[fiber.task] running",this.id),this.runState===c.DONE)return;switch(this.runState=c.RUNNING,this.step()){case u.CONTINUE:this.schedule("continue");return;case u.SUSPEND:this.runState=c.SUSPENDED;return;case u.DONE:this.runState=c.DONE;return}},`fiber#${this.id}.${e}`));}runFinalizersOnce(e){if(!this.finalizersDrained)for(this.finalizersDrained=true;this.fiberFinalizers.length>0;){let t=this.fiberFinalizers.pop();try{t(e);}catch{}}}notify(e){if(this.result==null&&this.closing==null){this.finishing=true,this.closing=e,this.runFinalizersOnce(e),this.result=e;for(let t of this.joiners)t(e);this.joiners.length=0;}}onSuccess(e){let t=this.stack.pop();if(!t){this.notify({_tag:"Success",value:e});return}this.current=t._tag==="SuccessCont"?t.k(e):t.onSuccess(e);}onFailure(e){for(;this.stack.length>0;){let t=this.stack.pop();if(t._tag==="FoldCont"){this.current=t.onFailure(e);return}}this.notify({_tag:"Failure",error:e});}step(){console.log("[fiber.step] enter",{fiber:this.id,current:this.current?._tag,result:this.result!=null,interrupted:this.interrupted,closing:this.closing!=null,finishing:this.finishing,stack:this.stack.length});let e=u.CONTINUE;if(this.result!=null)return e=u.DONE,e;if(this.interrupted&&this.closing==null)return console.log("[fiber.step] interrupted: failing now",{fiber:this.id}),this.notify({_tag:"Failure",error:{_tag:"Interrupted"}}),e=u.DONE,e;let t=this.current;switch(t._tag){case "Succeed":{console.log("[fiber.step] Succeed",{fiber:this.id}),this.onSuccess(t.value);break}case "Fail":{console.log("[fiber.step] Fail",{fiber:this.id}),this.onFailure(t.error);break}case "Sync":{console.log("[fiber.step] Sync",{fiber:this.id});try{let r=t.thunk(this.env);console.log("[fiber.step] Sync success",{fiber:this.id}),this.onSuccess(r);}catch(r){console.log("[fiber.step] Sync threw",{fiber:this.id,e:r}),this.onFailure(r);}break}case "FlatMap":{console.log("[fiber.step] FlatMap push cont",{fiber:this.id}),this.stack.push({_tag:"SuccessCont",k:t.andThen}),this.current=t.first;break}case "Fold":{console.log("[fiber.step] Fold push cont",{fiber:this.id}),this.stack.push({_tag:"FoldCont",onFailure:t.onFailure,onSuccess:t.onSuccess}),this.current=t.first;break}case "Async":{if(this.finishing)break;let r=false,o=s=>{if(!(this.result!=null||this.closing!=null)){if(this.interrupted){this.onFailure({_tag:"Interrupted"});return}s._tag==="Success"?this.onSuccess(s.value):this.onFailure(s.error),this.schedule("async-resume");}},i=s=>{r||(r=true,this.scheduler.schedule(()=>o(s),`fiber#${this.id}.async-resume`));},a=t.register(this.env,i);typeof a=="function"&&this.addFinalizer(()=>{r=true;try{a();}catch{}}),e=u.SUSPEND;break}}return this.result!=null&&(e=u.DONE),e}};function M(n){return l((e,t)=>{let r=false,o=s=>{r||(r=true,t(s));},i=s=>o({_tag:"Failure",error:s instanceof Error?s:new Error(String(s))}),a=s=>o({_tag:"Success",value:s});try{typeof n=="function"&&n.length>=1?n((s,h)=>s?i(s):a(h)):n().then(a,i);}catch(s){i(s);}})}function b(n,e,t=g){let r=new A(n,e,t);return r.schedule("initial-step"),r}function Q(n,e,t){b(n,e).join(t);}function G(n,e){return new Promise((t,r)=>{b(n,e).join(i=>{let a=i;a._tag==="Success"?t(a.value):r(a.error);});})}function H(n,e){return l((t,r)=>{n(t).then(o=>r({_tag:"Success",value:o})).catch(o=>r({_tag:"Failure",error:e(o)}));})}function L(n){return l((e,t)=>{let r=false,o=i=>{r||(r=true,t(i));};try{n((i,a)=>{o(i?{_tag:"Failure",error:i}:{_tag:"Success",value:a});});}catch(i){o({_tag:"Failure",error:i instanceof Error?i:new Error(String(i))});}})}function $(n){return v((t,r)=>n.length===1?n(r):n(t,r),t=>m(t)?{_tag:"Abort"}:{_tag:"PromiseRejected",reason:t})}function v(n,e){return l((t,r)=>{let o=new AbortController,i=false,a=s=>{i||(i=true,r(s));};try{(n.length===1?n(o.signal):n(t,o.signal)).then(h=>a({_tag:"Success",value:h})).catch(h=>a({_tag:"Failure",error:e(h)}));}catch(s){a({_tag:"Failure",error:e(s)});}return ()=>{i=true,o.abort();}})}var m=n=>typeof n=="object"&&n!==null&&"name"in n&&n.name==="AbortError";exports.a=p;exports.b=x;exports.c=F;exports.d=k;exports.e=d;exports.f=R;exports.g=y;exports.h=_;exports.i=l;exports.j=N;exports.k=E;exports.l=q;exports.m=D;exports.n=f;exports.o=g;exports.p=A;exports.q=M;exports.r=b;exports.s=Q;exports.t=G;exports.u=H;exports.v=L;exports.w=$;exports.x=v;
1
+ 'use strict';function p(n,e,t){return {_tag:"Fold",first:n,onFailure:e,onSuccess:t}}function x(n,e){return p(n,t=>e(t),t=>d(t))}function F(n,e){return p(n,t=>S(e(t)),t=>d(t))}function k(){return y(()=>{})}var d=n=>({_tag:"Succeed",value:n}),S=n=>({_tag:"Fail",error:n}),y=n=>({_tag:"Sync",thunk:n}),_=n=>y(()=>n()),l=n=>({_tag:"Async",register:n});function N(n,e){return E(n,t=>d(e(t)))}function E(n,e){return {_tag:"FlatMap",first:n,andThen:e}}function q(n,e,t){return E(n,r=>(t.addFinalizer(o=>e(r,o)),d(r)))}function w(n){return l(n)}var f=class{queue=[];flushing=false;requested=false;schedule(e,t="anonymous"){if(console.log("[Scheduler.schedule] typeof task =",typeof e,"tag=",t),typeof e!="function"){console.error("[Scheduler.schedule] NON-FUNCTION TASK!",{tag:t,task:e});return}this.queue.push({tag:t,task:e}),this.requestFlush(),console.log("SCHEDULER",{flushing:this.flushing,q:this.queue.length,next:this.queue[0]?.tag,head:this.queue.slice(0,5).map(r=>r.tag)});}requestFlush(){console.log("requestFlush",{flushing:this.flushing,requested:this.requested,q:this.queue.length}),!this.flushing&&(this.requested||(this.requested=true,queueMicrotask(()=>{console.log(">> microtask fired",{flushing:this.flushing,requested:this.requested,q:this.queue.length}),this.flush();})));}flush(){if(console.log("FLUSH enter",{flushing:this.flushing,requested:this.requested,q:this.queue.length}),!this.flushing){this.flushing=true,this.requested=false;try{for(;this.queue.length>0;){let e=this.queue.shift();console.log("[flush] dequeued",{tag:e.tag,typeofTask:typeof e.task});try{console.log("TASK typeof",typeof e.task),e.task();}catch(t){console.error("[flush] task threw",t);}}}finally{this.flushing=false,console.log("FLUSH exit",{requested:this.requested,q:this.queue.length}),this.queue.length>0&&this.requestFlush();}}}},g=new f;var u={CONTINUE:"Continue",SUSPEND:"Suspend",DONE:"Done"},c={QUEUED:"Queued",RUNNING:"Running",SUSPENDED:"Suspended",DONE:"Done"},R=1,A=class{constructor(e,t,r){this.scheduler=r;this.id=R++,this.current=e,this.env=t;}id;closing=null;finishing=false;runState=c.RUNNING;interrupted=false;result=null;joiners=[];current;env;stack=[];fiberFinalizers=[];finalizersDrained=false;addFinalizer(e){this.fiberFinalizers.push(e);}status(){return this.result==null?"Running":this.interrupted?"Interrupted":"Done"}join(e){this.result!=null?e(this.result):this.joiners.push(e);}interrupt(){this.result==null&&(this.interrupted||(this.interrupted=true,this.schedule("interrupt-step")));}schedule(e="step"){console.log("[fiber.schedule]",{fiber:this.id,tag:e,runState:this.runState,schedulerCtor:this.scheduler?.constructor?.name,schedulerScheduleType:typeof this.scheduler?.schedule}),!(this.runState===c.DONE||this.runState===c.QUEUED)&&(this.runState=c.QUEUED,this.scheduler.schedule(()=>{if(console.log("[fiber.task] running",this.id),this.runState===c.DONE)return;switch(this.runState=c.RUNNING,this.step()){case u.CONTINUE:this.schedule("continue");return;case u.SUSPEND:this.runState=c.SUSPENDED;return;case u.DONE:this.runState=c.DONE;return}},`fiber#${this.id}.${e}`));}runFinalizersOnce(e){if(!this.finalizersDrained)for(this.finalizersDrained=true;this.fiberFinalizers.length>0;){let t=this.fiberFinalizers.pop();try{t(e);}catch{}}}notify(e){if(this.result==null&&this.closing==null){this.finishing=true,this.closing=e,this.runFinalizersOnce(e),this.result=e;for(let t of this.joiners)t(e);this.joiners.length=0;}}onSuccess(e){let t=this.stack.pop();if(!t){this.notify({_tag:"Success",value:e});return}this.current=t._tag==="SuccessCont"?t.k(e):t.onSuccess(e);}onFailure(e){for(;this.stack.length>0;){let t=this.stack.pop();if(t._tag==="FoldCont"){this.current=t.onFailure(e);return}}this.notify({_tag:"Failure",error:e});}step(){console.log("[fiber.step] enter",{fiber:this.id,current:this.current?._tag,result:this.result!=null,interrupted:this.interrupted,closing:this.closing!=null,finishing:this.finishing,stack:this.stack.length});let e=u.CONTINUE;if(this.result!=null)return e=u.DONE,e;if(this.interrupted&&this.closing==null)return console.log("[fiber.step] interrupted: failing now",{fiber:this.id}),this.notify({_tag:"Failure",error:{_tag:"Interrupted"}}),e=u.DONE,e;let t=this.current;switch(t._tag){case "Succeed":{console.log("[fiber.step] Succeed",{fiber:this.id}),this.onSuccess(t.value);break}case "Fail":{console.log("[fiber.step] Fail",{fiber:this.id}),this.onFailure(t.error);break}case "Sync":{console.log("[fiber.step] Sync",{fiber:this.id});try{let r=t.thunk(this.env);console.log("[fiber.step] Sync success",{fiber:this.id}),this.onSuccess(r);}catch(r){console.log("[fiber.step] Sync threw",{fiber:this.id,e:r}),this.onFailure(r);}break}case "FlatMap":{console.log("[fiber.step] FlatMap push cont",{fiber:this.id}),this.stack.push({_tag:"SuccessCont",k:t.andThen}),this.current=t.first;break}case "Fold":{console.log("[fiber.step] Fold push cont",{fiber:this.id}),this.stack.push({_tag:"FoldCont",onFailure:t.onFailure,onSuccess:t.onSuccess}),this.current=t.first;break}case "Async":{if(this.finishing)break;let r=false,i=s=>{r||(r=true,this.scheduler.schedule(()=>{this.result!=null||this.closing!=null||(this.current=s._tag==="Success"?{_tag:"Succeed",value:s.value}:{_tag:"Fail",error:s.error},this.schedule("async-resume"));},`fiber#${this.id}.async-wakeup`));},a=t.register(this.env,i);typeof a=="function"&&this.addFinalizer(()=>{r=true;try{a();}catch{}}),e=u.SUSPEND;break}}return this.result!=null&&(e=u.DONE),e}};function M(n){return l((e,t)=>{let r=false,o=s=>{r||(r=true,t(s));},i=s=>o({_tag:"Failure",error:s instanceof Error?s:new Error(String(s))}),a=s=>o({_tag:"Success",value:s});try{typeof n=="function"&&n.length>=1?n((s,h)=>s?i(s):a(h)):n().then(a,i);}catch(s){i(s);}})}function b(n,e,t=g){let r=new A(n,e,t);return r.schedule("initial-step"),r}function Q(n,e,t){b(n,e).join(t);}function G(n,e){return new Promise((t,r)=>{b(n,e).join(i=>{let a=i;a._tag==="Success"?t(a.value):r(a.error);});})}function H(n,e){return l((t,r)=>{n(t).then(o=>r({_tag:"Success",value:o})).catch(o=>r({_tag:"Failure",error:e(o)}));})}function L(n){return l((e,t)=>{let r=false,o=i=>{r||(r=true,t(i));};try{n((i,a)=>{o(i?{_tag:"Failure",error:i}:{_tag:"Success",value:a});});}catch(i){o({_tag:"Failure",error:i instanceof Error?i:new Error(String(i))});}})}function $(n){return v((t,r)=>n.length===1?n(r):n(t,r),t=>m(t)?{_tag:"Abort"}:{_tag:"PromiseRejected",reason:t})}function v(n,e){return l((t,r)=>{let o=new AbortController,i=false,a=s=>{i||(i=true,r(s));};try{(n.length===1?n(o.signal):n(t,o.signal)).then(h=>a({_tag:"Success",value:h})).catch(h=>a({_tag:"Failure",error:e(h)}));}catch(s){a({_tag:"Failure",error:e(s)});}return ()=>{i=true,o.abort();}})}var m=n=>typeof n=="object"&&n!==null&&"name"in n&&n.name==="AbortError";exports.a=p;exports.b=x;exports.c=F;exports.d=k;exports.e=d;exports.f=S;exports.g=y;exports.h=_;exports.i=l;exports.j=N;exports.k=E;exports.l=q;exports.m=w;exports.n=f;exports.o=g;exports.p=A;exports.q=M;exports.r=b;exports.s=Q;exports.t=G;exports.u=H;exports.v=L;exports.w=$;exports.x=v;
@@ -9,24 +9,28 @@ type HttpError = {
9
9
  _tag: "FetchError";
10
10
  message: string;
11
11
  };
12
- type ResponseSpec = {
12
+ type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS";
13
+ type HttpRequest = {
14
+ method: HttpMethod;
15
+ url: string;
16
+ headers?: Record<string, string>;
17
+ body?: string;
18
+ init?: Omit<RequestInit, "method" | "headers" | "body">;
19
+ };
20
+ type HttpWireResponse = {
13
21
  status: number;
14
22
  statusText: string;
15
23
  headers: Record<string, string>;
16
24
  bodyText: string;
17
25
  ms: number;
18
26
  };
19
- type HttpClient = {
20
- get: (url: string, init?: Omit<RequestInit, "method">) => Async<unknown, HttpError, ResponseSpec>;
21
- post: (url: string, body?: string, init?: Omit<RequestInit, "method" | "body">) => Async<unknown, HttpError, ResponseSpec>;
22
- getText: (url: string, init?: Omit<RequestInit, "method">) => Async<unknown, HttpError, string>;
23
- getJson: <A>(url: string, init?: Omit<RequestInit, "method">) => Async<unknown, HttpError, A>;
24
- postJson: <A extends object>(url: string, body: A, init?: Omit<RequestInit, "method" | "body">) => Async<unknown, HttpError, ResponseSpec>;
25
- };
26
27
  type MakeHttpConfig = {
27
28
  baseUrl?: string;
28
29
  headers?: Record<string, string>;
29
30
  };
31
+ type HttpClient = (req: HttpRequest) => Async<unknown, HttpError, HttpWireResponse>;
30
32
  declare function makeHttp(cfg?: MakeHttpConfig): HttpClient;
33
+ declare const mapAsync: <R, E, A, B>(fa: Async<R, E, A>, f: (a: A) => B) => Async<R, E, B>;
34
+ declare const mapTryAsync: <R, E, A, B>(fa: Async<R, E, A>, f: (a: A) => B) => Async<R, E, B>;
31
35
 
32
- export { type HttpClient, type HttpError, type ResponseSpec, makeHttp };
36
+ export { type HttpClient, type HttpError, type HttpMethod, type HttpRequest, type HttpWireResponse, type MakeHttpConfig, makeHttp, mapAsync, mapTryAsync };
@@ -9,24 +9,28 @@ type HttpError = {
9
9
  _tag: "FetchError";
10
10
  message: string;
11
11
  };
12
- type ResponseSpec = {
12
+ type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS";
13
+ type HttpRequest = {
14
+ method: HttpMethod;
15
+ url: string;
16
+ headers?: Record<string, string>;
17
+ body?: string;
18
+ init?: Omit<RequestInit, "method" | "headers" | "body">;
19
+ };
20
+ type HttpWireResponse = {
13
21
  status: number;
14
22
  statusText: string;
15
23
  headers: Record<string, string>;
16
24
  bodyText: string;
17
25
  ms: number;
18
26
  };
19
- type HttpClient = {
20
- get: (url: string, init?: Omit<RequestInit, "method">) => Async<unknown, HttpError, ResponseSpec>;
21
- post: (url: string, body?: string, init?: Omit<RequestInit, "method" | "body">) => Async<unknown, HttpError, ResponseSpec>;
22
- getText: (url: string, init?: Omit<RequestInit, "method">) => Async<unknown, HttpError, string>;
23
- getJson: <A>(url: string, init?: Omit<RequestInit, "method">) => Async<unknown, HttpError, A>;
24
- postJson: <A extends object>(url: string, body: A, init?: Omit<RequestInit, "method" | "body">) => Async<unknown, HttpError, ResponseSpec>;
25
- };
26
27
  type MakeHttpConfig = {
27
28
  baseUrl?: string;
28
29
  headers?: Record<string, string>;
29
30
  };
31
+ type HttpClient = (req: HttpRequest) => Async<unknown, HttpError, HttpWireResponse>;
30
32
  declare function makeHttp(cfg?: MakeHttpConfig): HttpClient;
33
+ declare const mapAsync: <R, E, A, B>(fa: Async<R, E, A>, f: (a: A) => B) => Async<R, E, B>;
34
+ declare const mapTryAsync: <R, E, A, B>(fa: Async<R, E, A>, f: (a: A) => B) => Async<R, E, B>;
31
35
 
32
- export { type HttpClient, type HttpError, type ResponseSpec, makeHttp };
36
+ export { type HttpClient, type HttpError, type HttpMethod, type HttpRequest, type HttpWireResponse, type MakeHttpConfig, makeHttp, mapAsync, mapTryAsync };
@@ -1 +1 @@
1
- 'use strict';var chunkREJAVP4D_js=require('../chunk-REJAVP4D.js');var h=s=>s instanceof DOMException&&s.name==="AbortError"?{_tag:"Abort"}:typeof s=="object"&&s&&"_tag"in s?s:{_tag:"FetchError",message:String(s)};function y(s={}){let p=s.baseUrl??"",d=s.headers??{},n=t=>chunkREJAVP4D_js.x(async e=>{let r;try{r=new URL(t.url,p);}catch{throw {_tag:"BadUrl",message:`URL inv\xE1lida: ${t.url}`}}let g=performance.now(),o=await fetch(r,{...t,headers:{...d,...t.headers??{}},signal:e}),c=await o.text(),i={};return o.headers.forEach((m,u)=>i[u]=m),{status:o.status,statusText:o.statusText,headers:i,bodyText:c,ms:Math.round(performance.now()-g)}},h);return {get:(t,e)=>n({url:t,method:"GET",...e??{}}),post:(t,e,r)=>n({url:t,method:"POST",body:e&&e.length>0?e:void 0,...r??{}}),getText:(t,e)=>n({url:t,method:"GET",...e??{}}).map(r=>r.bodyText),getJson:(t,e)=>n({url:t,method:"GET",...e??{}}).map(r=>JSON.parse(r.bodyText)),postJson:(t,e,r)=>n({url:t,method:"POST",headers:{"content-type":"application/json",...r?.headers??{}},body:JSON.stringify(e),...r??{}})}}exports.makeHttp=y;
1
+ 'use strict';var chunkOETP4M4Z_js=require('../chunk-OETP4M4Z.js');var h=t=>t instanceof DOMException&&t.name==="AbortError"?{_tag:"Abort"}:typeof t=="object"&&t&&"_tag"in t?t:{_tag:"FetchError",message:String(t)};function b(t={}){let e=t.baseUrl??"",s=t.headers??{};return r=>chunkOETP4M4Z_js.x(async y=>{let a;try{a=new URL(r.url,e);}catch{throw {_tag:"BadUrl",message:`URL inv\xE1lida: ${r.url}`}}let g=performance.now(),n=await fetch(a,{...r.init??{},method:r.method,headers:{...s,...r.headers??{}},body:r.body,signal:y}),m=await n.text(),p={};return n.headers.forEach((u,E)=>p[E]=u),{status:n.status,statusText:n.statusText,headers:p,bodyText:m,ms:Math.round(performance.now()-g)}},h)}var l=(t,e)=>chunkOETP4M4Z_js.k(t,s=>chunkOETP4M4Z_js.e(e(s))),x=(t,e)=>chunkOETP4M4Z_js.k(t,s=>chunkOETP4M4Z_js.g(()=>e(s)));exports.makeHttp=b;exports.mapAsync=l;exports.mapTryAsync=x;
@@ -1 +1 @@
1
- import {x}from'../chunk-JLFYFKQ2.mjs';var h=s=>s instanceof DOMException&&s.name==="AbortError"?{_tag:"Abort"}:typeof s=="object"&&s&&"_tag"in s?s:{_tag:"FetchError",message:String(s)};function y(s={}){let p=s.baseUrl??"",d=s.headers??{},n=t=>x(async e=>{let r;try{r=new URL(t.url,p);}catch{throw {_tag:"BadUrl",message:`URL inv\xE1lida: ${t.url}`}}let g=performance.now(),o=await fetch(r,{...t,headers:{...d,...t.headers??{}},signal:e}),c=await o.text(),i={};return o.headers.forEach((m,u)=>i[u]=m),{status:o.status,statusText:o.statusText,headers:i,bodyText:c,ms:Math.round(performance.now()-g)}},h);return {get:(t,e)=>n({url:t,method:"GET",...e??{}}),post:(t,e,r)=>n({url:t,method:"POST",body:e&&e.length>0?e:void 0,...r??{}}),getText:(t,e)=>n({url:t,method:"GET",...e??{}}).map(r=>r.bodyText),getJson:(t,e)=>n({url:t,method:"GET",...e??{}}).map(r=>JSON.parse(r.bodyText)),postJson:(t,e,r)=>n({url:t,method:"POST",headers:{"content-type":"application/json",...r?.headers??{}},body:JSON.stringify(e),...r??{}})}}export{y as makeHttp};
1
+ import {k,x as x$1,e,g}from'../chunk-HYS5U72G.mjs';var h=t=>t instanceof DOMException&&t.name==="AbortError"?{_tag:"Abort"}:typeof t=="object"&&t&&"_tag"in t?t:{_tag:"FetchError",message:String(t)};function b(t={}){let e=t.baseUrl??"",s=t.headers??{};return r=>x$1(async y=>{let a;try{a=new URL(r.url,e);}catch{throw {_tag:"BadUrl",message:`URL inv\xE1lida: ${r.url}`}}let g=performance.now(),n=await fetch(a,{...r.init??{},method:r.method,headers:{...s,...r.headers??{}},body:r.body,signal:y}),m=await n.text(),p={};return n.headers.forEach((u,E)=>p[E]=u),{status:n.status,statusText:n.statusText,headers:p,bodyText:m,ms:Math.round(performance.now()-g)}},h)}var l=(t,e$1)=>k(t,s=>e(e$1(s))),x=(t,e)=>k(t,s=>g(()=>e(s)));export{b as makeHttp,l as mapAsync,x as mapTryAsync};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- 'use strict';var chunkREJAVP4D_js=require('./chunk-REJAVP4D.js');var S={_tag:"None"},b=e=>({_tag:"Some",value:e});var k=e=>chunkREJAVP4D_js.e(e),_=e=>chunkREJAVP4D_js.f(e),Ee=e=>chunkREJAVP4D_js.g(r=>e(r)),g=(e,r)=>chunkREJAVP4D_js.j(e,r),N=(e,r)=>chunkREJAVP4D_js.k(e,t=>r(t)),w=(e,r)=>chunkREJAVP4D_js.c(e,r),ie=(e,r)=>chunkREJAVP4D_js.a(e,t=>r(t),t=>chunkREJAVP4D_js.e(t));function C(e,r){return chunkREJAVP4D_js.a(e,t=>t._tag==="Some"?chunkREJAVP4D_js.f(t):r(),t=>chunkREJAVP4D_js.e(t))}var pe=()=>_(S);function Ae(){let e=false,r=new Set;return {isCancelled:()=>e,onCancel:n=>{if(e){try{n();}catch{}return ()=>{}}return r.add(n),()=>{r.delete(n);}},cancel:()=>{if(!e){e=true;for(let n of r)try{n();}catch{}r.clear();}}}}function Re(e,r){return e.onCancel(()=>r.abort())}var H=1,x=class e{constructor(r){this.env=r;this.id=H++;}id;closed=false;children=new Set;subScopes=new Set;finalizers=[];addFinalizer(r){if(this.closed)throw new Error("Trying to add finalizer to closed scope");this.finalizers.push(r);}subScope(){if(this.closed)throw new Error("Scope closed");let r=new e(this.env);return this.subScopes.add(r),r}fork(r,t){if(this.closed)throw new Error("Scope closed");let n=chunkREJAVP4D_js.r(r,t);return this.children.add(n),n.join(()=>{this.children.delete(n);}),n}close(r={_tag:"Success",value:void 0}){if(!this.closed){for(this.closed=true,this.children.forEach(t=>t.interrupt()),this.subScopes.forEach(t=>t.close(r));this.finalizers.length>0;){let n=this.finalizers.pop()(r);chunkREJAVP4D_js.r(n,this.env);}this.children.clear(),this.subScopes.clear();}}isClosed(){return this.closed}};function de(e){let r=new x({});try{return e(r)}finally{r.close();}}function T(e,r,t,n,o){return chunkREJAVP4D_js.i((a,c)=>{let E=t.subScope(),s=false,R=E.fork(e,a),d=E.fork(r,a),m=u=>{E.fork(u,a).join(f=>{E.close(f),c(f);});};R.join(u=>{s||(s=true,m(n(u,d,E)));}),d.join(u=>{s||(s=true,m(o(u,R,E)));});})}var P=e=>e._tag==="None"?S:b(e.value),Z=e=>({_tag:"FromPull",pull:e}),we=(e,r,t=true)=>({_tag:"Merge",left:e,right:r,flip:t}),$=()=>({_tag:"Empty"}),W=e=>({_tag:"Emit",value:e}),F=(e,r)=>({_tag:"Concat",left:e,right:r}),M=e=>({_tag:"Flatten",stream:e});function L(e,r,t,n,o){return (a,c,E)=>{if(console.log(`[mergePull#${o}] winner=${e} exit=${a._tag}`),a._tag==="Failure"&&console.log(`[mergePull#${o}] failure error=`,a.error),a._tag==="Success"&&console.log(`[mergePull#${o}] success -> interrupt other`),a._tag==="Success"){let[d,m]=a.value;c.interrupt();let u=Z(e==="L"?v(m,t,!n,o):v(r,m,!n,o));return chunkREJAVP4D_js.e([d,u])}let s=a.error;if(typeof s=="object"&&s!==null&&s._tag==="Interrupted")return chunkREJAVP4D_js.f(s);let R=s;return R._tag==="None"?l(e==="L"?t:r):chunkREJAVP4D_js.f(R)}}function v(e,r,t,n){return chunkREJAVP4D_js.i((o,a)=>{let c=++n;console.log(`[mergePull#${c}] start flip=${t}`);let E=new x(o);console.log(`[mergePull#${c}] built pulls`);let s=l(e),R=l(r);console.log(`[mergePull#${c}] built pulls`);let d=L("L",e,r,t,c),m=L("R",e,r,t,c);console.log(`[mergePull#${c}] calling raceWith`);let u=T(s,R,E,d,m);console.log(`[mergePull#${c}] forking handler`),E.fork(u,o).join(f=>{console.log(`[mergePull#${c}] handler joined exit=${f._tag}`),E.close(f),console.log(`[mergePull#${c}] scope closed, calling cb`),a(f);});})}function Ce(e,r){return Z(v(e,r,true,0))}function l(e){switch(e._tag){case "Empty":return _(S);case "Emit":return g(w(e.value,r=>b(r)),r=>[r,$()]);case "FromPull":return console.log("[uncons] FromPull"),e.pull;case "Concat":return C(g(l(e.left),([r,t])=>[r,F(t,e.right)]),()=>l(e.right));case "Flatten":return N(l(e.stream),([r,t])=>C(g(l(r),([n,o])=>[n,F(o,M(t))]),()=>l(M(t))));case "Merge":return console.log("[makeMergePull] defined"),v(e.left,e.right,e.flip,0)}}function h(e,r){switch(e._tag){case "Empty":return $();case "Emit":return W(g(e.value,r));case "FromPull":return Z(g(e.pull,([t,n])=>[r(t),h(n,r)]));case "Concat":return F(h(e.left,r),h(e.right,r));case "Flatten":{let t=h(e.stream,n=>h(n,r));return M(t)}}}function Pe(e,r){let t=n=>Z(n>r?chunkREJAVP4D_js.f(S):chunkREJAVP4D_js.e([n,t(n+1)]));return t(e)}function D(e,r){let t=chunkREJAVP4D_js.a(chunkREJAVP4D_js.c(l(e),n=>P(n)),n=>chunkREJAVP4D_js.f(n),([n,o])=>chunkREJAVP4D_js.a(chunkREJAVP4D_js.c(l(r),a=>P(a)),a=>chunkREJAVP4D_js.f(a),([a,c])=>chunkREJAVP4D_js.e([[n,a],D(o,c)])));return Z(t)}function Me(e,r){let t=n=>chunkREJAVP4D_js.a(chunkREJAVP4D_js.c(l(n),o=>P(o)),o=>o._tag==="None"?chunkREJAVP4D_js.e(void 0):chunkREJAVP4D_js.f(o),([o,a])=>chunkREJAVP4D_js.k(chunkREJAVP4D_js.c(r(o),c=>b(c)),()=>t(a)));return chunkREJAVP4D_js.a(t(e),n=>n._tag==="None"?chunkREJAVP4D_js.e(void 0):chunkREJAVP4D_js.f(n.value),()=>chunkREJAVP4D_js.e(void 0))}function $e(e){let r=$();for(let t=e.length-1;t>=0;t--){let n=W(k(e[t]));r=F(n,r);}return r}function je(e){let r=(t,n)=>chunkREJAVP4D_js.a(l(t),o=>o._tag==="None"?k(n):_(o),([o,a])=>r(a,[...n,o]));return w(r(e,[]),t=>{if(t._tag==="Some")return t.value;throw new Error("unreachable: stream end handled as success")})}Object.defineProperty(exports,"RuntimeFiber",{enumerable:true,get:function(){return chunkREJAVP4D_js.p}});Object.defineProperty(exports,"Scheduler",{enumerable:true,get:function(){return chunkREJAVP4D_js.n}});Object.defineProperty(exports,"acquireRelease",{enumerable:true,get:function(){return chunkREJAVP4D_js.l}});Object.defineProperty(exports,"async",{enumerable:true,get:function(){return chunkREJAVP4D_js.i}});Object.defineProperty(exports,"asyncCatchAll",{enumerable:true,get:function(){return chunkREJAVP4D_js.b}});Object.defineProperty(exports,"asyncFail",{enumerable:true,get:function(){return chunkREJAVP4D_js.f}});Object.defineProperty(exports,"asyncFlatMap",{enumerable:true,get:function(){return chunkREJAVP4D_js.k}});Object.defineProperty(exports,"asyncFold",{enumerable:true,get:function(){return chunkREJAVP4D_js.a}});Object.defineProperty(exports,"asyncInterruptible",{enumerable:true,get:function(){return chunkREJAVP4D_js.m}});Object.defineProperty(exports,"asyncMap",{enumerable:true,get:function(){return chunkREJAVP4D_js.j}});Object.defineProperty(exports,"asyncMapError",{enumerable:true,get:function(){return chunkREJAVP4D_js.c}});Object.defineProperty(exports,"asyncSucceed",{enumerable:true,get:function(){return chunkREJAVP4D_js.e}});Object.defineProperty(exports,"asyncSync",{enumerable:true,get:function(){return chunkREJAVP4D_js.g}});Object.defineProperty(exports,"asyncTotal",{enumerable:true,get:function(){return chunkREJAVP4D_js.h}});Object.defineProperty(exports,"fork",{enumerable:true,get:function(){return chunkREJAVP4D_js.r}});Object.defineProperty(exports,"from",{enumerable:true,get:function(){return chunkREJAVP4D_js.q}});Object.defineProperty(exports,"fromCallback",{enumerable:true,get:function(){return chunkREJAVP4D_js.v}});Object.defineProperty(exports,"fromPromise",{enumerable:true,get:function(){return chunkREJAVP4D_js.u}});Object.defineProperty(exports,"fromPromiseAbortable",{enumerable:true,get:function(){return chunkREJAVP4D_js.x}});Object.defineProperty(exports,"globalScheduler",{enumerable:true,get:function(){return chunkREJAVP4D_js.o}});Object.defineProperty(exports,"toPromise",{enumerable:true,get:function(){return chunkREJAVP4D_js.t}});Object.defineProperty(exports,"tryPromiseAbortable",{enumerable:true,get:function(){return chunkREJAVP4D_js.w}});Object.defineProperty(exports,"unit",{enumerable:true,get:function(){return chunkREJAVP4D_js.d}});Object.defineProperty(exports,"unsafeRunAsync",{enumerable:true,get:function(){return chunkREJAVP4D_js.s}});exports.Scope=x;exports.catchAll=ie;exports.collectStream=je;exports.concatStream=F;exports.emitStream=W;exports.emptyStream=$;exports.end=pe;exports.fail=_;exports.flatMap=N;exports.flattenStream=M;exports.foreachStream=Me;exports.fromArray=$e;exports.fromPull=Z;exports.linkAbortController=Re;exports.makeCancelToken=Ae;exports.map=g;exports.mapError=w;exports.mapStream=h;exports.merge=Ce;exports.mergeStream=we;exports.none=S;exports.orElseOptional=C;exports.rangeStream=Pe;exports.some=b;exports.succeed=k;exports.sync=Ee;exports.uncons=l;exports.withScope=de;exports.zip=D;
1
+ 'use strict';var chunkOETP4M4Z_js=require('./chunk-OETP4M4Z.js');var S={_tag:"None"},b=e=>({_tag:"Some",value:e});var k=e=>chunkOETP4M4Z_js.e(e),_=e=>chunkOETP4M4Z_js.f(e),Ee=e=>chunkOETP4M4Z_js.g(r=>e(r)),g=(e,r)=>chunkOETP4M4Z_js.j(e,r),N=(e,r)=>chunkOETP4M4Z_js.k(e,t=>r(t)),w=(e,r)=>chunkOETP4M4Z_js.c(e,r),ie=(e,r)=>chunkOETP4M4Z_js.a(e,t=>r(t),t=>chunkOETP4M4Z_js.e(t));function C(e,r){return chunkOETP4M4Z_js.a(e,t=>t._tag==="Some"?chunkOETP4M4Z_js.f(t):r(),t=>chunkOETP4M4Z_js.e(t))}var pe=()=>_(S);function Ae(){let e=false,r=new Set;return {isCancelled:()=>e,onCancel:n=>{if(e){try{n();}catch{}return ()=>{}}return r.add(n),()=>{r.delete(n);}},cancel:()=>{if(!e){e=true;for(let n of r)try{n();}catch{}r.clear();}}}}function Re(e,r){return e.onCancel(()=>r.abort())}var H=1,x=class e{constructor(r){this.env=r;this.id=H++;}id;closed=false;children=new Set;subScopes=new Set;finalizers=[];addFinalizer(r){if(this.closed)throw new Error("Trying to add finalizer to closed scope");this.finalizers.push(r);}subScope(){if(this.closed)throw new Error("Scope closed");let r=new e(this.env);return this.subScopes.add(r),r}fork(r,t){if(this.closed)throw new Error("Scope closed");let n=chunkOETP4M4Z_js.r(r,t);return this.children.add(n),n.join(()=>{this.children.delete(n);}),n}close(r={_tag:"Success",value:void 0}){if(!this.closed){for(this.closed=true,this.children.forEach(t=>t.interrupt()),this.subScopes.forEach(t=>t.close(r));this.finalizers.length>0;){let n=this.finalizers.pop()(r);chunkOETP4M4Z_js.r(n,this.env);}this.children.clear(),this.subScopes.clear();}}isClosed(){return this.closed}};function de(e){let r=new x({});try{return e(r)}finally{r.close();}}function T(e,r,t,n,o){return chunkOETP4M4Z_js.i((a,c)=>{let E=t.subScope(),s=false,R=E.fork(e,a),d=E.fork(r,a),m=u=>{E.fork(u,a).join(f=>{E.close(f),c(f);});};R.join(u=>{s||(s=true,m(n(u,d,E)));}),d.join(u=>{s||(s=true,m(o(u,R,E)));});})}var P=e=>e._tag==="None"?S:b(e.value),Z=e=>({_tag:"FromPull",pull:e}),we=(e,r,t=true)=>({_tag:"Merge",left:e,right:r,flip:t}),$=()=>({_tag:"Empty"}),W=e=>({_tag:"Emit",value:e}),F=(e,r)=>({_tag:"Concat",left:e,right:r}),M=e=>({_tag:"Flatten",stream:e});function L(e,r,t,n,o){return (a,c,E)=>{if(console.log(`[mergePull#${o}] winner=${e} exit=${a._tag}`),a._tag==="Failure"&&console.log(`[mergePull#${o}] failure error=`,a.error),a._tag==="Success"&&console.log(`[mergePull#${o}] success -> interrupt other`),a._tag==="Success"){let[d,m]=a.value;c.interrupt();let u=Z(e==="L"?v(m,t,!n,o):v(r,m,!n,o));return chunkOETP4M4Z_js.e([d,u])}let s=a.error;if(typeof s=="object"&&s!==null&&s._tag==="Interrupted")return chunkOETP4M4Z_js.f(s);let R=s;return R._tag==="None"?l(e==="L"?t:r):chunkOETP4M4Z_js.f(R)}}function v(e,r,t,n){return chunkOETP4M4Z_js.i((o,a)=>{let c=++n;console.log(`[mergePull#${c}] start flip=${t}`);let E=new x(o);console.log(`[mergePull#${c}] built pulls`);let s=l(e),R=l(r);console.log(`[mergePull#${c}] built pulls`);let d=L("L",e,r,t,c),m=L("R",e,r,t,c);console.log(`[mergePull#${c}] calling raceWith`);let u=T(s,R,E,d,m);console.log(`[mergePull#${c}] forking handler`),E.fork(u,o).join(f=>{console.log(`[mergePull#${c}] handler joined exit=${f._tag}`),E.close(f),console.log(`[mergePull#${c}] scope closed, calling cb`),a(f);});})}function Ce(e,r){return Z(v(e,r,true,0))}function l(e){switch(e._tag){case "Empty":return _(S);case "Emit":return g(w(e.value,r=>b(r)),r=>[r,$()]);case "FromPull":return console.log("[uncons] FromPull"),e.pull;case "Concat":return C(g(l(e.left),([r,t])=>[r,F(t,e.right)]),()=>l(e.right));case "Flatten":return N(l(e.stream),([r,t])=>C(g(l(r),([n,o])=>[n,F(o,M(t))]),()=>l(M(t))));case "Merge":return console.log("[makeMergePull] defined"),v(e.left,e.right,e.flip,0)}}function h(e,r){switch(e._tag){case "Empty":return $();case "Emit":return W(g(e.value,r));case "FromPull":return Z(g(e.pull,([t,n])=>[r(t),h(n,r)]));case "Concat":return F(h(e.left,r),h(e.right,r));case "Flatten":{let t=h(e.stream,n=>h(n,r));return M(t)}}}function Pe(e,r){let t=n=>Z(n>r?chunkOETP4M4Z_js.f(S):chunkOETP4M4Z_js.e([n,t(n+1)]));return t(e)}function D(e,r){let t=chunkOETP4M4Z_js.a(chunkOETP4M4Z_js.c(l(e),n=>P(n)),n=>chunkOETP4M4Z_js.f(n),([n,o])=>chunkOETP4M4Z_js.a(chunkOETP4M4Z_js.c(l(r),a=>P(a)),a=>chunkOETP4M4Z_js.f(a),([a,c])=>chunkOETP4M4Z_js.e([[n,a],D(o,c)])));return Z(t)}function Me(e,r){let t=n=>chunkOETP4M4Z_js.a(chunkOETP4M4Z_js.c(l(n),o=>P(o)),o=>o._tag==="None"?chunkOETP4M4Z_js.e(void 0):chunkOETP4M4Z_js.f(o),([o,a])=>chunkOETP4M4Z_js.k(chunkOETP4M4Z_js.c(r(o),c=>b(c)),()=>t(a)));return chunkOETP4M4Z_js.a(t(e),n=>n._tag==="None"?chunkOETP4M4Z_js.e(void 0):chunkOETP4M4Z_js.f(n.value),()=>chunkOETP4M4Z_js.e(void 0))}function $e(e){let r=$();for(let t=e.length-1;t>=0;t--){let n=W(k(e[t]));r=F(n,r);}return r}function je(e){let r=(t,n)=>chunkOETP4M4Z_js.a(l(t),o=>o._tag==="None"?k(n):_(o),([o,a])=>r(a,[...n,o]));return w(r(e,[]),t=>{if(t._tag==="Some")return t.value;throw new Error("unreachable: stream end handled as success")})}Object.defineProperty(exports,"RuntimeFiber",{enumerable:true,get:function(){return chunkOETP4M4Z_js.p}});Object.defineProperty(exports,"Scheduler",{enumerable:true,get:function(){return chunkOETP4M4Z_js.n}});Object.defineProperty(exports,"acquireRelease",{enumerable:true,get:function(){return chunkOETP4M4Z_js.l}});Object.defineProperty(exports,"async",{enumerable:true,get:function(){return chunkOETP4M4Z_js.i}});Object.defineProperty(exports,"asyncCatchAll",{enumerable:true,get:function(){return chunkOETP4M4Z_js.b}});Object.defineProperty(exports,"asyncFail",{enumerable:true,get:function(){return chunkOETP4M4Z_js.f}});Object.defineProperty(exports,"asyncFlatMap",{enumerable:true,get:function(){return chunkOETP4M4Z_js.k}});Object.defineProperty(exports,"asyncFold",{enumerable:true,get:function(){return chunkOETP4M4Z_js.a}});Object.defineProperty(exports,"asyncInterruptible",{enumerable:true,get:function(){return chunkOETP4M4Z_js.m}});Object.defineProperty(exports,"asyncMap",{enumerable:true,get:function(){return chunkOETP4M4Z_js.j}});Object.defineProperty(exports,"asyncMapError",{enumerable:true,get:function(){return chunkOETP4M4Z_js.c}});Object.defineProperty(exports,"asyncSucceed",{enumerable:true,get:function(){return chunkOETP4M4Z_js.e}});Object.defineProperty(exports,"asyncSync",{enumerable:true,get:function(){return chunkOETP4M4Z_js.g}});Object.defineProperty(exports,"asyncTotal",{enumerable:true,get:function(){return chunkOETP4M4Z_js.h}});Object.defineProperty(exports,"fork",{enumerable:true,get:function(){return chunkOETP4M4Z_js.r}});Object.defineProperty(exports,"from",{enumerable:true,get:function(){return chunkOETP4M4Z_js.q}});Object.defineProperty(exports,"fromCallback",{enumerable:true,get:function(){return chunkOETP4M4Z_js.v}});Object.defineProperty(exports,"fromPromise",{enumerable:true,get:function(){return chunkOETP4M4Z_js.u}});Object.defineProperty(exports,"fromPromiseAbortable",{enumerable:true,get:function(){return chunkOETP4M4Z_js.x}});Object.defineProperty(exports,"globalScheduler",{enumerable:true,get:function(){return chunkOETP4M4Z_js.o}});Object.defineProperty(exports,"toPromise",{enumerable:true,get:function(){return chunkOETP4M4Z_js.t}});Object.defineProperty(exports,"tryPromiseAbortable",{enumerable:true,get:function(){return chunkOETP4M4Z_js.w}});Object.defineProperty(exports,"unit",{enumerable:true,get:function(){return chunkOETP4M4Z_js.d}});Object.defineProperty(exports,"unsafeRunAsync",{enumerable:true,get:function(){return chunkOETP4M4Z_js.s}});exports.Scope=x;exports.catchAll=ie;exports.collectStream=je;exports.concatStream=F;exports.emitStream=W;exports.emptyStream=$;exports.end=pe;exports.fail=_;exports.flatMap=N;exports.flattenStream=M;exports.foreachStream=Me;exports.fromArray=$e;exports.fromPull=Z;exports.linkAbortController=Re;exports.makeCancelToken=Ae;exports.map=g;exports.mapError=w;exports.mapStream=h;exports.merge=Ce;exports.mergeStream=we;exports.none=S;exports.orElseOptional=C;exports.rangeStream=Pe;exports.some=b;exports.succeed=k;exports.sync=Ee;exports.uncons=l;exports.withScope=de;exports.zip=D;
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import {a,f,k as k$1,j,c,e,g as g$1,r,i}from'./chunk-JLFYFKQ2.mjs';export{p as RuntimeFiber,n as Scheduler,l as acquireRelease,i as async,b as asyncCatchAll,f as asyncFail,k as asyncFlatMap,a as asyncFold,m as asyncInterruptible,j as asyncMap,c as asyncMapError,e as asyncSucceed,g as asyncSync,h as asyncTotal,r as fork,q as from,v as fromCallback,u as fromPromise,x as fromPromiseAbortable,o as globalScheduler,t as toPromise,w as tryPromiseAbortable,d as unit,s as unsafeRunAsync}from'./chunk-JLFYFKQ2.mjs';var S={_tag:"None"},b=e=>({_tag:"Some",value:e});var k=e$1=>e(e$1),_=e=>f(e),Ee=e=>g$1(r=>e(r)),g=(e,r)=>j(e,r),N=(e,r)=>k$1(e,t=>r(t)),w=(e,r)=>c(e,r),ie=(e$1,r)=>a(e$1,t=>r(t),t=>e(t));function C(e$1,r){return a(e$1,t=>t._tag==="Some"?f(t):r(),t=>e(t))}var pe=()=>_(S);function Ae(){let e=false,r=new Set;return {isCancelled:()=>e,onCancel:n=>{if(e){try{n();}catch{}return ()=>{}}return r.add(n),()=>{r.delete(n);}},cancel:()=>{if(!e){e=true;for(let n of r)try{n();}catch{}r.clear();}}}}function Re(e,r){return e.onCancel(()=>r.abort())}var H=1,x=class e{constructor(r){this.env=r;this.id=H++;}id;closed=false;children=new Set;subScopes=new Set;finalizers=[];addFinalizer(r){if(this.closed)throw new Error("Trying to add finalizer to closed scope");this.finalizers.push(r);}subScope(){if(this.closed)throw new Error("Scope closed");let r=new e(this.env);return this.subScopes.add(r),r}fork(r$1,t){if(this.closed)throw new Error("Scope closed");let n=r(r$1,t);return this.children.add(n),n.join(()=>{this.children.delete(n);}),n}close(r$1={_tag:"Success",value:void 0}){if(!this.closed){for(this.closed=true,this.children.forEach(t=>t.interrupt()),this.subScopes.forEach(t=>t.close(r$1));this.finalizers.length>0;){let n=this.finalizers.pop()(r$1);r(n,this.env);}this.children.clear(),this.subScopes.clear();}}isClosed(){return this.closed}};function de(e){let r=new x({});try{return e(r)}finally{r.close();}}function T(e,r,t,n,o){return i((a,c)=>{let E=t.subScope(),s=false,R=E.fork(e,a),d=E.fork(r,a),m=u=>{E.fork(u,a).join(f=>{E.close(f),c(f);});};R.join(u=>{s||(s=true,m(n(u,d,E)));}),d.join(u=>{s||(s=true,m(o(u,R,E)));});})}var P=e=>e._tag==="None"?S:b(e.value),Z=e=>({_tag:"FromPull",pull:e}),we=(e,r,t=true)=>({_tag:"Merge",left:e,right:r,flip:t}),$=()=>({_tag:"Empty"}),W=e=>({_tag:"Emit",value:e}),F=(e,r)=>({_tag:"Concat",left:e,right:r}),M=e=>({_tag:"Flatten",stream:e});function L(e$1,r,t,n,o){return (a,c,E)=>{if(console.log(`[mergePull#${o}] winner=${e$1} exit=${a._tag}`),a._tag==="Failure"&&console.log(`[mergePull#${o}] failure error=`,a.error),a._tag==="Success"&&console.log(`[mergePull#${o}] success -> interrupt other`),a._tag==="Success"){let[d,m]=a.value;c.interrupt();let u=Z(e$1==="L"?v(m,t,!n,o):v(r,m,!n,o));return e([d,u])}let s=a.error;if(typeof s=="object"&&s!==null&&s._tag==="Interrupted")return f(s);let R=s;return R._tag==="None"?l(e$1==="L"?t:r):f(R)}}function v(e,r,t,n){return i((o,a)=>{let c=++n;console.log(`[mergePull#${c}] start flip=${t}`);let E=new x(o);console.log(`[mergePull#${c}] built pulls`);let s=l(e),R=l(r);console.log(`[mergePull#${c}] built pulls`);let d=L("L",e,r,t,c),m=L("R",e,r,t,c);console.log(`[mergePull#${c}] calling raceWith`);let u=T(s,R,E,d,m);console.log(`[mergePull#${c}] forking handler`),E.fork(u,o).join(f=>{console.log(`[mergePull#${c}] handler joined exit=${f._tag}`),E.close(f),console.log(`[mergePull#${c}] scope closed, calling cb`),a(f);});})}function Ce(e,r){return Z(v(e,r,true,0))}function l(e){switch(e._tag){case "Empty":return _(S);case "Emit":return g(w(e.value,r=>b(r)),r=>[r,$()]);case "FromPull":return console.log("[uncons] FromPull"),e.pull;case "Concat":return C(g(l(e.left),([r,t])=>[r,F(t,e.right)]),()=>l(e.right));case "Flatten":return N(l(e.stream),([r,t])=>C(g(l(r),([n,o])=>[n,F(o,M(t))]),()=>l(M(t))));case "Merge":return console.log("[makeMergePull] defined"),v(e.left,e.right,e.flip,0)}}function h(e,r){switch(e._tag){case "Empty":return $();case "Emit":return W(g(e.value,r));case "FromPull":return Z(g(e.pull,([t,n])=>[r(t),h(n,r)]));case "Concat":return F(h(e.left,r),h(e.right,r));case "Flatten":{let t=h(e.stream,n=>h(n,r));return M(t)}}}function Pe(e$1,r){let t=n=>Z(n>r?f(S):e([n,t(n+1)]));return t(e$1)}function D(e$1,r){let t=a(c(l(e$1),n=>P(n)),n=>f(n),([n,o])=>a(c(l(r),a=>P(a)),a=>f(a),([a,c])=>e([[n,a],D(o,c)])));return Z(t)}function Me(e$1,r){let t=n=>a(c(l(n),o=>P(o)),o=>o._tag==="None"?e(void 0):f(o),([o,a])=>k$1(c(r(o),c=>b(c)),()=>t(a)));return a(t(e$1),n=>n._tag==="None"?e(void 0):f(n.value),()=>e(void 0))}function $e(e){let r=$();for(let t=e.length-1;t>=0;t--){let n=W(k(e[t]));r=F(n,r);}return r}function je(e){let r=(t,n)=>a(l(t),o=>o._tag==="None"?k(n):_(o),([o,a])=>r(a,[...n,o]));return w(r(e,[]),t=>{if(t._tag==="Some")return t.value;throw new Error("unreachable: stream end handled as success")})}export{x as Scope,ie as catchAll,je as collectStream,F as concatStream,W as emitStream,$ as emptyStream,pe as end,_ as fail,N as flatMap,M as flattenStream,Me as foreachStream,$e as fromArray,Z as fromPull,Re as linkAbortController,Ae as makeCancelToken,g as map,w as mapError,h as mapStream,Ce as merge,we as mergeStream,S as none,C as orElseOptional,Pe as rangeStream,b as some,k as succeed,Ee as sync,l as uncons,de as withScope,D as zip};
1
+ import {a,f,k as k$1,j,c,e,g as g$1,r,i}from'./chunk-HYS5U72G.mjs';export{p as RuntimeFiber,n as Scheduler,l as acquireRelease,i as async,b as asyncCatchAll,f as asyncFail,k as asyncFlatMap,a as asyncFold,m as asyncInterruptible,j as asyncMap,c as asyncMapError,e as asyncSucceed,g as asyncSync,h as asyncTotal,r as fork,q as from,v as fromCallback,u as fromPromise,x as fromPromiseAbortable,o as globalScheduler,t as toPromise,w as tryPromiseAbortable,d as unit,s as unsafeRunAsync}from'./chunk-HYS5U72G.mjs';var S={_tag:"None"},b=e=>({_tag:"Some",value:e});var k=e$1=>e(e$1),_=e=>f(e),Ee=e=>g$1(r=>e(r)),g=(e,r)=>j(e,r),N=(e,r)=>k$1(e,t=>r(t)),w=(e,r)=>c(e,r),ie=(e$1,r)=>a(e$1,t=>r(t),t=>e(t));function C(e$1,r){return a(e$1,t=>t._tag==="Some"?f(t):r(),t=>e(t))}var pe=()=>_(S);function Ae(){let e=false,r=new Set;return {isCancelled:()=>e,onCancel:n=>{if(e){try{n();}catch{}return ()=>{}}return r.add(n),()=>{r.delete(n);}},cancel:()=>{if(!e){e=true;for(let n of r)try{n();}catch{}r.clear();}}}}function Re(e,r){return e.onCancel(()=>r.abort())}var H=1,x=class e{constructor(r){this.env=r;this.id=H++;}id;closed=false;children=new Set;subScopes=new Set;finalizers=[];addFinalizer(r){if(this.closed)throw new Error("Trying to add finalizer to closed scope");this.finalizers.push(r);}subScope(){if(this.closed)throw new Error("Scope closed");let r=new e(this.env);return this.subScopes.add(r),r}fork(r$1,t){if(this.closed)throw new Error("Scope closed");let n=r(r$1,t);return this.children.add(n),n.join(()=>{this.children.delete(n);}),n}close(r$1={_tag:"Success",value:void 0}){if(!this.closed){for(this.closed=true,this.children.forEach(t=>t.interrupt()),this.subScopes.forEach(t=>t.close(r$1));this.finalizers.length>0;){let n=this.finalizers.pop()(r$1);r(n,this.env);}this.children.clear(),this.subScopes.clear();}}isClosed(){return this.closed}};function de(e){let r=new x({});try{return e(r)}finally{r.close();}}function T(e,r,t,n,o){return i((a,c)=>{let E=t.subScope(),s=false,R=E.fork(e,a),d=E.fork(r,a),m=u=>{E.fork(u,a).join(f=>{E.close(f),c(f);});};R.join(u=>{s||(s=true,m(n(u,d,E)));}),d.join(u=>{s||(s=true,m(o(u,R,E)));});})}var P=e=>e._tag==="None"?S:b(e.value),Z=e=>({_tag:"FromPull",pull:e}),we=(e,r,t=true)=>({_tag:"Merge",left:e,right:r,flip:t}),$=()=>({_tag:"Empty"}),W=e=>({_tag:"Emit",value:e}),F=(e,r)=>({_tag:"Concat",left:e,right:r}),M=e=>({_tag:"Flatten",stream:e});function L(e$1,r,t,n,o){return (a,c,E)=>{if(console.log(`[mergePull#${o}] winner=${e$1} exit=${a._tag}`),a._tag==="Failure"&&console.log(`[mergePull#${o}] failure error=`,a.error),a._tag==="Success"&&console.log(`[mergePull#${o}] success -> interrupt other`),a._tag==="Success"){let[d,m]=a.value;c.interrupt();let u=Z(e$1==="L"?v(m,t,!n,o):v(r,m,!n,o));return e([d,u])}let s=a.error;if(typeof s=="object"&&s!==null&&s._tag==="Interrupted")return f(s);let R=s;return R._tag==="None"?l(e$1==="L"?t:r):f(R)}}function v(e,r,t,n){return i((o,a)=>{let c=++n;console.log(`[mergePull#${c}] start flip=${t}`);let E=new x(o);console.log(`[mergePull#${c}] built pulls`);let s=l(e),R=l(r);console.log(`[mergePull#${c}] built pulls`);let d=L("L",e,r,t,c),m=L("R",e,r,t,c);console.log(`[mergePull#${c}] calling raceWith`);let u=T(s,R,E,d,m);console.log(`[mergePull#${c}] forking handler`),E.fork(u,o).join(f=>{console.log(`[mergePull#${c}] handler joined exit=${f._tag}`),E.close(f),console.log(`[mergePull#${c}] scope closed, calling cb`),a(f);});})}function Ce(e,r){return Z(v(e,r,true,0))}function l(e){switch(e._tag){case "Empty":return _(S);case "Emit":return g(w(e.value,r=>b(r)),r=>[r,$()]);case "FromPull":return console.log("[uncons] FromPull"),e.pull;case "Concat":return C(g(l(e.left),([r,t])=>[r,F(t,e.right)]),()=>l(e.right));case "Flatten":return N(l(e.stream),([r,t])=>C(g(l(r),([n,o])=>[n,F(o,M(t))]),()=>l(M(t))));case "Merge":return console.log("[makeMergePull] defined"),v(e.left,e.right,e.flip,0)}}function h(e,r){switch(e._tag){case "Empty":return $();case "Emit":return W(g(e.value,r));case "FromPull":return Z(g(e.pull,([t,n])=>[r(t),h(n,r)]));case "Concat":return F(h(e.left,r),h(e.right,r));case "Flatten":{let t=h(e.stream,n=>h(n,r));return M(t)}}}function Pe(e$1,r){let t=n=>Z(n>r?f(S):e([n,t(n+1)]));return t(e$1)}function D(e$1,r){let t=a(c(l(e$1),n=>P(n)),n=>f(n),([n,o])=>a(c(l(r),a=>P(a)),a=>f(a),([a,c])=>e([[n,a],D(o,c)])));return Z(t)}function Me(e$1,r){let t=n=>a(c(l(n),o=>P(o)),o=>o._tag==="None"?e(void 0):f(o),([o,a])=>k$1(c(r(o),c=>b(c)),()=>t(a)));return a(t(e$1),n=>n._tag==="None"?e(void 0):f(n.value),()=>e(void 0))}function $e(e){let r=$();for(let t=e.length-1;t>=0;t--){let n=W(k(e[t]));r=F(n,r);}return r}function je(e){let r=(t,n)=>a(l(t),o=>o._tag==="None"?k(n):_(o),([o,a])=>r(a,[...n,o]));return w(r(e,[]),t=>{if(t._tag==="Some")return t.value;throw new Error("unreachable: stream end handled as success")})}export{x as Scope,ie as catchAll,je as collectStream,F as concatStream,W as emitStream,$ as emptyStream,pe as end,_ as fail,N as flatMap,M as flattenStream,Me as foreachStream,$e as fromArray,Z as fromPull,Re as linkAbortController,Ae as makeCancelToken,g as map,w as mapError,h as mapStream,Ce as merge,we as mergeStream,S as none,C as orElseOptional,Pe as rangeStream,b as some,k as succeed,Ee as sync,l as uncons,de as withScope,D as zip};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brass-runtime",
3
- "version": "1.4.6",
3
+ "version": "1.5.0",
4
4
  "description": "Effect runtime utilities for TypeScript",
5
5
  "license": "ISC",
6
6
  "author": "",