through2 4.0.2 → 5.0.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/types/web.d.ts ADDED
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Build a TransformStream around a transformation function (classic /
3
+ * async / async generator; auto-dispatched).
4
+ *
5
+ * @example Classic controller form (multiple enqueue per chunk)
6
+ * transform((chunk, controller) => {
7
+ * controller.enqueue(chunk)
8
+ * controller.enqueue({ size: chunk.length })
9
+ * })
10
+ * @example Async (returned value enqueued)
11
+ * transform(async (chunk) => chunk.toString().toUpperCase())
12
+ * @example Async generator (cross-chunk state is just a local var)
13
+ * transform(async function * (source) {
14
+ * let buf = ''
15
+ * for await (const chunk of source) {
16
+ * buf += chunk.toString()
17
+ * const lines = buf.split('\n')
18
+ * buf = lines.pop()
19
+ * for (const line of lines) yield line
20
+ * }
21
+ * if (buf) yield buf
22
+ * })
23
+ * @example Pipe a fetch response
24
+ * await response.body.pipeThrough(transform(async (chunk) => chunk)).pipeTo(dest)
25
+ *
26
+ * @param {WebTransformFn} [transformFn]
27
+ * @param {WebFlushFn} [flushFn]
28
+ * @returns {{ readable: ReadableStream<any>, writable: WritableStream<any> }}
29
+ */
30
+ export function transform(transformFn?: WebTransformFn, flushFn?: WebFlushFn): {
31
+ readable: ReadableStream<any>;
32
+ writable: WritableStream<any>;
33
+ };
34
+ export default transform;
35
+ export type ClassicWebTransformFn = (chunk: any, controller: TransformStreamDefaultController<any>) => void;
36
+ export type AsyncWebTransformFn = (chunk: any) => any | Promise<any>;
37
+ export type AsyncGenWebTransformFn = (source: AsyncIterable<any>) => AsyncGenerator<any, void, void>;
38
+ export type WebTransformFn = ClassicWebTransformFn | AsyncWebTransformFn | AsyncGenWebTransformFn;
39
+ export type ClassicWebFlushFn = (controller: TransformStreamDefaultController<any>) => void;
40
+ export type AsyncWebFlushFn = () => any | Promise<any>;
41
+ export type WebFlushFn = ClassicWebFlushFn | AsyncWebFlushFn;
42
+ //# sourceMappingURL=web.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"web.d.ts","sourceRoot":"","sources":["../web.js"],"names":[],"mappings":"AA6BA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wCAJW,cAAc,YACd,UAAU,GACR;IAAE,QAAQ,EAAE,cAAc,CAAC,GAAG,CAAC,CAAC;IAAC,QAAQ,EAAE,cAAc,CAAC,GAAG,CAAC,CAAA;CAAE,CA2C5E;;oCA3Fa,CAAC,KAAK,EAAE,GAAG,EAAE,UAAU,EAAE,gCAAgC,CAAC,GAAG,CAAC,KAAK,IAAI;kCACvE,CAAC,KAAK,EAAE,GAAG,KAAK,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;qCAClC,CAAC,MAAM,EAAE,aAAa,CAAC,GAAG,CAAC,KAAK,cAAc,CAAC,GAAG,EAAE,IAAI,EAAE,IAAI,CAAC;6BAC/D,qBAAqB,GAAG,mBAAmB,GAAG,sBAAsB;gCACpE,CAAC,UAAU,EAAE,gCAAgC,CAAC,GAAG,CAAC,KAAK,IAAI;8BAC3D,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;yBACxB,iBAAiB,GAAG,eAAe"}
package/web.js ADDED
@@ -0,0 +1,241 @@
1
+ /**
2
+ * @file Tiny utility for inserting transformation logic into Web Streams
3
+ * pipelines. Returns `TransformStream` instances; zero runtime dependencies;
4
+ * runs anywhere `TransformStream` is a global (modern browsers, Node.js,
5
+ * Deno, Bun, Cloudflare Workers). See the root `through2` entry for the
6
+ * Node.js streams variant.
7
+ */
8
+
9
+ /** @typedef {(chunk: any, controller: TransformStreamDefaultController<any>) => void} ClassicWebTransformFn */
10
+ /** @typedef {(chunk: any) => any | Promise<any>} AsyncWebTransformFn */
11
+ /** @typedef {(source: AsyncIterable<any>) => AsyncGenerator<any, void, void>} AsyncGenWebTransformFn */
12
+ /** @typedef {ClassicWebTransformFn | AsyncWebTransformFn | AsyncGenWebTransformFn} WebTransformFn */
13
+ /** @typedef {(controller: TransformStreamDefaultController<any>) => void} ClassicWebFlushFn */
14
+ /** @typedef {() => any | Promise<any>} AsyncWebFlushFn */
15
+ /** @typedef {ClassicWebFlushFn | AsyncWebFlushFn} WebFlushFn */
16
+
17
+ const AsyncFunction = async function () {}.constructor
18
+ const AsyncGeneratorFunction = async function * () {}.constructor
19
+
20
+ /**
21
+ * @param {Function} fn
22
+ * @returns {'async' | 'asyncgen' | 'classic'}
23
+ */
24
+ function fnKind (fn) {
25
+ if (fn instanceof AsyncGeneratorFunction) return 'asyncgen'
26
+ if (fn instanceof AsyncFunction) return 'async'
27
+ return 'classic'
28
+ }
29
+
30
+ /**
31
+ * Build a TransformStream around a transformation function (classic /
32
+ * async / async generator; auto-dispatched).
33
+ *
34
+ * @example Classic controller form (multiple enqueue per chunk)
35
+ * transform((chunk, controller) => {
36
+ * controller.enqueue(chunk)
37
+ * controller.enqueue({ size: chunk.length })
38
+ * })
39
+ * @example Async (returned value enqueued)
40
+ * transform(async (chunk) => chunk.toString().toUpperCase())
41
+ * @example Async generator (cross-chunk state is just a local var)
42
+ * transform(async function * (source) {
43
+ * let buf = ''
44
+ * for await (const chunk of source) {
45
+ * buf += chunk.toString()
46
+ * const lines = buf.split('\n')
47
+ * buf = lines.pop()
48
+ * for (const line of lines) yield line
49
+ * }
50
+ * if (buf) yield buf
51
+ * })
52
+ * @example Pipe a fetch response
53
+ * await response.body.pipeThrough(transform(async (chunk) => chunk)).pipeTo(dest)
54
+ *
55
+ * @param {WebTransformFn} [transformFn]
56
+ * @param {WebFlushFn} [flushFn]
57
+ * @returns {{ readable: ReadableStream<any>, writable: WritableStream<any> }}
58
+ */
59
+ export function transform (transformFn, flushFn) {
60
+ if (typeof transformFn !== 'function') {
61
+ /** @type {ClassicWebTransformFn} */
62
+ const passthrough = (chunk, controller) => controller.enqueue(chunk)
63
+ transformFn = passthrough
64
+ }
65
+
66
+ const tKind = fnKind(transformFn)
67
+
68
+ if (tKind === 'asyncgen') {
69
+ return asyncGenTransform(/** @type {AsyncGenWebTransformFn} */ (transformFn), flushFn)
70
+ }
71
+
72
+ /** @type {Transformer<any, any>} */
73
+ const inner = {}
74
+
75
+ if (tKind === 'async') {
76
+ const fn = /** @type {AsyncWebTransformFn} */ (transformFn)
77
+ inner.transform = async (chunk, controller) => {
78
+ const out = await fn(chunk)
79
+ if (out !== undefined) controller.enqueue(out)
80
+ }
81
+ } else {
82
+ const fn = /** @type {ClassicWebTransformFn} */ (transformFn)
83
+ inner.transform = (chunk, controller) => fn(chunk, controller)
84
+ }
85
+
86
+ if (flushFn) {
87
+ if (fnKind(flushFn) === 'async') {
88
+ const fn = /** @type {AsyncWebFlushFn} */ (flushFn)
89
+ inner.flush = async (controller) => {
90
+ const out = await fn()
91
+ if (out !== undefined) controller.enqueue(out)
92
+ }
93
+ } else {
94
+ const fn = /** @type {ClassicWebFlushFn} */ (flushFn)
95
+ inner.flush = (controller) => fn(controller)
96
+ }
97
+ }
98
+
99
+ return new TransformStream(inner)
100
+ }
101
+
102
+ /**
103
+ * Drive an async-generator transform as a `{ readable, writable }` pair.
104
+ *
105
+ * The pair shape (rather than a `TransformStream`) is required because we
106
+ * need cancellation hooks: the `Transformer.cancel` callback is in the
107
+ * WHATWG Streams spec but not yet implemented in major browsers as of 2026,
108
+ * whereas `ReadableStream.cancel` and `WritableStream.abort` are universally
109
+ * available. The pair satisfies `pipeThrough`'s structural contract.
110
+ *
111
+ * Backpressure follows the standard pull-based model: `pull()` enqueues one
112
+ * yielded value per call and is invoked by the runtime exactly when the
113
+ * readable buffer has room; `write()` returns a pending promise when the
114
+ * internal queue is full, propagating pressure upstream.
115
+ *
116
+ * @param {AsyncGenWebTransformFn} gen
117
+ * @param {WebFlushFn} [flushFn]
118
+ * @returns {{ readable: ReadableStream<any>, writable: WritableStream<any> }}
119
+ */
120
+ function asyncGenTransform (gen, flushFn) {
121
+ /** @type {any[]} */
122
+ const queue = []
123
+ /** @type {Array<(value?: any) => void>} */
124
+ const sourceWakeups = []
125
+ /** @type {Array<(value?: any) => void>} */
126
+ const writeWaiters = []
127
+ let sourceEnded = false
128
+ let flushed = false
129
+
130
+ const QUEUE_HWM = 16
131
+
132
+ const wakeOne = (/** @type {Array<(value?: any) => void>} */ arr) => {
133
+ const w = arr.shift()
134
+ if (w) w()
135
+ }
136
+ const wakeAll = (/** @type {Array<(value?: any) => void>} */ arr) => {
137
+ while (arr.length) /** @type {(value?: any) => void} */ (arr.shift())()
138
+ }
139
+
140
+ // The source iterable user code consumes via `for await (const x of source)`.
141
+ const source = (async function * () {
142
+ while (true) {
143
+ while (queue.length > 0) {
144
+ yield queue.shift()
145
+ wakeOne(writeWaiters)
146
+ }
147
+ if (sourceEnded) return
148
+ await new Promise((resolve) => { sourceWakeups.push(resolve) })
149
+ }
150
+ })()
151
+
152
+ // Build the user's iterator once; pull() drives it on demand.
153
+ const iter = gen(source)
154
+
155
+ // Controllers captured in start() so the two sides can cross-propagate
156
+ // termination (matching the WHATWG TransformStream behaviour: cancel on
157
+ // one side errors the other).
158
+ /** @type {ReadableStreamDefaultController<any> | null} */
159
+ let readableController = null
160
+ /** @type {WritableStreamDefaultController | null} */
161
+ let writableController = null
162
+ let terminating = false
163
+
164
+ // Shared cleanup: end the source, finalize the user's generator (running
165
+ // its `finally`), error the opposite side. Idempotent.
166
+ const finalize = async (/** @type {any} */ reason, /** @type {'readable'|'writable'} */ origin) => {
167
+ if (terminating) return
168
+ terminating = true
169
+ sourceEnded = true
170
+ wakeAll(sourceWakeups)
171
+ wakeAll(writeWaiters)
172
+ if (typeof iter.return === 'function') {
173
+ try { await iter.return() } catch { /* user finally threw; ignored */ }
174
+ }
175
+ if (origin === 'readable' && writableController) {
176
+ try { writableController.error(reason) } catch { /* already errored */ }
177
+ } else if (origin === 'writable' && readableController) {
178
+ try { readableController.error(reason) } catch { /* already errored */ }
179
+ }
180
+ }
181
+
182
+ return {
183
+ readable: new ReadableStream({
184
+ start (controller) { readableController = controller },
185
+ async pull (controller) {
186
+ try {
187
+ const { value, done } = await iter.next()
188
+ if (!done) {
189
+ controller.enqueue(value)
190
+ return
191
+ }
192
+ if (!flushed) {
193
+ flushed = true
194
+ if (flushFn) {
195
+ if (fnKind(flushFn) === 'async') {
196
+ const fn = /** @type {AsyncWebFlushFn} */ (flushFn)
197
+ const out = await fn()
198
+ if (out !== undefined) controller.enqueue(out)
199
+ } else {
200
+ // Classic flush expects a TransformStreamDefaultController-ish
201
+ // shape; synthesize one over the ReadableStream's controller.
202
+ /** @type {any} */
203
+ const proxy = {
204
+ enqueue: (/** @type {any} */ c) => controller.enqueue(c),
205
+ error: (/** @type {any} */ e) => controller.error(e),
206
+ terminate: () => controller.close()
207
+ }
208
+ const fn = /** @type {ClassicWebFlushFn} */ (flushFn)
209
+ fn(proxy)
210
+ }
211
+ }
212
+ }
213
+ controller.close()
214
+ } catch (err) {
215
+ controller.error(err)
216
+ }
217
+ },
218
+ cancel (reason) { return finalize(reason, 'readable') }
219
+ }),
220
+ writable: new WritableStream({
221
+ start (controller) { writableController = controller },
222
+ write (chunk) {
223
+ queue.push(chunk)
224
+ wakeOne(sourceWakeups)
225
+ if (queue.length >= QUEUE_HWM) {
226
+ return new Promise((resolve) => { writeWaiters.push(resolve) })
227
+ }
228
+ return undefined
229
+ },
230
+ close () {
231
+ // Clean end: let the source iterable return so the user's `for await`
232
+ // exits normally and pull() can run any flush logic.
233
+ sourceEnded = true
234
+ wakeAll(sourceWakeups)
235
+ },
236
+ abort (reason) { return finalize(reason, 'writable') }
237
+ })
238
+ }
239
+ }
240
+
241
+ export default transform