@lmvz-ds/components 0.12.5-alpha.5 → 0.13.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.
Files changed (119) hide show
  1. package/dist/{esm/Effect-BhQLGXPs.js → cjs/assets-CB5ikzmP.js} +857 -4832
  2. package/dist/cjs/{icons-7wUEcWEo.js → icons-DM_TTn48.js} +363 -113
  3. package/dist/cjs/{index-CVw4GUo6.js → index-Bp6Dd2i1.js} +4 -2
  4. package/dist/cjs/{index-9ZJx0550.js → index-D3BMpL5w.js} +0 -3
  5. package/dist/cjs/index.cjs.js +4 -6
  6. package/dist/cjs/lmvz-action.cjs.entry.js +1 -1
  7. package/dist/cjs/lmvz-button.cjs.entry.js +7 -10
  8. package/dist/cjs/lmvz-card.cjs.entry.js +3 -4
  9. package/dist/cjs/lmvz-chip.cjs.entry.js +1 -1
  10. package/dist/cjs/lmvz-components.cjs.js +1 -1
  11. package/dist/cjs/lmvz-header.cjs.entry.js +13 -12
  12. package/dist/cjs/lmvz-icon.cjs.entry.js +8 -10
  13. package/dist/cjs/lmvz-input.cjs.entry.js +8 -11
  14. package/dist/cjs/lmvz-menuitem.cjs.entry.js +5 -7
  15. package/dist/cjs/loader.cjs.js +1 -1
  16. package/dist/cjs/reactive-controller-host-BMDEj1kX.js +168 -0
  17. package/dist/collection/components/lmvz-button/lmvz-button.js +4 -4
  18. package/dist/collection/components/lmvz-header/lmvz-header.js +11 -8
  19. package/dist/collection/components/lmvz-icon/lmvz-icon.js +2 -2
  20. package/dist/collection/components/lmvz-icon/test/icons.unit.js +21 -12
  21. package/dist/collection/components/lmvz-input/lmvz-input.css +5 -2
  22. package/dist/collection/components/lmvz-input/lmvz-input.js +3 -3
  23. package/dist/collection/components/lmvz-menuitem/lmvz-menuitem.js +4 -4
  24. package/dist/collection/integration/header-integration.js +4 -2
  25. package/dist/collection/utils/{validation → aria}/aria-validation-controller.js +15 -34
  26. package/dist/collection/utils/{list-keyboard-controller.js → aria/list-keyboard-controller.js} +1 -1
  27. package/dist/collection/utils/{http.test.js → http.unit.js} +7 -6
  28. package/dist/components/index.js +1 -1
  29. package/dist/components/lmvz-action.js +1 -1
  30. package/dist/components/lmvz-button.js +1 -1
  31. package/dist/components/lmvz-card.js +1 -1
  32. package/dist/components/lmvz-chip.js +1 -1
  33. package/dist/components/lmvz-header.js +1 -1
  34. package/dist/components/lmvz-icon.js +1 -1
  35. package/dist/components/lmvz-input.js +1 -1
  36. package/dist/components/lmvz-menuitem.js +1 -1
  37. package/dist/components/p-BBDH9X49.js +1 -0
  38. package/dist/components/{p-DMLRPGid.js → p-BfTCfPZ1.js} +1 -1
  39. package/dist/components/p-Bs6_m7Uw.js +1 -0
  40. package/dist/components/p-CMteT-Yo.js +1 -0
  41. package/dist/components/p-vi4YzJmv.js +1 -0
  42. package/dist/{cjs/Effect-CNhHt4Xb.js → esm/assets-ozES4zSA.js} +785 -5032
  43. package/dist/esm/{icons-Bx1wWPM2.js → icons-kpJZ1u9g.js} +268 -18
  44. package/dist/esm/{index-Bt32KzDW.js → index-BfTCfPZ1.js} +3 -1
  45. package/dist/esm/{index-smGPjoDX.js → index-T5ljELGS.js} +1 -3
  46. package/dist/esm/index.js +3 -5
  47. package/dist/esm/lmvz-action.entry.js +1 -1
  48. package/dist/esm/lmvz-button.entry.js +5 -8
  49. package/dist/esm/lmvz-card.entry.js +2 -3
  50. package/dist/esm/lmvz-chip.entry.js +1 -1
  51. package/dist/esm/lmvz-components.js +2 -2
  52. package/dist/esm/lmvz-header.entry.js +11 -10
  53. package/dist/esm/lmvz-icon.entry.js +5 -7
  54. package/dist/esm/lmvz-input.entry.js +6 -9
  55. package/dist/esm/lmvz-menuitem.entry.js +3 -5
  56. package/dist/esm/loader.js +2 -2
  57. package/dist/esm/reactive-controller-host-CZ3dGAjR.js +165 -0
  58. package/dist/lmvz-components/index.esm.js +1 -1
  59. package/dist/lmvz-components/lmvz-components.esm.js +1 -1
  60. package/dist/lmvz-components/p-16878d4c.entry.js +1 -0
  61. package/dist/lmvz-components/p-4ad8c332.entry.js +1 -0
  62. package/dist/lmvz-components/p-5eee0752.entry.js +1 -0
  63. package/dist/lmvz-components/p-8ea1a349.entry.js +1 -0
  64. package/dist/lmvz-components/{p-d4b68381.entry.js → p-980688a0.entry.js} +1 -1
  65. package/dist/lmvz-components/{p-DMLRPGid.js → p-BfTCfPZ1.js} +1 -1
  66. package/dist/lmvz-components/p-CZ3dGAjR.js +1 -0
  67. package/dist/lmvz-components/p-D9lc4ayG.js +1 -0
  68. package/dist/lmvz-components/p-T5ljELGS.js +2 -0
  69. package/dist/lmvz-components/p-a34542fa.entry.js +1 -0
  70. package/dist/lmvz-components/p-d2bf6a3f.entry.js +1 -0
  71. package/dist/lmvz-components/{p-9faac8f3.entry.js → p-feda2ec5.entry.js} +1 -1
  72. package/dist/lmvz-components/p-iviTjlUy.js +1 -0
  73. package/dist/manifest.json +3 -3
  74. package/dist/types/components/lmvz-button/lmvz-button.d.ts +2 -2
  75. package/dist/types/components/lmvz-header/lmvz-header.d.ts +5 -4
  76. package/dist/types/components/lmvz-icon/lmvz-icon.d.ts +1 -1
  77. package/dist/types/components/lmvz-input/lmvz-input.d.ts +1 -1
  78. package/dist/types/components/lmvz-menuitem/lmvz-menuitem.d.ts +2 -2
  79. package/dist/types/components.d.ts +6 -0
  80. package/dist/types/utils/{validation → aria}/aria-validation-controller.d.ts +1 -5
  81. package/dist/types/utils/{element-activation-controller.d.ts → aria/element-activation-controller.d.ts} +2 -2
  82. package/dist/types/utils/{list-keyboard-controller.d.ts → aria/list-keyboard-controller.d.ts} +1 -1
  83. package/hydrate/index.js +9610 -50169
  84. package/hydrate/index.mjs +9610 -50169
  85. package/package.json +17 -18
  86. package/readme.md +18 -0
  87. package/dist/cjs/MutableQueue-Bk9tBfaK.js +0 -462
  88. package/dist/cjs/_commonjsHelpers-CFO10eej.js +0 -7
  89. package/dist/cjs/aria-validation-controller-B3hMkau3.js +0 -2930
  90. package/dist/cjs/assets-BguFB3wV.js +0 -71
  91. package/dist/cjs/axe-BNqwbBGU.js +0 -32834
  92. package/dist/components/p-3I3wZmp8.js +0 -1
  93. package/dist/components/p-B85MJLTf.js +0 -1
  94. package/dist/components/p-BaPwpeMs.js +0 -1
  95. package/dist/components/p-CAi33KTt.js +0 -1
  96. package/dist/components/p-CdofjRtQ.js +0 -1
  97. package/dist/components/p-D1HbKFuh.js +0 -12
  98. package/dist/components/p-UwhTS2ue.js +0 -1
  99. package/dist/esm/MutableQueue-CNlEFklh.js +0 -431
  100. package/dist/esm/_commonjsHelpers-B85MJLTf.js +0 -5
  101. package/dist/esm/aria-validation-controller-iA4YWFG-.js +0 -2927
  102. package/dist/esm/assets-Iu8neKuE.js +0 -67
  103. package/dist/esm/axe-cRQ9Ux1I.js +0 -32832
  104. package/dist/lmvz-components/p-1a10fcbd.entry.js +0 -1
  105. package/dist/lmvz-components/p-274c36df.entry.js +0 -1
  106. package/dist/lmvz-components/p-4XIjw3k8.js +0 -1
  107. package/dist/lmvz-components/p-4b70fe08.entry.js +0 -1
  108. package/dist/lmvz-components/p-51Fb_qqD.js +0 -1
  109. package/dist/lmvz-components/p-68001ab7.entry.js +0 -1
  110. package/dist/lmvz-components/p-77e26e71.entry.js +0 -1
  111. package/dist/lmvz-components/p-B85MJLTf.js +0 -1
  112. package/dist/lmvz-components/p-BhQLGXPs.js +0 -1
  113. package/dist/lmvz-components/p-CXWyvf0D.js +0 -1
  114. package/dist/lmvz-components/p-D1HbKFuh.js +0 -12
  115. package/dist/lmvz-components/p-D7I-Bc5i.js +0 -1
  116. package/dist/lmvz-components/p-c8b78793.entry.js +0 -1
  117. package/dist/lmvz-components/p-smGPjoDX.js +0 -2
  118. /package/dist/collection/utils/{element-activation-controller.js → aria/element-activation-controller.js} +0 -0
  119. /package/dist/types/utils/{http.test.d.ts → http.unit.d.ts} +0 -0
@@ -1,2927 +0,0 @@
1
- import { B as Build } from './index-smGPjoDX.js';
2
- import { a6 as make$4, a7 as modify$1, a8 as get$1, a9 as update$1, aa as isInterrupted$1, ab as fail$2, ac as failureOrCause$1, ad as flipCauseOption$1, ae as map$3, af as die$1, ag as interrupt$2, ah as isDieType$1, ai as interruptors$1, aj as isInterruptedOnly$1, ak as join$1, al as interruptFiber, am as _await$1, an as inheritAll$1, ao as interruptAsFiber, N as pipe, F as flatMap$2, q as sync$1, ap as dual, j as map$4, L as make$5, aq as deferredMake, ar as Class, as as pipeArguments, v as suspend$2, at as catchAll, au as interrupt$3, av as get$2, y as none, B as some, aw as uninterruptible, ax as withFiberRuntime, K as set, U as asVoid, ay as whenEffect, az as deferredSucceed, Y as zipRight$1, aA as forEachConcurrentDiscard, aB as deferredAwait, x as succeed$1, aC as fromIterable, aD as empty, aE as splitAt, aF as isEmpty, aG as deferredUnsafeMake, X as onInterrupt, aH as fromIterable$1, aI as deferredUnsafeDone, aJ as prepend, aK as filter, aL as appendAll, aM as append, aN as deferredInterruptWith, aO as empty$1, aP as void_$1, o as fiberId, S as hasProperty, aQ as isEffect, i as identity, aR as match$1, aS as _void, aT as ignore, aU as zipWith, aV as exit, aW as sync$2, aX as provide, aY as matchCauseEffect, aZ as zipRight$3, a_ as flatMap$3, a$ as forkDaemon, b0 as interruptible, b1 as suspend$3, b2 as ensuring$2, b3 as uninterruptible$1, b4 as map$5, b5 as zip$1, b6 as forEach, s as succeed$3, A as isSome, b7 as getOrElse, b8 as dieMessage, b9 as catchAllCause, ba as uninterruptibleMask, bb as all$1, bc as fork, bd as sequential, be as acquireUseRelease, bf as forkIn, bg as size$2, bh as combineAll, bi as intoDeferred, bj as zipLeft, bk as tapErrorCause, bl as addFinalizer, bm as failCause$4, bn as flatten$2, bo as fiberIdWith, bp as interrupt$4, d as left, b as right, bq as matchCause, br as scopedWith$2, bs as unsafeGet, bt as constVoid, bu as scope, $ as gen, bv as withFiberRuntime$1, bw as make$7, bx as extend, by as close, bz as raceWith, bA as runtime, bB as tap, bC as addFinalizerExit, bD as makeSemaphore, bE as when, bF as race, bG as as, m as match$3, bH as repeat, bI as asVoid$1, T as equals, bJ as raceFirst, bK as forever, bL as of$1, bM as fail$4, bN as mapError, bO as reduce, bP as map$7, bQ as match$4, bR as splitWhere, bS as head, bT as filterMap, c as catchAll$1, bU as catchSomeCause, bV as unsafeFromArray, bW as runFork, bX as promise, bY as async } from './Effect-BhQLGXPs.js';
3
- import { a as unbounded$2, l as length, p as poll, E as EmptyMutableQueue, o as offer$2, b as pollUpTo, c as isEmpty$1, e as offerAll, f as bounded$2, g as capacity, h as isFailure, z as zipRight$2, s as succeed$2, j as failCause$3, m as match$2, k as all, v as void_$2, n as die$2, q as map$6, r as make$6, t as isDone, w as succeed$4, _ as _await$2, x as failCause$5, y as fail$3, A as zip$2, B as isSuccess } from './MutableQueue-CNlEFklh.js';
4
-
5
- /**
6
- * @since 2.0.0
7
- * @category constructors
8
- */
9
- const make$3 = make$4;
10
- /**
11
- * @since 2.0.0
12
- * @category getters
13
- */
14
- const get = get$1;
15
- /**
16
- * @since 2.0.0
17
- * @category utils
18
- */
19
- const modify = modify$1;
20
- /**
21
- * @since 2.0.0
22
- * @category utils
23
- */
24
- const update = update$1;
25
-
26
- /**
27
- * Creates a `Fail` cause from an expected error.
28
- *
29
- * **Details**
30
- *
31
- * This function constructs a `Cause` carrying an error of type `E`. It's used
32
- * when you want to represent a known or anticipated failure in your effectful
33
- * computations.
34
- *
35
- * @see {@link isFailure} Check if a `Cause` contains a failure
36
- *
37
- * @since 2.0.0
38
- * @category Constructors
39
- */
40
- const fail$1 = fail$2;
41
- /**
42
- * Creates a `Die` cause from an unexpected error.
43
- *
44
- * **Details**
45
- *
46
- * This function wraps an unhandled or unknown defect (like a runtime crash)
47
- * into a `Cause`. It's useful for capturing unforeseen issues in a structured
48
- * way.
49
- *
50
- * @see {@link isDie} Check if a `Cause` contains a defect
51
- *
52
- * @since 2.0.0
53
- * @category Constructors
54
- */
55
- const die = die$1;
56
- /**
57
- * Creates an `Interrupt` cause from a `FiberId`.
58
- *
59
- * **Details**
60
- *
61
- * This function represents a fiber that has been interrupted. It stores the
62
- * identifier of the interrupted fiber, enabling precise tracking of concurrent
63
- * cancellations.
64
- *
65
- * @see {@link isInterrupted} Check if a `Cause` contains an interruption
66
- *
67
- * @since 2.0.0
68
- * @category Constructors
69
- */
70
- const interrupt$1 = interrupt$2;
71
- /**
72
- * Checks if a `Cause` is a `Die` type.
73
- *
74
- * @see {@link die} Create a new `Die` cause
75
- *
76
- * @since 2.0.0
77
- * @category Guards
78
- */
79
- const isDieType = isDieType$1;
80
- /**
81
- * Checks if a `Cause` contains an interruption.
82
- *
83
- * **Details**
84
- *
85
- * This function returns `true` if the `Cause` includes any fiber interruptions.
86
- *
87
- * @since 2.0.0
88
- * @category Getters
89
- */
90
- const isInterrupted = isInterrupted$1;
91
- /**
92
- * Checks if a `Cause` contains only interruptions.
93
- *
94
- * **Details**
95
- *
96
- * This function returns `true` if the `Cause` has been interrupted but does not
97
- * contain any other failures, such as `Fail` or `Die`. It's helpful for
98
- * verifying purely "cancellation" scenarios.
99
- *
100
- * @since 2.0.0
101
- * @category Getters
102
- */
103
- const isInterruptedOnly = isInterruptedOnly$1;
104
- /**
105
- * Collects all `FiberId`s responsible for interrupting a fiber.
106
- *
107
- * **Details**
108
- *
109
- * This function returns a set of IDs indicating which fibers caused
110
- * interruptions within this `Cause`. It's useful for debugging concurrency
111
- * issues or tracing cancellations.
112
- *
113
- * @since 2.0.0
114
- * @category Getters
115
- */
116
- const interruptors = interruptors$1;
117
- /**
118
- * Splits a `Cause` into either its first `Fail` error or the rest of the cause
119
- * (which might only contain `Die` or `Interrupt`).
120
- *
121
- * **Details**
122
- *
123
- * This function either returns the checked error (`E`) or the remaining
124
- * `Cause<never>` with defects/interruptions. It helps you decide if there's a
125
- * recoverable path or if only unhandled issues remain.
126
- *
127
- * @since 2.0.0
128
- * @category Getters
129
- */
130
- const failureOrCause = failureOrCause$1;
131
- /**
132
- * Strips out failures with an error of `None` from a `Cause<Option<E>>`.
133
- *
134
- * **Details**
135
- *
136
- * This function turns a `Cause<Option<E>>` into an `Option<Cause<E>>`. If the
137
- * cause only contains failures of `None`, it becomes `None`; otherwise, it
138
- * returns a `Cause` of the remaining errors. It's helpful when working with
139
- * optional errors and filtering out certain error paths.
140
- *
141
- * @since 2.0.0
142
- * @category Getters
143
- */
144
- const flipCauseOption = flipCauseOption$1;
145
- /**
146
- * Transforms the errors in a `Cause` using a user-provided function.
147
- *
148
- * **Details**
149
- *
150
- * This function applies `f` to each `Fail` error while leaving defects (`Die`)
151
- * and interruptions untouched. It's useful for changing or simplifying error
152
- * types in your effectful workflows.
153
- *
154
- * @see {@link as} Replace errors with a single constant
155
- *
156
- * @since 2.0.0
157
- * @category Mapping
158
- */
159
- const map$2 = map$3;
160
-
161
- const _await = _await$1;
162
- /**
163
- * Inherits values from all `FiberRef` instances into current fiber. This
164
- * will resume immediately.
165
- *
166
- * @since 2.0.0
167
- * @category destructors
168
- */
169
- const inheritAll = inheritAll$1;
170
- /**
171
- * Interrupts the fiber from whichever fiber is calling this method. If the
172
- * fiber has already exited, the returned effect will resume immediately.
173
- * Otherwise, the effect will resume when the fiber exits.
174
- *
175
- * @since 2.0.0
176
- * @category interruption
177
- */
178
- const interrupt = interruptFiber;
179
- /**
180
- * Interrupts the fiber as if interrupted from the specified fiber. If the
181
- * fiber has already exited, the returned effect will resume immediately.
182
- * Otherwise, the effect will resume when the fiber exits.
183
- *
184
- * @since 2.0.0
185
- * @category interruption
186
- */
187
- const interruptAs = interruptAsFiber;
188
- /**
189
- * Joins the fiber, which suspends the joining fiber until the result of the
190
- * fiber has been determined. Attempting to join a fiber that has erred will
191
- * result in a catchable error. Joining an interrupted fiber will result in an
192
- * "inner interruption" of this fiber, unlike interruption triggered by
193
- * another fiber, "inner interruption" can be caught and recovered.
194
- *
195
- * @since 2.0.0
196
- * @category destructors
197
- */
198
- const join = join$1;
199
-
200
- /** @internal */
201
- const EnqueueSymbolKey = "effect/QueueEnqueue";
202
- /** @internal */
203
- const EnqueueTypeId = /*#__PURE__*/Symbol.for(EnqueueSymbolKey);
204
- /** @internal */
205
- const DequeueSymbolKey = "effect/QueueDequeue";
206
- /** @internal */
207
- const DequeueTypeId = /*#__PURE__*/Symbol.for(DequeueSymbolKey);
208
- /** @internal */
209
- const QueueStrategySymbolKey = "effect/QueueStrategy";
210
- /** @internal */
211
- const QueueStrategyTypeId = /*#__PURE__*/Symbol.for(QueueStrategySymbolKey);
212
- /** @internal */
213
- const BackingQueueSymbolKey = "effect/BackingQueue";
214
- /** @internal */
215
- const BackingQueueTypeId = /*#__PURE__*/Symbol.for(BackingQueueSymbolKey);
216
- const queueStrategyVariance = {
217
- /* c8 ignore next */
218
- _A: _ => _
219
- };
220
- const backingQueueVariance = {
221
- /* c8 ignore next */
222
- _A: _ => _
223
- };
224
- /** @internal */
225
- const enqueueVariance = {
226
- /* c8 ignore next */
227
- _In: _ => _
228
- };
229
- /** @internal */
230
- const dequeueVariance = {
231
- /* c8 ignore next */
232
- _Out: _ => _
233
- };
234
- /** @internal */
235
- class QueueImpl extends Class {
236
- queue;
237
- takers;
238
- shutdownHook;
239
- shutdownFlag;
240
- strategy;
241
- [EnqueueTypeId] = enqueueVariance;
242
- [DequeueTypeId] = dequeueVariance;
243
- constructor(/** @internal */
244
- queue, /** @internal */
245
- takers, /** @internal */
246
- shutdownHook, /** @internal */
247
- shutdownFlag, /** @internal */
248
- strategy) {
249
- super();
250
- this.queue = queue;
251
- this.takers = takers;
252
- this.shutdownHook = shutdownHook;
253
- this.shutdownFlag = shutdownFlag;
254
- this.strategy = strategy;
255
- }
256
- pipe() {
257
- return pipeArguments(this, arguments);
258
- }
259
- commit() {
260
- return this.take;
261
- }
262
- capacity() {
263
- return this.queue.capacity();
264
- }
265
- get size() {
266
- return suspend$2(() => catchAll(this.unsafeSize(), () => interrupt$3));
267
- }
268
- unsafeSize() {
269
- if (get$2(this.shutdownFlag)) {
270
- return none();
271
- }
272
- return some(this.queue.length() - length(this.takers) + this.strategy.surplusSize());
273
- }
274
- get isEmpty() {
275
- return map$4(this.size, size => size <= 0);
276
- }
277
- get isFull() {
278
- return map$4(this.size, size => size >= this.capacity());
279
- }
280
- get shutdown() {
281
- return uninterruptible(withFiberRuntime(state => {
282
- pipe(this.shutdownFlag, set(true));
283
- return pipe(forEachConcurrentDiscard(unsafePollAll(this.takers), d => deferredInterruptWith(d, state.id()), false, false), zipRight$1(this.strategy.shutdown), whenEffect(deferredSucceed(this.shutdownHook, void 0)), asVoid);
284
- }));
285
- }
286
- get isShutdown() {
287
- return sync$1(() => get$2(this.shutdownFlag));
288
- }
289
- get awaitShutdown() {
290
- return deferredAwait(this.shutdownHook);
291
- }
292
- isActive() {
293
- return !get$2(this.shutdownFlag);
294
- }
295
- unsafeOffer(value) {
296
- if (get$2(this.shutdownFlag)) {
297
- return false;
298
- }
299
- let noRemaining;
300
- if (this.queue.length() === 0) {
301
- const taker = pipe(this.takers, poll(EmptyMutableQueue));
302
- if (taker !== EmptyMutableQueue) {
303
- unsafeCompleteDeferred(taker, value);
304
- noRemaining = true;
305
- } else {
306
- noRemaining = false;
307
- }
308
- } else {
309
- noRemaining = false;
310
- }
311
- if (noRemaining) {
312
- return true;
313
- }
314
- // Not enough takers, offer to the queue
315
- const succeeded = this.queue.offer(value);
316
- unsafeCompleteTakers(this.strategy, this.queue, this.takers);
317
- return succeeded;
318
- }
319
- offer(value) {
320
- return suspend$2(() => {
321
- if (get$2(this.shutdownFlag)) {
322
- return interrupt$3;
323
- }
324
- let noRemaining;
325
- if (this.queue.length() === 0) {
326
- const taker = pipe(this.takers, poll(EmptyMutableQueue));
327
- if (taker !== EmptyMutableQueue) {
328
- unsafeCompleteDeferred(taker, value);
329
- noRemaining = true;
330
- } else {
331
- noRemaining = false;
332
- }
333
- } else {
334
- noRemaining = false;
335
- }
336
- if (noRemaining) {
337
- return succeed$1(true);
338
- }
339
- // Not enough takers, offer to the queue
340
- const succeeded = this.queue.offer(value);
341
- unsafeCompleteTakers(this.strategy, this.queue, this.takers);
342
- return succeeded ? succeed$1(true) : this.strategy.handleSurplus([value], this.queue, this.takers, this.shutdownFlag);
343
- });
344
- }
345
- offerAll(iterable) {
346
- return suspend$2(() => {
347
- if (get$2(this.shutdownFlag)) {
348
- return interrupt$3;
349
- }
350
- const values = fromIterable(iterable);
351
- const pTakers = this.queue.length() === 0 ? fromIterable(unsafePollN(this.takers, values.length)) : empty;
352
- const [forTakers, remaining] = pipe(values, splitAt(pTakers.length));
353
- for (let i = 0; i < pTakers.length; i++) {
354
- const taker = pTakers[i];
355
- const item = forTakers[i];
356
- unsafeCompleteDeferred(taker, item);
357
- }
358
- if (remaining.length === 0) {
359
- return succeed$1(true);
360
- }
361
- // Not enough takers, offer to the queue
362
- const surplus = this.queue.offerAll(remaining);
363
- unsafeCompleteTakers(this.strategy, this.queue, this.takers);
364
- return isEmpty(surplus) ? succeed$1(true) : this.strategy.handleSurplus(surplus, this.queue, this.takers, this.shutdownFlag);
365
- });
366
- }
367
- get take() {
368
- return withFiberRuntime(state => {
369
- if (get$2(this.shutdownFlag)) {
370
- return interrupt$3;
371
- }
372
- const item = this.queue.poll(EmptyMutableQueue);
373
- if (item !== EmptyMutableQueue) {
374
- this.strategy.unsafeOnQueueEmptySpace(this.queue, this.takers);
375
- return succeed$1(item);
376
- } else {
377
- // Add the deferred to takers, then:
378
- // - Try to take again in case a value was added since
379
- // - Wait for the deferred to be completed
380
- // - Clean up resources in case of interruption
381
- const deferred = deferredUnsafeMake(state.id());
382
- return pipe(suspend$2(() => {
383
- pipe(this.takers, offer$2(deferred));
384
- unsafeCompleteTakers(this.strategy, this.queue, this.takers);
385
- return get$2(this.shutdownFlag) ? interrupt$3 : deferredAwait(deferred);
386
- }), onInterrupt(() => {
387
- return sync$1(() => unsafeRemove(this.takers, deferred));
388
- }));
389
- }
390
- });
391
- }
392
- get takeAll() {
393
- return suspend$2(() => {
394
- return get$2(this.shutdownFlag) ? interrupt$3 : sync$1(() => {
395
- const values = this.queue.pollUpTo(Number.POSITIVE_INFINITY);
396
- this.strategy.unsafeOnQueueEmptySpace(this.queue, this.takers);
397
- return fromIterable$1(values);
398
- });
399
- });
400
- }
401
- takeUpTo(max) {
402
- return suspend$2(() => get$2(this.shutdownFlag) ? interrupt$3 : sync$1(() => {
403
- const values = this.queue.pollUpTo(max);
404
- this.strategy.unsafeOnQueueEmptySpace(this.queue, this.takers);
405
- return fromIterable$1(values);
406
- }));
407
- }
408
- takeBetween(min, max) {
409
- return suspend$2(() => takeRemainderLoop(this, min, max, empty$1()));
410
- }
411
- }
412
- /** @internal */
413
- const takeRemainderLoop = (self, min, max, acc) => {
414
- if (max < min) {
415
- return succeed$1(acc);
416
- }
417
- return pipe(takeUpTo(self, max), flatMap$2(bs => {
418
- const remaining = min - bs.length;
419
- if (remaining === 1) {
420
- return pipe(take$1(self), map$4(b => pipe(acc, appendAll(bs), append(b))));
421
- }
422
- if (remaining > 1) {
423
- return pipe(take$1(self), flatMap$2(b => takeRemainderLoop(self, remaining - 1, max - bs.length - 1, pipe(acc, appendAll(bs), append(b)))));
424
- }
425
- return succeed$1(pipe(acc, appendAll(bs)));
426
- }));
427
- };
428
- /** @internal */
429
- const bounded$1 = requestedCapacity => pipe(sync$1(() => bounded$2(requestedCapacity)), flatMap$2(queue => make$2(backingQueueFromMutableQueue(queue), backPressureStrategy())));
430
- /** @internal */
431
- const unbounded$1 = () => pipe(sync$1(() => unbounded$2()), flatMap$2(queue => make$2(backingQueueFromMutableQueue(queue), droppingStrategy())));
432
- /** @internal */
433
- const unsafeMake = (queue, takers, shutdownHook, shutdownFlag, strategy) => {
434
- return new QueueImpl(queue, takers, shutdownHook, shutdownFlag, strategy);
435
- };
436
- /** @internal */
437
- const make$2 = (queue, strategy) => pipe(deferredMake(), map$4(deferred => unsafeMake(queue, unbounded$2(), deferred, make$5(false), strategy)));
438
- /** @internal */
439
- class BackingQueueFromMutableQueue {
440
- mutable;
441
- [BackingQueueTypeId] = backingQueueVariance;
442
- constructor(mutable) {
443
- this.mutable = mutable;
444
- }
445
- poll(def) {
446
- return poll(this.mutable, def);
447
- }
448
- pollUpTo(limit) {
449
- return pollUpTo(this.mutable, limit);
450
- }
451
- offerAll(elements) {
452
- return offerAll(this.mutable, elements);
453
- }
454
- offer(element) {
455
- return offer$2(this.mutable, element);
456
- }
457
- capacity() {
458
- return capacity(this.mutable);
459
- }
460
- length() {
461
- return length(this.mutable);
462
- }
463
- }
464
- /** @internal */
465
- const backingQueueFromMutableQueue = mutable => new BackingQueueFromMutableQueue(mutable);
466
- /** @internal */
467
- const size$1 = self => self.size;
468
- /** @internal */
469
- const isShutdown$1 = self => self.isShutdown;
470
- /** @internal */
471
- const shutdown$1 = self => self.shutdown;
472
- /** @internal */
473
- const offer$1 = /*#__PURE__*/dual(2, (self, value) => self.offer(value));
474
- /** @internal */
475
- const take$1 = self => self.take;
476
- /** @internal */
477
- const takeUpTo = /*#__PURE__*/dual(2, (self, max) => self.takeUpTo(max));
478
- /** @internal */
479
- const takeBetween$1 = /*#__PURE__*/dual(3, (self, min, max) => self.takeBetween(min, max));
480
- // -----------------------------------------------------------------------------
481
- // Strategy
482
- // -----------------------------------------------------------------------------
483
- /** @internal */
484
- const backPressureStrategy = () => new BackPressureStrategy();
485
- /** @internal */
486
- const droppingStrategy = () => new DroppingStrategy();
487
- /** @internal */
488
- class BackPressureStrategy {
489
- [QueueStrategyTypeId] = queueStrategyVariance;
490
- putters = /*#__PURE__*/unbounded$2();
491
- surplusSize() {
492
- return length(this.putters);
493
- }
494
- onCompleteTakersWithEmptyQueue(takers) {
495
- while (!isEmpty$1(this.putters) && !isEmpty$1(takers)) {
496
- const taker = poll(takers, void 0);
497
- const putter = poll(this.putters, void 0);
498
- if (putter[2]) {
499
- unsafeCompleteDeferred(putter[1], true);
500
- }
501
- unsafeCompleteDeferred(taker, putter[0]);
502
- }
503
- }
504
- get shutdown() {
505
- return pipe(fiberId, flatMap$2(fiberId => pipe(sync$1(() => unsafePollAll(this.putters)), flatMap$2(putters => forEachConcurrentDiscard(putters, ([_, deferred, isLastItem]) => isLastItem ? pipe(deferredInterruptWith(deferred, fiberId), asVoid) : void_$1, false, false)))));
506
- }
507
- handleSurplus(iterable, queue, takers, isShutdown) {
508
- return withFiberRuntime(state => {
509
- const deferred = deferredUnsafeMake(state.id());
510
- return pipe(suspend$2(() => {
511
- this.unsafeOffer(iterable, deferred);
512
- this.unsafeOnQueueEmptySpace(queue, takers);
513
- unsafeCompleteTakers(this, queue, takers);
514
- return get$2(isShutdown) ? interrupt$3 : deferredAwait(deferred);
515
- }), onInterrupt(() => sync$1(() => this.unsafeRemove(deferred))));
516
- });
517
- }
518
- unsafeOnQueueEmptySpace(queue, takers) {
519
- let keepPolling = true;
520
- while (keepPolling && (queue.capacity() === Number.POSITIVE_INFINITY || queue.length() < queue.capacity())) {
521
- const putter = pipe(this.putters, poll(EmptyMutableQueue));
522
- if (putter === EmptyMutableQueue) {
523
- keepPolling = false;
524
- } else {
525
- const offered = queue.offer(putter[0]);
526
- if (offered && putter[2]) {
527
- unsafeCompleteDeferred(putter[1], true);
528
- } else if (!offered) {
529
- unsafeOfferAll(this.putters, pipe(unsafePollAll(this.putters), prepend(putter)));
530
- }
531
- unsafeCompleteTakers(this, queue, takers);
532
- }
533
- }
534
- }
535
- unsafeOffer(iterable, deferred) {
536
- const stuff = fromIterable(iterable);
537
- for (let i = 0; i < stuff.length; i++) {
538
- const value = stuff[i];
539
- if (i === stuff.length - 1) {
540
- pipe(this.putters, offer$2([value, deferred, true]));
541
- } else {
542
- pipe(this.putters, offer$2([value, deferred, false]));
543
- }
544
- }
545
- }
546
- unsafeRemove(deferred) {
547
- unsafeOfferAll(this.putters, pipe(unsafePollAll(this.putters), filter(([, _]) => _ !== deferred)));
548
- }
549
- }
550
- /** @internal */
551
- class DroppingStrategy {
552
- [QueueStrategyTypeId] = queueStrategyVariance;
553
- surplusSize() {
554
- return 0;
555
- }
556
- get shutdown() {
557
- return void_$1;
558
- }
559
- onCompleteTakersWithEmptyQueue() {}
560
- handleSurplus(_iterable, _queue, _takers, _isShutdown) {
561
- return succeed$1(false);
562
- }
563
- unsafeOnQueueEmptySpace(_queue, _takers) {
564
- //
565
- }
566
- }
567
- /** @internal */
568
- const unsafeCompleteDeferred = (deferred, a) => {
569
- return deferredUnsafeDone(deferred, succeed$1(a));
570
- };
571
- /** @internal */
572
- const unsafeOfferAll = (queue, as) => {
573
- return pipe(queue, offerAll(as));
574
- };
575
- /** @internal */
576
- const unsafePollAll = queue => {
577
- return pipe(queue, pollUpTo(Number.POSITIVE_INFINITY));
578
- };
579
- /** @internal */
580
- const unsafePollN = (queue, max) => {
581
- return pipe(queue, pollUpTo(max));
582
- };
583
- /** @internal */
584
- const unsafeRemove = (queue, a) => {
585
- unsafeOfferAll(queue, pipe(unsafePollAll(queue), filter(b => a !== b)));
586
- };
587
- /** @internal */
588
- const unsafeCompleteTakers = (strategy, queue, takers) => {
589
- // Check both a taker and an item are in the queue, starting with the taker
590
- let keepPolling = true;
591
- while (keepPolling && queue.length() !== 0) {
592
- const taker = pipe(takers, poll(EmptyMutableQueue));
593
- if (taker !== EmptyMutableQueue) {
594
- const element = queue.poll(EmptyMutableQueue);
595
- if (element !== EmptyMutableQueue) {
596
- unsafeCompleteDeferred(taker, element);
597
- strategy.unsafeOnQueueEmptySpace(queue, takers);
598
- } else {
599
- unsafeOfferAll(takers, pipe(unsafePollAll(takers), prepend(taker)));
600
- }
601
- keepPolling = true;
602
- } else {
603
- keepPolling = false;
604
- }
605
- }
606
- if (keepPolling && queue.length() === 0 && !isEmpty$1(takers)) {
607
- strategy.onCompleteTakersWithEmptyQueue(takers);
608
- }
609
- };
610
-
611
- /**
612
- * Makes a new bounded `Queue`. When the capacity of the queue is reached, any
613
- * additional calls to `offer` will be suspended until there is more room in
614
- * the queue.
615
- *
616
- * **Note**: When possible use only power of 2 capacities; this will provide
617
- * better performance by utilising an optimised version of the underlying
618
- * `RingBuffer`.
619
- *
620
- * @since 2.0.0
621
- * @category constructors
622
- */
623
- const bounded = bounded$1;
624
- /**
625
- * Creates a new unbounded `Queue`.
626
- *
627
- * @since 2.0.0
628
- * @category constructors
629
- */
630
- const unbounded = unbounded$1;
631
- /**
632
- * Retrieves the size of the queue, which is equal to the number of elements
633
- * in the queue. This may be negative if fibers are suspended waiting for
634
- * elements to be added to the queue.
635
- *
636
- * @since 2.0.0
637
- * @category getters
638
- */
639
- const size = size$1;
640
- /**
641
- * Returns `true` if `shutdown` has been called, otherwise returns `false`.
642
- *
643
- * @since 2.0.0
644
- * @category getters
645
- */
646
- const isShutdown = isShutdown$1;
647
- /**
648
- * Interrupts any fibers that are suspended on `offer` or `take`. Future calls
649
- * to `offer*` and `take*` will be interrupted immediately.
650
- *
651
- * @since 2.0.0
652
- * @category utils
653
- */
654
- const shutdown = shutdown$1;
655
- /**
656
- * Places one value in the queue.
657
- *
658
- * @since 2.0.0
659
- * @category utils
660
- */
661
- const offer = offer$1;
662
- /**
663
- * Takes the oldest value in the queue. If the queue is empty, this will return
664
- * a computation that resumes when an item has been added to the queue.
665
- *
666
- * @since 2.0.0
667
- * @category utils
668
- */
669
- const take = take$1;
670
- /**
671
- * Takes a number of elements from the queue between the specified minimum and
672
- * maximum. If there are fewer than the minimum number of elements available,
673
- * suspends until at least the minimum number of elements have been collected.
674
- *
675
- * @since 2.0.0
676
- * @category utils
677
- */
678
- const takeBetween = takeBetween$1;
679
-
680
- /** @internal */
681
- const OP_CONTINUE = "Continue";
682
- /** @internal */
683
- const OP_CLOSE = "Close";
684
- /** @internal */
685
- const OP_YIELD = "Yield";
686
-
687
- /** @internal */
688
- const ChildExecutorDecisionSymbolKey = "effect/ChannelChildExecutorDecision";
689
- /** @internal */
690
- const ChildExecutorDecisionTypeId = /*#__PURE__*/Symbol.for(ChildExecutorDecisionSymbolKey);
691
- /** @internal */
692
- const proto$7 = {
693
- [ChildExecutorDecisionTypeId]: ChildExecutorDecisionTypeId
694
- };
695
- /** @internal */
696
- const Continue = _ => {
697
- const op = Object.create(proto$7);
698
- op._tag = OP_CONTINUE;
699
- return op;
700
- };
701
-
702
- /** @internal */
703
- const OP_CONTINUATION_K = "ContinuationK";
704
- /** @internal */
705
- const OP_CONTINUATION_FINALIZER = "ContinuationFinalizer";
706
-
707
- /** @internal */
708
- const ContinuationTypeId = /*#__PURE__*/Symbol.for("effect/ChannelContinuation");
709
- const continuationVariance = {
710
- /* c8 ignore next */
711
- _Env: _ => _,
712
- /* c8 ignore next */
713
- _InErr: _ => _,
714
- /* c8 ignore next */
715
- _InElem: _ => _,
716
- /* c8 ignore next */
717
- _InDone: _ => _,
718
- /* c8 ignore next */
719
- _OutErr: _ => _,
720
- /* c8 ignore next */
721
- _OutDone: _ => _,
722
- /* c8 ignore next */
723
- _OutErr2: _ => _,
724
- /* c8 ignore next */
725
- _OutElem: _ => _,
726
- /* c8 ignore next */
727
- _OutDone2: _ => _
728
- };
729
- /** @internal */
730
- class ContinuationKImpl {
731
- onSuccess;
732
- onHalt;
733
- _tag = OP_CONTINUATION_K;
734
- [ContinuationTypeId] = continuationVariance;
735
- constructor(onSuccess, onHalt) {
736
- this.onSuccess = onSuccess;
737
- this.onHalt = onHalt;
738
- }
739
- onExit(exit) {
740
- return isFailure(exit) ? this.onHalt(exit.cause) : this.onSuccess(exit.value);
741
- }
742
- }
743
- /** @internal */
744
- class ContinuationFinalizerImpl {
745
- finalizer;
746
- _tag = OP_CONTINUATION_FINALIZER;
747
- [ContinuationTypeId] = continuationVariance;
748
- constructor(finalizer) {
749
- this.finalizer = finalizer;
750
- }
751
- }
752
-
753
- /** @internal */
754
- const OP_PULL_AFTER_NEXT = "PullAfterNext";
755
- /** @internal */
756
- const OP_PULL_AFTER_ALL_ENQUEUED = "PullAfterAllEnqueued";
757
-
758
- /** @internal */
759
- const UpstreamPullStrategySymbolKey = "effect/ChannelUpstreamPullStrategy";
760
- /** @internal */
761
- const UpstreamPullStrategyTypeId = /*#__PURE__*/Symbol.for(UpstreamPullStrategySymbolKey);
762
- const upstreamPullStrategyVariance = {
763
- /* c8 ignore next */
764
- _A: _ => _
765
- };
766
- /** @internal */
767
- const proto$6 = {
768
- [UpstreamPullStrategyTypeId]: upstreamPullStrategyVariance
769
- };
770
- /** @internal */
771
- const PullAfterNext = emitSeparator => {
772
- const op = Object.create(proto$6);
773
- op._tag = OP_PULL_AFTER_NEXT;
774
- op.emitSeparator = emitSeparator;
775
- return op;
776
- };
777
-
778
- /** @internal */
779
- const OP_BRACKET_OUT = "BracketOut";
780
- /** @internal */
781
- const OP_BRIDGE = "Bridge";
782
- /** @internal */
783
- const OP_CONCAT_ALL = "ConcatAll";
784
- /** @internal */
785
- const OP_EMIT$2 = "Emit";
786
- /** @internal */
787
- const OP_ENSURING = "Ensuring";
788
- /** @internal */
789
- const OP_FAIL = "Fail";
790
- /** @internal */
791
- const OP_FOLD = "Fold";
792
- /** @internal */
793
- const OP_FROM_EFFECT$1 = "FromEffect";
794
- /** @internal */
795
- const OP_PIPE_TO = "PipeTo";
796
- /** @internal */
797
- const OP_PROVIDE = "Provide";
798
- /** @internal */
799
- const OP_READ$1 = "Read";
800
- /** @internal */
801
- const OP_SUCCEED = "Succeed";
802
- /** @internal */
803
- const OP_SUCCEED_NOW = "SucceedNow";
804
- /** @internal */
805
- const OP_SUSPEND = "Suspend";
806
-
807
- /** @internal */
808
- const ChannelSymbolKey = "effect/Channel";
809
- /** @internal */
810
- const ChannelTypeId = /*#__PURE__*/Symbol.for(ChannelSymbolKey);
811
- const channelVariance = {
812
- /* c8 ignore next */
813
- _Env: _ => _,
814
- /* c8 ignore next */
815
- _InErr: _ => _,
816
- /* c8 ignore next */
817
- _InElem: _ => _,
818
- /* c8 ignore next */
819
- _InDone: _ => _,
820
- /* c8 ignore next */
821
- _OutErr: _ => _,
822
- /* c8 ignore next */
823
- _OutElem: _ => _,
824
- /* c8 ignore next */
825
- _OutDone: _ => _
826
- };
827
- /** @internal */
828
- const proto$5 = {
829
- [ChannelTypeId]: channelVariance,
830
- pipe() {
831
- return pipeArguments(this, arguments);
832
- }
833
- };
834
- /** @internal */
835
- const isChannel = u => hasProperty(u, ChannelTypeId) || isEffect(u);
836
- /** @internal */
837
- const acquireReleaseOut = /*#__PURE__*/dual(2, (self, release) => {
838
- const op = Object.create(proto$5);
839
- op._tag = OP_BRACKET_OUT;
840
- op.acquire = () => self;
841
- op.finalizer = release;
842
- return op;
843
- });
844
- /** @internal */
845
- const concatAllWith = (channels, f, g) => {
846
- const op = Object.create(proto$5);
847
- op._tag = OP_CONCAT_ALL;
848
- op.combineInners = f;
849
- op.combineAll = g;
850
- op.onPull = () => PullAfterNext(none());
851
- op.onEmit = () => Continue;
852
- op.value = () => channels;
853
- op.k = identity;
854
- return op;
855
- };
856
- /** @internal */
857
- const concatMapWith = /*#__PURE__*/dual(4, (self, f, g, h) => {
858
- const op = Object.create(proto$5);
859
- op._tag = OP_CONCAT_ALL;
860
- op.combineInners = g;
861
- op.combineAll = h;
862
- op.onPull = () => PullAfterNext(none());
863
- op.onEmit = () => Continue;
864
- op.value = () => self;
865
- op.k = f;
866
- return op;
867
- });
868
- /** @internal */
869
- const embedInput = /*#__PURE__*/dual(2, (self, input) => {
870
- const op = Object.create(proto$5);
871
- op._tag = OP_BRIDGE;
872
- op.input = input;
873
- op.channel = self;
874
- return op;
875
- });
876
- /** @internal */
877
- const ensuringWith = /*#__PURE__*/dual(2, (self, finalizer) => {
878
- const op = Object.create(proto$5);
879
- op._tag = OP_ENSURING;
880
- op.channel = self;
881
- op.finalizer = finalizer;
882
- return op;
883
- });
884
- /** @internal */
885
- const fail = error => failCause$2(fail$1(error));
886
- /** @internal */
887
- const failCause$2 = cause => failCauseSync(() => cause);
888
- /** @internal */
889
- const failCauseSync = evaluate => {
890
- const op = Object.create(proto$5);
891
- op._tag = OP_FAIL;
892
- op.error = evaluate;
893
- return op;
894
- };
895
- /** @internal */
896
- const flatMap$1 = /*#__PURE__*/dual(2, (self, f) => {
897
- const op = Object.create(proto$5);
898
- op._tag = OP_FOLD;
899
- op.channel = self;
900
- op.k = new ContinuationKImpl(f, failCause$2);
901
- return op;
902
- });
903
- /** @internal */
904
- const fromEffect$3 = effect => {
905
- const op = Object.create(proto$5);
906
- op._tag = OP_FROM_EFFECT$1;
907
- op.effect = () => effect;
908
- return op;
909
- };
910
- /** @internal */
911
- const pipeTo = /*#__PURE__*/dual(2, (self, that) => {
912
- const op = Object.create(proto$5);
913
- op._tag = OP_PIPE_TO;
914
- op.left = () => self;
915
- op.right = () => that;
916
- return op;
917
- });
918
- /** @internal */
919
- const readWith = options => readWithCause({
920
- onInput: options.onInput,
921
- onFailure: cause => match$1(failureOrCause(cause), {
922
- onLeft: options.onFailure,
923
- onRight: failCause$2
924
- }),
925
- onDone: options.onDone
926
- });
927
- /** @internal */
928
- const readWithCause = options => {
929
- const op = Object.create(proto$5);
930
- op._tag = OP_READ$1;
931
- op.more = options.onInput;
932
- op.done = new ContinuationKImpl(options.onDone, options.onFailure);
933
- return op;
934
- };
935
- /** @internal */
936
- const succeed = value => sync(() => value);
937
- /** @internal */
938
- const succeedNow = result => {
939
- const op = Object.create(proto$5);
940
- op._tag = OP_SUCCEED_NOW;
941
- op.terminal = result;
942
- return op;
943
- };
944
- /** @internal */
945
- const suspend$1 = evaluate => {
946
- const op = Object.create(proto$5);
947
- op._tag = OP_SUSPEND;
948
- op.channel = evaluate;
949
- return op;
950
- };
951
- const sync = evaluate => {
952
- const op = Object.create(proto$5);
953
- op._tag = OP_SUCCEED;
954
- op.evaluate = evaluate;
955
- return op;
956
- };
957
- const void_ = /*#__PURE__*/succeedNow(void 0);
958
- /** @internal */
959
- const write = out => {
960
- const op = Object.create(proto$5);
961
- op._tag = OP_EMIT$2;
962
- op.out = out;
963
- return op;
964
- };
965
-
966
- /** @internal */
967
- const OP_DONE$1 = "Done";
968
- /** @internal */
969
- const OP_EMIT$1 = "Emit";
970
- /** @internal */
971
- const OP_FROM_EFFECT = "FromEffect";
972
- /** @internal */
973
- const OP_READ = "Read";
974
-
975
- /** @internal */
976
- const ChannelStateTypeId = /*#__PURE__*/Symbol.for("effect/ChannelState");
977
- const channelStateVariance = {
978
- /* c8 ignore next */
979
- _E: _ => _,
980
- /* c8 ignore next */
981
- _R: _ => _
982
- };
983
- /** @internal */
984
- const proto$4 = {
985
- [ChannelStateTypeId]: channelStateVariance
986
- };
987
- /** @internal */
988
- const Done = () => {
989
- const op = Object.create(proto$4);
990
- op._tag = OP_DONE$1;
991
- return op;
992
- };
993
- /** @internal */
994
- const Emit$1 = () => {
995
- const op = Object.create(proto$4);
996
- op._tag = OP_EMIT$1;
997
- return op;
998
- };
999
- /** @internal */
1000
- const fromEffect$2 = effect => {
1001
- const op = Object.create(proto$4);
1002
- op._tag = OP_FROM_EFFECT;
1003
- op.effect = effect;
1004
- return op;
1005
- };
1006
- /** @internal */
1007
- const Read = (upstream, onEffect, onEmit, onDone) => {
1008
- const op = Object.create(proto$4);
1009
- op._tag = OP_READ;
1010
- op.upstream = upstream;
1011
- op.onEffect = onEffect;
1012
- op.onEmit = onEmit;
1013
- op.onDone = onDone;
1014
- return op;
1015
- };
1016
- /** @internal */
1017
- const isFromEffect = self => self._tag === OP_FROM_EFFECT;
1018
- /** @internal */
1019
- const effect = self => isFromEffect(self) ? self.effect : _void;
1020
- /** @internal */
1021
- const effectOrUndefinedIgnored = self => isFromEffect(self) ? ignore(self.effect) : undefined;
1022
-
1023
- /** @internal */
1024
- const OP_PULL_FROM_CHILD = "PullFromChild";
1025
- /** @internal */
1026
- const OP_PULL_FROM_UPSTREAM = "PullFromUpstream";
1027
- /** @internal */
1028
- const OP_DRAIN_CHILD_EXECUTORS = "DrainChildExecutors";
1029
- /** @internal */
1030
- const OP_EMIT = "Emit";
1031
- /**
1032
- * Execute the `childExecutor` and on each emitted value, decide what to do by
1033
- * `onEmit`.
1034
- *
1035
- * @internal
1036
- */
1037
- class PullFromChild {
1038
- childExecutor;
1039
- parentSubexecutor;
1040
- onEmit;
1041
- _tag = OP_PULL_FROM_CHILD;
1042
- constructor(childExecutor, parentSubexecutor, onEmit) {
1043
- this.childExecutor = childExecutor;
1044
- this.parentSubexecutor = parentSubexecutor;
1045
- this.onEmit = onEmit;
1046
- }
1047
- close(exit$1) {
1048
- const fin1 = this.childExecutor.close(exit$1);
1049
- const fin2 = this.parentSubexecutor.close(exit$1);
1050
- if (fin1 !== undefined && fin2 !== undefined) {
1051
- return zipWith(exit(fin1), exit(fin2), (exit1, exit2) => pipe(exit1, zipRight$2(exit2)));
1052
- } else if (fin1 !== undefined) {
1053
- return fin1;
1054
- } else if (fin2 !== undefined) {
1055
- return fin2;
1056
- } else {
1057
- return undefined;
1058
- }
1059
- }
1060
- enqueuePullFromChild(_child) {
1061
- return this;
1062
- }
1063
- }
1064
- /**
1065
- * Execute `upstreamExecutor` and for each emitted element, spawn a child
1066
- * channel and continue with processing it by `PullFromChild`.
1067
- *
1068
- * @internal
1069
- */
1070
- class PullFromUpstream {
1071
- upstreamExecutor;
1072
- createChild;
1073
- lastDone;
1074
- activeChildExecutors;
1075
- combineChildResults;
1076
- combineWithChildResult;
1077
- onPull;
1078
- onEmit;
1079
- _tag = OP_PULL_FROM_UPSTREAM;
1080
- constructor(upstreamExecutor, createChild, lastDone, activeChildExecutors, combineChildResults, combineWithChildResult, onPull, onEmit) {
1081
- this.upstreamExecutor = upstreamExecutor;
1082
- this.createChild = createChild;
1083
- this.lastDone = lastDone;
1084
- this.activeChildExecutors = activeChildExecutors;
1085
- this.combineChildResults = combineChildResults;
1086
- this.combineWithChildResult = combineWithChildResult;
1087
- this.onPull = onPull;
1088
- this.onEmit = onEmit;
1089
- }
1090
- close(exit$1) {
1091
- const fin1 = this.upstreamExecutor.close(exit$1);
1092
- const fins = [...this.activeChildExecutors.map(child => child !== undefined ? child.childExecutor.close(exit$1) : undefined), fin1];
1093
- const result = fins.reduce((acc, next) => {
1094
- if (acc !== undefined && next !== undefined) {
1095
- return zipWith(acc, exit(next), (exit1, exit2) => zipRight$2(exit1, exit2));
1096
- } else if (acc !== undefined) {
1097
- return acc;
1098
- } else if (next !== undefined) {
1099
- return exit(next);
1100
- } else {
1101
- return undefined;
1102
- }
1103
- }, undefined);
1104
- return result === undefined ? result : result;
1105
- }
1106
- enqueuePullFromChild(child) {
1107
- return new PullFromUpstream(this.upstreamExecutor, this.createChild, this.lastDone, [...this.activeChildExecutors, child], this.combineChildResults, this.combineWithChildResult, this.onPull, this.onEmit);
1108
- }
1109
- }
1110
- /**
1111
- * Transformed from `PullFromUpstream` when upstream has finished but there
1112
- * are still active child executors.
1113
- *
1114
- * @internal
1115
- */
1116
- class DrainChildExecutors {
1117
- upstreamExecutor;
1118
- lastDone;
1119
- activeChildExecutors;
1120
- upstreamDone;
1121
- combineChildResults;
1122
- combineWithChildResult;
1123
- onPull;
1124
- _tag = OP_DRAIN_CHILD_EXECUTORS;
1125
- constructor(upstreamExecutor, lastDone, activeChildExecutors, upstreamDone, combineChildResults, combineWithChildResult, onPull) {
1126
- this.upstreamExecutor = upstreamExecutor;
1127
- this.lastDone = lastDone;
1128
- this.activeChildExecutors = activeChildExecutors;
1129
- this.upstreamDone = upstreamDone;
1130
- this.combineChildResults = combineChildResults;
1131
- this.combineWithChildResult = combineWithChildResult;
1132
- this.onPull = onPull;
1133
- }
1134
- close(exit$1) {
1135
- const fin1 = this.upstreamExecutor.close(exit$1);
1136
- const fins = [...this.activeChildExecutors.map(child => child !== undefined ? child.childExecutor.close(exit$1) : undefined), fin1];
1137
- const result = fins.reduce((acc, next) => {
1138
- if (acc !== undefined && next !== undefined) {
1139
- return zipWith(acc, exit(next), (exit1, exit2) => zipRight$2(exit1, exit2));
1140
- } else if (acc !== undefined) {
1141
- return acc;
1142
- } else if (next !== undefined) {
1143
- return exit(next);
1144
- } else {
1145
- return undefined;
1146
- }
1147
- }, undefined);
1148
- return result === undefined ? result : result;
1149
- }
1150
- enqueuePullFromChild(child) {
1151
- return new DrainChildExecutors(this.upstreamExecutor, this.lastDone, [...this.activeChildExecutors, child], this.upstreamDone, this.combineChildResults, this.combineWithChildResult, this.onPull);
1152
- }
1153
- }
1154
- /** @internal */
1155
- class Emit {
1156
- value;
1157
- next;
1158
- _tag = OP_EMIT;
1159
- constructor(value, next) {
1160
- this.value = value;
1161
- this.next = next;
1162
- }
1163
- close(exit) {
1164
- const result = this.next.close(exit);
1165
- return result === undefined ? result : result;
1166
- }
1167
- enqueuePullFromChild(_child) {
1168
- return this;
1169
- }
1170
- }
1171
-
1172
- /** @internal */
1173
- const OP_PULLED = "Pulled";
1174
- /** @internal */
1175
- const OP_NO_UPSTREAM = "NoUpstream";
1176
-
1177
- /** @internal */
1178
- const UpstreamPullRequestSymbolKey = "effect/ChannelUpstreamPullRequest";
1179
- /** @internal */
1180
- const UpstreamPullRequestTypeId = /*#__PURE__*/Symbol.for(UpstreamPullRequestSymbolKey);
1181
- const upstreamPullRequestVariance = {
1182
- /* c8 ignore next */
1183
- _A: _ => _
1184
- };
1185
- /** @internal */
1186
- const proto$3 = {
1187
- [UpstreamPullRequestTypeId]: upstreamPullRequestVariance
1188
- };
1189
- /** @internal */
1190
- const Pulled = value => {
1191
- const op = Object.create(proto$3);
1192
- op._tag = OP_PULLED;
1193
- op.value = value;
1194
- return op;
1195
- };
1196
- /** @internal */
1197
- const NoUpstream = activeDownstreamCount => {
1198
- const op = Object.create(proto$3);
1199
- op._tag = OP_NO_UPSTREAM;
1200
- op.activeDownstreamCount = activeDownstreamCount;
1201
- return op;
1202
- };
1203
-
1204
- /** @internal */
1205
- class ChannelExecutor {
1206
- _activeSubexecutor = undefined;
1207
- _cancelled = undefined;
1208
- _closeLastSubstream = undefined;
1209
- _currentChannel;
1210
- _done = undefined;
1211
- _doneStack = [];
1212
- _emitted = undefined;
1213
- _executeCloseLastSubstream;
1214
- _input = undefined;
1215
- _inProgressFinalizer = undefined;
1216
- _providedEnv;
1217
- constructor(initialChannel, providedEnv, executeCloseLastSubstream) {
1218
- this._currentChannel = initialChannel;
1219
- this._executeCloseLastSubstream = executeCloseLastSubstream;
1220
- this._providedEnv = providedEnv;
1221
- }
1222
- run() {
1223
- let result = undefined;
1224
- while (result === undefined) {
1225
- if (this._cancelled !== undefined) {
1226
- result = this.processCancellation();
1227
- } else if (this._activeSubexecutor !== undefined) {
1228
- result = this.runSubexecutor();
1229
- } else {
1230
- try {
1231
- if (this._currentChannel === undefined) {
1232
- result = Done();
1233
- } else {
1234
- if (isEffect(this._currentChannel)) {
1235
- this._currentChannel = fromEffect$3(this._currentChannel);
1236
- }
1237
- switch (this._currentChannel._tag) {
1238
- case OP_BRACKET_OUT:
1239
- {
1240
- result = this.runBracketOut(this._currentChannel);
1241
- break;
1242
- }
1243
- case OP_BRIDGE:
1244
- {
1245
- const bridgeInput = this._currentChannel.input;
1246
- // PipeTo(left, Bridge(queue, channel))
1247
- // In a fiber: repeatedly run left and push its outputs to the queue
1248
- // Add a finalizer to interrupt the fiber and close the executor
1249
- this._currentChannel = this._currentChannel.channel;
1250
- if (this._input !== undefined) {
1251
- const inputExecutor = this._input;
1252
- this._input = undefined;
1253
- const drainer = () => flatMap$3(bridgeInput.awaitRead(), () => suspend$3(() => {
1254
- const state = inputExecutor.run();
1255
- switch (state._tag) {
1256
- case OP_DONE$1:
1257
- {
1258
- return match$2(inputExecutor.getDone(), {
1259
- onFailure: cause => bridgeInput.error(cause),
1260
- onSuccess: value => bridgeInput.done(value)
1261
- });
1262
- }
1263
- case OP_EMIT$1:
1264
- {
1265
- return flatMap$3(bridgeInput.emit(inputExecutor.getEmit()), () => drainer());
1266
- }
1267
- case OP_FROM_EFFECT:
1268
- {
1269
- return matchCauseEffect(state.effect, {
1270
- onFailure: cause => bridgeInput.error(cause),
1271
- onSuccess: () => drainer()
1272
- });
1273
- }
1274
- case OP_READ:
1275
- {
1276
- return readUpstream(state, () => drainer(), cause => bridgeInput.error(cause));
1277
- }
1278
- }
1279
- }));
1280
- result = fromEffect$2(flatMap$3(forkDaemon(interruptible(drainer())), fiber => sync$2(() => this.addFinalizer(exit => flatMap$3(interrupt(fiber), () => suspend$3(() => {
1281
- const effect = this.restorePipe(exit, inputExecutor);
1282
- return effect !== undefined ? effect : _void;
1283
- }))))));
1284
- }
1285
- break;
1286
- }
1287
- case OP_CONCAT_ALL:
1288
- {
1289
- const executor = new ChannelExecutor(this._currentChannel.value(), this._providedEnv, effect => sync$2(() => {
1290
- const prevLastClose = this._closeLastSubstream === undefined ? _void : this._closeLastSubstream;
1291
- this._closeLastSubstream = pipe(prevLastClose, zipRight$3(effect));
1292
- }));
1293
- executor._input = this._input;
1294
- const channel = this._currentChannel;
1295
- this._activeSubexecutor = new PullFromUpstream(executor, value => channel.k(value), undefined, [], (x, y) => channel.combineInners(x, y), (x, y) => channel.combineAll(x, y), request => channel.onPull(request), value => channel.onEmit(value));
1296
- this._closeLastSubstream = undefined;
1297
- this._currentChannel = undefined;
1298
- break;
1299
- }
1300
- case OP_EMIT$2:
1301
- {
1302
- this._emitted = this._currentChannel.out;
1303
- this._currentChannel = this._activeSubexecutor !== undefined ? undefined : void_;
1304
- result = Emit$1();
1305
- break;
1306
- }
1307
- case OP_ENSURING:
1308
- {
1309
- this.runEnsuring(this._currentChannel);
1310
- break;
1311
- }
1312
- case OP_FAIL:
1313
- {
1314
- result = this.doneHalt(this._currentChannel.error());
1315
- break;
1316
- }
1317
- case OP_FOLD:
1318
- {
1319
- this._doneStack.push(this._currentChannel.k);
1320
- this._currentChannel = this._currentChannel.channel;
1321
- break;
1322
- }
1323
- case OP_FROM_EFFECT$1:
1324
- {
1325
- const effect = this._providedEnv === undefined ? this._currentChannel.effect() : pipe(this._currentChannel.effect(), provide(this._providedEnv));
1326
- result = fromEffect$2(matchCauseEffect(effect, {
1327
- onFailure: cause => {
1328
- const state = this.doneHalt(cause);
1329
- return state !== undefined && isFromEffect(state) ? state.effect : _void;
1330
- },
1331
- onSuccess: value => {
1332
- const state = this.doneSucceed(value);
1333
- return state !== undefined && isFromEffect(state) ? state.effect : _void;
1334
- }
1335
- }));
1336
- break;
1337
- }
1338
- case OP_PIPE_TO:
1339
- {
1340
- const previousInput = this._input;
1341
- const leftExec = new ChannelExecutor(this._currentChannel.left(), this._providedEnv, effect => this._executeCloseLastSubstream(effect));
1342
- leftExec._input = previousInput;
1343
- this._input = leftExec;
1344
- this.addFinalizer(exit => {
1345
- const effect = this.restorePipe(exit, previousInput);
1346
- return effect !== undefined ? effect : _void;
1347
- });
1348
- this._currentChannel = this._currentChannel.right();
1349
- break;
1350
- }
1351
- case OP_PROVIDE:
1352
- {
1353
- const previousEnv = this._providedEnv;
1354
- this._providedEnv = this._currentChannel.context();
1355
- this._currentChannel = this._currentChannel.inner;
1356
- this.addFinalizer(() => sync$2(() => {
1357
- this._providedEnv = previousEnv;
1358
- }));
1359
- break;
1360
- }
1361
- case OP_READ$1:
1362
- {
1363
- const read = this._currentChannel;
1364
- result = Read(this._input, identity, emitted => {
1365
- try {
1366
- this._currentChannel = read.more(emitted);
1367
- } catch (error) {
1368
- this._currentChannel = read.done.onExit(die$2(error));
1369
- }
1370
- return undefined;
1371
- }, exit => {
1372
- const onExit = exit => {
1373
- return read.done.onExit(exit);
1374
- };
1375
- this._currentChannel = onExit(exit);
1376
- return undefined;
1377
- });
1378
- break;
1379
- }
1380
- case OP_SUCCEED:
1381
- {
1382
- result = this.doneSucceed(this._currentChannel.evaluate());
1383
- break;
1384
- }
1385
- case OP_SUCCEED_NOW:
1386
- {
1387
- result = this.doneSucceed(this._currentChannel.terminal);
1388
- break;
1389
- }
1390
- case OP_SUSPEND:
1391
- {
1392
- this._currentChannel = this._currentChannel.channel();
1393
- break;
1394
- }
1395
- }
1396
- }
1397
- } catch (error) {
1398
- this._currentChannel = failCause$2(die(error));
1399
- }
1400
- }
1401
- }
1402
- return result;
1403
- }
1404
- getDone() {
1405
- return this._done;
1406
- }
1407
- getEmit() {
1408
- return this._emitted;
1409
- }
1410
- cancelWith(exit) {
1411
- this._cancelled = exit;
1412
- }
1413
- clearInProgressFinalizer() {
1414
- this._inProgressFinalizer = undefined;
1415
- }
1416
- storeInProgressFinalizer(finalizer) {
1417
- this._inProgressFinalizer = finalizer;
1418
- }
1419
- popAllFinalizers(exit) {
1420
- const finalizers = [];
1421
- let next = this._doneStack.pop();
1422
- while (next) {
1423
- if (next._tag === "ContinuationFinalizer") {
1424
- finalizers.push(next.finalizer);
1425
- }
1426
- next = this._doneStack.pop();
1427
- }
1428
- const effect = finalizers.length === 0 ? _void : runFinalizers(finalizers, exit);
1429
- this.storeInProgressFinalizer(effect);
1430
- return effect;
1431
- }
1432
- popNextFinalizers() {
1433
- const builder = [];
1434
- while (this._doneStack.length !== 0) {
1435
- const cont = this._doneStack[this._doneStack.length - 1];
1436
- if (cont._tag === OP_CONTINUATION_K) {
1437
- return builder;
1438
- }
1439
- builder.push(cont);
1440
- this._doneStack.pop();
1441
- }
1442
- return builder;
1443
- }
1444
- restorePipe(exit, prev) {
1445
- const currInput = this._input;
1446
- this._input = prev;
1447
- if (currInput !== undefined) {
1448
- const effect = currInput.close(exit);
1449
- return effect;
1450
- }
1451
- return _void;
1452
- }
1453
- close(exit$1) {
1454
- let runInProgressFinalizers = undefined;
1455
- const finalizer = this._inProgressFinalizer;
1456
- if (finalizer !== undefined) {
1457
- runInProgressFinalizers = pipe(finalizer, ensuring$2(sync$2(() => this.clearInProgressFinalizer())));
1458
- }
1459
- let closeSelf = undefined;
1460
- const selfFinalizers = this.popAllFinalizers(exit$1);
1461
- if (selfFinalizers !== undefined) {
1462
- closeSelf = pipe(selfFinalizers, ensuring$2(sync$2(() => this.clearInProgressFinalizer())));
1463
- }
1464
- const closeSubexecutors = this._activeSubexecutor === undefined ? undefined : this._activeSubexecutor.close(exit$1);
1465
- if (closeSubexecutors === undefined && runInProgressFinalizers === undefined && closeSelf === undefined) {
1466
- return undefined;
1467
- }
1468
- return pipe(exit(ifNotNull(closeSubexecutors)), zip$1(exit(ifNotNull(runInProgressFinalizers))), zip$1(exit(ifNotNull(closeSelf))), map$5(([[exit1, exit2], exit3]) => pipe(exit1, zipRight$2(exit2), zipRight$2(exit3))), uninterruptible$1,
1469
- // TODO: remove
1470
- flatMap$3(exit => suspend$3(() => exit)));
1471
- }
1472
- doneSucceed(value) {
1473
- if (this._doneStack.length === 0) {
1474
- this._done = succeed$2(value);
1475
- this._currentChannel = undefined;
1476
- return Done();
1477
- }
1478
- const head = this._doneStack[this._doneStack.length - 1];
1479
- if (head._tag === OP_CONTINUATION_K) {
1480
- this._doneStack.pop();
1481
- this._currentChannel = head.onSuccess(value);
1482
- return undefined;
1483
- }
1484
- const finalizers = this.popNextFinalizers();
1485
- if (this._doneStack.length === 0) {
1486
- this._doneStack = finalizers.reverse();
1487
- this._done = succeed$2(value);
1488
- this._currentChannel = undefined;
1489
- return Done();
1490
- }
1491
- const finalizerEffect = runFinalizers(finalizers.map(f => f.finalizer), succeed$2(value));
1492
- this.storeInProgressFinalizer(finalizerEffect);
1493
- const effect = pipe(finalizerEffect, ensuring$2(sync$2(() => this.clearInProgressFinalizer())), uninterruptible$1, flatMap$3(() => sync$2(() => this.doneSucceed(value))));
1494
- return fromEffect$2(effect);
1495
- }
1496
- doneHalt(cause) {
1497
- if (this._doneStack.length === 0) {
1498
- this._done = failCause$3(cause);
1499
- this._currentChannel = undefined;
1500
- return Done();
1501
- }
1502
- const head = this._doneStack[this._doneStack.length - 1];
1503
- if (head._tag === OP_CONTINUATION_K) {
1504
- this._doneStack.pop();
1505
- try {
1506
- this._currentChannel = head.onHalt(cause);
1507
- } catch (error) {
1508
- this._currentChannel = failCause$2(die(error));
1509
- }
1510
- return undefined;
1511
- }
1512
- const finalizers = this.popNextFinalizers();
1513
- if (this._doneStack.length === 0) {
1514
- this._doneStack = finalizers.reverse();
1515
- this._done = failCause$3(cause);
1516
- this._currentChannel = undefined;
1517
- return Done();
1518
- }
1519
- const finalizerEffect = runFinalizers(finalizers.map(f => f.finalizer), failCause$3(cause));
1520
- this.storeInProgressFinalizer(finalizerEffect);
1521
- const effect = pipe(finalizerEffect, ensuring$2(sync$2(() => this.clearInProgressFinalizer())), uninterruptible$1, flatMap$3(() => sync$2(() => this.doneHalt(cause))));
1522
- return fromEffect$2(effect);
1523
- }
1524
- processCancellation() {
1525
- this._currentChannel = undefined;
1526
- this._done = this._cancelled;
1527
- this._cancelled = undefined;
1528
- return Done();
1529
- }
1530
- runBracketOut(bracketOut) {
1531
- const effect = uninterruptible$1(matchCauseEffect(this.provide(bracketOut.acquire()), {
1532
- onFailure: cause => sync$2(() => {
1533
- this._currentChannel = failCause$2(cause);
1534
- }),
1535
- onSuccess: out => sync$2(() => {
1536
- this.addFinalizer(exit => this.provide(bracketOut.finalizer(out, exit)));
1537
- this._currentChannel = write(out);
1538
- })
1539
- }));
1540
- return fromEffect$2(effect);
1541
- }
1542
- provide(effect) {
1543
- if (this._providedEnv === undefined) {
1544
- return effect;
1545
- }
1546
- return pipe(effect, provide(this._providedEnv));
1547
- }
1548
- runEnsuring(ensuring) {
1549
- this.addFinalizer(ensuring.finalizer);
1550
- this._currentChannel = ensuring.channel;
1551
- }
1552
- addFinalizer(f) {
1553
- this._doneStack.push(new ContinuationFinalizerImpl(f));
1554
- }
1555
- runSubexecutor() {
1556
- const subexecutor = this._activeSubexecutor;
1557
- switch (subexecutor._tag) {
1558
- case OP_PULL_FROM_CHILD:
1559
- {
1560
- return this.pullFromChild(subexecutor.childExecutor, subexecutor.parentSubexecutor, subexecutor.onEmit, subexecutor);
1561
- }
1562
- case OP_PULL_FROM_UPSTREAM:
1563
- {
1564
- return this.pullFromUpstream(subexecutor);
1565
- }
1566
- case OP_DRAIN_CHILD_EXECUTORS:
1567
- {
1568
- return this.drainChildExecutors(subexecutor);
1569
- }
1570
- case OP_EMIT:
1571
- {
1572
- this._emitted = subexecutor.value;
1573
- this._activeSubexecutor = subexecutor.next;
1574
- return Emit$1();
1575
- }
1576
- }
1577
- }
1578
- replaceSubexecutor(nextSubExec) {
1579
- this._currentChannel = undefined;
1580
- this._activeSubexecutor = nextSubExec;
1581
- }
1582
- finishWithExit(exit) {
1583
- const state = match$2(exit, {
1584
- onFailure: cause => this.doneHalt(cause),
1585
- onSuccess: value => this.doneSucceed(value)
1586
- });
1587
- this._activeSubexecutor = undefined;
1588
- return state === undefined ? _void : effect(state);
1589
- }
1590
- finishSubexecutorWithCloseEffect(subexecutorDone, ...closeFuncs) {
1591
- this.addFinalizer(() => pipe(closeFuncs, forEach(closeFunc => pipe(sync$2(() => closeFunc(subexecutorDone)), flatMap$3(closeEffect => closeEffect !== undefined ? closeEffect : _void)), {
1592
- discard: true
1593
- })));
1594
- const state = pipe(subexecutorDone, match$2({
1595
- onFailure: cause => this.doneHalt(cause),
1596
- onSuccess: value => this.doneSucceed(value)
1597
- }));
1598
- this._activeSubexecutor = undefined;
1599
- return state;
1600
- }
1601
- applyUpstreamPullStrategy(upstreamFinished, queue, strategy) {
1602
- switch (strategy._tag) {
1603
- case OP_PULL_AFTER_NEXT:
1604
- {
1605
- const shouldPrepend = !upstreamFinished || queue.some(subexecutor => subexecutor !== undefined);
1606
- return [strategy.emitSeparator, shouldPrepend ? [undefined, ...queue] : queue];
1607
- }
1608
- case OP_PULL_AFTER_ALL_ENQUEUED:
1609
- {
1610
- const shouldEnqueue = !upstreamFinished || queue.some(subexecutor => subexecutor !== undefined);
1611
- return [strategy.emitSeparator, shouldEnqueue ? [...queue, undefined] : queue];
1612
- }
1613
- }
1614
- }
1615
- pullFromChild(childExecutor, parentSubexecutor, onEmitted, subexecutor) {
1616
- return Read(childExecutor, identity, emitted => {
1617
- const childExecutorDecision = onEmitted(emitted);
1618
- switch (childExecutorDecision._tag) {
1619
- case OP_CONTINUE:
1620
- {
1621
- break;
1622
- }
1623
- case OP_CLOSE:
1624
- {
1625
- this.finishWithDoneValue(childExecutor, parentSubexecutor, childExecutorDecision.value);
1626
- break;
1627
- }
1628
- case OP_YIELD:
1629
- {
1630
- const modifiedParent = parentSubexecutor.enqueuePullFromChild(subexecutor);
1631
- this.replaceSubexecutor(modifiedParent);
1632
- break;
1633
- }
1634
- }
1635
- this._activeSubexecutor = new Emit(emitted, this._activeSubexecutor);
1636
- return undefined;
1637
- }, match$2({
1638
- onFailure: cause => {
1639
- const state = this.handleSubexecutorFailure(childExecutor, parentSubexecutor, cause);
1640
- return state === undefined ? undefined : effectOrUndefinedIgnored(state);
1641
- },
1642
- onSuccess: doneValue => {
1643
- this.finishWithDoneValue(childExecutor, parentSubexecutor, doneValue);
1644
- return undefined;
1645
- }
1646
- }));
1647
- }
1648
- finishWithDoneValue(childExecutor, parentSubexecutor, doneValue) {
1649
- const subexecutor = parentSubexecutor;
1650
- switch (subexecutor._tag) {
1651
- case OP_PULL_FROM_UPSTREAM:
1652
- {
1653
- const modifiedParent = new PullFromUpstream(subexecutor.upstreamExecutor, subexecutor.createChild, subexecutor.lastDone !== undefined ? subexecutor.combineChildResults(subexecutor.lastDone, doneValue) : doneValue, subexecutor.activeChildExecutors, subexecutor.combineChildResults, subexecutor.combineWithChildResult, subexecutor.onPull, subexecutor.onEmit);
1654
- this._closeLastSubstream = childExecutor.close(succeed$2(doneValue));
1655
- this.replaceSubexecutor(modifiedParent);
1656
- break;
1657
- }
1658
- case OP_DRAIN_CHILD_EXECUTORS:
1659
- {
1660
- const modifiedParent = new DrainChildExecutors(subexecutor.upstreamExecutor, subexecutor.lastDone !== undefined ? subexecutor.combineChildResults(subexecutor.lastDone, doneValue) : doneValue, subexecutor.activeChildExecutors, subexecutor.upstreamDone, subexecutor.combineChildResults, subexecutor.combineWithChildResult, subexecutor.onPull);
1661
- this._closeLastSubstream = childExecutor.close(succeed$2(doneValue));
1662
- this.replaceSubexecutor(modifiedParent);
1663
- break;
1664
- }
1665
- }
1666
- }
1667
- handleSubexecutorFailure(childExecutor, parentSubexecutor, cause) {
1668
- return this.finishSubexecutorWithCloseEffect(failCause$3(cause), exit => parentSubexecutor.close(exit), exit => childExecutor.close(exit));
1669
- }
1670
- pullFromUpstream(subexecutor) {
1671
- if (subexecutor.activeChildExecutors.length === 0) {
1672
- return this.performPullFromUpstream(subexecutor);
1673
- }
1674
- const activeChild = subexecutor.activeChildExecutors[0];
1675
- const parentSubexecutor = new PullFromUpstream(subexecutor.upstreamExecutor, subexecutor.createChild, subexecutor.lastDone, subexecutor.activeChildExecutors.slice(1), subexecutor.combineChildResults, subexecutor.combineWithChildResult, subexecutor.onPull, subexecutor.onEmit);
1676
- if (activeChild === undefined) {
1677
- return this.performPullFromUpstream(parentSubexecutor);
1678
- }
1679
- this.replaceSubexecutor(new PullFromChild(activeChild.childExecutor, parentSubexecutor, activeChild.onEmit));
1680
- return undefined;
1681
- }
1682
- performPullFromUpstream(subexecutor) {
1683
- return Read(subexecutor.upstreamExecutor, effect => {
1684
- const closeLastSubstream = this._closeLastSubstream === undefined ? _void : this._closeLastSubstream;
1685
- this._closeLastSubstream = undefined;
1686
- return pipe(this._executeCloseLastSubstream(closeLastSubstream), zipRight$3(effect));
1687
- }, emitted => {
1688
- if (this._closeLastSubstream !== undefined) {
1689
- const closeLastSubstream = this._closeLastSubstream;
1690
- this._closeLastSubstream = undefined;
1691
- return pipe(this._executeCloseLastSubstream(closeLastSubstream), map$5(() => {
1692
- const childExecutor = new ChannelExecutor(subexecutor.createChild(emitted), this._providedEnv, this._executeCloseLastSubstream);
1693
- childExecutor._input = this._input;
1694
- const [emitSeparator, updatedChildExecutors] = this.applyUpstreamPullStrategy(false, subexecutor.activeChildExecutors, subexecutor.onPull(Pulled(emitted)));
1695
- this._activeSubexecutor = new PullFromChild(childExecutor, new PullFromUpstream(subexecutor.upstreamExecutor, subexecutor.createChild, subexecutor.lastDone, updatedChildExecutors, subexecutor.combineChildResults, subexecutor.combineWithChildResult, subexecutor.onPull, subexecutor.onEmit), subexecutor.onEmit);
1696
- if (isSome(emitSeparator)) {
1697
- this._activeSubexecutor = new Emit(emitSeparator.value, this._activeSubexecutor);
1698
- }
1699
- return undefined;
1700
- }));
1701
- }
1702
- const childExecutor = new ChannelExecutor(subexecutor.createChild(emitted), this._providedEnv, this._executeCloseLastSubstream);
1703
- childExecutor._input = this._input;
1704
- const [emitSeparator, updatedChildExecutors] = this.applyUpstreamPullStrategy(false, subexecutor.activeChildExecutors, subexecutor.onPull(Pulled(emitted)));
1705
- this._activeSubexecutor = new PullFromChild(childExecutor, new PullFromUpstream(subexecutor.upstreamExecutor, subexecutor.createChild, subexecutor.lastDone, updatedChildExecutors, subexecutor.combineChildResults, subexecutor.combineWithChildResult, subexecutor.onPull, subexecutor.onEmit), subexecutor.onEmit);
1706
- if (isSome(emitSeparator)) {
1707
- this._activeSubexecutor = new Emit(emitSeparator.value, this._activeSubexecutor);
1708
- }
1709
- return undefined;
1710
- }, exit => {
1711
- if (subexecutor.activeChildExecutors.some(subexecutor => subexecutor !== undefined)) {
1712
- const drain = new DrainChildExecutors(subexecutor.upstreamExecutor, subexecutor.lastDone, [undefined, ...subexecutor.activeChildExecutors], subexecutor.upstreamExecutor.getDone(), subexecutor.combineChildResults, subexecutor.combineWithChildResult, subexecutor.onPull);
1713
- if (this._closeLastSubstream !== undefined) {
1714
- const closeLastSubstream = this._closeLastSubstream;
1715
- this._closeLastSubstream = undefined;
1716
- return pipe(this._executeCloseLastSubstream(closeLastSubstream), map$5(() => this.replaceSubexecutor(drain)));
1717
- }
1718
- this.replaceSubexecutor(drain);
1719
- return undefined;
1720
- }
1721
- const closeLastSubstream = this._closeLastSubstream;
1722
- const state = this.finishSubexecutorWithCloseEffect(pipe(exit, map$6(a => subexecutor.combineWithChildResult(subexecutor.lastDone, a))), () => closeLastSubstream, exit => subexecutor.upstreamExecutor.close(exit));
1723
- return state === undefined ? undefined :
1724
- // NOTE: assuming finalizers cannot fail
1725
- effectOrUndefinedIgnored(state);
1726
- });
1727
- }
1728
- drainChildExecutors(subexecutor) {
1729
- if (subexecutor.activeChildExecutors.length === 0) {
1730
- const lastClose = this._closeLastSubstream;
1731
- if (lastClose !== undefined) {
1732
- this.addFinalizer(() => succeed$3(lastClose));
1733
- }
1734
- return this.finishSubexecutorWithCloseEffect(subexecutor.upstreamDone, () => lastClose, exit => subexecutor.upstreamExecutor.close(exit));
1735
- }
1736
- const activeChild = subexecutor.activeChildExecutors[0];
1737
- const rest = subexecutor.activeChildExecutors.slice(1);
1738
- if (activeChild === undefined) {
1739
- const [emitSeparator, remainingExecutors] = this.applyUpstreamPullStrategy(true, rest, subexecutor.onPull(NoUpstream(rest.reduce((n, curr) => curr !== undefined ? n + 1 : n, 0))));
1740
- this.replaceSubexecutor(new DrainChildExecutors(subexecutor.upstreamExecutor, subexecutor.lastDone, remainingExecutors, subexecutor.upstreamDone, subexecutor.combineChildResults, subexecutor.combineWithChildResult, subexecutor.onPull));
1741
- if (isSome(emitSeparator)) {
1742
- this._emitted = emitSeparator.value;
1743
- return Emit$1();
1744
- }
1745
- return undefined;
1746
- }
1747
- const parentSubexecutor = new DrainChildExecutors(subexecutor.upstreamExecutor, subexecutor.lastDone, rest, subexecutor.upstreamDone, subexecutor.combineChildResults, subexecutor.combineWithChildResult, subexecutor.onPull);
1748
- this.replaceSubexecutor(new PullFromChild(activeChild.childExecutor, parentSubexecutor, activeChild.onEmit));
1749
- return undefined;
1750
- }
1751
- }
1752
- const ifNotNull = effect => effect !== undefined ? effect : _void;
1753
- const runFinalizers = (finalizers, exit$1) => {
1754
- return pipe(forEach(finalizers, fin => exit(fin(exit$1))), map$5(exits => pipe(all(exits), getOrElse(() => void_$2))), flatMap$3(exit => suspend$3(() => exit)));
1755
- };
1756
- /**
1757
- * @internal
1758
- */
1759
- const readUpstream = (r, onSuccess, onFailure) => {
1760
- const readStack = [r];
1761
- const read = () => {
1762
- const current = readStack.pop();
1763
- if (current === undefined || current.upstream === undefined) {
1764
- return dieMessage("Unexpected end of input for channel execution");
1765
- }
1766
- const state = current.upstream.run();
1767
- switch (state._tag) {
1768
- case OP_EMIT$1:
1769
- {
1770
- const emitEffect = current.onEmit(current.upstream.getEmit());
1771
- if (readStack.length === 0) {
1772
- if (emitEffect === undefined) {
1773
- return suspend$3(onSuccess);
1774
- }
1775
- return pipe(emitEffect, matchCauseEffect({
1776
- onFailure,
1777
- onSuccess
1778
- }));
1779
- }
1780
- if (emitEffect === undefined) {
1781
- return suspend$3(() => read());
1782
- }
1783
- return pipe(emitEffect, matchCauseEffect({
1784
- onFailure,
1785
- onSuccess: () => read()
1786
- }));
1787
- }
1788
- case OP_DONE$1:
1789
- {
1790
- const doneEffect = current.onDone(current.upstream.getDone());
1791
- if (readStack.length === 0) {
1792
- if (doneEffect === undefined) {
1793
- return suspend$3(onSuccess);
1794
- }
1795
- return pipe(doneEffect, matchCauseEffect({
1796
- onFailure,
1797
- onSuccess
1798
- }));
1799
- }
1800
- if (doneEffect === undefined) {
1801
- return suspend$3(() => read());
1802
- }
1803
- return pipe(doneEffect, matchCauseEffect({
1804
- onFailure,
1805
- onSuccess: () => read()
1806
- }));
1807
- }
1808
- case OP_FROM_EFFECT:
1809
- {
1810
- readStack.push(current);
1811
- return pipe(current.onEffect(state.effect), catchAllCause(cause => suspend$3(() => {
1812
- const doneEffect = current.onDone(failCause$3(cause));
1813
- return doneEffect === undefined ? _void : doneEffect;
1814
- })), matchCauseEffect({
1815
- onFailure,
1816
- onSuccess: () => read()
1817
- }));
1818
- }
1819
- case OP_READ:
1820
- {
1821
- readStack.push(current);
1822
- readStack.push(state);
1823
- return suspend$3(() => read());
1824
- }
1825
- }
1826
- };
1827
- return read();
1828
- };
1829
- /** @internal */
1830
- const runIn = /*#__PURE__*/dual(2, (self, scope) => {
1831
- const run = (channelDeferred, scopeDeferred, scope) => acquireUseRelease(sync$2(() => new ChannelExecutor(self, void 0, identity)), exec => suspend$3(() => runScopedInterpret(exec.run(), exec).pipe(intoDeferred(channelDeferred), zipRight$3(_await$2(channelDeferred)), zipLeft(_await$2(scopeDeferred)))), (exec, exit) => {
1832
- const finalize = exec.close(exit);
1833
- if (finalize === undefined) {
1834
- return _void;
1835
- }
1836
- return tapErrorCause(finalize, cause => addFinalizer(scope, failCause$4(cause)));
1837
- });
1838
- return uninterruptibleMask(restore => all$1([fork(scope, sequential), make$6(), make$6()]).pipe(flatMap$3(([child, channelDeferred, scopeDeferred]) => restore(run(channelDeferred, scopeDeferred, child)).pipe(forkIn(scope), flatMap$3(fiber => scope.addFinalizer(exit => {
1839
- const interruptors$1 = isFailure(exit) ? interruptors(exit.cause) : undefined;
1840
- return isDone(channelDeferred).pipe(flatMap$3(isDone => isDone ? succeed$4(scopeDeferred, void 0).pipe(zipRight$3(_await(fiber)), zipRight$3(inheritAll(fiber))) : succeed$4(scopeDeferred, void 0).pipe(zipRight$3(interruptors$1 && size$2(interruptors$1) > 0 ? interruptAs(fiber, combineAll(interruptors$1)) : interrupt(fiber)), zipRight$3(inheritAll(fiber)))));
1841
- }).pipe(zipRight$3(restore(_await$2(channelDeferred)))))))));
1842
- });
1843
- /** @internal */
1844
- const runScopedInterpret = (channelState, exec) => {
1845
- const op = channelState;
1846
- switch (op._tag) {
1847
- case OP_FROM_EFFECT:
1848
- {
1849
- return pipe(op.effect, flatMap$3(() => runScopedInterpret(exec.run(), exec)));
1850
- }
1851
- case OP_EMIT$1:
1852
- {
1853
- // Can't really happen because Out <:< Nothing. So just skip ahead.
1854
- return runScopedInterpret(exec.run(), exec);
1855
- }
1856
- case OP_DONE$1:
1857
- {
1858
- return suspend$3(() => exec.getDone());
1859
- }
1860
- case OP_READ:
1861
- {
1862
- return readUpstream(op, () => runScopedInterpret(exec.run(), exec), failCause$4);
1863
- }
1864
- }
1865
- };
1866
-
1867
- /** @internal */
1868
- const OP_DONE = "Done";
1869
- /** @internal */
1870
- const OP_AWAIT = "Await";
1871
-
1872
- /** @internal */
1873
- const MergeDecisionSymbolKey = "effect/ChannelMergeDecision";
1874
- /** @internal */
1875
- const MergeDecisionTypeId = /*#__PURE__*/Symbol.for(MergeDecisionSymbolKey);
1876
- /** @internal */
1877
- const proto$2 = {
1878
- [MergeDecisionTypeId]: {
1879
- _R: _ => _,
1880
- _E0: _ => _,
1881
- _Z0: _ => _,
1882
- _E: _ => _,
1883
- _Z: _ => _
1884
- }
1885
- };
1886
- /** @internal */
1887
- const Await = f => {
1888
- const op = Object.create(proto$2);
1889
- op._tag = OP_AWAIT;
1890
- op.f = f;
1891
- return op;
1892
- };
1893
-
1894
- /** @internal */
1895
- const OP_BOTH_RUNNING = "BothRunning";
1896
- /** @internal */
1897
- const OP_LEFT_DONE = "LeftDone";
1898
- /** @internal */
1899
- const OP_RIGHT_DONE = "RightDone";
1900
-
1901
- /** @internal */
1902
- const MergeStateSymbolKey = "effect/ChannelMergeState";
1903
- /** @internal */
1904
- const MergeStateTypeId = /*#__PURE__*/Symbol.for(MergeStateSymbolKey);
1905
- /** @internal */
1906
- const proto$1 = {
1907
- [MergeStateTypeId]: MergeStateTypeId
1908
- };
1909
- /** @internal */
1910
- const BothRunning = (left, right) => {
1911
- const op = Object.create(proto$1);
1912
- op._tag = OP_BOTH_RUNNING;
1913
- op.left = left;
1914
- op.right = right;
1915
- return op;
1916
- };
1917
- /** @internal */
1918
- const LeftDone = f => {
1919
- const op = Object.create(proto$1);
1920
- op._tag = OP_LEFT_DONE;
1921
- op.f = f;
1922
- return op;
1923
- };
1924
- /** @internal */
1925
- const RightDone = f => {
1926
- const op = Object.create(proto$1);
1927
- op._tag = OP_RIGHT_DONE;
1928
- op.f = f;
1929
- return op;
1930
- };
1931
-
1932
- /** @internal */
1933
- const OP_BACK_PRESSURE = "BackPressure";
1934
- /** @internal */
1935
- const OP_BUFFER_SLIDING = "BufferSliding";
1936
-
1937
- /** @internal */
1938
- const MergeStrategySymbolKey = "effect/ChannelMergeStrategy";
1939
- /** @internal */
1940
- const MergeStrategyTypeId = /*#__PURE__*/Symbol.for(MergeStrategySymbolKey);
1941
- /** @internal */
1942
- const proto = {
1943
- [MergeStrategyTypeId]: MergeStrategyTypeId
1944
- };
1945
- /** @internal */
1946
- const BackPressure = _ => {
1947
- const op = Object.create(proto);
1948
- op._tag = OP_BACK_PRESSURE;
1949
- return op;
1950
- };
1951
- /** @internal */
1952
- const BufferSliding = _ => {
1953
- const op = Object.create(proto);
1954
- op._tag = OP_BUFFER_SLIDING;
1955
- return op;
1956
- };
1957
- /** @internal */
1958
- const match = /*#__PURE__*/dual(2, (self, {
1959
- onBackPressure,
1960
- onBufferSliding
1961
- }) => {
1962
- switch (self._tag) {
1963
- case OP_BACK_PRESSURE:
1964
- {
1965
- return onBackPressure();
1966
- }
1967
- case OP_BUFFER_SLIDING:
1968
- {
1969
- return onBufferSliding();
1970
- }
1971
- }
1972
- });
1973
-
1974
- /** @internal */
1975
- const OP_STATE_EMPTY = "Empty";
1976
- /** @internal */
1977
- const OP_STATE_EMIT = "Emit";
1978
- /** @internal */
1979
- const OP_STATE_ERROR = "Error";
1980
- /** @internal */
1981
- const OP_STATE_DONE = "Done";
1982
- /** @internal */
1983
- const stateEmpty = notifyProducer => ({
1984
- _tag: OP_STATE_EMPTY,
1985
- notifyProducer
1986
- });
1987
- /** @internal */
1988
- const stateEmit = notifyConsumers => ({
1989
- _tag: OP_STATE_EMIT,
1990
- notifyConsumers
1991
- });
1992
- /** @internal */
1993
- const stateError = cause => ({
1994
- _tag: OP_STATE_ERROR,
1995
- cause
1996
- });
1997
- /** @internal */
1998
- const stateDone = done => ({
1999
- _tag: OP_STATE_DONE,
2000
- done
2001
- });
2002
- /** @internal */
2003
- class SingleProducerAsyncInputImpl {
2004
- ref;
2005
- constructor(ref) {
2006
- this.ref = ref;
2007
- }
2008
- awaitRead() {
2009
- return flatten$2(modify(this.ref, state => state._tag === OP_STATE_EMPTY ? [_await$2(state.notifyProducer), state] : [_void, state]));
2010
- }
2011
- get close() {
2012
- return fiberIdWith(fiberId => this.error(interrupt$1(fiberId)));
2013
- }
2014
- done(value) {
2015
- return flatten$2(modify(this.ref, state => {
2016
- switch (state._tag) {
2017
- case OP_STATE_EMPTY:
2018
- {
2019
- return [_await$2(state.notifyProducer), state];
2020
- }
2021
- case OP_STATE_EMIT:
2022
- {
2023
- return [forEach(state.notifyConsumers, deferred => succeed$4(deferred, left(value)), {
2024
- discard: true
2025
- }), stateDone(value)];
2026
- }
2027
- case OP_STATE_ERROR:
2028
- {
2029
- return [interrupt$4, state];
2030
- }
2031
- case OP_STATE_DONE:
2032
- {
2033
- return [interrupt$4, state];
2034
- }
2035
- }
2036
- }));
2037
- }
2038
- emit(element) {
2039
- return flatMap$3(make$6(), deferred => flatten$2(modify(this.ref, state => {
2040
- switch (state._tag) {
2041
- case OP_STATE_EMPTY:
2042
- {
2043
- return [_await$2(state.notifyProducer), state];
2044
- }
2045
- case OP_STATE_EMIT:
2046
- {
2047
- const notifyConsumer = state.notifyConsumers[0];
2048
- const notifyConsumers = state.notifyConsumers.slice(1);
2049
- if (notifyConsumer !== undefined) {
2050
- return [succeed$4(notifyConsumer, right(element)), notifyConsumers.length === 0 ? stateEmpty(deferred) : stateEmit(notifyConsumers)];
2051
- }
2052
- throw new Error("Bug: Channel.SingleProducerAsyncInput.emit - Queue was empty! please report an issue at https://github.com/Effect-TS/effect/issues");
2053
- }
2054
- case OP_STATE_ERROR:
2055
- {
2056
- return [interrupt$4, state];
2057
- }
2058
- case OP_STATE_DONE:
2059
- {
2060
- return [interrupt$4, state];
2061
- }
2062
- }
2063
- })));
2064
- }
2065
- error(cause) {
2066
- return flatten$2(modify(this.ref, state => {
2067
- switch (state._tag) {
2068
- case OP_STATE_EMPTY:
2069
- {
2070
- return [_await$2(state.notifyProducer), state];
2071
- }
2072
- case OP_STATE_EMIT:
2073
- {
2074
- return [forEach(state.notifyConsumers, deferred => failCause$5(deferred, cause), {
2075
- discard: true
2076
- }), stateError(cause)];
2077
- }
2078
- case OP_STATE_ERROR:
2079
- {
2080
- return [interrupt$4, state];
2081
- }
2082
- case OP_STATE_DONE:
2083
- {
2084
- return [interrupt$4, state];
2085
- }
2086
- }
2087
- }));
2088
- }
2089
- get take() {
2090
- return this.takeWith(cause => failCause$3(map$2(cause, left)), elem => succeed$2(elem), done => fail$3(right(done)));
2091
- }
2092
- takeWith(onError, onElement, onDone) {
2093
- return flatMap$3(make$6(), deferred => flatten$2(modify(this.ref, state => {
2094
- switch (state._tag) {
2095
- case OP_STATE_EMPTY:
2096
- {
2097
- return [zipRight$3(succeed$4(state.notifyProducer, void 0), matchCause(_await$2(deferred), {
2098
- onFailure: onError,
2099
- onSuccess: match$1({
2100
- onLeft: onDone,
2101
- onRight: onElement
2102
- })
2103
- })), stateEmit([deferred])];
2104
- }
2105
- case OP_STATE_EMIT:
2106
- {
2107
- return [matchCause(_await$2(deferred), {
2108
- onFailure: onError,
2109
- onSuccess: match$1({
2110
- onLeft: onDone,
2111
- onRight: onElement
2112
- })
2113
- }), stateEmit([...state.notifyConsumers, deferred])];
2114
- }
2115
- case OP_STATE_ERROR:
2116
- {
2117
- return [succeed$3(onError(state.cause)), state];
2118
- }
2119
- case OP_STATE_DONE:
2120
- {
2121
- return [succeed$3(onDone(state.done)), state];
2122
- }
2123
- }
2124
- })));
2125
- }
2126
- }
2127
- /** @internal */
2128
- const make$1 = () => pipe(make$6(), flatMap$3(deferred => make$3(stateEmpty(deferred))), map$5(ref => new SingleProducerAsyncInputImpl(ref)));
2129
-
2130
- /** @internal */
2131
- const concatMap = /*#__PURE__*/dual(2, (self, f) => concatMapWith(self, f, () => void 0, () => void 0));
2132
- /** @internal */
2133
- const drain$1 = self => {
2134
- const drainer = readWithCause({
2135
- onInput: () => drainer,
2136
- onFailure: failCause$2,
2137
- onDone: succeed
2138
- });
2139
- return pipeTo(self, drainer);
2140
- };
2141
- /** @internal */
2142
- const ensuring$1 = /*#__PURE__*/dual(2, (self, finalizer) => ensuringWith(self, () => finalizer));
2143
- /** @internal */
2144
- const flatten$1 = self => flatMap$1(self, identity);
2145
- /** @internal */
2146
- const fromInput = input => unwrap(input.takeWith(failCause$2, elem => flatMap$1(write(elem), () => fromInput(input)), succeed));
2147
- /** @internal */
2148
- const identityChannel = () => readWith({
2149
- onInput: input => flatMap$1(write(input), () => identityChannel()),
2150
- onFailure: fail,
2151
- onDone: succeedNow
2152
- });
2153
- /** @internal */
2154
- const map$1 = /*#__PURE__*/dual(2, (self, f) => flatMap$1(self, a => sync(() => f(a))));
2155
- /** @internal */
2156
- const mapOut = /*#__PURE__*/dual(2, (self, f) => {
2157
- const reader = readWith({
2158
- onInput: outElem => flatMap$1(write(f(outElem)), () => reader),
2159
- onFailure: fail,
2160
- onDone: succeedNow
2161
- });
2162
- return pipeTo(self, reader);
2163
- });
2164
- /** @internal */
2165
- const mapOutEffectPar = /*#__PURE__*/dual(3, (self, f, n) => unwrapScopedWith$1(scope => gen(function* () {
2166
- const input = yield* make$1();
2167
- const queueReader = fromInput(input);
2168
- const queue = yield* bounded(n);
2169
- yield* addFinalizer(scope, shutdown(queue));
2170
- const errorSignal = yield* make$6();
2171
- const withPermits = n === Number.POSITIVE_INFINITY ? _ => identity : (yield* makeSemaphore(n)).withPermits;
2172
- const pull = yield* queueReader.pipe(pipeTo(self), toPullIn(scope));
2173
- yield* pull.pipe(matchCauseEffect({
2174
- onFailure: cause => offer(queue, failCause$4(cause)),
2175
- onSuccess: match$1({
2176
- onLeft: outDone => zipRight$3(interruptible(withPermits(n)(_void)), asVoid$1(offer(queue, succeed$3(left(outDone))))),
2177
- onRight: outElem => gen(function* () {
2178
- const deferred = yield* make$6();
2179
- const latch = yield* make$6();
2180
- yield* offer(queue, map$5(_await$2(deferred), right));
2181
- yield* succeed$4(latch, void 0).pipe(zipRight$3(uninterruptibleMask(restore => exit(restore(_await$2(errorSignal))).pipe(raceFirst(exit(restore(f(outElem)))), flatMap$3(identity))).pipe(tapErrorCause(cause => failCause$5(errorSignal, cause)), intoDeferred(deferred))), withPermits(1), forkIn(scope));
2182
- yield* _await$2(latch);
2183
- })
2184
- })
2185
- }), forever, interruptible, forkIn(scope));
2186
- const consumer = unwrap(matchCause(flatten$2(take(queue)), {
2187
- onFailure: failCause$2,
2188
- onSuccess: match$1({
2189
- onLeft: succeedNow,
2190
- onRight: outElem => flatMap$1(write(outElem), () => consumer)
2191
- })
2192
- }));
2193
- return embedInput(consumer, input);
2194
- })));
2195
- /** @internal */
2196
- const mergeAll = options => {
2197
- return channels => mergeAllWith(options)(channels, constVoid);
2198
- };
2199
- /** @internal */
2200
- const mergeAllWith = ({
2201
- bufferSize = 16,
2202
- concurrency,
2203
- mergeStrategy = BackPressure()
2204
- }) => (channels, f) => unwrapScopedWith$1(scope => gen(function* () {
2205
- const concurrencyN = concurrency === "unbounded" ? Number.MAX_SAFE_INTEGER : concurrency;
2206
- const input = yield* make$1();
2207
- const queueReader = fromInput(input);
2208
- const queue = yield* bounded(bufferSize);
2209
- yield* addFinalizer(scope, shutdown(queue));
2210
- const cancelers = yield* unbounded();
2211
- yield* addFinalizer(scope, shutdown(cancelers));
2212
- const lastDone = yield* make$3(none());
2213
- const errorSignal = yield* make$6();
2214
- const withPermits = (yield* makeSemaphore(concurrencyN)).withPermits;
2215
- const pull = yield* toPullIn(pipeTo(queueReader, channels), scope);
2216
- function evaluatePull(pull) {
2217
- return pull.pipe(flatMap$3(match$1({
2218
- onLeft: done => succeed$3(some(done)),
2219
- onRight: outElem => as(offer(queue, succeed$3(right(outElem))), none())
2220
- })), repeat({
2221
- until: _ => isSome(_)
2222
- }), flatMap$3(outDone => update(lastDone, match$3({
2223
- onNone: () => some(outDone.value),
2224
- onSome: lastDone => some(f(lastDone, outDone.value))
2225
- }))), catchAllCause(cause => isInterrupted(cause) ? failCause$4(cause) : offer(queue, failCause$4(cause)).pipe(zipRight$3(succeed$4(errorSignal, void 0)), asVoid$1)));
2226
- }
2227
- yield* pull.pipe(matchCauseEffect({
2228
- onFailure: cause => offer(queue, failCause$4(cause)).pipe(zipRight$3(succeed$3(false))),
2229
- onSuccess: match$1({
2230
- onLeft: outDone => raceWith(interruptible(_await$2(errorSignal)), interruptible(withPermits(concurrencyN)(_void)), {
2231
- onSelfDone: (_, permitAcquisition) => as(interrupt(permitAcquisition), false),
2232
- onOtherDone: (_, failureAwait) => zipRight$3(interrupt(failureAwait), get(lastDone).pipe(flatMap$3(match$3({
2233
- onNone: () => offer(queue, succeed$3(left(outDone))),
2234
- onSome: lastDone => offer(queue, succeed$3(left(f(lastDone, outDone))))
2235
- })), as(false)))
2236
- }),
2237
- onRight: channel => match(mergeStrategy, {
2238
- onBackPressure: () => gen(function* () {
2239
- const latch = yield* make$6();
2240
- const raceEffects = scopedWith$2(scope => toPullIn(pipeTo(queueReader, channel), scope).pipe(flatMap$3(pull => race(exit(evaluatePull(pull)), exit(interruptible(_await$2(errorSignal))))), flatMap$3(identity)));
2241
- yield* succeed$4(latch, void 0).pipe(zipRight$3(raceEffects), withPermits(1), forkIn(scope));
2242
- yield* _await$2(latch);
2243
- const errored = yield* isDone(errorSignal);
2244
- return !errored;
2245
- }),
2246
- onBufferSliding: () => gen(function* () {
2247
- const canceler = yield* make$6();
2248
- const latch = yield* make$6();
2249
- const size$1 = yield* size(cancelers);
2250
- yield* take(cancelers).pipe(flatMap$3(canceler => succeed$4(canceler, void 0)), when(() => size$1 >= concurrencyN));
2251
- yield* offer(cancelers, canceler);
2252
- const raceEffects = scopedWith$2(scope => toPullIn(pipeTo(queueReader, channel), scope).pipe(flatMap$3(pull => exit(evaluatePull(pull)).pipe(race(exit(interruptible(_await$2(errorSignal)))), race(exit(interruptible(_await$2(canceler)))))), flatMap$3(identity)));
2253
- yield* succeed$4(latch, void 0).pipe(zipRight$3(raceEffects), withPermits(1), forkIn(scope));
2254
- yield* _await$2(latch);
2255
- const errored = yield* isDone(errorSignal);
2256
- return !errored;
2257
- })
2258
- })
2259
- })
2260
- }), repeat({
2261
- while: _ => _
2262
- }), forkIn(scope));
2263
- const consumer = pipe(take(queue), flatten$2, matchCause({
2264
- onFailure: failCause$2,
2265
- onSuccess: match$1({
2266
- onLeft: succeedNow,
2267
- onRight: outElem => flatMap$1(write(outElem), () => consumer)
2268
- })
2269
- }), unwrap);
2270
- return embedInput(consumer, input);
2271
- }));
2272
- /** @internal */
2273
- const mergeMap = /*#__PURE__*/dual(3, (self, f, options) => mergeAll(options)(mapOut(self, f)));
2274
- /** @internal */
2275
- const mergeWith = /*#__PURE__*/dual(2, (self, options) => {
2276
- function merge(scope) {
2277
- return gen(function* () {
2278
- const input = yield* make$1();
2279
- const queueReader = fromInput(input);
2280
- const pullL = yield* toPullIn(pipeTo(queueReader, self), scope);
2281
- const pullR = yield* toPullIn(pipeTo(queueReader, options.other), scope);
2282
- function handleSide(exit, fiber, pull) {
2283
- return (done, both, single) => {
2284
- function onDecision(decision) {
2285
- const op = decision;
2286
- if (op._tag === OP_DONE) {
2287
- return succeed$3(fromEffect$3(zipRight$3(interrupt(fiber), op.effect)));
2288
- }
2289
- return map$5(_await(fiber), match$2({
2290
- onFailure: cause => fromEffect$3(op.f(failCause$3(cause))),
2291
- onSuccess: match$1({
2292
- onLeft: done => fromEffect$3(op.f(succeed$2(done))),
2293
- onRight: elem => zipRight(write(elem), go(single(op.f)))
2294
- })
2295
- }));
2296
- }
2297
- return match$2(exit, {
2298
- onFailure: cause => onDecision(done(failCause$3(cause))),
2299
- onSuccess: match$1({
2300
- onLeft: z => onDecision(done(succeed$2(z))),
2301
- onRight: elem => succeed$3(flatMap$1(write(elem), () => flatMap$1(fromEffect$3(forkIn(interruptible(pull), scope)), leftFiber => go(both(leftFiber, fiber)))))
2302
- })
2303
- });
2304
- };
2305
- }
2306
- function go(state) {
2307
- switch (state._tag) {
2308
- case OP_BOTH_RUNNING:
2309
- {
2310
- const leftJoin = interruptible(join(state.left));
2311
- const rightJoin = interruptible(join(state.right));
2312
- return unwrap(raceWith(leftJoin, rightJoin, {
2313
- onSelfDone: (leftExit, rf) => zipRight$3(interrupt(rf), handleSide(leftExit, state.right, pullL)(options.onSelfDone, BothRunning, f => LeftDone(f))),
2314
- onOtherDone: (rightExit, lf) => zipRight$3(interrupt(lf), handleSide(rightExit, state.left, pullR)(options.onOtherDone, (left, right) => BothRunning(right, left), f => RightDone(f)))
2315
- }));
2316
- }
2317
- case OP_LEFT_DONE:
2318
- {
2319
- return unwrap(map$5(exit(pullR), match$2({
2320
- onFailure: cause => fromEffect$3(state.f(failCause$3(cause))),
2321
- onSuccess: match$1({
2322
- onLeft: done => fromEffect$3(state.f(succeed$2(done))),
2323
- onRight: elem => flatMap$1(write(elem), () => go(LeftDone(state.f)))
2324
- })
2325
- })));
2326
- }
2327
- case OP_RIGHT_DONE:
2328
- {
2329
- return unwrap(map$5(exit(pullL), match$2({
2330
- onFailure: cause => fromEffect$3(state.f(failCause$3(cause))),
2331
- onSuccess: match$1({
2332
- onLeft: done => fromEffect$3(state.f(succeed$2(done))),
2333
- onRight: elem => flatMap$1(write(elem), () => go(RightDone(state.f)))
2334
- })
2335
- })));
2336
- }
2337
- }
2338
- }
2339
- return fromEffect$3(withFiberRuntime$1(parent => {
2340
- const inherit = withFiberRuntime$1(state => {
2341
- state.transferChildren(parent.scope());
2342
- return _void;
2343
- });
2344
- const leftFiber = interruptible(pullL).pipe(ensuring$2(inherit), forkIn(scope));
2345
- const rightFiber = interruptible(pullR).pipe(ensuring$2(inherit), forkIn(scope));
2346
- return zipWith(leftFiber, rightFiber, (left, right) => BothRunning(left, right));
2347
- })).pipe(flatMap$1(go), embedInput(input));
2348
- });
2349
- }
2350
- return unwrapScopedWith$1(merge);
2351
- });
2352
- /** @internal */
2353
- const pipeToOrFail = /*#__PURE__*/dual(2, (self, that) => suspend$1(() => {
2354
- let channelException = undefined;
2355
- const reader = readWith({
2356
- onInput: outElem => flatMap$1(write(outElem), () => reader),
2357
- onFailure: outErr => {
2358
- channelException = ChannelException(outErr);
2359
- return failCause$2(die(channelException));
2360
- },
2361
- onDone: succeedNow
2362
- });
2363
- const writer = readWithCause({
2364
- onInput: outElem => pipe(write(outElem), flatMap$1(() => writer)),
2365
- onFailure: cause => isDieType(cause) && isChannelException(cause.defect) && equals(cause.defect, channelException) ? fail(cause.defect.error) : failCause$2(cause),
2366
- onDone: succeedNow
2367
- });
2368
- return pipeTo(pipeTo(pipeTo(self, reader), that), writer);
2369
- }));
2370
- /** @internal */
2371
- const run$1 = self => scopedWith$2(scope => runIn(self, scope));
2372
- /** @internal */
2373
- const runDrain$2 = self => run$1(drain$1(self));
2374
- /** @internal */
2375
- const scoped = effect => unwrap(uninterruptibleMask(restore => map$5(make$7(), scope => acquireReleaseOut(tapErrorCause(restore(extend(effect, scope)), cause => close(scope, failCause$3(cause))), (_, exit) => close(scope, exit)))));
2376
- /** @internal */
2377
- const scopedWith$1 = f => unwrapScoped(map$5(scope, scope => flatMap$1(fromEffect$3(f(scope)), write)));
2378
- /** @internal */
2379
- const toPullIn = /*#__PURE__*/dual(2, (self, scope) => zip$1(sync$2(() => new ChannelExecutor(self, void 0, identity)), runtime()).pipe(tap(([executor, runtime]) => addFinalizerExit(scope, exit => {
2380
- const finalizer = executor.close(exit);
2381
- return finalizer !== undefined ? provide(finalizer, runtime) : _void;
2382
- })), uninterruptible$1, map$5(([executor]) => suspend$3(() => interpretToPull(executor.run(), executor)))));
2383
- /** @internal */
2384
- const interpretToPull = (channelState, exec) => {
2385
- const state = channelState;
2386
- switch (state._tag) {
2387
- case OP_DONE$1:
2388
- {
2389
- return match$2(exec.getDone(), {
2390
- onFailure: failCause$4,
2391
- onSuccess: done => succeed$3(left(done))
2392
- });
2393
- }
2394
- case OP_EMIT$1:
2395
- {
2396
- return succeed$3(right(exec.getEmit()));
2397
- }
2398
- case OP_FROM_EFFECT:
2399
- {
2400
- return pipe(state.effect, flatMap$3(() => interpretToPull(exec.run(), exec)));
2401
- }
2402
- case OP_READ:
2403
- {
2404
- return readUpstream(state, () => interpretToPull(exec.run(), exec), cause => failCause$4(cause));
2405
- }
2406
- }
2407
- };
2408
- /** @internal */
2409
- const unwrap = channel => flatten$1(fromEffect$3(channel));
2410
- /** @internal */
2411
- const unwrapScoped = self => concatAllWith(scoped(self), (d, _) => d, (d, _) => d);
2412
- /** @internal */
2413
- const unwrapScopedWith$1 = f => concatAllWith(scopedWith$1(f), (d, _) => d, (d, _) => d);
2414
- /** @internal */
2415
- const writeChunk = outs => writeChunkWriter(0, outs.length, outs);
2416
- /** @internal */
2417
- const writeChunkWriter = (idx, len, chunk) => {
2418
- return idx === len ? void_ : pipe(write(pipe(chunk, unsafeGet(idx))), flatMap$1(() => writeChunkWriter(idx + 1, len, chunk)));
2419
- };
2420
- /** @internal */
2421
- const zip = /*#__PURE__*/dual(args => isChannel(args[1]), (self, that, options) => options?.concurrent ? mergeWith(self, {
2422
- other: that,
2423
- onSelfDone: exit1 => Await(exit2 => suspend$3(() => zip$2(exit1, exit2))),
2424
- onOtherDone: exit2 => Await(exit1 => suspend$3(() => zip$2(exit1, exit2)))
2425
- }) : flatMap$1(self, a => map$1(that, b => [a, b])));
2426
- /** @internal */
2427
- const zipRight = /*#__PURE__*/dual(args => isChannel(args[1]), (self, that, options) => options?.concurrent ? map$1(zip(self, that, {
2428
- concurrent: true
2429
- }), tuple => tuple[1]) : flatMap$1(self, () => that));
2430
- /** @internal */
2431
- const ChannelExceptionTypeId = /*#__PURE__*/Symbol.for("effect/Channel/ChannelException");
2432
- /** @internal */
2433
- const ChannelException = error => ({
2434
- _tag: "ChannelException",
2435
- [ChannelExceptionTypeId]: ChannelExceptionTypeId,
2436
- error
2437
- });
2438
- /** @internal */
2439
- const isChannelException = u => hasProperty(u, ChannelExceptionTypeId);
2440
-
2441
- /** @internal */
2442
- const SinkTypeId = /*#__PURE__*/Symbol.for("effect/Sink");
2443
- const sinkVariance = {
2444
- /* c8 ignore next */
2445
- _A: _ => _,
2446
- /* c8 ignore next */
2447
- _In: _ => _,
2448
- /* c8 ignore next */
2449
- _L: _ => _,
2450
- /* c8 ignore next */
2451
- _E: _ => _,
2452
- /* c8 ignore next */
2453
- _R: _ => _
2454
- };
2455
- /** @internal */
2456
- class SinkImpl {
2457
- channel;
2458
- [SinkTypeId] = sinkVariance;
2459
- constructor(channel) {
2460
- this.channel = channel;
2461
- }
2462
- pipe() {
2463
- return pipeArguments(this, arguments);
2464
- }
2465
- }
2466
- /** @internal */
2467
- const drain = /*#__PURE__*/new SinkImpl(/*#__PURE__*/drain$1(/*#__PURE__*/identityChannel()));
2468
- /** @internal */
2469
- const fromEffect$1 = effect => new SinkImpl(fromEffect$3(effect));
2470
- /** @internal */
2471
- const toChannel$1 = self => isEffect(self) ? toChannel$1(fromEffect$1(self)) : self.channel;
2472
-
2473
- /** @internal */
2474
- const TakeSymbolKey = "effect/Take";
2475
- /** @internal */
2476
- const TakeTypeId = /*#__PURE__*/Symbol.for(TakeSymbolKey);
2477
- const takeVariance = {
2478
- /* c8 ignore next */
2479
- _A: _ => _,
2480
- /* c8 ignore next */
2481
- _E: _ => _
2482
- };
2483
- /** @internal */
2484
- class TakeImpl {
2485
- exit;
2486
- [TakeTypeId] = takeVariance;
2487
- constructor(exit) {
2488
- this.exit = exit;
2489
- }
2490
- pipe() {
2491
- return pipeArguments(this, arguments);
2492
- }
2493
- }
2494
- /** @internal */
2495
- const chunk = chunk => new TakeImpl(succeed$2(chunk));
2496
- /** @internal */
2497
- const end$1 = /*#__PURE__*/new TakeImpl(/*#__PURE__*/fail$3(/*#__PURE__*/none()));
2498
- /** @internal */
2499
- const failCause$1 = cause => new TakeImpl(failCause$3(pipe(cause, map$2(some))));
2500
- /** @internal */
2501
- const of = value => new TakeImpl(succeed$2(of$1(value)));
2502
-
2503
- /** @internal */
2504
- const end = () => fail$4(none());
2505
- /** @internal */
2506
- const failCause = cause => mapError(failCause$4(cause), some);
2507
-
2508
- /** @internal */
2509
- const StreamSymbolKey = "effect/Stream";
2510
- /** @internal */
2511
- const StreamTypeId = /*#__PURE__*/Symbol.for(StreamSymbolKey);
2512
- /** @internal */
2513
- const streamVariance = {
2514
- _R: _ => _,
2515
- _E: _ => _,
2516
- _A: _ => _
2517
- };
2518
- /** @internal */
2519
- class StreamImpl {
2520
- channel;
2521
- [StreamTypeId] = streamVariance;
2522
- constructor(channel) {
2523
- this.channel = channel;
2524
- }
2525
- pipe() {
2526
- return pipeArguments(this, arguments);
2527
- }
2528
- }
2529
- /** @internal */
2530
- const isStream = u => hasProperty(u, StreamTypeId) || isEffect(u);
2531
- /** @internal */
2532
- const DefaultChunkSize = 4096;
2533
- /** @internal */
2534
- const ensuring = /*#__PURE__*/dual(2, (self, finalizer) => new StreamImpl(pipe(toChannel(self), ensuring$1(finalizer))));
2535
- /** @internal */
2536
- const flatMap = /*#__PURE__*/dual(args => isStream(args[0]), (self, f, options) => {
2537
- const bufferSize = options?.bufferSize ?? 16;
2538
- if (options?.switch) {
2539
- return matchConcurrency(options?.concurrency, () => flatMapParSwitchBuffer(self, 1, bufferSize, f), n => flatMapParSwitchBuffer(self, n, bufferSize, f));
2540
- }
2541
- return matchConcurrency(options?.concurrency, () => new StreamImpl(concatMap(toChannel(self), as => pipe(as, map$7(a => toChannel(f(a))), reduce(void_, (left, right) => pipe(left, zipRight(right)))))), _ => new StreamImpl(pipe(toChannel(self), concatMap(writeChunk), mergeMap(out => toChannel(f(out)), options))));
2542
- });
2543
- /** @internal */
2544
- const matchConcurrency = (concurrency, sequential, bounded) => {
2545
- switch (concurrency) {
2546
- case undefined:
2547
- return sequential();
2548
- case "unbounded":
2549
- return bounded(Number.MAX_SAFE_INTEGER);
2550
- default:
2551
- return concurrency > 1 ? bounded(concurrency) : sequential();
2552
- }
2553
- };
2554
- const flatMapParSwitchBuffer = /*#__PURE__*/dual(4, (self, n, bufferSize, f) => new StreamImpl(pipe(toChannel(self), concatMap(writeChunk), mergeMap(out => toChannel(f(out)), {
2555
- concurrency: n,
2556
- mergeStrategy: BufferSliding(),
2557
- bufferSize
2558
- }))));
2559
- /** @internal */
2560
- const flatten = /*#__PURE__*/dual(args => isStream(args[0]), (self, options) => flatMap(self, identity, options));
2561
- /** @internal */
2562
- const flattenChunks = self => {
2563
- const flatten = readWithCause({
2564
- onInput: chunks => flatMap$1(writeChunk(chunks), () => flatten),
2565
- onFailure: failCause$2,
2566
- onDone: () => void_
2567
- });
2568
- return new StreamImpl(pipe(toChannel(self), pipeTo(flatten)));
2569
- };
2570
- /** @internal */
2571
- const flattenExitOption = self => {
2572
- const processChunk = (chunk, cont) => {
2573
- const [toEmit, rest] = pipe(chunk, splitWhere(exit => !isSuccess(exit)));
2574
- const next = pipe(head(rest), match$3({
2575
- onNone: () => cont,
2576
- onSome: match$2({
2577
- onFailure: cause => match$3(flipCauseOption(cause), {
2578
- onNone: () => void_,
2579
- onSome: failCause$2
2580
- }),
2581
- onSuccess: () => void_
2582
- })
2583
- }));
2584
- return pipe(write(pipe(toEmit, filterMap(exit => isSuccess(exit) ? some(exit.value) : none()))), flatMap$1(() => next));
2585
- };
2586
- const process = readWithCause({
2587
- onInput: chunk => processChunk(chunk, process),
2588
- onFailure: cause => failCause$2(cause),
2589
- onDone: () => void_
2590
- });
2591
- return new StreamImpl(pipe(toChannel(self), pipeTo(process)));
2592
- };
2593
- /** @internal */
2594
- const flattenTake = self => flattenChunks(flattenExitOption(pipe(self, map(take => take.exit))));
2595
- /** @internal */
2596
- const toChannel = stream => {
2597
- if ("channel" in stream) {
2598
- return stream.channel;
2599
- } else if (isEffect(stream)) {
2600
- return toChannel(fromEffect(stream));
2601
- } else {
2602
- throw new TypeError(`Expected a Stream.`);
2603
- }
2604
- };
2605
- /** @internal */
2606
- const fromEffect = effect => pipe(effect, mapError(some), fromEffectOption);
2607
- /** @internal */
2608
- const fromEffectOption = effect => new StreamImpl(unwrap(match$4(effect, {
2609
- onFailure: match$3({
2610
- onNone: () => void_,
2611
- onSome: fail
2612
- }),
2613
- onSuccess: a => write(of$1(a))
2614
- })));
2615
- /** @internal */
2616
- const fromQueue$1 = (queue, options) => pipe(takeBetween(queue, 1, options?.maxChunkSize ?? DefaultChunkSize), catchAllCause(cause => pipe(isShutdown(queue), flatMap$3(isShutdown => isShutdown && isInterrupted(cause) ? end() : failCause(cause)))), repeatEffectChunkOption, options?.shutdown ? ensuring(shutdown(queue)) : identity);
2617
- /** @internal */
2618
- const map = /*#__PURE__*/dual(2, (self, f) => new StreamImpl(pipe(toChannel(self), mapOut(map$7(f)))));
2619
- /** @internal */
2620
- const mapEffectSequential = /*#__PURE__*/dual(2, (self, f) => {
2621
- const loop = iterator => {
2622
- const next = iterator.next();
2623
- if (next.done) {
2624
- return readWithCause({
2625
- onInput: elem => loop(elem[Symbol.iterator]()),
2626
- onFailure: failCause$2,
2627
- onDone: succeed
2628
- });
2629
- } else {
2630
- const value = next.value;
2631
- return unwrap(map$5(f(value), a2 => flatMap$1(write(of$1(a2)), () => loop(iterator))));
2632
- }
2633
- };
2634
- return new StreamImpl(pipe(toChannel(self), pipeTo(suspend$1(() => loop(empty$1()[Symbol.iterator]())))));
2635
- });
2636
- /** @internal */
2637
- const mapEffectPar = /*#__PURE__*/dual(3, (self, n, f) => new StreamImpl(pipe(toChannel(self), concatMap(writeChunk), mapOutEffectPar(f, n), mapOut(of$1))));
2638
- /** @internal */
2639
- const repeatEffectChunkOption = effect => unfoldChunkEffect(effect, effect => pipe(map$5(effect, chunk => some([chunk, effect])), catchAll$1(match$3({
2640
- onNone: () => succeed$3(none()),
2641
- onSome: fail$4
2642
- }))));
2643
- /** @internal */
2644
- const run = /*#__PURE__*/dual(2, (self, sink) => toChannel(self).pipe(pipeToOrFail(toChannel$1(sink)), runDrain$2));
2645
- /** @internal */
2646
- const runDrain$1 = self => run(self, drain);
2647
- /** @internal */
2648
- const scopedWith = f => new StreamImpl(scopedWith$1(scope => f(scope).pipe(map$5(of$1))));
2649
- /** @internal */
2650
- const suspend = stream => new StreamImpl(suspend$1(() => toChannel(stream())));
2651
- /** @internal */
2652
- const unfoldChunkEffect = (s, f) => suspend(() => {
2653
- const loop = s => unwrap(map$5(f(s), match$3({
2654
- onNone: () => void_,
2655
- onSome: ([chunk, s]) => flatMap$1(write(chunk), () => loop(s))
2656
- })));
2657
- return new StreamImpl(loop(s));
2658
- });
2659
- /** @internal */
2660
- const unwrapScopedWith = f => flatten(scopedWith(scope => f(scope)));
2661
-
2662
- /** @internal */
2663
- const GroupBySymbolKey = "effect/GroupBy";
2664
- /** @internal */
2665
- const GroupByTypeId = /*#__PURE__*/Symbol.for(GroupBySymbolKey);
2666
- const groupByVariance = {
2667
- /* c8 ignore next */
2668
- _R: _ => _,
2669
- /* c8 ignore next */
2670
- _E: _ => _,
2671
- /* c8 ignore next */
2672
- _K: _ => _,
2673
- /* c8 ignore next */
2674
- _V: _ => _
2675
- };
2676
- /** @internal */
2677
- const isGroupBy = u => hasProperty(u, GroupByTypeId);
2678
- /** @internal */
2679
- const evaluate = /*#__PURE__*/dual(args => isGroupBy(args[0]), (self, f, options) => flatMap(self.grouped, ([key, queue]) => f(key, flattenTake(fromQueue$1(queue, {
2680
- shutdown: true
2681
- }))), {
2682
- concurrency: "unbounded",
2683
- bufferSize: options?.bufferSize ?? 16
2684
- }));
2685
- /** @internal */
2686
- const make = grouped => ({
2687
- [GroupByTypeId]: groupByVariance,
2688
- pipe() {
2689
- return pipeArguments(this, arguments);
2690
- },
2691
- grouped
2692
- });
2693
- /** @internal */
2694
- const mapEffectOptions = /*#__PURE__*/dual(args => typeof args[0] !== "function", (self, f, options) => {
2695
- if (options?.key) {
2696
- return evaluate(groupByKey(self, options.key, {
2697
- bufferSize: options.bufferSize
2698
- }), (_, s) => mapEffectSequential(s, f));
2699
- }
2700
- return matchConcurrency(options?.concurrency, () => mapEffectSequential(self, f), n => options?.unordered ? flatMap(self, a => fromEffect(f(a)), {
2701
- concurrency: n
2702
- }) : mapEffectPar(self, n, f));
2703
- });
2704
- /** @internal */
2705
- const groupByKey = /*#__PURE__*/dual(args => typeof args[0] !== "function", (self, f, options) => {
2706
- const loop = (map, outerQueue) => readWithCause({
2707
- onInput: input => flatMap$1(fromEffect$3(forEach(groupByIterable(input, f), ([key, values]) => {
2708
- const innerQueue = map.get(key);
2709
- if (innerQueue === undefined) {
2710
- return pipe(bounded(options?.bufferSize ?? 16), flatMap$3(innerQueue => pipe(sync$2(() => {
2711
- map.set(key, innerQueue);
2712
- }), zipRight$3(offer(outerQueue, of([key, innerQueue]))), zipRight$3(pipe(offer(innerQueue, chunk(values)), catchSomeCause(cause => isInterruptedOnly(cause) ? some(_void) : none()))))));
2713
- }
2714
- return catchSomeCause(offer(innerQueue, chunk(values)), cause => isInterruptedOnly(cause) ? some(_void) : none());
2715
- }, {
2716
- discard: true
2717
- })), () => loop(map, outerQueue)),
2718
- onFailure: cause => fromEffect$3(offer(outerQueue, failCause$1(cause))),
2719
- onDone: () => fromEffect$3(pipe(forEach(map.entries(), ([_, innerQueue]) => pipe(offer(innerQueue, end$1), catchSomeCause(cause => isInterruptedOnly(cause) ? some(_void) : none())), {
2720
- discard: true
2721
- }), zipRight$3(offer(outerQueue, end$1))))
2722
- });
2723
- return make(unwrapScopedWith(scope => gen(function* () {
2724
- const map = new Map();
2725
- const queue = yield* unbounded();
2726
- yield* addFinalizer(scope, shutdown(queue));
2727
- return yield* toChannel(self).pipe(pipeTo(loop(map, queue)), drain$1, runIn(scope), forkIn(scope), as(flattenTake(fromQueue$1(queue, {
2728
- shutdown: true
2729
- }))));
2730
- })));
2731
- });
2732
- /**
2733
- * A variant of `groupBy` that retains the insertion order of keys.
2734
- *
2735
- * @internal
2736
- */
2737
- const groupByIterable = /*#__PURE__*/dual(2, (iterable, f) => {
2738
- const builder = [];
2739
- const iterator = iterable[Symbol.iterator]();
2740
- const map = new Map();
2741
- let next;
2742
- while ((next = iterator.next()) && !next.done) {
2743
- const value = next.value;
2744
- const key = f(value);
2745
- if (map.has(key)) {
2746
- const innerBuilder = map.get(key);
2747
- innerBuilder.push(value);
2748
- } else {
2749
- const innerBuilder = [value];
2750
- builder.push([key, innerBuilder]);
2751
- map.set(key, innerBuilder);
2752
- }
2753
- }
2754
- return unsafeFromArray(builder.map(tuple => [tuple[0], unsafeFromArray(tuple[1])]));
2755
- });
2756
-
2757
- /**
2758
- * Creates a stream from a queue of values
2759
- *
2760
- * **Options**
2761
- *
2762
- * - `maxChunkSize`: The maximum number of queued elements to put in one chunk in the stream
2763
- * - `shutdown`: If `true`, the queue will be shutdown after the stream is evaluated (defaults to `false`)
2764
- *
2765
- * @since 2.0.0
2766
- * @category constructors
2767
- */
2768
- const fromQueue = fromQueue$1;
2769
- /**
2770
- * Maps over elements of the stream with the specified effectful function.
2771
- *
2772
- * @example
2773
- * ```ts
2774
- * import { Effect, Random, Stream } from "effect"
2775
- *
2776
- * const stream = Stream.make(10, 20, 30).pipe(
2777
- * Stream.mapEffect((n) => Random.nextIntBetween(0, n))
2778
- * )
2779
- *
2780
- * Effect.runPromise(Stream.runCollect(stream)).then(console.log)
2781
- * // Example Output: { _id: 'Chunk', values: [ 7, 19, 8 ] }
2782
- * ```
2783
- *
2784
- * @since 2.0.0
2785
- * @category mapping
2786
- */
2787
- const mapEffect = mapEffectOptions;
2788
- /**
2789
- * Runs the stream only for its effects. The emitted elements are discarded.
2790
- *
2791
- * @since 2.0.0
2792
- * @category destructors
2793
- */
2794
- const runDrain = runDrain$1;
2795
-
2796
- class ReactiveControllerHost {
2797
- controllers = new Set();
2798
- addController(controller) {
2799
- this.controllers.add(controller);
2800
- }
2801
- removeController(controller) {
2802
- this.controllers.delete(controller);
2803
- }
2804
- get activeControllers() {
2805
- return Array.from(this.controllers).filter(controller => !controller.disabled);
2806
- }
2807
- connectedCallback() {
2808
- if (!this.controllers.size) {
2809
- console.warn('ReactiveControllerHost connected with no controllers registered.', this);
2810
- }
2811
- this.activeControllers.forEach(controller => controller.hostConnected?.());
2812
- }
2813
- disconnectedCallback() {
2814
- this.activeControllers.forEach(controller => controller.hostDisconnected?.());
2815
- }
2816
- componentWillLoad() {
2817
- this.activeControllers.forEach(controller => controller.hostWillLoad?.());
2818
- }
2819
- componentDidLoad() {
2820
- this.activeControllers.forEach(controller => controller.hostDidLoad?.());
2821
- }
2822
- componentWillRender() {
2823
- this.activeControllers.forEach(controller => controller.hostWillRender?.());
2824
- }
2825
- componentDidRender() {
2826
- this.activeControllers.forEach(controller => controller.hostDidRender?.());
2827
- }
2828
- componentWillUpdate() {
2829
- this.activeControllers.forEach(controller => controller.hostWillUpdate?.());
2830
- }
2831
- componentDidUpdate() {
2832
- this.activeControllers.forEach(controller => controller.hostDidUpdate?.());
2833
- }
2834
- }
2835
-
2836
- class AriaValidationController {
2837
- host;
2838
- config;
2839
- static get globalValidationEnabled() {
2840
- return Build.isDev;
2841
- }
2842
- static axe = this.globalValidationEnabled ? import('./axe-cRQ9Ux1I.js').then(function (n) { return n.a; }) : null;
2843
- static axeQueue = null;
2844
- static axeStreamFiber = null;
2845
- visibilityObserver;
2846
- elementQueued = false;
2847
- elementValidated = false;
2848
- knownValidationErrors = [];
2849
- get disabled() {
2850
- return true;
2851
- }
2852
- constructor(host, config) {
2853
- this.host = host;
2854
- this.config = config;
2855
- AriaValidationController.initializeAxeStream();
2856
- }
2857
- static initializeAxeStream() {
2858
- if (!this.globalValidationEnabled)
2859
- return;
2860
- if (this.axeStreamFiber)
2861
- return;
2862
- const program = gen(function* () {
2863
- const queue = (AriaValidationController.axeQueue = yield* bounded(100));
2864
- const axeLib = yield* promise(() => AriaValidationController.axe);
2865
- if (!axeLib) {
2866
- console.error('Axe library not available, ARIA validation will not run.');
2867
- return;
2868
- }
2869
- const stream = fromQueue(queue).pipe(mapEffect(({ context, onComplete }) => async(resume => {
2870
- axeLib.run(context, {}, (error, results) => {
2871
- onComplete(error, results);
2872
- resume(_void);
2873
- });
2874
- })));
2875
- yield* runDrain(stream);
2876
- });
2877
- this.axeStreamFiber = runFork(program);
2878
- }
2879
- hostDidLoad() {
2880
- if (this.elementQueued || this.elementValidated)
2881
- return;
2882
- if (!this.host.el.checkVisibility()) {
2883
- this.observeVisibilityOnce();
2884
- return;
2885
- }
2886
- this.enqueueValidation();
2887
- }
2888
- hostDidUpdate() {
2889
- this.checkLazyValidation();
2890
- }
2891
- hostDisconnected() {
2892
- this.discardVisibilityObserver();
2893
- }
2894
- observeVisibilityOnce() {
2895
- this.visibilityObserver = new IntersectionObserver(entries => {
2896
- for (const entry of entries) {
2897
- if (entry.target !== this.host.el)
2898
- continue;
2899
- if (!entry.isIntersecting)
2900
- continue;
2901
- this.checkLazyValidation();
2902
- this.discardVisibilityObserver();
2903
- }
2904
- }, {
2905
- root: this.host.el.parentElement,
2906
- rootMargin: '0px',
2907
- threshold: 0.01,
2908
- });
2909
- this.visibilityObserver.observe(this.host.el);
2910
- }
2911
- checkLazyValidation() {
2912
- if (!this.config?.reValidateOnPropChanges && (this.elementQueued || this.elementValidated))
2913
- return;
2914
- this.enqueueValidation();
2915
- }
2916
- enqueueValidation() {
2917
- return;
2918
- }
2919
- discardVisibilityObserver() {
2920
- if (!this.visibilityObserver)
2921
- return;
2922
- this.visibilityObserver.disconnect();
2923
- this.visibilityObserver = undefined;
2924
- }
2925
- }
2926
-
2927
- export { AriaValidationController as A, ReactiveControllerHost as R };