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
@@ -7,22 +7,23 @@
7
7
  * read of a page's changes, its session registers the recorder too, so every later document
8
8
  * records from its start.
9
9
  */
10
- import { Effect, Schema, SynchronizedRef } from "effect";
10
+ import { Deferred, Effect, Schema, SynchronizedRef } from "effect";
11
11
 
12
12
  import { type BrowserError, Failed } from "../../BrowserError.ts";
13
13
  import { Navigated, PageLoaded } from "../../BrowserEvent.ts";
14
+ import { match } from "../../Matching.ts";
15
+ import * as Url from "../../Url.ts";
14
16
  import { edit, type Edit } from "../input/edit.inpage.ts";
15
17
  import { evidence } from "../input/evidence.inpage.ts";
16
18
  import { guard, type Guard } from "../input/guard.inpage.ts";
17
19
  import { targets, type Targets } from "../input/targets.inpage.ts";
18
20
  import { context } from "../reading/context.inpage.ts";
19
- import { controls, type Controls } from "../reading/controls.inpage.ts";
21
+ import { controls } from "../reading/controls.inpage.ts";
20
22
  import { expectations, type Expectations } from "../reading/expect.inpage.ts";
21
- import { match } from "../reading/match.inpage.ts";
22
- import { names } from "../reading/names.inpage.ts";
23
+ import { elements, names } from "../reading/names.inpage.ts";
23
24
  import { outline, type Outline } from "../reading/outline.inpage.ts";
24
25
  import { ready } from "../reading/ready.inpage.ts";
25
- import { subjects, type Subjects } from "../reading/subjects.inpage.ts";
26
+ import { states, subjects, type Subjects } from "../reading/subjects.inpage.ts";
26
27
  import { text, type Texts } from "../reading/text.inpage.ts";
27
28
  import { walk } from "../reading/walk.inpage.ts";
28
29
  import { changes, type Changes } from "../timeline/changes.inpage.ts";
@@ -31,18 +32,20 @@ import { history } from "../timeline/history.inpage.ts";
31
32
  import { marks } from "../timeline/marks.inpage.ts";
32
33
  import { record, type Recorder } from "../timeline/record.inpage.ts";
33
34
  import { sight } from "../timeline/sight.inpage.ts";
34
- import { contextGone, failWith, type PageContext, undispatched } from "./context.ts";
35
- import * as Url from "./url.ts";
35
+ import { contextGone, decodeWith, failWith, type PageContext } from "./context.ts";
36
+ import { Script } from "./port.ts";
36
37
 
37
38
  /** What the script installs: a version, and a function of one of its parts for each call. */
38
39
  export interface PageApi {
39
40
  readonly version: number;
41
+ readonly refs: { next: number };
42
+ dispose: () => void;
40
43
  snapshot: Outline["snapshot"];
41
44
  find: Subjects["find"];
42
45
  until: Expectations["until"];
43
- waitUntil: Controls["waitUntil"];
44
46
  text: Texts["read"];
45
47
  record: Recorder["start"];
48
+ stopRecord: Recorder["stop"];
46
49
  changes: Changes["read"];
47
50
  ready: ReturnType<typeof ready>["wait"];
48
51
  settle: ReturnType<typeof ready>["settle"];
@@ -64,58 +67,83 @@ declare global {
64
67
  var __effectBrowser: PageApi | undefined;
65
68
  }
66
69
 
67
- // Like the parts it receives, this is evaluated from its source text.
68
- const install = (
69
- makeNames: typeof names,
70
- makeWalk: typeof walk,
71
- makeMatch: typeof match,
72
- makeContext: typeof context,
73
- makeSubjects: typeof subjects,
74
- makeExpectations: typeof expectations,
75
- makeText: typeof text,
76
- makeControls: typeof controls,
77
- makeFold: typeof fold,
78
- makeHistory: typeof history,
79
- makeSight: typeof sight,
80
- makeMarks: typeof marks,
81
- makeRecord: typeof record,
82
- makeChanges: typeof changes,
83
- makeReady: typeof ready,
84
- makeOutline: typeof outline,
85
- makeTargets: typeof targets,
86
- makeEvidence: typeof evidence,
87
- makeGuard: typeof guard,
88
- makeEdit: typeof edit,
89
- makeAddresses: typeof Url.addresses,
90
- ): PageApi => {
70
+ /** Named factories make the composition contract independent of their declaration order. */
71
+ export const parts = {
72
+ elements,
73
+ names,
74
+ walk,
75
+ match,
76
+ context,
77
+ subjects,
78
+ states,
79
+ expectations,
80
+ text,
81
+ controls,
82
+ fold,
83
+ history,
84
+ sight,
85
+ marks,
86
+ record,
87
+ changes,
88
+ ready,
89
+ outline,
90
+ targets,
91
+ evidence,
92
+ guard,
93
+ edit,
94
+ addresses: Url.addresses,
95
+ };
96
+
97
+ // Like the parts it receives, this is evaluated from its source text. The named function also
98
+ // hashes its own source, so changing the composition invalidates an installation too.
99
+ type Parts = typeof parts;
100
+
101
+ export function install(parts: Parts): PageApi {
102
+ const source =
103
+ install.toString() +
104
+ Object.entries(parts)
105
+ .map(([name, factory]) => name + factory.toString())
106
+ .join("");
107
+
108
+ let version = 0x811c9dc5;
109
+
110
+ for (let index = 0; index < source.length; index++)
111
+ version = Math.imul(version ^ source.charCodeAt(index), 0x01000193);
112
+ version >>>= 0;
91
113
  const installed = globalThis.__effectBrowser;
92
114
 
93
- if (installed !== undefined && installed.version === 20) return installed;
94
- const named = makeNames();
95
- const walked = makeWalk(named);
96
- const placing = makeContext(named, walked);
97
- const subjected = makeSubjects(named, walked, makeMatch(), placing);
98
- const texts = makeText(named, walked);
99
- const controlled = makeControls(named, walked, subjected, texts);
100
- const kept = makeHistory(makeFold());
101
- const seeing = makeSight(named, walked, texts, kept);
102
- const marking = makeMarks(named, kept, seeing);
103
- const recorder = makeRecord(named, texts, kept, seeing, marking);
104
- const read = makeOutline(named, walked, subjected, texts, controlled, makeAddresses());
105
- const located = makeTargets(named, walked, placing);
106
- const guarded = makeGuard(named, located, makeEvidence(named, placing));
107
- const edited = makeEdit(named, guarded, placing);
108
- const readiness = makeReady(walked, texts, kept, recorder);
115
+ if (installed !== undefined && installed.version === version) return installed;
116
+ installed?.dispose?.();
117
+ const named = parts.names(parts.elements());
118
+
119
+ if (installed?.refs !== undefined) named.refs.next = installed.refs.next;
120
+ const walked = parts.walk(named);
121
+ const placing = parts.context(named, walked);
122
+ const matching = parts.match();
123
+ const subjected = parts.subjects(named, walked, matching, placing, parts.states(named));
124
+ const texts = parts.text(named, walked);
125
+ const controlled = parts.controls(named, subjected, texts);
126
+ const kept = parts.history(parts.fold());
127
+ const seeing = parts.sight(named, walked, texts, kept);
128
+ const marking = parts.marks(named, kept, seeing);
129
+ const recorder = parts.record(named, texts, kept, seeing, marking);
130
+ const read = parts.outline(named, walked, subjected, texts, controlled, parts.addresses());
131
+ const located = parts.targets(named, walked, placing);
132
+ const guarded = parts.guard(named, located, parts.evidence(named, placing));
133
+ const edited = parts.edit(named, guarded, placing);
134
+ const readiness = parts.ready(walked, texts, kept);
109
135
 
110
136
  const api: PageApi = {
111
- version: 20,
137
+ version,
138
+ refs: named.refs,
139
+ dispose: () => recorder.stop(),
112
140
  snapshot: read.snapshot,
113
141
  find: subjected.find,
114
- until: makeExpectations(named, subjected).until,
115
- waitUntil: controlled.waitUntil,
142
+ until: parts.expectations(named, subjected, matching).until,
116
143
  text: texts.read,
117
144
  record: recorder.start,
118
- changes: makeChanges(named, placing, kept, seeing, marking, recorder).read,
145
+ stopRecord: recorder.stop,
146
+ changes: parts.changes(named, placing, kept, seeing, marking, recorder).read,
119
147
  ready: readiness.wait,
120
148
  settle: readiness.settle,
121
149
  point: located.point,
@@ -133,10 +161,12 @@ const install = (
133
161
  globalThis.__effectBrowser = api;
134
162
 
135
163
  return api;
136
- };
164
+ }
137
165
 
138
- /** The expression that installs the script and evaluates to its API. */
139
- export const installSource = `(${install.toString()})(${[names, walk, match, context, subjects, expectations, text, controls, fold, history, sight, marks, record, changes, ready, outline, targets, evidence, guard, edit, Url.addresses].join(", ")})`;
166
+ /** The expression that installs the script and evaluates to its API; packaging freezes it. */
167
+ export const installSource = `(${install.toString()})({${Object.entries(parts)
168
+ .map(([name, factory]) => `${name}: ${factory.toString()}`)
169
+ .join(", ")}})`;
140
170
 
141
171
  const worldName = "effect-browser";
142
172
 
@@ -146,10 +176,17 @@ const recorderSource = `if (globalThis === globalThis.top) globalThis.__effectBr
146
176
  // What a call reads in a world without the script's API. A context id can name another world once
147
177
  // the page has moved to a new process, so a cached id that reads this is not the library's world.
148
178
  const missing = "effect-browser: no __effectBrowser in this world";
179
+ const missingSource = Schema.encodeSync(Schema.fromJsonString(Schema.String))(missing);
149
180
 
150
181
  const isMissing = (error: BrowserError) =>
151
182
  error.reason._tag === "Failed" && error.reason.detail === missing;
152
183
 
184
+ const Evaluated = Schema.Struct({
185
+ value: Schema.optionalKey(Schema.Unknown),
186
+ error: Schema.optionalKey(Schema.String),
187
+ nextRef: Schema.Finite,
188
+ });
189
+
153
190
  /** A frame as a page session reports its commit. */
154
191
  export const Commit = Schema.Struct({
155
192
  parentId: Schema.optionalKey(Schema.String),
@@ -188,19 +225,102 @@ export const mainFrame = (page: string, event: typeof MainFrameEvent.Type) =>
188
225
  export const scriptCall = (name: string, ...args: ReadonlyArray<unknown>): string =>
189
226
  `${name}(${args.map((arg) => JSON.stringify(arg)).join(", ")})`;
190
227
 
191
- export const make = Effect.fnUntraced(function* (page: PageContext) {
192
- const { id, cdp, native, span, publish, now } = page;
228
+ const runIn = (page: PageContext, operation: string, expression: string, contextId: number) =>
229
+ page
230
+ .native(operation, () =>
231
+ page.protocol.send("Runtime.evaluate", {
232
+ contextId,
233
+ expression,
234
+ returnByValue: true,
235
+ awaitPromise: true,
236
+ }),
237
+ )
238
+ .pipe(
239
+ Effect.flatMap(({ result, exceptionDetails: thrown }) =>
240
+ thrown === undefined
241
+ ? Effect.succeed<unknown>(result.value)
242
+ : failWith(
243
+ operation,
244
+ new Failed({ detail: thrown.exception?.description ?? thrown.text }),
245
+ ),
246
+ ),
247
+ );
248
+
249
+ /** Session-owned registrations; the recorder can expire independently of the page script. */
250
+ const registrationFor = Effect.fnUntraced(function* (page: PageContext) {
251
+ const { native, span } = page;
193
252
  const { send } = page.protocol;
253
+
194
254
  // How far this session has registered: the script, then the recorder, which the first read of
195
255
  // changes asks for. One caller takes each step, once, while the others wait.
196
- const registration = yield* SynchronizedRef.make<"none" | "script" | "recorder">("none");
256
+ const registration = yield* SynchronizedRef.make<{
257
+ readonly script: boolean;
258
+ readonly recorder?: string | undefined;
259
+ }>({ script: false });
260
+
261
+ // The registration belongs to this session and the world to the page, so a session that attaches
262
+ // later, as after a reconnect, registers again and finds the script already installed. With the
263
+ // Page domain enabled, a source runs in each new document, in the order registered;
264
+ // `runImmediately` runs it now.
265
+ const addScript = (operation: string, source: string) =>
266
+ native(operation, () =>
267
+ send("Page.addScriptToEvaluateOnNewDocument", { source, worldName, runImmediately: true }),
268
+ );
269
+
270
+ const register = (operation: string) =>
271
+ Effect.all(
272
+ [
273
+ page.paging(operation),
274
+ addScript(operation, `if (globalThis === globalThis.top) ${installSource};`),
275
+ ],
276
+ { concurrency: "unbounded" },
277
+ ).pipe(span("Page.register", {}, "Debug"));
278
+
279
+ /** Register the script once; the change-reader lifetime owns its removable registration. */
280
+ const ensure = (operation: string, recorder: boolean) =>
281
+ SynchronizedRef.updateEffect(registration, (state) =>
282
+ Effect.gen(function* () {
283
+ if (!state.script) yield* register(operation);
284
+ if (recorder && state.recorder === undefined) {
285
+ const registered = yield* addScript(operation, recorderSource);
286
+
287
+ return { script: true, recorder: registered.identifier };
288
+ }
289
+
290
+ return { ...state, script: true };
291
+ }),
292
+ );
293
+
294
+ const removeRecorder = (operation: string) =>
295
+ SynchronizedRef.updateEffect(registration, (state) => {
296
+ const identifier = state.recorder;
297
+
298
+ return identifier === undefined
299
+ ? Effect.succeed(state)
300
+ : native(operation, () =>
301
+ send("Page.removeScriptToEvaluateOnNewDocument", { identifier }),
302
+ ).pipe(Effect.as({ script: true }));
303
+ });
304
+
305
+ return { ensure, removeRecorder };
306
+ });
307
+
308
+ export const make = Effect.fnUntraced(function* (page: PageContext) {
309
+ const { id, cdp, native, span, publish, now } = page;
310
+ const { send } = page.protocol;
311
+ const { ensure, removeRecorder } = yield* registrationFor(page);
312
+
197
313
  // The current document's world, forgotten when the main frame commits another document; the
198
314
  // commits this session has seen, the latest marked on the page; the page's address; and how far
199
315
  // the current document has loaded.
200
316
  let world: number | undefined;
201
317
  let documents = 0;
318
+ let nextDocument = Deferred.makeUnsafe<void>();
202
319
  let url = Url.redact(page.url);
203
320
  let loaded: PageLoaded | undefined;
321
+ // Every script call can allocate refs (including guards and point input), so the bridge,
322
+ // rather than individual readers, owns the floor across the page's documents.
323
+ let nextRef = 1;
204
324
  // The latest commits' loaders and the documents they began, newest last: a capture connection
205
325
  // sees the same commits, and numbers its frames by them.
206
326
  const loaders = new Map<string, number>();
@@ -219,6 +339,8 @@ export const make = Effect.fnUntraced(function* (page: PageContext) {
219
339
  page.activity.documentAt = now();
220
340
  world = undefined;
221
341
  loaded = undefined;
342
+ Deferred.doneUnsafe(nextDocument, Effect.void);
343
+ nextDocument = Deferred.makeUnsafe<void>();
222
344
  }
223
345
  url = seen.url;
224
346
  const sameDocument = seen.loader === undefined;
@@ -256,41 +378,6 @@ export const make = Effect.fnUntraced(function* (page: PageContext) {
256
378
  /** The document the main frame's latest commit of `loader` began, if this session counted it. */
257
379
  const documentOf = (loader: string) => loaders.get(loader);
258
380
 
259
- // The registration belongs to this session and the world to the page, so a session that attaches
260
- // later, as after a reconnect, registers again and finds the script already installed. With the
261
- // Page domain enabled, a source runs in each new document, in the order registered;
262
- // `runImmediately` runs it now.
263
- const addScript = (operation: string, source: string) =>
264
- native(operation, () =>
265
- send("Page.addScriptToEvaluateOnNewDocument", { source, worldName, runImmediately: true }),
266
- );
267
-
268
- const register = (operation: string) =>
269
- Effect.all(
270
- [
271
- page.paging(operation),
272
- addScript(operation, `if (globalThis === globalThis.top) ${installSource};`),
273
- ],
274
- { concurrency: "unbounded" },
275
- ).pipe(span("Page.register", {}, "Debug"));
276
-
277
- /** Take registration from `from` to `to` by `step`, unless it is past `from` already. */
278
- const advance = (
279
- from: "none" | "script",
280
- to: "script" | "recorder",
281
- step: Effect.Effect<unknown, BrowserError>,
282
- ) =>
283
- SynchronizedRef.updateEffect(registration, (state) =>
284
- state === from ? Effect.as(step, to) : Effect.succeed(state),
285
- );
286
-
287
- /** Register the script once, and the recorder after it once a read of changes asks for it. */
288
- const ensure = (operation: string, recorder: boolean) =>
289
- Effect.andThen(
290
- advance("none", "script", register(operation)),
291
- recorder ? advance("script", "recorder", addScript(operation, recorderSource)) : Effect.void,
292
- );
293
-
294
381
  const createWorld = (operation: string) =>
295
382
  Effect.gen(function* () {
296
383
  yield* ensure(operation, false);
@@ -318,31 +405,34 @@ export const make = Effect.fnUntraced(function* (page: PageContext) {
318
405
  ).pipe(Effect.map((created) => created.executionContextId));
319
406
 
320
407
  const run = (operation: string, expression: string, contextId: number) =>
321
- native(operation, () =>
322
- send("Runtime.evaluate", { contextId, expression, returnByValue: true, awaitPromise: true }),
323
- ).pipe(
324
- Effect.flatMap(({ result, exceptionDetails: thrown }) =>
325
- thrown === undefined
326
- ? Effect.succeed<unknown>(result.value)
327
- : failWith(
328
- operation,
329
- new Failed({ detail: thrown.exception?.description ?? thrown.text }),
330
- ),
331
- ),
332
- );
408
+ runIn(page, operation, expression, contextId);
333
409
 
334
410
  const evaluateIn = (operation: string, call: string, contextId: number) =>
335
- run(
336
- operation,
337
- `globalThis.__effectBrowser === undefined ? ${JSON.stringify(missing)} : globalThis.__effectBrowser.${call}`,
338
- contextId,
339
- ).pipe(
340
- Effect.filterOrFail(
341
- (value) => value !== missing,
342
- () => undispatched(operation, new Failed({ detail: missing })),
343
- ),
411
+ Effect.gen(function* () {
412
+ const result = yield* run(
413
+ operation,
414
+ `(async () => {
415
+ const api = globalThis.__effectBrowser;
416
+ if (api === undefined) return ${missingSource};
417
+ api.refs.next = Math.max(api.refs.next, ${nextRef});
418
+ try { return { value: await globalThis.__effectBrowser.${call}, nextRef: api.refs.next }; }
419
+ catch (error) { return { error: error instanceof Error ? error.message : String(error), nextRef: api.refs.next }; }
420
+ })()`,
421
+ contextId,
422
+ );
423
+
424
+ if (result === missing) return yield* failWith(operation, new Failed({ detail: missing }));
425
+ const evaluated = yield* decodeWith(operation, Evaluated)(result);
426
+
427
+ nextRef = Math.max(nextRef, evaluated.nextRef);
428
+
429
+ return evaluated.error === undefined
430
+ ? evaluated.value
431
+ : yield* failWith(operation, new Failed({ detail: evaluated.error }));
432
+ }).pipe(
344
433
  // One round trip to the page. Its arguments can hold typed text, so only the call is named.
345
434
  span("Page.evaluate", { function: call.split("(")[0] }, "Trace"),
435
+ Effect.provideService(Script, call.split("(")[0]),
346
436
  );
347
437
 
348
438
  // Ordinary reads can recreate a document's world. Approval validation deliberately cannot. A
@@ -379,12 +469,18 @@ export const make = Effect.fnUntraced(function* (page: PageContext) {
379
469
  evaluateIn,
380
470
  evaluateWithContext,
381
471
  currentDocument,
472
+ /** Wait for the owning protocol session to observe a replacement before retrying its read. */
473
+ waitForDocument: (before: number) =>
474
+ Effect.suspend(() => (documents === before ? Deferred.await(nextDocument) : Effect.void)),
382
475
  frameTag,
383
476
  documentOf,
384
477
  /** How far the current document has loaded, as this session heard; nothing until parsed. */
385
478
  loaded: () => loaded,
386
479
  /** Register the recorder, so every later document records from its start. */
387
480
  registerRecorder: (operation: string) => ensure(operation, true),
481
+ /** Stop future documents and the current recorder at the host idle deadline. */
482
+ unregisterRecorder: (operation: string) =>
483
+ removeRecorder(operation).pipe(Effect.andThen(evaluate(operation, scriptCall("stopRecord")))),
388
484
  };
389
485
  });
390
486
 
@@ -17,25 +17,18 @@ import {
17
17
  import type { CDPSession, Page as PlaywrightPage } from "playwright-core";
18
18
 
19
19
  import type { CaptureSource } from "../../Browser.ts";
20
- import {
21
- BrowserError,
22
- Closed,
23
- Failed,
24
- InvalidRequest,
25
- type Reason,
26
- Timeout,
27
- } from "../../BrowserError.ts";
20
+ import * as Errors from "../../BrowserError.ts";
28
21
  import type { BrowserEvent } from "../../BrowserEvent.ts";
22
+ import * as BrowserClock from "../../Clock.ts";
29
23
  import type { InputGuard, Point } from "../../Page.ts";
30
24
  import type { Gate } from "../input/gate.ts";
31
- import { Current } from "../input/replies.ts";
32
- import * as BrowserClock from "../pictures/clock.ts";
33
25
  import * as Lane from "./lane.ts";
34
26
  import type { Openings } from "./openings.ts";
35
- import * as Url from "./url.ts";
27
+ import * as Port from "./port.ts";
28
+ import { Current } from "./replies.ts";
36
29
 
37
30
  /** Why a page is gone. */
38
- export type ClosedCause = Closed["cause"];
31
+ export type ClosedCause = Errors.Closed["cause"];
39
32
 
40
33
  /** What every page of a browser shares, from its options. */
41
34
  export interface Settings {
@@ -58,6 +51,7 @@ export interface MakeOptions {
58
51
  readonly url: string;
59
52
  readonly playwright: PlaywrightPage;
60
53
  readonly cdp: CDPSession;
54
+ readonly nativePort?: Port.Hooks["native"] | undefined;
61
55
  /** A call's reply, or a failure as for a closed page once the browser is lost first. */
62
56
  readonly untilLost: <A>(reply: Promise<A>) => Promise<A>;
63
57
  readonly settings: Settings;
@@ -72,58 +66,19 @@ export interface MakeOptions {
72
66
  /** Registration of the actual popups this page's current input opened. */
73
67
  readonly openings: Openings;
74
68
  /** Succeeds once the page's own session holds focus emulation, which keeps it painting behind. */
75
- readonly focused: Effect.Effect<void, BrowserError>;
69
+ readonly focused: Effect.Effect<void, Errors.BrowserError>;
76
70
  /** Succeeds once the page's own session has the Page domain on, so it sees every later commit. */
77
- readonly paging: (operation: string) => Effect.Effect<void, BrowserError>;
71
+ readonly paging: (operation: string) => Effect.Effect<void, Errors.BrowserError>;
78
72
  /** Why the page is gone, once it is: its browser's loss, else its own close or crash. */
79
73
  readonly closedBy: () => ClosedCause;
80
74
  /** Where the page's screencast runs, if not on its own session. */
81
75
  readonly capture?: CaptureSource | undefined;
82
76
  }
83
77
 
84
- const messageOf = (cause: unknown): string =>
85
- cause instanceof Error ? cause.message : typeof cause === "string" ? cause : "unknown error";
86
-
87
- const closedPattern =
88
- /has been closed|Target closed|Session closed|browser has disconnected|Target page, context or browser/i;
89
-
90
- /**
91
- * Map a Playwright or protocol failure to a reason, `Closed` with `closed` as its cause for a page
92
- * or browser that is gone. A call that gives Playwright a timeout passes the same bound, so its
93
- * `Timeout` reports it; without one, Playwright's own message stays.
94
- */
95
- export const reasonOf = (
96
- cause: unknown,
97
- timeoutMillis?: number,
98
- closed: ClosedCause = "connection",
99
- ): Reason => {
100
- const message = messageOf(cause);
101
-
102
- if (closedPattern.test(message)) return new Closed({ cause: closed });
103
- if (cause instanceof Error && cause.name === "TimeoutError" && timeoutMillis !== undefined)
104
- return new Timeout({ millis: timeoutMillis });
105
- const line = message.split("\n")[0] ?? message;
106
-
107
- return new Failed({ detail: Url.redactWithin(line.replace(/^[\w.]+: /, "")) });
108
- };
78
+ export { call, reasonOf, undispatched, failWith, refuse } from "../../BrowserError.ts";
79
+ import { call, failWith, undispatched } from "../../BrowserError.ts";
109
80
 
110
- /**
111
- * One Playwright or protocol call, failing undispatched. A closed page says why it is gone as the
112
- * browser knows then: the library's own calls fail with the browser's loss, and Playwright fails
113
- * its calls on a dropped connection after reporting the context closed.
114
- */
115
- export const call = <A>(
116
- operation: string,
117
- run: () => Promise<A>,
118
- closedBy: () => ClosedCause,
119
- timeoutMillis?: number,
120
- ) =>
121
- Effect.tryPromise({
122
- try: run,
123
- catch: (cause) => undispatched(operation, reasonOf(cause, timeoutMillis, closedBy())),
124
- });
125
-
126
- export const contextGone = (error: BrowserError) =>
81
+ export const contextGone = (error: Errors.BrowserError) =>
127
82
  error.reason._tag === "Failed" &&
128
83
  /Cannot find context|Execution context was destroyed|__effectBrowser|Inspected target navigated/i.test(
129
84
  error.reason.detail,
@@ -157,24 +112,15 @@ const track = <A>(reply: Promise<A>) => Fiber.getCurrent()?.getRef(Current)?.tra
157
112
 
158
113
  // A message's size on the wire, give or take its envelope.
159
114
  const sizeOf = (value: unknown) =>
160
- value === undefined ? 0 : Buffer.byteLength(JSON.stringify(value));
161
-
162
- /** A failure of `operation` before any of its input reached the browser. */
163
- export const undispatched = (operation: string, reason: Reason) =>
164
- new BrowserError({ operation, reason, dispatched: false });
165
-
166
- export const failWith = (operation: string, reason: Reason) =>
167
- Effect.fail(undispatched(operation, reason));
168
-
169
- /** Refuse a request to `operation` that could never succeed, before sending anything. */
170
- export const refuse = (operation: string, detail: string) =>
171
- failWith(operation, new InvalidRequest({ detail }));
115
+ value === undefined ? 0 : new TextEncoder().encode(JSON.stringify(value)).byteLength;
172
116
 
173
117
  export const decodeWith =
174
118
  <A>(operation: string, schema: Schema.Codec<A, unknown>) =>
175
119
  (value: unknown) =>
176
120
  Schema.decodeUnknownEffect(schema)(value).pipe(
177
- Effect.mapError((error) => undispatched(operation, new Failed({ detail: error.message }))),
121
+ Effect.mapError((error) =>
122
+ undispatched(operation, new Errors.Failed({ detail: error.message })),
123
+ ),
178
124
  );
179
125
 
180
126
  export const make = (options: MakeOptions, scope: Scope.Scope) => {
@@ -267,7 +213,9 @@ export const make = (options: MakeOptions, scope: Scope.Scope) => {
267
213
  // Every protocol or Playwright call. Errors are undispatched here; `perform` marks them
268
214
  // dispatched once input has gone out.
269
215
  const native = <A>(operation: string, run: () => Promise<A>, timeoutMillis?: number) =>
270
- call(operation, () => track(run()), options.closedBy, timeoutMillis);
216
+ call(operation, () => options.untilLost(track(run())), options.closedBy, timeoutMillis).pipe(
217
+ Effect.provideService(Port.Operation, operation),
218
+ );
271
219
 
272
220
  /** Fail with `Timeout` once `duration` has passed, the action timeout unless another is given. */
273
221
  const within =
@@ -275,7 +223,8 @@ export const make = (options: MakeOptions, scope: Scope.Scope) => {
275
223
  <A, E, R>(effect: Effect.Effect<A, E, R>) =>
276
224
  Effect.timeoutOrElse(effect, {
277
225
  duration,
278
- orElse: () => failWith(operation, new Timeout({ millis: Duration.toMillis(duration) })),
226
+ orElse: () =>
227
+ failWith(operation, new Errors.Timeout({ millis: Duration.toMillis(duration) })),
279
228
  });
280
229
 
281
230
  // Stop a navigation whose bounded wait failed. The stop and original mutation keep their
@@ -301,9 +250,10 @@ export const make = (options: MakeOptions, scope: Scope.Scope) => {
301
250
  now,
302
251
  actionTimeout: options.settings.actionTimeout,
303
252
  documentAt: () => activity.documentAt,
304
- gone: (operation) => undispatched(operation, new Closed({ cause: options.closedBy() })),
253
+ gone: (operation) => undispatched(operation, new Errors.Closed({ cause: options.closedBy() })),
305
254
  scope,
306
- inputGate: options.inputGate,
255
+ beforeWrite: options.inputGate?.check,
256
+ refusal: options.inputGate?.refused,
307
257
  });
308
258
 
309
259
  // Where this page's latest move left its pointer, which is where its next plain glide starts and
@@ -0,0 +1,58 @@
1
+ /** Scoped dialog responses publish their actual outcome and invalidate their page after failed answers. */
2
+ import { Effect, Queue } from "effect";
3
+ import type { Dialog, Page as PlaywrightPage } from "playwright-core";
4
+
5
+ import type { BrowserError } from "../../BrowserError.ts";
6
+ import * as Events from "../../BrowserEvent.ts";
7
+
8
+ /**
9
+ * What a page's own Playwright events publish, its close and crash aside, while its scope is
10
+ * open. Dialogs are answered: alerts accepted, others dismissed. The page's own session tells its
11
+ * documents' commits and loads.
12
+ */
13
+ export const listen = Effect.fnUntraced(function* (
14
+ playwright: PlaywrightPage,
15
+ page: string,
16
+ publish: (event: Events.BrowserEvent) => number,
17
+ now: () => number,
18
+ answer: (accept: boolean) => Effect.Effect<void, BrowserError>,
19
+ on: { readonly close: () => void; readonly crash: () => void; readonly failed: () => void },
20
+ ) {
21
+ const dialogs = yield* Queue.bounded<Pick<Events.DialogShown, "kind" | "message">>(8);
22
+
23
+ const dialog = (shown: Dialog) => {
24
+ if (!Queue.offerUnsafe(dialogs, { kind: shown.type(), message: shown.message().slice(0, 500) }))
25
+ on.failed();
26
+ };
27
+
28
+ yield* Queue.take(dialogs).pipe(
29
+ Effect.flatMap(({ kind, message }) => {
30
+ const accept = kind === "alert" || kind === "beforeunload";
31
+
32
+ const record = (answer: Events.DialogShown["answer"]) =>
33
+ Effect.sync(() => {
34
+ publish(new Events.DialogShown({ at: now(), page, kind, message, answer }));
35
+ });
36
+
37
+ return answer(accept).pipe(
38
+ Effect.tap(() => record(accept ? "accepted" : "dismissed")),
39
+ Effect.tapError(() => record("failed").pipe(Effect.andThen(Effect.sync(on.failed)))),
40
+ );
41
+ }),
42
+ Effect.forever,
43
+ Effect.forkScoped,
44
+ );
45
+ yield* Effect.acquireRelease(
46
+ Effect.sync(() => {
47
+ playwright.on("close", on.close);
48
+ playwright.on("crash", on.crash);
49
+ playwright.on("dialog", dialog);
50
+ }),
51
+ () =>
52
+ Effect.sync(() => {
53
+ playwright.off("close", on.close);
54
+ playwright.off("crash", on.crash);
55
+ playwright.off("dialog", dialog);
56
+ }),
57
+ );
58
+ });