@soffinal/stream 0.2.3 → 0.2.4
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 +63 -5
- package/dist/index.js +2 -2
- package/dist/index.js.map +3 -3
- package/dist/stream.d.ts +46 -5
- package/dist/stream.d.ts.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -5,9 +5,9 @@
|
|
|
5
5
|
[](https://opensource.org/licenses/MIT)
|
|
6
6
|
[](https://bundlephobia.com/package/@soffinal/stream)
|
|
7
7
|
|
|
8
|
-
> **
|
|
8
|
+
> **Type-safe event emitters that scale**
|
|
9
9
|
|
|
10
|
-
Stream
|
|
10
|
+
Stream is like EventEmitter, but better. Send events to multiple listeners, transform data with `filter` and `map`, and never worry about memory leaks. Works with DOM elements, WebSockets, user interactions, or any async data source. Fully typed, zero dependencies, 5.5KB.
|
|
11
11
|
|
|
12
12
|
## Table of Contents
|
|
13
13
|
|
|
@@ -30,6 +30,7 @@ Stream provides multicast event pipelines with functional composition capabiliti
|
|
|
30
30
|
- **Documentation-as-Distribution** - Copy-paste transformers embedded in JSDoc, no separate packages needed
|
|
31
31
|
- **Async-First** - Native async/await support with configurable concurrency control
|
|
32
32
|
- **Concurrency Strategies** - Sequential, concurrent-unordered, concurrent-ordered processing
|
|
33
|
+
- **Automatic Cleanup** - WeakRef-based listener cleanup prevents memory leaks
|
|
33
34
|
- **Multicast Streams** - One stream, unlimited consumers
|
|
34
35
|
- **Awaitable** - `await stream` for next value
|
|
35
36
|
- **Async Iterable** - Native `for await` loop support
|
|
@@ -110,6 +111,12 @@ const runningAverage = numbers
|
|
|
110
111
|
})
|
|
111
112
|
);
|
|
112
113
|
|
|
114
|
+
// Automatic cleanup with DOM elements
|
|
115
|
+
const element = document.createElement('div');
|
|
116
|
+
events.listen(value => {
|
|
117
|
+
element.textContent = value;
|
|
118
|
+
}, element); // Auto-removed when element is GC'd
|
|
119
|
+
|
|
113
120
|
// Copy-paste transformers from JSDoc
|
|
114
121
|
const limited = numbers.pipe(take(5)); // Limit to 5 items
|
|
115
122
|
const indexed = events.pipe(withIndex()); // Add indices
|
|
@@ -186,6 +193,55 @@ for await (const event of userEvents) {
|
|
|
186
193
|
}
|
|
187
194
|
```
|
|
188
195
|
|
|
196
|
+
### Automatic Listener Cleanup
|
|
197
|
+
|
|
198
|
+
Stream provides three cleanup mechanisms to prevent memory leaks:
|
|
199
|
+
|
|
200
|
+
```typescript
|
|
201
|
+
const stream = new Stream<string>();
|
|
202
|
+
|
|
203
|
+
// 1. Manual cleanup
|
|
204
|
+
const cleanup = stream.listen(value => console.log(value));
|
|
205
|
+
cleanup(); // Remove listener
|
|
206
|
+
|
|
207
|
+
// 2. AbortSignal cleanup
|
|
208
|
+
const controller = new AbortController();
|
|
209
|
+
stream.listen(value => console.log(value), controller.signal);
|
|
210
|
+
controller.abort(); // Remove listener
|
|
211
|
+
|
|
212
|
+
// 3. WeakRef automatic cleanup (NEW!)
|
|
213
|
+
const element = document.createElement('div');
|
|
214
|
+
stream.listen(value => {
|
|
215
|
+
element.textContent = value;
|
|
216
|
+
}, element);
|
|
217
|
+
// Listener automatically removed when element is garbage collected
|
|
218
|
+
// Perfect for DOM elements, components, and temporary objects
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
**WeakRef Benefits:**
|
|
222
|
+
- Zero memory leaks with DOM elements
|
|
223
|
+
- No manual cleanup needed
|
|
224
|
+
- Works with any object (components, instances, etc.)
|
|
225
|
+
- Leverages JavaScript's garbage collector
|
|
226
|
+
- Ideal for UI frameworks (React, Vue, Svelte, etc.)
|
|
227
|
+
|
|
228
|
+
```typescript
|
|
229
|
+
// Real-world example: Component lifecycle
|
|
230
|
+
function createComponent() {
|
|
231
|
+
const element = document.createElement('div');
|
|
232
|
+
const dataStream = new Stream<Data>();
|
|
233
|
+
|
|
234
|
+
// Auto-cleanup when component unmounts
|
|
235
|
+
dataStream.listen(data => {
|
|
236
|
+
element.innerHTML = renderTemplate(data);
|
|
237
|
+
}, element);
|
|
238
|
+
|
|
239
|
+
return element;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// When element is removed from DOM and GC'd, listener is automatically cleaned up
|
|
243
|
+
```
|
|
244
|
+
|
|
189
245
|
### Pipe: Stream-to-Stream Composition
|
|
190
246
|
|
|
191
247
|
The `pipe` method enforces composition - it only accepts functions that return Stream instances, maintaining the infinite pipeline:
|
|
@@ -547,9 +603,10 @@ activeUsers.add("user1");
|
|
|
547
603
|
|
|
548
604
|
#### Core Methods
|
|
549
605
|
|
|
550
|
-
- `push(...values: T[]): void` - Emit values to all listeners
|
|
551
|
-
- `listen(callback: (value: T) => void,
|
|
606
|
+
- `push(...values: T[]): void` - Emit values to all listeners (auto-removes GC'd listeners)
|
|
607
|
+
- `listen(callback: (value: T) => void, context?: AbortSignal | Stream<any> | object): () => void` - Add listener with optional cleanup
|
|
552
608
|
- `pipe<OUTPUT extends Stream<any>>(transformer: (stream: this) => OUTPUT): OUTPUT` - Apply any transformer
|
|
609
|
+
- `withContext(context: object): AsyncIterator<T>` - Async iterator bound to context lifetime
|
|
553
610
|
|
|
554
611
|
#### Async Interface
|
|
555
612
|
|
|
@@ -637,10 +694,11 @@ activeUsers.add("user1");
|
|
|
637
694
|
- **Fast startup** - Zero dependencies, instant initialization
|
|
638
695
|
- **Efficient pipelines** - Optimized transformer composition
|
|
639
696
|
- **Memory bounded** - Built-in backpressure handling
|
|
697
|
+
- **Automatic cleanup** - WeakRef prevents memory leaks
|
|
640
698
|
|
|
641
699
|
## Runtime Support
|
|
642
700
|
|
|
643
|
-
- **Modern browsers** supporting ES2020+
|
|
701
|
+
- **Modern browsers** supporting ES2020+ (WeakRef support)
|
|
644
702
|
- **Node.js** 16+
|
|
645
703
|
- **Deno** 1.0+
|
|
646
704
|
- **Bun** 1.0+
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
class z{_listeners=new
|
|
1
|
+
class z{_listeners=new Map;_generatorFn;_generator;_listenerAdded;_listenerRemoved;constructor(Z){this._generatorFn=Z instanceof z?()=>Z[Symbol.asyncIterator]():Z}get hasListeners(){return this._listeners.size>0}get listenerAdded(){if(!this._listenerAdded)this._listenerAdded=new z;return this._listenerAdded}get listenerRemoved(){if(!this._listenerRemoved)this._listenerRemoved=new z;return this._listenerRemoved}async*[Symbol.asyncIterator](){let Z=[],G,J=this.listen((Q)=>{Z.push(Q),G?.()});try{while(!0)if(Z.length)yield Z.shift();else await new Promise((Q)=>G=Q)}finally{J(),Z.length=0,G=void 0;return}}push(Z,...G){G.unshift(Z);let J=[];for(let Q of G)for(let[K,X]of this._listeners){if(X&&!X.deref()){J.push(K);continue}K(Q)}for(let Q of J)this._listeners.delete(Q)}async*withContext(Z){let G=new WeakRef(Z);try{for await(let J of this){if(!G.deref())break;yield J}}finally{return}}listen(Z,G){let J=this,Q,K;if(G instanceof AbortSignal){if(G?.aborted)return()=>{};G?.addEventListener("abort",X),Q=()=>G?.removeEventListener("abort",X)}else if(G instanceof z)Q=G?.listen(X);else if(G)K=new WeakRef(G);if(J._listeners.set(Z,K),J._listenerAdded?.push(),J._generatorFn&&J._listeners.size===1)J._generator=J._generatorFn(),(async()=>{for await(let Y of J._generator)J.push(Y)})();return X;function X(){if(J._listeners.delete(Z),J._listenerRemoved?.push(),J._listeners.size===0)J._generator?.return(),J._generator=void 0;Q?.(),Q=void 0,K=void 0}}then(Z){return new Promise((G)=>{let J=this.listen((Q)=>{G(Q),J()})}).then(Z)}pipe(Z){return Z(this)}}var V=(Z,G)=>{return(J)=>{if(!G||typeof G==="object"){let{strategy:K="sequential"}=G??{},X=Z;if(K==="sequential")return new z(async function*(){for await(let Y of J){let $=await X(Y);if($)yield Y;if($===void 0)return}});if(K==="concurrent-unordered")return new z(async function*(){let Y=Symbol.for("__abort"),$=[],_,H=J.listen(async(W)=>{let j=await X(W);if(j!==!1)j===void 0?$.push(Y):$.push(W),_?.(),_=void 0});try{while(!0)if($.length){let W=$.shift();if(W===Y)break;yield W}else await new Promise((W)=>_=W)}finally{$.length=0,H(),_=void 0}});if(K==="concurrent-ordered")return new z(async function*(){let Y=[],$,_=J.listen((H)=>{let W=X(H);Y.push({resultPromise:W,value:H}),(async()=>{await W,$?.(),$=void 0})()});try{while(!0)if(Y.length){let{resultPromise:H,value:W}=Y.shift(),j=await H;if(j)yield W;if(j===void 0)break}else await new Promise((H)=>$=H)}finally{Y.length=0,_(),$=void 0}})}let Q=G;return new z(async function*(){let K=Z;for await(let X of J){let Y=await Q(K,X);if(!Y)return;let[$,_]=Y;if(K=_,$)yield X}})}};var I=(Z,G)=>{return(J)=>{if(!G||typeof G==="object"){let{strategy:K="sequential"}=G??{},X=Z;if(K==="sequential")return new z(async function*(){for await(let Y of J)yield await X(Y)});if(K==="concurrent-unordered")return new z(async function*(){let Y=[],$,_=J.listen(async(H)=>{Y.push(await X(H)),$?.(),$=void 0});try{while(!0)if(Y.length)yield Y.shift();else await new Promise((H)=>$=H)}finally{Y.length=0,_(),$=void 0}});if(K==="concurrent-ordered")return new z(async function*(){let Y=[],$,_=J.listen((H)=>{let W=X(H);Y.push(W),(async()=>{await W,$?.(),$=void 0})()});try{while(!0)if(Y.length)yield await Y.shift();else await new Promise((H)=>$=H)}finally{Y.length=0,_(),$=void 0}})}let Q=G;return new z(async function*(){let K=Z;for await(let X of J){let[Y,$]=await Q(K,X);K=$,yield Y}})}};function q(...Z){return(G)=>new z(async function*(){let J=[G,...Z],Q=[],K,X=J.map((Y)=>Y.listen(($)=>{Q.push($),K?.()}));try{while(!0)if(Q.length)yield Q.shift();else await new Promise((Y)=>K=Y)}finally{X.forEach((Y)=>Y())}})}function A(Z=0){return(G)=>{return new z(async function*(){for await(let J of G)if(Array.isArray(J)){let Q=J.flat(Z);for(let K=0;K<Q.length;K++)yield Q[K]}else yield J})}}class B{_items=[];_insertStream;_deleteStream;_clearStream;constructor(Z){if(Z)this._items=[...Z];let G=this;function J(K,X){if(X===0)return 0;return K<0?(K%X+X)%X:K%X}this.insert=new Proxy((K,X)=>{let Y=K<0?Math.max(0,G._items.length+K+1):Math.min(K,G._items.length);return G._items.splice(Y,0,X),G._insertStream?.push([Y,X]),Q},{get(K,X){if(X in K)return K[X];if(!G._insertStream)G._insertStream=new z;return G._insertStream[X]}}),this.delete=new Proxy((K)=>{if(K<0||K>=G._items.length)return;let X=G._items.splice(K,1)[0];return G._deleteStream?.push([K,X]),X},{get(K,X){if(X in K)return K[X];if(!G._deleteStream)G._deleteStream=new z;return G._deleteStream[X]}}),this.clear=new Proxy(()=>{if(G._items.length>0)G._items.length=0,G._clearStream?.push()},{get(K,X){if(X in K)return K[X];if(!G._clearStream)G._clearStream=new z;return G._clearStream[X]}});let Q=new Proxy(this,{get(K,X){if(typeof X==="string"&&/^-?\d+$/.test(X)){let Y=parseInt(X);if(K._items.length===0)return;let $=J(Y,K._items.length);return K._items[$]}return K[X]},set(K,X,Y){if(typeof X==="string"&&/^-?\d+$/.test(X)){let $=parseInt(X);if(K._items.length===0)return K._items.push(Y),K._insertStream?.push([0,Y]),!0;let _=J($,K._items.length);if(K._items[_]!==Y)K._items[_]=Y,K._insertStream?.push([_,Y]);return!0}return K[X]=Y,!0}});return Q}get(Z){return this._items[Z]}get length(){return this._items.length}values(){return this._items[Symbol.iterator]()}[Symbol.iterator](){return this._items[Symbol.iterator]()}}class D extends globalThis.Map{_setStream;_deleteStream;_clearStream;constructor(Z){super(Z);let G=this;this.set=new Proxy((J,Q)=>{if(globalThis.Map.prototype.has.call(G,J)&&globalThis.Map.prototype.get.call(G,J)===Q)return G;return globalThis.Map.prototype.set.call(G,J,Q),G._setStream?.push([J,Q]),G},{get(J,Q){if(Q in J)return J[Q];if(!G._setStream)G._setStream=new z;return G._setStream[Q]}}),this.delete=new Proxy((J)=>{if(!globalThis.Map.prototype.has.call(G,J))return!1;let Q=globalThis.Map.prototype.get.call(G,J);return globalThis.Map.prototype.delete.call(G,J),G._deleteStream?.push([J,Q]),!0},{get(J,Q){if(Q in J)return J[Q];if(!G._deleteStream)G._deleteStream=new z;return G._deleteStream[Q]}}),this.clear=new Proxy(()=>{if(G.size>0)globalThis.Map.prototype.clear.call(G),G._clearStream?.push()},{get(J,Q){if(Q in J)return J[Q];if(!G._clearStream)G._clearStream=new z;return G._clearStream[Q]}})}}class F extends globalThis.Set{_addStream;_deleteStream;_clearStream;constructor(Z){super(Z);let G=this;this.add=new Proxy((J)=>{if(globalThis.Set.prototype.has.call(G,J))return G;return globalThis.Set.prototype.add.call(G,J),G._addStream?.push(J),G},{get(J,Q){if(Q in J)return J[Q];if(!G._addStream)G._addStream=new z;return G._addStream[Q]}}),this.delete=new Proxy((J)=>{if(!globalThis.Set.prototype.has.call(G,J))return!1;return globalThis.Set.prototype.delete.call(G,J),G._deleteStream?.push(J),!0},{get(J,Q){if(Q in J)return J[Q];if(!G._deleteStream)G._deleteStream=new z;return G._deleteStream[Q]}}),this.clear=new Proxy(()=>{if(G.size>0)globalThis.Set.prototype.clear.call(G),G._clearStream?.push()},{get(J,Q){if(Q in J)return J[Q];if(!G._clearStream)G._clearStream=new z;return G._clearStream[Q]}})}}class N extends z{_value;constructor(Z,G){super(G);this._value=Z}push(...Z){for(let G of Z)this.value=G}get value(){return this._value}set value(Z){this._value=Z,super.push(Z)}}export{q as merge,I as map,A as flat,V as filter,z as Stream,N as State,F as Set,D as Map,B as List};
|
|
2
2
|
|
|
3
|
-
//# debugId=
|
|
3
|
+
//# debugId=652D0058F0A0040264756E2164756E21
|
|
4
4
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/stream.ts", "../src/transformers/filter.ts", "../src/transformers/map.ts", "../src/transformers/merge.ts", "../src/transformers/flat.ts", "../src/reactive/list.ts", "../src/reactive/map.ts", "../src/reactive/set.ts", "../src/reactive/state.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"/**\n * A reactive streaming library that provides async-first data structures with built-in event streams.\n *\n * @template VALUE - The type of values that flow through the stream\n *\n * @example\n * ```typescript\n * // Basic usage\n * const stream = new Stream<number>();\n * stream.listen(value => console.log(value));\n * stream.push(1, 2, 3);\n *\n * // With async generator\n * const timerStream = new Stream(async function* () {\n * let count = 0;\n * while (count < 5) {\n * yield count++;\n * await new Promise(resolve => setTimeout(resolve, 1000));\n * }\n * });\n *\n * // Async iteration\n * for await (const value of stream) {\n * console.log(value);\n * if (value === 10) break;\n * }\n * ```\n *\n * @example\n * // 📦 COPY-PASTE TRANSFORMERS LIBRARY - Essential transformers for immediate use\n *\n * // FILTERING TRANSFORMERS\n *\n * const take = <T>(n: number) =>\n * filter<T, { count: number }>({ count: 0 }, (state, value) => {\n * if (state.count >= n) return;\n * return [true, { count: state.count + 1 }];\n * });\n *\n * const distinct = <T>() =>\n * filter<T, { seen: Set<T> }>({ seen: new Set() }, (state, value) => {\n * if (state.seen.has(value)) return [false, state];\n * state.seen.add(value);\n * return [true, state];\n * });\n *\n * const tap = <T>(fn: (value: T) => void | Promise<void>) =>\n * filter<T, {}>({}, async (_, value) => {\n * await fn(value);\n * return [true, {}];\n * });\n *\n * // MAPPING TRANSFORMERS\n *\n * const withIndex = <T>() =>\n * map<T, { index: number }, { value: T; index: number }>(\n * { index: 0 },\n * (state, value) => [\n * { value, index: state.index },\n * { index: state.index + 1 }\n * ]\n * );\n *\n * const delay = <T>(ms: number) =>\n * map<T, {}, T>({}, async (_, value) => {\n * await new Promise(resolve => setTimeout(resolve, ms));\n * return [value, {}];\n * });\n *\n * const scan = <T, U>(fn: (acc: U, value: T) => U, initial: U) =>\n * map<T, { acc: U }, U>({ acc: initial }, (state, value) => {\n * const newAcc = fn(state.acc, value);\n * return [newAcc, { acc: newAcc }];\n * });\n *\n * // STATE CONVERTER\n * const toState = <T>(initialValue: T) => (stream: Stream<T>) => {\n * return new State(initialValue, stream);\n * };\n *\n * // Usage: stream.pipe(simpleFilter(x => x > 0)).pipe(take(5)).pipe(toState(0));\n */\nexport class Stream<VALUE = unknown> implements AsyncIterable<VALUE> {\n protected _listeners: Set<(value: VALUE) => void> = new Set<(value: VALUE) => void>();\n protected _generatorFn: Stream.FunctionGenerator<VALUE> | undefined;\n protected _generator: AsyncGenerator<VALUE, void> | undefined;\n protected _listenerAdded: Stream<void> | undefined;\n protected _listenerRemoved: Stream<void> | undefined;\n\n /**\n * Creates a new Stream instance.\n *\n * @param generatorFn - Optional async generator function to produce values you can use it for creating stream with custom transformation\n *\n * @see {@link Stream} - Complete copy-paste transformers library\n *\n * @example\n * ```typescript\n * // Empty stream\n * const stream = new Stream<string>();\n *\n * // Stream with generator\n * const countdown = new Stream(async function* () {\n * for (let i = 5; i > 0; i--) {\n * yield i;\n * await new Promise(resolve => setTimeout(resolve, 1000));\n * }\n * });\n *\n * // Stream with custom transformer\n * function filter<VALUE>(source:Stream<VALUE>,predicate:(value:VALUE) => boolean):Stream<VALUE>{\n * return new Stream<VALUE>(async function* () {\n * for await (const value of source) {\n * if (predicate(value)) yield value ;\n * }\n * });\n * }\n * const source = new Stream<number>();\n * const even = filter(source,v=> v % 2 === 0)\n * even.listen(console.log);\n * source.push(1, 2, 3, 4); // 2,4\n * ```\n */\n constructor();\n constructor(stream: Stream.FunctionGenerator<VALUE> | Stream<VALUE>);\n constructor(stream?: Stream.FunctionGenerator<VALUE> | Stream<VALUE>) {\n this._generatorFn = stream instanceof Stream ? () => stream[Symbol.asyncIterator]() : stream;\n }\n\n /**\n * Returns true if the stream has active listeners.\n *\n * @see {@link Stream} - Complete copy-paste transformers library\n *\n * @example\n * ```typescript\n * const stream = new Stream<number>();\n * console.log(stream.hasListeners); // false\n *\n * const cleanup = stream.listen(value => console.log(value));\n * console.log(stream.hasListeners); // true\n *\n * cleanup();\n * console.log(stream.hasListeners); // false\n * ```\n */\n get hasListeners(): boolean {\n return this._listeners.size > 0;\n }\n\n /**\n * Stream that emits when a listener is added.\n *\n * @see {@link Stream} - Complete copy-paste transformers library\n *\n * @example\n * ```typescript\n * const stream = new Stream<number>();\n * stream.listenerAdded.listen(() => console.log('Listener added'));\n *\n * stream.listen(value => console.log(value)); // Triggers 'Listener added'\n * ```\n */\n get listenerAdded(): Stream<void> {\n if (!this._listenerAdded) this._listenerAdded = new Stream<void>();\n return this._listenerAdded;\n }\n\n /**\n * Stream that emits when a listener is removed.\n *\n * @see {@link Stream} - Complete copy-paste transformers library\n *\n * @example\n * ```typescript\n * const stream = new Stream<number>();\n * stream.listenerRemoved.listen(() => console.log('Listener removed'));\n *\n * const cleanup = stream.listen(value => console.log(value));\n * cleanup(); // Triggers 'Listener removed'\n * ```\n */\n get listenerRemoved(): Stream<void> {\n if (!this._listenerRemoved) this._listenerRemoved = new Stream<void>();\n return this._listenerRemoved;\n }\n async *[Symbol.asyncIterator](): AsyncGenerator<VALUE, void> {\n const queue: VALUE[] = [];\n let resolver: Function | undefined;\n\n const abort = this.listen((value) => {\n queue.push(value);\n resolver?.();\n });\n\n try {\n while (true) {\n if (queue.length) yield queue.shift()!;\n else await new Promise<void>((resolve) => (resolver = resolve));\n }\n } finally {\n abort();\n queue.length = 0;\n resolver = undefined;\n return;\n }\n }\n\n /**\n * Pushes one or more values to all listeners.\n *\n * @see {@link Stream} - Complete copy-paste transformers library\n *\n * @param value - The first value to push\n * @param values - Additional values to push\n *\n * @example\n * ```typescript\n * const stream = new Stream<number>();\n * stream.listen(value => console.log('Received:', value));\n *\n * stream.push(1); // Received: 1\n * stream.push(2, 3, 4); // Received: 2, Received: 3, Received: 4\n * ```\n */\n push(value: VALUE, ...values: VALUE[]): void {\n values.unshift(value);\n for (const value of values) {\n for (const listener of this._listeners) {\n listener(value);\n }\n }\n }\n\n /**\n * Adds a listener to the stream.\n *\n * @param listener - Function to call when values are pushed\n * @param signal - Optional AbortSignal for cleanup\n * @returns Cleanup function to remove the listener\n *\n * @see {@link Stream} - Complete copy-paste transformers library\n *\n * @example\n * ```typescript\n * const stream = new Stream<string>();\n *\n * // Basic listener\n * const cleanup = stream.listen(value => console.log(value));\n *\n * // With AbortSignal\n * const controller = new AbortController();\n * stream.listen(value => console.log(value), controller.signal);\n * controller.abort(); // Removes listener\n *\n * // Manual cleanup\n * cleanup();\n * ```\n */\n listen(listener: (value: VALUE) => void, signal?: AbortSignal | Stream<any>): () => void {\n const self = this;\n let signalAbort: Function | undefined;\n\n if (signal instanceof AbortSignal) {\n if (signal?.aborted) return () => {};\n signal?.addEventListener(\"abort\", abort);\n signalAbort = () => signal?.removeEventListener(\"abort\", abort);\n } else {\n signalAbort = signal?.listen(abort);\n }\n\n self._listeners.add(listener);\n\n self._listenerAdded?.push();\n\n if (self._generatorFn && self._listeners.size === 1) {\n self._generator = self._generatorFn();\n (async () => {\n for await (const value of self._generator!) {\n self.push(value);\n }\n })();\n }\n return abort;\n function abort(): void {\n self._listeners.delete(listener);\n self._listenerRemoved?.push();\n if (self._listeners.size === 0) {\n self._generator?.return();\n self._generator = undefined;\n }\n signalAbort?.();\n }\n }\n\n /**\n * Promise-like interface that resolves with the next value.\n *\n * @param onfulfilled - Optional transformation function\n * @returns Promise that resolves with the first value\n *\n * @see {@link Stream} - Complete copy-paste transformers library\n *\n * @example\n * ```typescript\n * const stream = new Stream<number>();\n *\n * setTimeout(()=>{\n * stream.push(5);\n * })\n * // Wait for first value\n * const firstValue = await stream; // Resolves promises with 5\n *\n *\n * ```\n */\n then(onfulfilled?: ((value: VALUE) => VALUE | PromiseLike<VALUE>) | null): Promise<VALUE> {\n return new Promise<VALUE>((resolve) => {\n const abort = this.listen((value) => {\n resolve(value);\n abort();\n });\n }).then(onfulfilled);\n }\n\n /**\n * Applies a transformer function to this stream, enabling functional composition.\n *\n * @param transformer - Function that takes a stream and returns any output type\n * @returns The result of the transformer function\n *\n * @see {@link Stream} - Complete copy-paste transformers library\n *\n * @example\n * ```typescript\n * const numbers = new Stream<number>();\n *\n * // Chain transformers\n * const result = numbers\n * .pipe(filter({}, (_, n) => [n > 0, {}]))\n * .pipe(map({}, (_, n) => [n * 2, {}]))\n * .pipe(toState(0));\n *\n * // Custom transformer\n * const throttle = <T>(ms: number) => (stream: Stream<T>) =>\n * new Stream<T>(async function* () {\n * let lastEmit = 0;\n * for await (const value of stream) {\n * const now = Date.now();\n * if (now - lastEmit >= ms) {\n * yield value;\n * lastEmit = now;\n * }\n * }\n * });\n *\n * // Transform to any type\n * const stringResult = numbers.pipe(throttle(1000));\n * const stateResult = numbers.pipe(toState(0));\n * ```\n */\n pipe<OUTPUT extends Stream<any>>(transformer: (stream: this) => OUTPUT): OUTPUT {\n return transformer(this);\n }\n}\n\nexport namespace Stream {\n export type ValueOf<STREAM> = STREAM extends Stream<infer VALUE> ? VALUE : never;\n export type FunctionGenerator<VALUE> = () => AsyncGenerator<VALUE, void>;\n}\n",
|
|
5
|
+
"/**\n * A reactive streaming library that provides async-first data structures with built-in event streams.\n *\n * @template VALUE - The type of values that flow through the stream\n *\n * @example\n * ```typescript\n * // Basic usage\n * const stream = new Stream<number>();\n * stream.listen(value => console.log(value));\n * stream.push(1, 2, 3);\n *\n * // With async generator\n * const timerStream = new Stream(async function* () {\n * let count = 0;\n * while (count < 5) {\n * yield count++;\n * await new Promise(resolve => setTimeout(resolve, 1000));\n * }\n * });\n *\n * // Async iteration\n * for await (const value of stream) {\n * console.log(value);\n * if (value === 10) break;\n * }\n * ```\n *\n * @example\n * // 📦 COPY-PASTE TRANSFORMERS LIBRARY - Essential transformers for immediate use\n *\n * // FILTERING TRANSFORMERS\n *\n * const take = <T>(n: number) =>\n * filter<T, { count: number }>({ count: 0 }, (state, value) => {\n * if (state.count >= n) return;\n * return [true, { count: state.count + 1 }];\n * });\n *\n * const distinct = <T>() =>\n * filter<T, { seen: Set<T> }>({ seen: new Set() }, (state, value) => {\n * if (state.seen.has(value)) return [false, state];\n * state.seen.add(value);\n * return [true, state];\n * });\n *\n * const tap = <T>(fn: (value: T) => void | Promise<void>) =>\n * filter<T, {}>({}, async (_, value) => {\n * await fn(value);\n * return [true, {}];\n * });\n *\n * // MAPPING TRANSFORMERS\n *\n * const withIndex = <T>() =>\n * map<T, { index: number }, { value: T; index: number }>(\n * { index: 0 },\n * (state, value) => [\n * { value, index: state.index },\n * { index: state.index + 1 }\n * ]\n * );\n *\n * const delay = <T>(ms: number) =>\n * map<T, {}, T>({}, async (_, value) => {\n * await new Promise(resolve => setTimeout(resolve, ms));\n * return [value, {}];\n * });\n *\n * const scan = <T, U>(fn: (acc: U, value: T) => U, initial: U) =>\n * map<T, { acc: U }, U>({ acc: initial }, (state, value) => {\n * const newAcc = fn(state.acc, value);\n * return [newAcc, { acc: newAcc }];\n * });\n *\n * // STATE CONVERTER\n * const toState = <T>(initialValue: T) => (stream: Stream<T>) => {\n * return new State(initialValue, stream);\n * };\n *\n * // Usage: stream.pipe(filter(x => x > 0)).pipe(take(5)).pipe(toState(0));\n */\nexport class Stream<VALUE = unknown> implements AsyncIterable<VALUE> {\n protected _listeners: Map<(value: VALUE) => void, WeakRef<object> | undefined> = new Map();\n protected _generatorFn: Stream.FunctionGenerator<VALUE> | undefined;\n protected _generator: AsyncGenerator<VALUE, void> | undefined;\n protected _listenerAdded: Stream<void> | undefined;\n protected _listenerRemoved: Stream<void> | undefined;\n\n /**\n * Creates a new Stream instance.\n *\n * @param generatorFn - Optional async generator function to produce values you can use it for creating stream with custom transformation\n *\n * @see {@link Stream} - Complete copy-paste transformers library\n *\n * @example\n * ```typescript\n * // Empty stream\n * const stream = new Stream<string>();\n *\n * // Stream with generator\n * const countdown = new Stream(async function* () {\n * for (let i = 5; i > 0; i--) {\n * yield i;\n * await new Promise(resolve => setTimeout(resolve, 1000));\n * }\n * });\n *\n * // Stream with custom transformer\n * function filter<VALUE>(source:Stream<VALUE>,predicate:(value:VALUE) => boolean):Stream<VALUE>{\n * return new Stream<VALUE>(async function* () {\n * for await (const value of source) {\n * if (predicate(value)) yield value ;\n * }\n * });\n * }\n * const source = new Stream<number>();\n * const even = filter(source,v=> v % 2 === 0)\n * even.listen(console.log);\n * source.push(1, 2, 3, 4); // 2,4\n * ```\n */\n constructor();\n constructor(stream: Stream.FunctionGenerator<VALUE> | Stream<VALUE>);\n constructor(stream?: Stream.FunctionGenerator<VALUE> | Stream<VALUE>) {\n this._generatorFn = stream instanceof Stream ? () => stream[Symbol.asyncIterator]() : stream;\n }\n\n /**\n * Returns true if the stream has active listeners.\n *\n * @see {@link Stream} - Complete copy-paste transformers library\n *\n * @example\n * ```typescript\n * const stream = new Stream<number>();\n * console.log(stream.hasListeners); // false\n *\n * const cleanup = stream.listen(value => console.log(value));\n * console.log(stream.hasListeners); // true\n *\n * cleanup();\n * console.log(stream.hasListeners); // false\n * ```\n */\n get hasListeners(): boolean {\n return this._listeners.size > 0;\n }\n\n /**\n * Stream that emits when a listener is added.\n *\n * @see {@link Stream} - Complete copy-paste transformers library\n *\n * @example\n * ```typescript\n * const stream = new Stream<number>();\n * stream.listenerAdded.listen(() => console.log('Listener added'));\n *\n * stream.listen(value => console.log(value)); // Triggers 'Listener added'\n * ```\n */\n get listenerAdded(): Stream<void> {\n if (!this._listenerAdded) this._listenerAdded = new Stream<void>();\n return this._listenerAdded;\n }\n\n /**\n * Stream that emits when a listener is removed.\n *\n * @see {@link Stream} - Complete copy-paste transformers library\n *\n * @example\n * ```typescript\n * const stream = new Stream<number>();\n * stream.listenerRemoved.listen(() => console.log('Listener removed'));\n *\n * const cleanup = stream.listen(value => console.log(value));\n * cleanup(); // Triggers 'Listener removed'\n * ```\n */\n get listenerRemoved(): Stream<void> {\n if (!this._listenerRemoved) this._listenerRemoved = new Stream<void>();\n return this._listenerRemoved;\n }\n async *[Symbol.asyncIterator](): AsyncGenerator<VALUE, void> {\n const queue: VALUE[] = [];\n let resolver: Function | undefined;\n\n const abort = this.listen((value) => {\n queue.push(value);\n resolver?.();\n });\n\n try {\n while (true) {\n if (queue.length) yield queue.shift()!;\n else await new Promise<void>((resolve) => (resolver = resolve));\n }\n } finally {\n abort();\n queue.length = 0;\n resolver = undefined;\n return;\n }\n }\n\n /**\n * Pushes one or more values to all listeners.\n * Automatically removes listeners whose context objects have been garbage collected.\n *\n * @see {@link Stream} - Complete copy-paste transformers library\n *\n * @param value - The first value to push\n * @param values - Additional values to push\n *\n * @example\n * ```typescript\n * const stream = new Stream<number>();\n * stream.listen(value => console.log('Received:', value));\n *\n * stream.push(1); // Received: 1\n * stream.push(2, 3, 4); // Received: 2, Received: 3, Received: 4\n * ```\n */\n push(value: VALUE, ...values: VALUE[]): void {\n values.unshift(value);\n const deadListeners = [];\n for (const value of values) {\n for (const [listener, ctx] of this._listeners) {\n if (ctx && !ctx.deref()) {\n deadListeners.push(listener);\n continue;\n }\n listener(value);\n }\n }\n for (const listener of deadListeners) {\n this._listeners.delete(listener);\n }\n }\n\n /**\n * Creates an async iterator bound to a context object's lifetime.\n * Automatically stops iteration when the context is garbage collected.\n *\n * @param context - Object whose lifetime controls the iteration\n * @returns Async generator that stops when context is GC'd\n *\n * @see {@link Stream} - Complete copy-paste transformers library\n *\n * @example\n * ```typescript\n * const stream = new Stream<number>();\n * const element = document.createElement('div');\n *\n * (async () => {\n * for await (const value of stream.withContext(element)) {\n * element.textContent = String(value);\n * }\n * })();\n *\n * // When element is removed and GC'd, iteration stops automatically\n * ```\n */\n async *withContext(context: object) {\n const ref = new WeakRef(context);\n try {\n for await (const value of this) {\n if (!ref.deref()) break;\n yield value;\n }\n } finally {\n return;\n }\n }\n\n /**\n * Adds a listener to the stream with optional automatic cleanup.\n *\n * @param listener - Function to call when values are pushed\n * @param signalOrStreamOrContext - Optional cleanup mechanism:\n * - AbortSignal: Remove listener when signal is aborted\n * - Stream: Remove listener when stream emits\n * - Object: Remove listener when object is garbage collected (WeakRef)\n * @returns Cleanup function to remove the listener\n *\n * @see {@link Stream} - Complete copy-paste transformers library\n *\n * @example\n * ```typescript\n * const stream = new Stream<string>();\n *\n * // Basic listener\n * const cleanup = stream.listen(value => console.log(value));\n *\n * // With AbortSignal\n * const controller = new AbortController();\n * stream.listen(value => console.log(value), controller.signal);\n * controller.abort(); // Removes listener\n *\n * // With Stream\n * const stopSignal = new Stream<void>();\n * stream.listen(value => console.log(value), stopSignal);\n * stopSignal.push(); // Removes listener\n *\n * // With DOM element (auto-cleanup when GC'd)\n * const element = document.createElement('div');\n * stream.listen(value => element.textContent = value, element);\n * // Listener automatically removed when element is garbage collected\n *\n * // Manual cleanup\n * cleanup();\n * ```\n */\n listen(listener: (value: VALUE) => void): () => void;\n listen(listener: (value: VALUE) => void, signal: AbortSignal): () => void;\n listen(listener: (value: VALUE) => void, stream: Stream<any>): () => void;\n listen(listener: (value: VALUE) => void, context: object): () => void;\n listen(listener: (value: VALUE) => void, signalOrStreamOrContext?: AbortSignal | Stream<any> | object): () => void {\n const self = this;\n let signalAbort: Function | undefined;\n let context: WeakRef<object> | undefined;\n\n if (signalOrStreamOrContext instanceof AbortSignal) {\n if (signalOrStreamOrContext?.aborted) return () => {};\n signalOrStreamOrContext?.addEventListener(\"abort\", abort);\n signalAbort = () => signalOrStreamOrContext?.removeEventListener(\"abort\", abort);\n } else if (signalOrStreamOrContext instanceof Stream) {\n signalAbort = signalOrStreamOrContext?.listen(abort);\n } else if (signalOrStreamOrContext) {\n context = new WeakRef(signalOrStreamOrContext);\n }\n\n self._listeners.set(listener, context);\n\n self._listenerAdded?.push();\n\n if (self._generatorFn && self._listeners.size === 1) {\n self._generator = self._generatorFn();\n (async () => {\n for await (const value of self._generator!) {\n self.push(value);\n }\n })();\n }\n return abort;\n function abort(): void {\n self._listeners.delete(listener);\n self._listenerRemoved?.push();\n if (self._listeners.size === 0) {\n self._generator?.return();\n self._generator = undefined;\n }\n signalAbort?.();\n signalAbort = undefined;\n context = undefined;\n }\n }\n\n /**\n * Promise-like interface that resolves with the next value.\n *\n * @param onfulfilled - Optional transformation function\n * @returns Promise that resolves with the first value\n *\n * @see {@link Stream} - Complete copy-paste transformers library\n *\n * @example\n * ```typescript\n * const stream = new Stream<number>();\n *\n * setTimeout(()=>{\n * stream.push(5);\n * })\n * // Wait for first value\n * const firstValue = await stream; // Resolves promises with 5\n *\n *\n * ```\n */\n then(onfulfilled?: ((value: VALUE) => VALUE | PromiseLike<VALUE>) | null): Promise<VALUE> {\n return new Promise<VALUE>((resolve) => {\n const abort = this.listen((value) => {\n resolve(value);\n abort();\n });\n }).then(onfulfilled);\n }\n\n /**\n * Applies a transformer function to this stream, enabling functional composition.\n *\n * @param transformer - Function that takes a stream and returns any output type\n * @returns The result of the transformer function\n *\n * @see {@link Stream} - Complete copy-paste transformers library\n *\n * @example\n * ```typescript\n * const numbers = new Stream<number>();\n *\n * // Chain transformers\n * const result = numbers\n * .pipe(filter({}, (_, n) => [n > 0, {}]))\n * .pipe(map({}, (_, n) => [n * 2, {}]))\n * .pipe(toState(0));\n *\n * // Custom transformer\n * const throttle = <T>(ms: number) => (stream: Stream<T>) =>\n * new Stream<T>(async function* () {\n * let lastEmit = 0;\n * for await (const value of stream) {\n * const now = Date.now();\n * if (now - lastEmit >= ms) {\n * yield value;\n * lastEmit = now;\n * }\n * }\n * });\n *\n * // Transform to any type\n * const stringResult = numbers.pipe(throttle(1000));\n * const stateResult = numbers.pipe(toState(0));\n * ```\n */\n pipe<OUTPUT extends Stream<any>>(transformer: (stream: this) => OUTPUT): OUTPUT {\n return transformer(this);\n }\n}\n\nexport namespace Stream {\n export type ValueOf<STREAM> = STREAM extends Stream<infer VALUE> ? VALUE : never;\n export type FunctionGenerator<VALUE> = () => AsyncGenerator<VALUE, void>;\n}\n",
|
|
6
6
|
"import { Stream } from \"../stream.ts\";\n\n/**\n * Adaptive filter transformer that maintains state and can terminate streams.\n * Supports multiple concurrency strategies for async predicates.\n *\n * @template VALUE - The type of values flowing through the stream\n * @template STATE - The type of the internal state object\n * @template FILTERED - The type of filtered values (for type guards)\n *\n * @param initialStateOrPredicate - Initial state object or predicate function\n * @param statefulPredicateOrOptions - Stateful predicate function or options for simple predicates\n *\n * @returns A transformer function that can be used with `.pipe()`\n *\n * @see {@link Stream} - Complete copy-paste transformers library\n *\n * @example\n * // Simple synchronous filtering\n * stream.pipe(filter((value) => value > 0))\n *\n * @example\n * // Type guard filtering (synchronous only)\n * stream.pipe(filter((value): value is number => typeof value === \"number\"))\n *\n * @example\n * // Async filtering with sequential strategy (default)\n * stream.pipe(\n * filter(async (value) => {\n * const valid = await validateAsync(value);\n * return valid;\n * })\n * )\n *\n * @example\n * // Async filtering with concurrent-unordered strategy\n * stream.pipe(\n * filter(async (value) => {\n * const result = await expensiveCheck(value);\n * return result;\n * }, { strategy: \"concurrent-unordered\" })\n * )\n *\n * @example\n * // Async filtering with concurrent-ordered strategy\n * stream.pipe(\n * filter(async (value) => {\n * const result = await apiValidation(value);\n * return result;\n * }, { strategy: \"concurrent-ordered\" })\n * )\n *\n * @example\n * // Stateful filtering (always sequential)\n * stream.pipe(\n * filter({ count: 0 }, (state, value) => {\n * if (state.count >= 10) return; // Terminate after 10 items\n * return [value > 0, { count: state.count + 1 }];\n * })\n * )\n *\n * @example\n * // Stateful filtering with complex state\n * stream.pipe(\n * filter({ seen: new Set() }, (state, value) => {\n * if (state.seen.has(value)) return [false, state]; // Duplicate\n * state.seen.add(value);\n * return [true, state]; // First occurrence\n * })\n * )\n *\n * @example\n * // Stream termination\n * stream.pipe(\n * filter(async (value) => {\n * if (value === \"STOP\") return; // Terminates stream\n * return value.length > 3;\n * })\n * )\n */\nexport const filter: filter.Filter = <\n VALUE,\n STATE extends Record<string, unknown> = {},\n FILTERED extends VALUE = VALUE\n>(\n initialStateOrPredicate: STATE | filter.Predicate<VALUE> | filter.GuardPredicate<VALUE, FILTERED>,\n statefulPredicateOrOptions?:\n | filter.StatefulPredicate<VALUE, STATE>\n | filter.StatefulGuardPredicate<VALUE, STATE, FILTERED>\n | filter.Options\n): ((stream: Stream<VALUE>) => Stream<FILTERED>) => {\n return (stream: Stream<VALUE>): Stream<FILTERED> => {\n if (!statefulPredicateOrOptions || typeof statefulPredicateOrOptions === \"object\") {\n const { strategy = \"sequential\" } = statefulPredicateOrOptions ?? {};\n\n const predicate = initialStateOrPredicate as filter.Predicate<VALUE>;\n\n if (strategy === \"sequential\") {\n return new Stream<FILTERED>(async function* () {\n for await (const value of stream) {\n const result = await predicate(value);\n if (result) yield value as FILTERED;\n if (result === undefined) return;\n }\n });\n }\n\n if (strategy === \"concurrent-unordered\") {\n return new Stream<FILTERED>(async function* () {\n const ABORT = Symbol.for(\"__abort\");\n\n let queue = new Array<FILTERED | typeof ABORT>();\n let resolver: Function | undefined;\n\n const abort = stream.listen(async (value) => {\n const result = await predicate(value);\n if (result !== false) {\n result === undefined ? queue.push(ABORT) : queue.push(value as FILTERED);\n resolver?.();\n resolver = undefined;\n }\n });\n\n try {\n while (true) {\n if (queue.length) {\n const value = queue.shift()!;\n if (value === ABORT) break;\n yield value;\n } else {\n await new Promise<void>((r) => (resolver = r));\n }\n }\n } finally {\n queue.length = 0;\n abort();\n resolver = undefined;\n }\n });\n }\n\n if (strategy === \"concurrent-ordered\") {\n return new Stream<FILTERED>(async function* () {\n let queue = new Array<{ resultPromise: boolean | void | Promise<boolean | void>; value: VALUE }>();\n let resolver: Function | undefined;\n\n const abort = stream.listen((value) => {\n const pormise = predicate(value);\n queue.push({ resultPromise: pormise, value });\n (async () => {\n await pormise;\n resolver?.();\n resolver = undefined;\n })();\n });\n\n try {\n while (true) {\n if (queue.length) {\n const { resultPromise, value } = queue.shift()!;\n const result = await resultPromise;\n if (result) yield value as FILTERED;\n if (result === undefined) break;\n } else {\n await new Promise<void>((r) => (resolver = r));\n }\n }\n } finally {\n queue.length = 0;\n abort();\n resolver = undefined;\n }\n });\n }\n }\n\n const predicate = statefulPredicateOrOptions as filter.StatefulGuardPredicate<VALUE, STATE>;\n\n return new Stream<FILTERED>(async function* () {\n let currentState = initialStateOrPredicate as STATE;\n for await (const value of stream) {\n const result = await predicate(currentState, value);\n if (!result) return;\n const [emit, state] = result;\n currentState = state;\n if (emit) {\n yield value as FILTERED;\n }\n }\n });\n };\n};\n\nexport namespace filter {\n export type Options = { strategy: \"sequential\" | \"concurrent-unordered\" | \"concurrent-ordered\" };\n export type Predicate<VALUE = unknown> = (value: VALUE) => boolean | void | Promise<boolean | void>;\n export type GuardPredicate<VALUE = unknown, FILTERED extends VALUE = VALUE> = (value: VALUE) => value is FILTERED;\n export type StatefulPredicate<VALUE = unknown, STATE extends Record<string, unknown> = {}> = (\n state: STATE,\n value: VALUE\n ) => [boolean, STATE] | void | Promise<[boolean, STATE] | void>;\n export type StatefulGuardPredicate<\n VALUE = unknown,\n STATE extends Record<string, unknown> = {},\n FILTERED extends VALUE = VALUE\n > = (state: STATE, value: VALUE) => [boolean, STATE, FILTERED] | void | Promise<[boolean, STATE, FILTERED] | void>;\n export interface Filter {\n <VALUE, FILTERED extends VALUE = VALUE>(predicate: GuardPredicate<VALUE, FILTERED>): (\n stream: Stream<VALUE>\n ) => Stream<FILTERED>;\n\n <VALUE>(predicate: Predicate<VALUE>, options?: Options): (stream: Stream<VALUE>) => Stream<VALUE>;\n\n <VALUE, STATE extends Record<string, unknown> = {}>(\n initialState: STATE,\n predicate: StatefulPredicate<VALUE, STATE>\n ): (stream: Stream<VALUE>) => Stream<VALUE>;\n\n <VALUE, STATE extends Record<string, unknown> = {}, FILTERED extends VALUE = VALUE>(\n initialState: STATE,\n predicate: StatefulGuardPredicate<VALUE, STATE, FILTERED>\n ): (stream: Stream<VALUE>) => Stream<FILTERED>;\n }\n}\n",
|
|
7
7
|
"import { Stream } from \"../stream.ts\";\n\n/**\n * Adaptive map transformer that transforms values while maintaining state.\n * Supports multiple concurrency strategies for async mappers.\n *\n * @template VALUE - The type of input values\n * @template STATE - The type of the internal state object\n * @template MAPPED - The type of output values after transformation\n *\n * @param initialStateOrMapper - Initial state object or mapper function\n * @param statefulMapperOrOptions - Stateful mapper function or options for simple mappers\n *\n * @returns A transformer function that can be used with `.pipe()`\n *\n * @see {@link Stream} - Complete copy-paste transformers library\n *\n * @example\n * // Simple synchronous transformation\n * stream.pipe(map((value) => value * 2))\n *\n * @example\n * // Type transformation\n * stream.pipe(map((value: number) => value.toString()))\n *\n * @example\n * // Async transformation with sequential strategy (default)\n * stream.pipe(\n * map(async (value) => {\n * const result = await processAsync(value);\n * return result;\n * })\n * )\n *\n * @example\n * // Async transformation with concurrent-unordered strategy\n * stream.pipe(\n * map(async (value) => {\n * const enriched = await enrichWithAPI(value);\n * return enriched;\n * }, { strategy: \"concurrent-unordered\" })\n * )\n *\n * @example\n * // Async transformation with concurrent-ordered strategy\n * stream.pipe(\n * map(async (value) => {\n * const processed = await heavyProcessing(value);\n * return processed;\n * }, { strategy: \"concurrent-ordered\" })\n * )\n *\n * @example\n * // Stateful transformation (always sequential)\n * stream.pipe(\n * map({ sum: 0 }, (state, value) => {\n * const newSum = state.sum + value;\n * return [{ value, runningSum: newSum }, { sum: newSum }];\n * })\n * )\n *\n * @example\n * // Complex stateful transformation\n * stream.pipe(\n * map({ count: 0, items: [] }, (state, value) => {\n * const newItems = [...state.items, value];\n * const newCount = state.count + 1;\n * return [\n * {\n * item: value,\n * index: newCount,\n * total: newItems.length,\n * history: newItems\n * },\n * { count: newCount, items: newItems }\n * ];\n * })\n * )\n *\n * @example\n * // Async stateful transformation\n * stream.pipe(\n * map({ cache: new Map() }, async (state, value) => {\n * const cached = state.cache.get(value);\n * if (cached) return [cached, state];\n *\n * const processed = await expensiveOperation(value);\n * const newCache = new Map(state.cache);\n * newCache.set(value, processed);\n *\n * return [processed, { cache: newCache }];\n * })\n * )\n */\nexport const map: map.Map = <VALUE, STATE extends Record<string, unknown>, MAPPED>(\n initialStateOrMapper: STATE | map.Mapper<VALUE, MAPPED>,\n statefulMapper?: map.StatefulMapper<VALUE, STATE, MAPPED> | map.Options\n): ((stream: Stream<VALUE>) => Stream<MAPPED>) => {\n return (stream: Stream<VALUE>): Stream<MAPPED> => {\n if (!statefulMapper || typeof statefulMapper === \"object\") {\n const { strategy = \"sequential\" } = statefulMapper ?? {};\n const mapper = initialStateOrMapper as map.Mapper<VALUE, MAPPED>;\n\n if (strategy === \"sequential\") {\n return new Stream<MAPPED>(async function* () {\n for await (const value of stream) {\n yield await mapper(value);\n }\n });\n }\n if (strategy === \"concurrent-unordered\") {\n return new Stream<MAPPED>(async function* () {\n let queue = new Array<MAPPED>();\n let resolver: Function | undefined;\n\n const abort = stream.listen(async (value) => {\n queue.push(await mapper(value));\n resolver?.();\n resolver = undefined;\n });\n\n try {\n while (true) {\n if (queue.length) {\n yield queue.shift()!;\n } else {\n await new Promise<void>((r) => (resolver = r));\n }\n }\n } finally {\n queue.length = 0;\n abort();\n resolver = undefined;\n }\n });\n }\n\n if (strategy === \"concurrent-ordered\") {\n return new Stream<MAPPED>(async function* () {\n let queue = new Array<MAPPED | Promise<MAPPED>>();\n let resolver: Function | undefined;\n\n const abort = stream.listen((value) => {\n const promise = mapper(value);\n\n queue.push(promise);\n\n (async () => {\n await promise;\n resolver?.();\n resolver = undefined;\n })();\n });\n\n try {\n while (true) {\n if (queue.length) {\n yield await queue.shift()!;\n } else {\n await new Promise<void>((r) => (resolver = r));\n }\n }\n } finally {\n queue.length = 0;\n abort();\n resolver = undefined;\n }\n });\n }\n }\n\n const mapper = statefulMapper as map.StatefulMapper<VALUE, STATE, MAPPED>;\n\n return new Stream<MAPPED>(async function* () {\n let currentState = initialStateOrMapper as STATE;\n for await (const value of stream) {\n const [mapped, state] = await mapper(currentState, value);\n currentState = state;\n yield mapped;\n }\n });\n };\n};\n\nexport namespace map {\n export type Options = { strategy: \"sequential\" | \"concurrent-unordered\" | \"concurrent-ordered\" };\n export type Mapper<VALUE = unknown, MAPPED = VALUE> = (value: VALUE) => MAPPED | Promise<MAPPED>;\n export type StatefulMapper<VALUE = unknown, STATE extends Record<string, unknown> = {}, MAPPED = VALUE> = (\n state: STATE,\n value: VALUE\n ) => [MAPPED, STATE] | Promise<[MAPPED, STATE]>;\n\n export interface Map {\n <VALUE, MAPPED>(mapper: Mapper<VALUE, MAPPED>, options?: Options): (stream: Stream<VALUE>) => Stream<MAPPED>;\n <VALUE, STATE extends Record<string, unknown> = {}, MAPPED = VALUE>(\n initialState: STATE,\n mapper: StatefulMapper<VALUE, STATE, MAPPED>\n ): (stream: Stream<VALUE>) => Stream<MAPPED>;\n }\n}\n",
|
|
8
8
|
"import { Stream } from \"../stream.ts\";\n\n/**\n * Merge multiple streams into a single stream with temporal ordering.\n * \n * @template VALUE - The type of values from the source stream\n * @template STREAMS - Tuple type of additional streams to merge\n * \n * @param streams - Additional streams to merge with the source stream\n * \n * @returns A transformer that merges all streams into one with union types\n *\n * @see {@link Stream} - Complete copy-paste transformers library\n *\n * @example\n * // Basic merge with type safety\n * const numbers = new Stream<number>();\n * const strings = new Stream<string>();\n * const merged = numbers.pipe(merge(strings));\n * // Type: Stream<number | string>\n * \n * @example\n * // Multiple streams\n * const stream1 = new Stream<number>();\n * const stream2 = new Stream<string>();\n * const stream3 = new Stream<boolean>();\n * \n * const combined = stream1.pipe(merge(stream2, stream3));\n * // Type: Stream<number | string | boolean>\n * \n\n */\nexport function merge<VALUE, STREAMS extends [Stream<any>, ...Stream<any>[]]>(\n ...streams: STREAMS\n): (stream: Stream<VALUE>) => Stream<VALUE | Stream.ValueOf<STREAMS[number]>> {\n return (stream: Stream<VALUE>): Stream<VALUE | Stream.ValueOf<STREAMS[number]>> =>\n new Stream<VALUE | Stream.ValueOf<STREAMS[number]>>(async function* () {\n const allStreams = [stream, ...streams];\n const queue: (VALUE | Stream.ValueOf<STREAMS[number]>)[] = [];\n let resolver: Function | undefined;\n\n const cleanups = allStreams.map((s) =>\n s.listen((value) => {\n queue.push(value);\n resolver?.();\n })\n );\n\n try {\n while (true) {\n if (queue.length) {\n yield queue.shift()!;\n } else {\n await new Promise((resolve) => (resolver = resolve));\n }\n }\n } finally {\n cleanups.forEach((cleanup) => cleanup());\n }\n });\n}\n",
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
"import { Stream } from \"../stream.ts\";\n\n/**\n * A reactive Set that extends the native Set with stream-based mutation events.\n * Emits events when items are added, deleted, or the set is cleared.\n *\n * @template VALUE - The type of values stored in the set\n *\n * @see {@link Stream} - Complete copy-paste transformers library\n *\n * @example\n * ```typescript\n * const activeUsers = new Set<string>();\n *\n * // Listen to additions\n * activeUsers.add.listen(userId => {\n * console.log(`User ${userId} came online`);\n * });\n *\n * // Listen to deletions\n * activeUsers.delete.listen(userId => {\n * console.log(`User ${userId} went offline`);\n * });\n *\n * activeUsers.add('alice'); // User alice came online\n * activeUsers.delete('alice'); // User alice went offline\n * ```\n */\nexport class Set<VALUE> extends globalThis.Set<VALUE> {\n protected _addStream?: Stream<VALUE>;\n protected _deleteStream?: Stream<VALUE>;\n protected _clearStream?: Stream<void>;\n\n /**\n * Adds a value to the set and emits the value to listeners.\n * Only emits if the value is actually added (not a duplicate).\n *\n * @see {@link Stream} - Complete copy-paste transformers library\n *\n * @example\n * ```typescript\n * const tags = new Set<string>();\n * tags.add.listen(tag => console.log('Added:', tag));\n *\n * tags.add('javascript'); // Added: javascript\n * tags.add('javascript'); // No emission (duplicate)\n * ```\n */\n declare add: ((value: VALUE) => this) & Stream<VALUE>;\n\n /**\n * Deletes a value from the set and emits the value to listeners.\n * Only emits if the value was actually deleted (existed in set).\n *\n * @see {@link Stream} - Complete copy-paste transformers library\n *\n * @example\n * ```typescript\n * const items = new Set(['a', 'b', 'c']);\n * items.delete.listen(item => console.log('Removed:', item));\n *\n * items.delete('b'); // Removed: b\n * items.delete('x'); // No emission (didn't exist)\n * ```\n */\n declare delete: ((value: VALUE) => boolean) & Stream<VALUE>;\n\n /**\n * Clears all values from the set and emits to listeners.\n * Only emits if the set was not already empty.\n *\n * @see {@link Stream} - Complete copy-paste transformers library\n *\n * @example\n * ```typescript\n * const cache = new Set([1, 2, 3]);\n * cache.clear.listen(() => console.log('Cache cleared'));\n *\n * cache.clear(); // Cache cleared\n * cache.clear(); // No emission (already empty)\n * ```\n */\n declare clear: (() => void) & Stream<void>;\n\n /**\n * Creates a new reactive Set.\n *\n * @param values - Optional iterable of initial values\n *\n * @see {@link Stream} - Complete copy-paste transformers library\n *\n * @example\n * ```typescript\n * // Empty set\n * const tags = new Set<string>();\n *\n * // With initial values\n * const colors = new Set(['red', 'green', 'blue']);\n *\n * // Listen to changes\n * colors.add.listen(color => updateUI(color));\n * colors.delete.listen(color => removeFromUI(color));\n * ```\n */\n constructor(values?: Iterable<VALUE>) {\n super(values);\n\n const self = this;\n\n this.add = new Proxy(\n (value: VALUE): this => {\n if (globalThis.Set.prototype.has.call(self, value)) return self;\n globalThis.Set.prototype.add.call(self, value);\n self._addStream?.push(value);\n return self;\n },\n {\n get(target, prop) {\n if (prop in target) return (target as any)[prop];\n if (!self._addStream) self._addStream = new Stream<VALUE>();\n return (self._addStream as any)[prop];\n },\n }\n ) as any;\n\n this.delete = new Proxy(\n (value: VALUE): boolean => {\n if (!globalThis.Set.prototype.has.call(self, value)) return false;\n globalThis.Set.prototype.delete.call(self, value);\n self._deleteStream?.push(value);\n return true;\n },\n {\n get(target, prop) {\n if (prop in target) return (target as any)[prop];\n if (!self._deleteStream) self._deleteStream = new Stream<VALUE>();\n return (self._deleteStream as any)[prop];\n },\n }\n ) as any;\n\n this.clear = new Proxy(\n (): void => {\n if (self.size > 0) {\n globalThis.Set.prototype.clear.call(self);\n self._clearStream?.push();\n }\n },\n {\n get(target, prop) {\n if (prop in target) return (target as any)[prop];\n if (!self._clearStream) self._clearStream = new Stream<void>();\n return (self._clearStream as any)[prop];\n },\n }\n ) as any;\n }\n}\n",
|
|
13
13
|
"import { Stream } from \"../stream.ts\";\n\n/**\n * A reactive state container that extends Stream to provide stateful value management.\n *\n * @template VALUE - The type of the state value\n *\n * @see {@link Stream} - Complete copy-paste transformers library\n *\n * @example\n * ```typescript\n * // Basic state\n * const counter = new State(0);\n * counter.listen(value => console.log('Counter:', value));\n * counter.value = 5; // Counter: 5\n *\n * // State from stream\n * const source = new Stream<number>();\n * const state = new State(0, source);\n * state.listen(value => console.log('State:', value));\n * source.push(1, 2, 3); // State: 1, State: 2, State: 3\n *\n * // State from transformed stream\n * const filtered = source.pipe(filter({}, (_, v) => [v > 0, {}]));\n * const derivedState = new State(-1, filtered);\n * ```\n */\nexport class State<VALUE = unknown> extends Stream<VALUE> {\n protected _value: VALUE;\n constructor(initialValue: VALUE);\n constructor(initialValue: VALUE, stream: Stream.FunctionGenerator<VALUE> | Stream<VALUE>);\n /**\n * Creates a new State with an initial value.\n *\n * @param initialValue - The initial state value\n *\n * @see {@link Stream} - Complete copy-paste transformers library\n *\n * @example\n * ```typescript\n * const count = new State(0);\n * const theme = new State<'light' | 'dark'>('light');\n * const user = new State<User | null>(null);\n * ```\n */\n constructor(initialValue: VALUE, stream?: Stream.FunctionGenerator<VALUE> | Stream<VALUE>) {\n super(stream!);\n this._value = initialValue;\n }\n /**\n * Updates the state with one or more values sequentially.\n * Each value triggers listeners and updates the current state.\n *\n * @param values - Values to set as state\n *\n * @see {@link Stream} - Complete copy-paste transformers library\n *\n * @example\n * ```typescript\n * const state = new State(0);\n * state.listen(v => console.log(v));\n *\n * state.push(1, 2, 3); // Logs: 1, 2, 3\n * console.log(state.value); // 3\n * ```\n */\n override push(...values: VALUE[]): void {\n for (const value of values) {\n this.value = value;\n }\n }\n /**\n * Gets the current state value.\n *\n * @see {@link Stream} - Complete copy-paste transformers library\n *\n * @example\n * ```typescript\n * const state = new State('hello');\n * console.log(state.value); // 'hello'\n * ```\n */\n get value(): VALUE {\n return this._value;\n }\n /**\n * Sets the current state value and notifies all listeners.\n *\n * @param value - The new state value\n *\n * @see {@link Stream} - Complete copy-paste transformers library\n *\n * @example\n * ```typescript\n * const state = new State(0);\n * state.listen(v => console.log('New value:', v));\n *\n * state.value = 42; // New value: 42\n * state.value = 100; // New value: 100\n * ```\n */\n set value(value: VALUE) {\n this._value = value;\n super.push(value);\n }\n}\n"
|
|
14
14
|
],
|
|
15
|
-
"mappings": "AAkFO,MAAM,CAAwD,CACzD,
|
|
16
|
-
"debugId": "
|
|
15
|
+
"mappings": "AAkFO,MAAM,CAAwD,CACzD,WAAuE,IAAI,IAC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,EACvB,IAET,CACE,GAAG,CAAC,EAAQ,EAAM,CAChB,GAAI,KAAQ,EAAQ,OAAQ,EAAe,GAC3C,GAAI,CAAC,EAAK,cAAe,EAAK,cAAgB,IAAI,EAClD,OAAQ,EAAK,cAAsB,GAEvC,CACF,EAEA,KAAK,MAAQ,IAAI,MACf,IAAY,CACV,GAAI,EAAK,KAAO,EACd,WAAW,IAAI,UAAU,MAAM,KAAK,CAAI,EACxC,EAAK,cAAc,KAAK,GAG5B,CACE,GAAG,CAAC,EAAQ,EAAM,CAChB,GAAI,KAAQ,EAAQ,OAAQ,EAAe,GAC3C,GAAI,CAAC,EAAK,aAAc,EAAK,aAAe,IAAI,EAChD,OAAQ,EAAK,aAAqB,GAEtC,CACF,EAEJ,CClIO,MAAM,UAA+B,CAAc,CAC9C,OAiBV,WAAW,CAAC,EAAqB,EAA0D,CACzF,MAAM,CAAO,EACb,KAAK,OAAS,EAmBP,IAAI,IAAI,EAAuB,CACtC,QAAW,KAAS,EAClB,KAAK,MAAQ,KAcb,MAAK,EAAU,CACjB,OAAO,KAAK,UAkBV,MAAK,CAAC,EAAc,CACtB,KAAK,OAAS,EACd,MAAM,KAAK,CAAK,EAEpB",
|
|
16
|
+
"debugId": "652D0058F0A0040264756E2164756E21",
|
|
17
17
|
"names": []
|
|
18
18
|
}
|
package/dist/stream.d.ts
CHANGED
|
@@ -78,10 +78,10 @@
|
|
|
78
78
|
* return new State(initialValue, stream);
|
|
79
79
|
* };
|
|
80
80
|
*
|
|
81
|
-
* // Usage: stream.pipe(
|
|
81
|
+
* // Usage: stream.pipe(filter(x => x > 0)).pipe(take(5)).pipe(toState(0));
|
|
82
82
|
*/
|
|
83
83
|
export declare class Stream<VALUE = unknown> implements AsyncIterable<VALUE> {
|
|
84
|
-
protected _listeners:
|
|
84
|
+
protected _listeners: Map<(value: VALUE) => void, WeakRef<object> | undefined>;
|
|
85
85
|
protected _generatorFn: Stream.FunctionGenerator<VALUE> | undefined;
|
|
86
86
|
protected _generator: AsyncGenerator<VALUE, void> | undefined;
|
|
87
87
|
protected _listenerAdded: Stream<void> | undefined;
|
|
@@ -172,6 +172,7 @@ export declare class Stream<VALUE = unknown> implements AsyncIterable<VALUE> {
|
|
|
172
172
|
[Symbol.asyncIterator](): AsyncGenerator<VALUE, void>;
|
|
173
173
|
/**
|
|
174
174
|
* Pushes one or more values to all listeners.
|
|
175
|
+
* Automatically removes listeners whose context objects have been garbage collected.
|
|
175
176
|
*
|
|
176
177
|
* @see {@link Stream} - Complete copy-paste transformers library
|
|
177
178
|
*
|
|
@@ -189,10 +190,37 @@ export declare class Stream<VALUE = unknown> implements AsyncIterable<VALUE> {
|
|
|
189
190
|
*/
|
|
190
191
|
push(value: VALUE, ...values: VALUE[]): void;
|
|
191
192
|
/**
|
|
192
|
-
*
|
|
193
|
+
* Creates an async iterator bound to a context object's lifetime.
|
|
194
|
+
* Automatically stops iteration when the context is garbage collected.
|
|
195
|
+
*
|
|
196
|
+
* @param context - Object whose lifetime controls the iteration
|
|
197
|
+
* @returns Async generator that stops when context is GC'd
|
|
198
|
+
*
|
|
199
|
+
* @see {@link Stream} - Complete copy-paste transformers library
|
|
200
|
+
*
|
|
201
|
+
* @example
|
|
202
|
+
* ```typescript
|
|
203
|
+
* const stream = new Stream<number>();
|
|
204
|
+
* const element = document.createElement('div');
|
|
205
|
+
*
|
|
206
|
+
* (async () => {
|
|
207
|
+
* for await (const value of stream.withContext(element)) {
|
|
208
|
+
* element.textContent = String(value);
|
|
209
|
+
* }
|
|
210
|
+
* })();
|
|
211
|
+
*
|
|
212
|
+
* // When element is removed and GC'd, iteration stops automatically
|
|
213
|
+
* ```
|
|
214
|
+
*/
|
|
215
|
+
withContext(context: object): AsyncGenerator<Awaited<VALUE>, void, unknown>;
|
|
216
|
+
/**
|
|
217
|
+
* Adds a listener to the stream with optional automatic cleanup.
|
|
193
218
|
*
|
|
194
219
|
* @param listener - Function to call when values are pushed
|
|
195
|
-
* @param
|
|
220
|
+
* @param signalOrStreamOrContext - Optional cleanup mechanism:
|
|
221
|
+
* - AbortSignal: Remove listener when signal is aborted
|
|
222
|
+
* - Stream: Remove listener when stream emits
|
|
223
|
+
* - Object: Remove listener when object is garbage collected (WeakRef)
|
|
196
224
|
* @returns Cleanup function to remove the listener
|
|
197
225
|
*
|
|
198
226
|
* @see {@link Stream} - Complete copy-paste transformers library
|
|
@@ -209,11 +237,24 @@ export declare class Stream<VALUE = unknown> implements AsyncIterable<VALUE> {
|
|
|
209
237
|
* stream.listen(value => console.log(value), controller.signal);
|
|
210
238
|
* controller.abort(); // Removes listener
|
|
211
239
|
*
|
|
240
|
+
* // With Stream
|
|
241
|
+
* const stopSignal = new Stream<void>();
|
|
242
|
+
* stream.listen(value => console.log(value), stopSignal);
|
|
243
|
+
* stopSignal.push(); // Removes listener
|
|
244
|
+
*
|
|
245
|
+
* // With DOM element (auto-cleanup when GC'd)
|
|
246
|
+
* const element = document.createElement('div');
|
|
247
|
+
* stream.listen(value => element.textContent = value, element);
|
|
248
|
+
* // Listener automatically removed when element is garbage collected
|
|
249
|
+
*
|
|
212
250
|
* // Manual cleanup
|
|
213
251
|
* cleanup();
|
|
214
252
|
* ```
|
|
215
253
|
*/
|
|
216
|
-
listen(listener: (value: VALUE) => void
|
|
254
|
+
listen(listener: (value: VALUE) => void): () => void;
|
|
255
|
+
listen(listener: (value: VALUE) => void, signal: AbortSignal): () => void;
|
|
256
|
+
listen(listener: (value: VALUE) => void, stream: Stream<any>): () => void;
|
|
257
|
+
listen(listener: (value: VALUE) => void, context: object): () => void;
|
|
217
258
|
/**
|
|
218
259
|
* Promise-like interface that resolves with the next value.
|
|
219
260
|
*
|
package/dist/stream.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream.d.ts","sourceRoot":"","sources":["../src/stream.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,SAAS,MAAM,CAAC,MAAM,KAAK,CAAC,GAAG,KAAK,GAAG,KAAK,CAAC;IACjF,KAAY,iBAAiB,CAAC,KAAK,IAAI,MAAM,cAAc,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;CAC1E"}
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@soffinal/stream",
|
|
3
3
|
"module": "./dist/index.js",
|
|
4
|
-
"version": "0.2.
|
|
5
|
-
"description": "
|
|
4
|
+
"version": "0.2.4",
|
|
5
|
+
"description": "Type-safe event emitters that scale",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"devDependencies": {
|
|
8
8
|
"@types/bun": "latest"
|