effect-browser 0.3.0-beta.20 → 0.3.0-beta.22

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 (243) hide show
  1. package/README.md +221 -158
  2. package/dist/Action-24sLOubi.d.mts +110 -0
  3. package/dist/Action.d.mts +2 -0
  4. package/dist/Action.mjs +141 -0
  5. package/dist/Action.mjs.map +1 -0
  6. package/dist/ActionPort.d.mts +15 -0
  7. package/dist/ActionPort.mjs +101 -0
  8. package/dist/ActionPort.mjs.map +1 -0
  9. package/dist/Browser-Cq2K1FEA.mjs +4075 -0
  10. package/dist/Browser-Cq2K1FEA.mjs.map +1 -0
  11. package/dist/Browser-wZhwZSlG.d.mts +167 -0
  12. package/dist/Browser.d.mts +2 -129
  13. package/dist/Browser.mjs +1 -1
  14. package/dist/{BrowserError-Coy7EW1N.d.mts → BrowserError-BlcmLVzn.d.mts} +22 -7
  15. package/dist/BrowserError.d.mts +2 -2
  16. package/dist/BrowserError.mjs +46 -9
  17. package/dist/BrowserError.mjs.map +1 -1
  18. package/dist/{BrowserEvent-dq6FRT8w.d.mts → BrowserEvent-lLqJ3GJS.d.mts} +93 -37
  19. package/dist/BrowserEvent.d.mts +2 -2
  20. package/dist/BrowserEvent.mjs +29 -24
  21. package/dist/BrowserEvent.mjs.map +1 -1
  22. package/dist/{Change-DqING3tr.d.mts → Change-Ba7INmay.d.mts} +4 -6
  23. package/dist/Change.d.mts +2 -2
  24. package/dist/Change.mjs +97 -2
  25. package/dist/Change.mjs.map +1 -0
  26. package/dist/Clock.d.mts +57 -0
  27. package/dist/Clock.mjs +80 -0
  28. package/dist/Clock.mjs.map +1 -0
  29. package/dist/{Frame-DkNdjjjr.d.mts → Frame-UEH2hO5T.d.mts} +10 -3
  30. package/dist/Frame.d.mts +2 -2
  31. package/dist/Frame.mjs +10 -2
  32. package/dist/Frame.mjs.map +1 -1
  33. package/dist/{Motion-DND6I-64.d.mts → Geometry-DJx9qrYy.d.mts} +7 -10
  34. package/dist/Geometry.d.mts +2 -0
  35. package/dist/Geometry.mjs +32 -0
  36. package/dist/Geometry.mjs.map +1 -0
  37. package/dist/LICENSE-jpeg-js +28 -0
  38. package/dist/Matching.d.mts +37 -0
  39. package/dist/{match.inpage-xOe9LNO0.mjs → Matching.mjs} +28 -4
  40. package/dist/Matching.mjs.map +1 -0
  41. package/dist/{Page-CfB6Zn1p.mjs → Page-BF5izr8R.mjs} +216 -31
  42. package/dist/Page-BF5izr8R.mjs.map +1 -0
  43. package/dist/{Page-ku6j5t-v.d.mts → Page-CvsOEorc.d.mts} +158 -185
  44. package/dist/Page.d.mts +2 -2
  45. package/dist/Page.mjs +1 -1
  46. package/dist/Released-tURbFmal.d.mts +15 -0
  47. package/dist/{Snapshot-B34hZ4Jl.d.mts → Snapshot-CtBVOtuu.d.mts} +6 -1
  48. package/dist/Snapshot.d.mts +1 -1
  49. package/dist/Snapshot.mjs.map +1 -1
  50. package/dist/Stillness-CNlvayIo.mjs +136 -0
  51. package/dist/Stillness-CNlvayIo.mjs.map +1 -0
  52. package/dist/Style-AO4V7Czt.mjs +357 -0
  53. package/dist/Style-AO4V7Czt.mjs.map +1 -0
  54. package/dist/Style.d.mts +72 -0
  55. package/dist/Style.mjs +2 -0
  56. package/dist/Url.d.mts +26 -0
  57. package/dist/Url.mjs +74 -0
  58. package/dist/Url.mjs.map +1 -0
  59. package/dist/Window-CMddGMt1.d.mts +34 -0
  60. package/dist/Window.d.mts +2 -0
  61. package/dist/Window.mjs +35 -0
  62. package/dist/Window.mjs.map +1 -0
  63. package/dist/connection-2KHI4_KN.d.mts +41 -0
  64. package/dist/connection-BTeO0Hiz.mjs +68 -0
  65. package/dist/connection-BTeO0Hiz.mjs.map +1 -0
  66. package/dist/index.d.mts +15 -17
  67. package/dist/index.mjs +11 -14
  68. package/dist/moment/Moment.d.mts +86 -0
  69. package/dist/{Moment.mjs → moment/Moment.mjs} +44 -38
  70. package/dist/moment/Moment.mjs.map +1 -0
  71. package/dist/{Plan-DJ4hEEna.d.mts → plan/index.d.mts} +169 -64
  72. package/dist/{Plan-C-d5QYS8.mjs → plan/index.mjs} +122 -155
  73. package/dist/plan/index.mjs.map +1 -0
  74. package/dist/{Policy.d.mts → policy/Policy.d.mts} +5 -9
  75. package/dist/{Policy.mjs → policy/Policy.mjs} +11 -21
  76. package/dist/policy/Policy.mjs.map +1 -0
  77. package/dist/presentation/Motion.d.mts +12 -0
  78. package/dist/{Motion.mjs → presentation/Motion.mjs} +4 -27
  79. package/dist/presentation/Motion.mjs.map +1 -0
  80. package/dist/presentation/Presentation.d.mts +30 -0
  81. package/dist/presentation/Presentation.mjs +105 -0
  82. package/dist/presentation/Presentation.mjs.map +1 -0
  83. package/dist/{Stage.d.mts → presentation/Stage.d.mts} +5 -8
  84. package/dist/{Stage.mjs → presentation/Stage.mjs} +68 -76
  85. package/dist/presentation/Stage.mjs.map +1 -0
  86. package/dist/presentation/feed.d.mts +20 -0
  87. package/dist/presentation/feed.mjs +18 -0
  88. package/dist/presentation/feed.mjs.map +1 -0
  89. package/dist/providers/Cdp.d.mts +9 -0
  90. package/dist/providers/Cdp.mjs +15 -0
  91. package/dist/providers/Cdp.mjs.map +1 -0
  92. package/dist/{Chromium.d.mts → providers/Chromium.d.mts} +6 -7
  93. package/dist/{Chromium.mjs → providers/Chromium.mjs} +7 -16
  94. package/dist/providers/Chromium.mjs.map +1 -0
  95. package/dist/providers/Released.d.mts +2 -0
  96. package/dist/providers/Released.mjs +12 -0
  97. package/dist/providers/Released.mjs.map +1 -0
  98. package/dist/stillness/Stillness.d.mts +12 -0
  99. package/dist/stillness/Stillness.mjs +2 -0
  100. package/dist/supervisor/Supervisor.d.mts +104 -0
  101. package/dist/supervisor/Supervisor.mjs +513 -0
  102. package/dist/supervisor/Supervisor.mjs.map +1 -0
  103. package/dist/testing/index.d.mts +337 -0
  104. package/dist/testing/index.mjs +515 -0
  105. package/dist/testing/index.mjs.map +1 -0
  106. package/dist/workerd/Cdp.d.mts +8 -0
  107. package/dist/workerd/Cdp.mjs +13 -0
  108. package/dist/workerd/Cdp.mjs.map +1 -0
  109. package/package.json +94 -33
  110. package/src/Action.ts +127 -0
  111. package/src/ActionPort.ts +128 -0
  112. package/src/Browser.ts +366 -225
  113. package/src/BrowserError.ts +63 -6
  114. package/src/BrowserEvent.ts +26 -25
  115. package/src/Change.ts +0 -2
  116. package/src/{internal/pictures/clock.ts → Clock.ts} +17 -6
  117. package/src/Frame.ts +14 -0
  118. package/src/Geometry.ts +48 -0
  119. package/src/{internal/reading/match.inpage.ts → Matching.ts} +34 -4
  120. package/src/Page.ts +111 -92
  121. package/src/Snapshot.ts +5 -0
  122. package/src/{internal/input/style.ts → Style.ts} +121 -14
  123. package/src/Window.ts +30 -0
  124. package/src/index.ts +8 -13
  125. package/src/internal/input/actions.ts +61 -119
  126. package/src/internal/input/dispatch.ts +3 -3
  127. package/src/internal/input/gate.ts +21 -18
  128. package/src/internal/input/guard.inpage.ts +25 -58
  129. package/src/internal/input/guard.ts +11 -20
  130. package/src/internal/input/keyboard.ts +12 -3
  131. package/src/internal/input/perform.ts +78 -60
  132. package/src/internal/input/pointer.ts +4 -2
  133. package/src/internal/input/settle.ts +7 -5
  134. package/src/internal/input/targets.inpage.ts +1 -1
  135. package/src/internal/input/targets.ts +4 -9
  136. package/src/internal/page/bridge.ts +210 -114
  137. package/src/internal/page/context.ts +23 -73
  138. package/src/internal/page/dialogs.ts +58 -0
  139. package/src/internal/page/identity.ts +6 -23
  140. package/src/internal/page/lane.ts +14 -15
  141. package/src/internal/page/navigation.ts +50 -42
  142. package/src/internal/page/openings.ts +11 -5
  143. package/src/internal/page/page.ts +44 -81
  144. package/src/internal/page/port.ts +125 -0
  145. package/src/internal/{input → page}/replies.ts +1 -1
  146. package/src/internal/page/request-owner.ts +269 -0
  147. package/src/internal/page/requests.ts +357 -0
  148. package/src/internal/page/scripts.ts +124 -0
  149. package/src/internal/pictures/capture.ts +255 -332
  150. package/src/internal/pictures/dimensions.ts +162 -0
  151. package/src/internal/pictures/frame.ts +68 -0
  152. package/src/internal/pictures/pictures.ts +57 -23
  153. package/src/internal/pictures/quiescence.ts +1 -1
  154. package/src/internal/pictures/state.ts +26 -0
  155. package/src/internal/pictures/transport.ts +21 -4
  156. package/src/internal/reading/controls.inpage.ts +5 -70
  157. package/src/internal/reading/expect.inpage.ts +13 -17
  158. package/src/internal/reading/names.inpage.ts +89 -45
  159. package/src/internal/reading/outline.inpage.ts +6 -7
  160. package/src/internal/reading/reading.ts +144 -176
  161. package/src/internal/reading/ready.inpage.ts +6 -17
  162. package/src/internal/reading/ready.ts +13 -135
  163. package/src/internal/reading/subjects.inpage.ts +83 -43
  164. package/src/internal/reading/walk.inpage.ts +33 -13
  165. package/src/internal/timeline/changes.ts +55 -6
  166. package/src/internal/timeline/events.ts +15 -5
  167. package/src/internal/timeline/history.inpage.ts +1 -1
  168. package/src/internal/timeline/record.inpage.ts +4 -1
  169. package/src/internal/timeline/window.ts +2 -1
  170. package/src/{Moment.ts → moment/Moment.ts} +13 -31
  171. package/src/{internal/timeline → moment}/words.ts +2 -2
  172. package/src/{internal/reading → plan}/choose.ts +3 -3
  173. package/src/plan/data.ts +117 -0
  174. package/src/plan/execute.ts +411 -0
  175. package/src/plan/index.ts +36 -0
  176. package/src/plan/record.ts +71 -0
  177. package/src/plan/targets.ts +71 -0
  178. package/src/{Policy.ts → policy/Policy.ts} +13 -10
  179. package/src/{Motion.ts → presentation/Motion.ts} +12 -46
  180. package/src/presentation/Presentation.ts +176 -0
  181. package/src/{Stage.ts → presentation/Stage.ts} +147 -112
  182. package/src/presentation/feed.ts +21 -0
  183. package/src/providers/Cdp.ts +16 -0
  184. package/src/{Chromium.ts → providers/Chromium.ts} +7 -10
  185. package/src/providers/Released.ts +13 -0
  186. package/src/providers/connection.ts +134 -0
  187. package/src/{internal/pictures/motion.ts → stillness/Pixels.ts} +4 -4
  188. package/src/stillness/Stillness.ts +166 -0
  189. package/src/supervisor/Supervisor.ts +170 -0
  190. package/src/supervisor/contract.ts +105 -0
  191. package/src/supervisor/lifecycle.ts +272 -0
  192. package/src/supervisor/runtime.ts +234 -0
  193. package/src/testing/TestBrowser.ts +115 -0
  194. package/src/testing/TestPage.ts +10 -0
  195. package/src/testing/evidence.ts +154 -0
  196. package/src/testing/index.ts +3 -0
  197. package/src/testing/model.ts +222 -0
  198. package/src/testing/page.ts +360 -0
  199. package/src/workerd/Cdp.ts +11 -0
  200. package/dist/Browser-BwCldIff.mjs +0 -629
  201. package/dist/Browser-BwCldIff.mjs.map +0 -1
  202. package/dist/Cdp.d.mts +0 -32
  203. package/dist/Cdp.mjs +0 -61
  204. package/dist/Cdp.mjs.map +0 -1
  205. package/dist/Change-DNvztNLu.mjs +0 -138
  206. package/dist/Change-DNvztNLu.mjs.map +0 -1
  207. package/dist/Chromium.mjs.map +0 -1
  208. package/dist/Expect.d.mts +0 -62
  209. package/dist/Expect.mjs +0 -114
  210. package/dist/Expect.mjs.map +0 -1
  211. package/dist/Moment.d.mts +0 -2
  212. package/dist/Moment.mjs.map +0 -1
  213. package/dist/Motion.d.mts +0 -2
  214. package/dist/Motion.mjs.map +0 -1
  215. package/dist/Page-CfB6Zn1p.mjs.map +0 -1
  216. package/dist/Plan-C-d5QYS8.mjs.map +0 -1
  217. package/dist/Plan.d.mts +0 -2
  218. package/dist/Plan.mjs +0 -2
  219. package/dist/Policy.mjs.map +0 -1
  220. package/dist/Presentation.d.mts +0 -48
  221. package/dist/Presentation.mjs +0 -118
  222. package/dist/Presentation.mjs.map +0 -1
  223. package/dist/Stage.mjs.map +0 -1
  224. package/dist/Supervisor-2mPjIYYs.mjs +0 -676
  225. package/dist/Supervisor-2mPjIYYs.mjs.map +0 -1
  226. package/dist/Supervisor-mVPeEUp8.d.mts +0 -317
  227. package/dist/Supervisor.d.mts +0 -2
  228. package/dist/Supervisor.mjs +0 -2
  229. package/dist/context-w3NJPRLo.mjs +0 -335
  230. package/dist/context-w3NJPRLo.mjs.map +0 -1
  231. package/dist/match.inpage-xOe9LNO0.mjs.map +0 -1
  232. package/dist/page-BKwfF6z-.mjs +0 -5099
  233. package/dist/page-BKwfF6z-.mjs.map +0 -1
  234. package/dist/url-Cd04Okid.mjs +0 -264
  235. package/dist/url-Cd04Okid.mjs.map +0 -1
  236. package/src/Cdp.ts +0 -101
  237. package/src/Expect.ts +0 -180
  238. package/src/Plan.ts +0 -674
  239. package/src/Presentation.ts +0 -196
  240. package/src/Supervisor.ts +0 -632
  241. package/src/internal/supervisor/lifecycle.ts +0 -484
  242. /package/src/{internal/page/url.ts → Url.ts} +0 -0
  243. /package/src/{internal/pictures → stillness}/utilsBundle.d.ts +0 -0
@@ -10,26 +10,24 @@ import {
10
10
  Exit,
11
11
  Option,
12
12
  Queue,
13
+ Result,
13
14
  type Scope,
14
15
  Semaphore,
15
16
  Stream,
16
17
  } from "effect";
18
+ import { Base64 } from "effect/encoding";
17
19
 
18
20
  import { type BrowserError, InvalidRequest } from "../../BrowserError.ts";
19
- import { BrowserPaint, CaptureStats, Frame, type ScreencastOptions } from "../../Frame.ts";
21
+ import { type Estimate, monotonicMillis } from "../../Clock.ts";
22
+ import { CaptureStats, type Frame, type ScreencastOptions, sameCapture } from "../../Frame.ts";
20
23
  import { undispatched } from "../page/context.ts";
21
- import { type Estimate, monotonicMillis, toHostTime, uncertaintyAt } from "./clock.ts";
22
24
  import { tally } from "./counts.ts";
25
+ import { readViewport, sizeFilter, type Size } from "./dimensions.ts";
26
+ import { orderedFrame, timed } from "./frame.ts";
23
27
  import * as Quiescence from "./quiescence.ts";
28
+ import { failureOf, initial, type State, step } from "./state.ts";
24
29
  import type { NativeFrame, Transport } from "./transport.ts";
25
30
 
26
- export { countsKept } from "./counts.ts";
27
-
28
- export interface Size {
29
- readonly width: number;
30
- readonly height: number;
31
- }
32
-
33
31
  interface Options {
34
32
  readonly id: string;
35
33
  /** Where each capture's screencast runs, found as it starts. */
@@ -57,20 +55,9 @@ type Envelope =
57
55
  | { readonly _tag: "Frame"; readonly sequence: number; readonly frame: Frame }
58
56
  | { readonly _tag: "Failure"; readonly error: BrowserError };
59
57
 
60
- interface Held {
61
- readonly frame: Frame;
62
- readonly timestamp: number;
63
- }
64
-
65
- /** Consecutive frames of one device size other than the expected one, oldest first. */
66
- interface Run {
67
- readonly device: Size;
68
- /** When its first frame arrived, on the owner's monotonic clock. */
69
- readonly since: number;
70
- readonly frames: Array<Held>;
71
- }
72
-
73
58
  interface Generation {
59
+ readonly id: number;
60
+ sequence: number;
74
61
  readonly subscribers: Set<Queue.Queue<Envelope>>;
75
62
  readonly transport: Transport;
76
63
  /** Stops handing the transport's frames to this generation. */
@@ -78,10 +65,10 @@ interface Generation {
78
65
  readonly calibration: Estimate;
79
66
  /** The native capture's settings; every reader of this generation shares them. */
80
67
  readonly quality: number;
81
- readonly size: Size | null;
82
- phase: "Capturing" | "Paused" | "Stopped";
68
+ size: Size | null;
69
+ readonly explicitSize: boolean;
70
+ state: State;
83
71
  predecessor: number | undefined;
84
- failure: BrowserError | undefined;
85
72
  }
86
73
 
87
74
  export interface Controller {
@@ -117,63 +104,6 @@ const replyCapacity = 32;
117
104
  const subscriberCapacity = 16;
118
105
  const deadline = Duration.seconds(2);
119
106
 
120
- // Device sizes can be fractional at some scale factors; the page reports whole pixels.
121
- const sameSize = (left: Size, right: Size) =>
122
- Math.abs(left.width - right.width) < 1 && Math.abs(left.height - right.height) < 1;
123
-
124
- // A frame is its device scaled to fit, so it keeps the device's shape to within a pixel a side.
125
- const sameShape = (image: Size, device: Size) =>
126
- Math.abs(image.width * device.height - image.height * device.width) <
127
- device.width + device.height;
128
-
129
- // Another capture's frames last only as long as it does; a run of frames that lasts longer is
130
- // the page's own.
131
- const outlasting = Duration.seconds(1);
132
-
133
- /**
134
- * A native frame as readers get it: its picture's size, else the capture's or its device's, and
135
- * its paint mapped by the browser's newest estimate, which may be older than the frame and says
136
- * less about later paint.
137
- */
138
- const timed = (
139
- options: Options,
140
- native: NativeFrame,
141
- timestamp: number,
142
- generation: Pick<Generation, "calibration" | "size" | "transport">,
143
- ) => {
144
- const data = Buffer.from(native.data, "base64");
145
- const image = options.imageSize(data);
146
- const device = { width: native.metadata.deviceWidth, height: native.metadata.deviceHeight };
147
- const size = image ?? generation.size ?? device;
148
- const estimate = options.latest() ?? generation.calibration;
149
- const hostTime = toHostTime(estimate, timestamp);
150
-
151
- const frame = new Frame({
152
- page: options.id,
153
- data,
154
- timing: new BrowserPaint({
155
- timestamp,
156
- hostTime,
157
- uncertaintyMillis: uncertaintyAt(estimate, hostTime),
158
- }),
159
- receivedAt: monotonicMillis(options.clock),
160
- width: size.width,
161
- height: size.height,
162
- ...generation.transport.frameTag(),
163
- });
164
-
165
- return { frame, image, device };
166
- };
167
-
168
- // A page too busy to report its viewport in time reads as null.
169
- const readViewport = (options: Options) =>
170
- options.viewport.pipe(
171
- Effect.interruptible,
172
- Effect.timeoutOrElse({ duration: deadline, orElse: () => Effect.succeed(null) }),
173
- Effect.orElseSucceed(() => null),
174
- Effect.provideService(Clock.Clock, options.clock),
175
- );
176
-
177
107
  /**
178
108
  * What a new capture starts with: where it runs, the clock's estimate, and the viewport unless
179
109
  * the reader gave a size. A capture connection attaches while the page's own session maps the
@@ -193,114 +123,6 @@ const prepare = (options: Options, screencast: ScreencastOptions) =>
193
123
  { concurrency: 2 },
194
124
  );
195
125
 
196
- /**
197
- * Keeps other captures' frames from readers. A clipped or scaled screenshot of the page, taken
198
- * from any session, draws frames into its running screencast without resizing the page, until
199
- * Chromium returns to the page's size. Either their picture has another shape than their device,
200
- * and they are dropped, or their device has another size than the page's frames.
201
- *
202
- * A frame of the expected device size goes to readers at once and drops any run of frames of
203
- * another size before it, as another capture's. A run waits, in order, until the page reports a
204
- * viewport of its size or until it outlasts any capture: then it was a real resize, so it goes to
205
- * readers and its size is expected. The page's report only shortens the wait, so a page too busy
206
- * to answer, or one measuring in other units as under browser zoom, never stalls the stream.
207
- */
208
- const sizeFilter = (
209
- options: Options,
210
- deliver: (frame: Frame, timestamp: number) => void,
211
- drop: (frames: number) => void,
212
- ) =>
213
- Effect.gen(function* () {
214
- // Until a capture reads its viewport or delivers a frame, its first frame stands in.
215
- let expected: Size | null = null;
216
- let run: Run | undefined;
217
- // Wakes the decider for a new run or an ended one; wakes while it is busy coalesce.
218
- const wake = yield* Queue.sliding<void>(1);
219
-
220
- const end = () => {
221
- if (run === undefined) return;
222
- drop(run.frames.length);
223
- run = undefined;
224
- Queue.offerUnsafe(wake, undefined);
225
- };
226
-
227
- const now = () => monotonicMillis(options.clock);
228
-
229
- const adopt = (adopted: Run) => {
230
- run = undefined;
231
- expected = adopted.device;
232
- for (const held of adopted.frames) deliver(held.frame, held.timestamp);
233
- };
234
-
235
- const decide: Effect.Effect<void> = Effect.suspend(() => {
236
- const deciding = run;
237
-
238
- if (deciding === undefined) return Effect.void;
239
-
240
- return readViewport(options).pipe(
241
- Effect.flatMap((viewport) => {
242
- if (run !== deciding) return decide;
243
- if (viewport !== null && sameSize(viewport, deciding.device))
244
- return Effect.sync(() => adopt(deciding));
245
-
246
- return outlast(deciding);
247
- }),
248
- );
249
- });
250
-
251
- // Waits until the run outlasts any capture, unless a newer frame decides it first.
252
- const outlast = (waiting: Run): Effect.Effect<void> =>
253
- Effect.suspend(() => {
254
- if (run !== waiting) return decide;
255
- const remaining = waiting.since + Duration.toMillis(outlasting) - now();
256
-
257
- if (remaining <= 0) return Effect.sync(() => adopt(waiting));
258
-
259
- return Effect.sleep(Duration.millis(remaining)).pipe(
260
- Effect.provideService(Clock.Clock, options.clock),
261
- Effect.race(Queue.take(wake)),
262
- Effect.andThen(outlast(waiting)),
263
- );
264
- });
265
-
266
- yield* Queue.take(wake).pipe(Effect.andThen(decide), Effect.forever, Effect.forkScoped);
267
-
268
- return {
269
- /** Drops the frames still waiting; their capture has stopped. */
270
- end,
271
- /** A new capture expects the viewport it read, if any. */
272
- restart: (viewport: Size | null) => {
273
- end();
274
- expected = viewport;
275
- },
276
- /** Whether a frame of this device size shows the page, as far as the capture knows. */
277
- offer: (frame: Frame, timestamp: number, image: Size | undefined, device: Size) => {
278
- if (image !== undefined && !sameShape(image, device)) {
279
- drop(1);
280
-
281
- return;
282
- }
283
- expected ??= device;
284
- if (sameSize(device, expected)) {
285
- end();
286
- deliver(frame, timestamp);
287
-
288
- return;
289
- }
290
- if (run !== undefined && !sameSize(run.device, device)) end();
291
- if (run === undefined) {
292
- run = { device, since: now(), frames: [] };
293
- Queue.offerUnsafe(wake, undefined);
294
- }
295
- run.frames.push({ frame, timestamp });
296
- if (run.frames.length > subscriberCapacity) {
297
- run.frames.shift();
298
- drop(1);
299
- }
300
- },
301
- };
302
- });
303
-
304
126
  /**
305
127
  * A running capture's failure, told once its page's fate is known. A capture can fail before the
306
128
  * page's own session hears why: a capture connection hears the browser's end before the connection
@@ -329,7 +151,9 @@ const synced = (
329
151
  error: (cause: unknown) => BrowserError,
330
152
  ): Effect.Effect<void, BrowserError> => {
331
153
  if (current === undefined) return Effect.void;
332
- if (current.failure !== undefined) return why(current.failure);
154
+ const failure = failureOf(current.state);
155
+
156
+ if (failure !== undefined) return why(failure);
333
157
 
334
158
  return Effect.tryPromise({ try: () => current.transport.sync(), catch: error }).pipe(
335
159
  Effect.catch(why),
@@ -368,9 +192,9 @@ const isCurrent = (
368
192
  latest: Option.Option<Frame>,
369
193
  ) =>
370
194
  generation !== undefined &&
371
- generation.phase === "Capturing" &&
372
- generation.failure === undefined &&
373
- Option.getOrUndefined(latest) === frame &&
195
+ generation.state._tag === "Capturing" &&
196
+ frame.capture !== undefined &&
197
+ sameCapture(frame, Option.getOrUndefined(latest)) &&
374
198
  generation.transport.frameTag().document === frame.document;
375
199
 
376
200
  const currentFrame = (generation: Generation, latest: Option.Option<Frame>) =>
@@ -427,7 +251,7 @@ const receive =
427
251
  fail: (current: Generation, error: BrowserError) => void,
428
252
  ) =>
429
253
  (native: NativeFrame) => {
430
- if (current.phase === "Stopped") return;
254
+ if (current.state._tag === "Stopped") return;
431
255
  counts.count("received");
432
256
  if (replies.size >= replyCapacity) {
433
257
  fail(current, options.error(new Error("screencast acknowledgement capacity exceeded")));
@@ -440,7 +264,7 @@ const receive =
440
264
  .then(
441
265
  () => undefined,
442
266
  (cause: unknown) => {
443
- if (current.phase !== "Stopped") fail(current, options.error(cause));
267
+ if (current.state._tag !== "Stopped") fail(current, options.error(cause));
444
268
  },
445
269
  )
446
270
  .then(() => void replies.delete(reply));
@@ -453,17 +277,118 @@ const receive =
453
277
  if (current.predecessor !== undefined && timestamp <= current.predecessor)
454
278
  return counts.count("late");
455
279
  Queue.offerUnsafe(renewing, undefined);
456
- const { frame, image, device } = timed(options, native, timestamp, current);
280
+ const decoded = Base64.decode(native.data);
457
281
 
458
- if (current.phase === "Paused") return counts.count("duringPictures");
282
+ if (Result.isFailure(decoded)) {
283
+ fail(
284
+ current,
285
+ options.error(new Error("the capture connection sent invalid base64 picture data")),
286
+ );
287
+
288
+ return;
289
+ }
290
+ current.sequence++;
291
+ const { frame, image, device } = timed(options, native, timestamp, current, decoded.success);
292
+
293
+ if (current.state._tag === "Paused") return counts.count("duringPictures");
459
294
  sizes.offer(frame, timestamp, image, device);
460
295
  };
461
296
 
297
+ const settingsOf = (current: Generation) => ({
298
+ format: "jpeg" as const,
299
+ quality: current.quality,
300
+ ...(current.size === null
301
+ ? {}
302
+ : { maxWidth: current.size.width, maxHeight: current.size.height }),
303
+ });
304
+
305
+ const healthy = (current: Generation) =>
306
+ Effect.suspend(() => {
307
+ const failure = failureOf(current.state);
308
+
309
+ return failure === undefined ? Effect.void : Effect.fail(failure);
310
+ });
311
+
312
+ // Native caps must follow implicit viewport growth or every following frame stays scaled down.
313
+ const followGrowth = (
314
+ changes: Queue.Queue<Size>,
315
+ lock: Semaphore.Semaphore,
316
+ generation: () => Generation | undefined,
317
+ pictures: ReturnType<typeof Quiescence.make<Generation>>,
318
+ fail: (current: Generation, error: BrowserError) => void,
319
+ ) =>
320
+ Queue.take(changes).pipe(
321
+ Effect.flatMap((size) =>
322
+ lock.withPermits(1)(
323
+ Effect.suspend(() => {
324
+ const current = generation();
325
+
326
+ if (
327
+ current === undefined ||
328
+ current.explicitSize ||
329
+ current.state._tag !== "Capturing" ||
330
+ (current.size !== null &&
331
+ size.width <= current.size.width &&
332
+ size.height <= current.size.height)
333
+ )
334
+ return Effect.void;
335
+
336
+ return pictures
337
+ .excluding(
338
+ Effect.sync(() => {
339
+ current.size = size;
340
+ }),
341
+ )
342
+ .pipe(Effect.catch((error) => Effect.sync(() => fail(current, error))));
343
+ }),
344
+ ),
345
+ ),
346
+ Effect.forever,
347
+ Effect.forkScoped,
348
+ );
349
+
350
+ interface Lease {
351
+ readonly current: Generation;
352
+ readonly subscription: Queue.Queue<Envelope>;
353
+ readonly baseline: number;
354
+ readonly frame: Frame | undefined;
355
+ }
356
+
357
+ /** The first subscription must exist before the native start can emit its only frame. */
358
+ const subscribe = (current: Generation) =>
359
+ Effect.gen(function* () {
360
+ const subscription = yield* Queue.sliding<Envelope>(subscriberCapacity);
361
+
362
+ current.subscribers.add(subscription);
363
+ const failure = failureOf(current.state);
364
+
365
+ if (failure !== undefined) Queue.offerUnsafe(subscription, { _tag: "Failure", error: failure });
366
+
367
+ return subscription;
368
+ });
369
+
370
+ const reader =
371
+ (
372
+ acquire: (options: ScreencastOptions) => Effect.Effect<Lease, BrowserError>,
373
+ leave: (lease: Lease) => Effect.Effect<void>,
374
+ why: (failure: BrowserError) => Effect.Effect<never, BrowserError>,
375
+ lost: (count: number) => void,
376
+ ): Controller["open"] =>
377
+ (settings = {}) =>
378
+ Effect.acquireRelease(acquire(settings).pipe(Effect.interruptible), leave).pipe(
379
+ Effect.map((lease) => ({
380
+ current: lease.frame,
381
+ stream: frames(lease.subscription, lease.baseline, why, lost),
382
+ })),
383
+ );
384
+
462
385
  export const make = (options: Options) =>
463
386
  Effect.gen(function* () {
464
387
  const lock = yield* Semaphore.make(1);
465
388
  const replies = new Set<Promise<void>>();
466
389
  let generation: Generation | undefined;
390
+ let generations = 0;
391
+ let lastHostTime = Number.NEGATIVE_INFINITY;
467
392
  // Done as the page's scope closes, once the page has gone and its browser's loss, if any, is
468
393
  // known.
469
394
  const closed = yield* Deferred.make<void>();
@@ -471,14 +396,10 @@ export const make = (options: Options) =>
471
396
  const isClosed = () => pageScope.state._tag === "Closed" || Deferred.isDoneUnsafe(closed);
472
397
  let latest = Option.none<Frame>();
473
398
  let history: ReadonlyArray<Frame> = [];
474
- const keepMillis = Duration.toMillis(options.frameHistory);
475
- const now = () => monotonicMillis(options.clock);
476
- const counts = tally(now);
399
+ const counts = tally(() => monotonicMillis(options.clock));
477
400
  // Frames delivered, which number them so that a reader can tell what it missed.
478
401
  let delivered = 0;
479
402
 
480
- const current = (frame: Frame) => isCurrent(frame, generation, latest);
481
-
482
403
  // Frames that show the page go to the running capture's readers.
483
404
  const deliver = (frame: Frame, timestamp: number) => {
484
405
  const current = generation;
@@ -489,16 +410,30 @@ export const make = (options: Options) =>
489
410
  return counts.count("late");
490
411
  if (current.predecessor !== undefined) counts.gap(timestamp - current.predecessor);
491
412
  current.predecessor = timestamp;
413
+ frame = orderedFrame(frame, lastHostTime);
414
+ lastHostTime = frame.hostTime;
492
415
  delivered++;
493
416
  counts.count("accepted");
494
417
  latest = Option.some(frame);
495
- history = [...history.filter((kept) => kept.hostTime >= frame.hostTime - keepMillis), frame];
418
+ history = [
419
+ ...history.filter(
420
+ (kept) => kept.hostTime >= frame.hostTime - Duration.toMillis(options.frameHistory),
421
+ ),
422
+ frame,
423
+ ];
496
424
  for (const subscriber of current.subscribers)
497
425
  Queue.offerUnsafe(subscriber, { _tag: "Frame", sequence: delivered, frame });
498
426
  };
499
427
 
500
- const sizes = yield* sizeFilter(options, deliver, (frames) =>
501
- counts.count("foreignSize", frames),
428
+ const resized = yield* Queue.sliding<Size>(1);
429
+
430
+ const sizes = yield* sizeFilter(
431
+ options,
432
+ deliver,
433
+ (frames) => counts.count("foreignSize", frames),
434
+ (size) => {
435
+ Queue.offerUnsafe(resized, size);
436
+ },
502
437
  );
503
438
 
504
439
  // On air a capture runs for hours, and its frames are timed by the browser's newest estimate,
@@ -506,11 +441,10 @@ export const make = (options: Options) =>
506
441
  const renewing = yield* renewals(options);
507
442
 
508
443
  const notifyFailure = (current: Generation, failure: BrowserError) => {
509
- if (current.failure !== undefined) return;
510
- current.failure = failure;
444
+ if (failureOf(current.state) !== undefined) return;
511
445
  for (const subscriber of current.subscribers)
512
446
  Queue.offerUnsafe(subscriber, { _tag: "Failure", error: failure });
513
- stop(current);
447
+ stop(current, failure);
514
448
  };
515
449
 
516
450
  const failed = (current: Generation) => (cause: unknown) =>
@@ -522,21 +456,16 @@ export const make = (options: Options) =>
522
456
  const startNative = (current: Generation) =>
523
457
  pictures.track(
524
458
  "screencast start",
525
- current.transport.start({
526
- format: "jpeg",
527
- quality: current.quality,
528
- ...(current.size === null
529
- ? {}
530
- : { maxWidth: current.size.width, maxHeight: current.size.height }),
531
- }),
459
+ current.transport.start(settingsOf(current)),
532
460
  failed(current),
533
461
  );
534
462
 
535
- const stop = (current: Generation) => {
536
- if (current.phase === "Stopped") return;
537
- const paused = current.phase === "Paused";
463
+ const stop = (current: Generation, failure?: BrowserError) => {
464
+ const stopped = current.state._tag === "Stopped";
465
+ const paused = current.state._tag === "Paused";
538
466
 
539
- current.phase = "Stopped";
467
+ current.state = step(current.state, { _tag: "Stop", failure });
468
+ if (stopped) return;
540
469
  sizes.end();
541
470
  current.unlisten();
542
471
  // A paused capture already owns its stop, including a reply still in flight.
@@ -551,11 +480,6 @@ export const make = (options: Options) =>
551
480
  .wait("screencast stop")
552
481
  .pipe(Effect.catch((error) => Effect.sync(() => notifyFailure(current, error))));
553
482
 
554
- const healthy = (current: Generation) =>
555
- Effect.suspend(() =>
556
- current.failure === undefined ? Effect.void : Effect.fail(current.failure),
557
- );
558
-
559
483
  const pictures = Quiescence.make({
560
484
  clock: options.clock,
561
485
  error: options.error,
@@ -566,8 +490,8 @@ export const make = (options: Options) =>
566
490
  },
567
491
  pause: (current): Effect.Effect<void, BrowserError> =>
568
492
  Effect.gen(function* () {
569
- if (current?.phase !== "Capturing" || current.failure !== undefined) return;
570
- current.phase = "Paused";
493
+ if (current?.state._tag !== "Capturing") return;
494
+ current.state = step(current.state, { _tag: "Pause" });
571
495
  latest = Option.none();
572
496
  sizes.end();
573
497
  void stopNative(current);
@@ -583,11 +507,9 @@ export const make = (options: Options) =>
583
507
  if (current.subscribers.size === 0) {
584
508
  stop(current);
585
509
  generation = undefined;
586
-
587
- return false;
588
510
  }
589
511
 
590
- return current.phase !== "Stopped" && current.failure === undefined && !isClosed();
512
+ return current.state._tag !== "Stopped" && !isClosed();
591
513
  };
592
514
 
593
515
  if (current === undefined || !resumable()) return;
@@ -601,13 +523,15 @@ export const make = (options: Options) =>
601
523
  if (!resumable()) return;
602
524
  sizes.restart(viewport);
603
525
  // Its only quiet-page frame can precede the native start acknowledgement.
604
- current.phase = "Capturing";
526
+ current.state = step(current.state, { _tag: "Resume" });
605
527
  void startNative(current);
606
528
  yield* pictures.wait("screencast start");
607
529
  yield* healthy(current);
608
530
  }),
609
531
  });
610
532
 
533
+ yield* followGrowth(resized, lock, () => generation, pictures, notifyFailure);
534
+
611
535
  // A reader leaves; the last one stops its generation.
612
536
  const leave = (current: Generation, subscription: Queue.Queue<Envelope>) =>
613
537
  Effect.gen(function* () {
@@ -621,110 +545,109 @@ export const make = (options: Options) =>
621
545
 
622
546
  const acquire = (screencast: ScreencastOptions) =>
623
547
  lock.withPermits(1)(
624
- Effect.gen(function* () {
625
- if (isClosed()) return yield* gone();
626
- let current = generation;
627
- const starting = current === undefined;
628
-
629
- if (current === undefined) {
630
- yield* pictures.idle;
631
- const [transport, { calibration, viewport }] = yield* prepare(options, screencast);
632
- const size = screencast.size ?? viewport;
633
-
548
+ Effect.uninterruptible(
549
+ Effect.gen(function* () {
634
550
  if (isClosed()) return yield* gone();
635
-
636
- current = {
637
- subscribers: new Set(),
638
- transport,
639
- unlisten: () => undefined,
640
- calibration,
641
- quality: screencast.quality ?? 80,
642
- size,
643
- phase: "Capturing",
644
- predecessor: undefined,
645
- failure: undefined,
646
- };
647
-
648
- generation = current;
649
- latest = Option.none();
650
- sizes.restart(viewport);
651
- } else if (
652
- (screencast.quality !== undefined && screencast.quality !== current.quality) ||
653
- (screencast.size !== undefined &&
654
- (screencast.size.width !== current.size?.width ||
655
- screencast.size.height !== current.size.height))
656
- )
657
- // One native capture serves every reader; silently giving a reader other settings
658
- // than it asked for would misstate its frames.
659
- return yield* undispatched(
660
- "screencast",
661
- new InvalidRequest({
662
- detail: `a screencast with quality ${current.quality}${
663
- current.size === null
664
- ? ""
665
- : ` and size ${current.size.width}x${current.size.height}`
666
- } is already running on this page; read it without options or with the same ones`,
667
- }),
668
- );
669
- // The callback API must apply sliding synchronously; PubSub.publishUnsafe skips it.
670
- const subscription = yield* Queue.sliding<Envelope>(subscriberCapacity);
671
-
672
- current.subscribers.add(subscription);
673
- // A reader that joins a capture that has failed is told as its other readers are.
674
- if (current.failure !== undefined)
675
- Queue.offerUnsafe(subscription, { _tag: "Failure", error: current.failure });
676
- const baseline = delivered;
677
- const frame = currentFrame(current, latest);
678
-
679
- if (starting) {
680
- const listening = current;
681
-
682
- current.unlisten = listening.transport.listen({
683
- frame: receive(options, current, replies, counts, sizes, renewing, notifyFailure),
684
- lost: (error) => notifyFailure(listening, error),
685
- });
686
-
687
- const screencast = Effect.promise(() => startNative(listening)).pipe(
688
- Effect.andThen(healthy(listening)),
689
- );
690
-
691
- const started = yield* options.watch.pipe(
692
- Effect.zip(screencast, { concurrent: true }),
693
- Effect.interruptible,
694
- Effect.timeoutOrElse({
695
- duration: deadline,
696
- orElse: () =>
697
- Effect.fail(options.error(new Error("screencast start exceeded its deadline"))),
698
- }),
699
- Effect.provideService(Clock.Clock, options.clock),
700
- Effect.exit,
701
- );
702
-
703
- if (Exit.isFailure(started)) {
704
- yield* leave(current, subscription);
705
-
706
- return yield* Effect.failCause(started.cause);
551
+ let current = generation;
552
+ const starting = current === undefined;
553
+
554
+ if (current === undefined) {
555
+ yield* pictures.idle;
556
+ const [transport, { calibration, viewport }] = yield* prepare(options, screencast);
557
+ const size = screencast.size ?? viewport;
558
+
559
+ if (isClosed()) return yield* gone();
560
+
561
+ current = {
562
+ id: ++generations,
563
+ sequence: 0,
564
+ subscribers: new Set(),
565
+ transport,
566
+ unlisten: () => undefined,
567
+ calibration,
568
+ quality: screencast.quality ?? 80,
569
+ size,
570
+ explicitSize: screencast.size !== undefined,
571
+ state: initial,
572
+ predecessor: undefined,
573
+ };
574
+
575
+ generation = current;
576
+ latest = Option.none();
577
+ sizes.restart(viewport);
578
+ } else if (
579
+ (screencast.quality !== undefined && screencast.quality !== current.quality) ||
580
+ (screencast.size !== undefined &&
581
+ (screencast.size.width !== current.size?.width ||
582
+ screencast.size.height !== current.size.height))
583
+ )
584
+ // One native capture serves every reader; silently giving a reader other settings
585
+ // than it asked for would misstate its frames.
586
+ return yield* undispatched(
587
+ "screencast",
588
+ new InvalidRequest({
589
+ detail: `a screencast with quality ${current.quality}${
590
+ current.size === null
591
+ ? ""
592
+ : ` and size ${current.size.width}x${current.size.height}`
593
+ } is already running on this page; read it without options or with the same ones`,
594
+ }),
595
+ );
596
+ // The callback API must apply sliding synchronously; PubSub.publishUnsafe skips it.
597
+ const subscription = yield* subscribe(current);
598
+ const baseline = delivered;
599
+ const frame = currentFrame(current, latest);
600
+
601
+ if (starting) {
602
+ const listening = current;
603
+
604
+ current.unlisten = listening.transport.listen({
605
+ frame: receive(options, current, replies, counts, sizes, renewing, notifyFailure),
606
+ lost: (error) => notifyFailure(listening, error),
607
+ });
608
+
609
+ const screencast = Effect.promise(() => startNative(listening)).pipe(
610
+ Effect.andThen(healthy(listening)),
611
+ );
612
+
613
+ const started = yield* options.watch.pipe(
614
+ Effect.zip(screencast, { concurrent: true }),
615
+ Effect.interruptible,
616
+ Effect.timeoutOrElse({
617
+ duration: deadline,
618
+ orElse: () =>
619
+ Effect.fail(options.error(new Error("screencast start exceeded its deadline"))),
620
+ }),
621
+ Effect.provideService(Clock.Clock, options.clock),
622
+ Effect.exit,
623
+ );
624
+
625
+ if (Exit.isFailure(started)) {
626
+ yield* leave(current, subscription);
627
+
628
+ return yield* Effect.failCause(started.cause);
629
+ }
707
630
  }
708
- }
709
-
710
- return { current, subscription, baseline, frame };
711
- }),
712
- );
713
631
 
714
- const open: Controller["open"] = (screencast = {}) =>
715
- Effect.acquireRelease(acquire(screencast), ({ current, subscription }) =>
716
- Effect.sync(() => current.subscribers.delete(subscription)).pipe(
717
- Effect.andThen(lock.withPermits(1)(leave(current, subscription))),
632
+ return { current, subscription, baseline, frame };
633
+ }),
718
634
  ),
719
- ).pipe(
720
- Effect.map((lease) => ({
721
- current: lease.frame,
722
- stream: frames(lease.subscription, lease.baseline, why, (count) =>
723
- counts.count("lost", count),
724
- ),
725
- })),
726
635
  );
727
636
 
637
+ const open = reader(
638
+ acquire,
639
+ ({ current, subscription }) =>
640
+ Effect.suspend(() => {
641
+ current.subscribers.delete(subscription);
642
+
643
+ return current.subscribers.size > 0
644
+ ? Queue.shutdown(subscription)
645
+ : lock.withPermits(1)(leave(current, subscription));
646
+ }),
647
+ why,
648
+ (count) => counts.count("lost", count),
649
+ );
650
+
728
651
  // The page's scope closes once the page has gone, when its browser's loss, if any, is known.
729
652
  yield* Effect.addFinalizer(() =>
730
653
  Effect.sync(() => Deferred.doneUnsafe(closed, Exit.void)).pipe(
@@ -749,12 +672,12 @@ export const make = (options: Options) =>
749
672
  Stream.unwrap(Effect.map(open(options), ({ stream }) => stream)),
750
673
  latest: Effect.sync(() => latest),
751
674
  recent: Effect.sync(() => history),
752
- active: Effect.sync(() => generation !== undefined && generation.phase !== "Stopped"),
675
+ active: Effect.sync(() => generation !== undefined && generation.state._tag !== "Stopped"),
753
676
  sync: Effect.suspend(() => synced(generation, why, options.error)),
754
- current,
677
+ current: (frame: Frame) => isCurrent(frame, generation, latest),
755
678
  confirm: confirmation(
756
679
  () => ({ generation, replies: replies.size }),
757
- current,
680
+ (frame: Frame) => isCurrent(frame, generation, latest),
758
681
  why,
759
682
  options.error,
760
683
  ),