effect-browser 0.3.0-beta.21 → 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 (248) hide show
  1. package/README.md +130 -159
  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-CiXHT1yO.d.mts → Browser-wZhwZSlG.d.mts} +51 -13
  12. package/dist/Browser.d.mts +2 -2
  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/Matching.d.mts +37 -0
  38. package/dist/Matching.mjs +72 -0
  39. package/dist/Matching.mjs.map +1 -0
  40. package/dist/Page-BF5izr8R.mjs +795 -0
  41. package/dist/Page-BF5izr8R.mjs.map +1 -0
  42. package/dist/{Page-ku6j5t-v.d.mts → Page-CvsOEorc.d.mts} +158 -185
  43. package/dist/Page.d.mts +2 -2
  44. package/dist/Page.mjs +1 -1
  45. package/dist/Released-tURbFmal.d.mts +15 -0
  46. package/dist/{Snapshot-B34hZ4Jl.d.mts → Snapshot-CtBVOtuu.d.mts} +6 -1
  47. package/dist/Snapshot.d.mts +1 -1
  48. package/dist/Snapshot.mjs.map +1 -1
  49. package/dist/Stillness-CNlvayIo.mjs +136 -0
  50. package/dist/Stillness-CNlvayIo.mjs.map +1 -0
  51. package/dist/Style-AO4V7Czt.mjs +357 -0
  52. package/dist/Style-AO4V7Czt.mjs.map +1 -0
  53. package/dist/Style.d.mts +72 -0
  54. package/dist/Style.mjs +2 -0
  55. package/dist/Url.d.mts +26 -0
  56. package/dist/Url.mjs +74 -0
  57. package/dist/Url.mjs.map +1 -0
  58. package/dist/Window-CMddGMt1.d.mts +34 -0
  59. package/dist/Window.d.mts +2 -0
  60. package/dist/Window.mjs +35 -0
  61. package/dist/Window.mjs.map +1 -0
  62. package/dist/{cdp-DL7XfEj5.d.mts → connection-2KHI4_KN.d.mts} +4 -4
  63. package/dist/{cdp-BMpYMWYe.mjs → connection-BTeO0Hiz.mjs} +5 -6
  64. package/dist/connection-BTeO0Hiz.mjs.map +1 -0
  65. package/dist/index.d.mts +15 -18
  66. package/dist/index.mjs +11 -15
  67. package/dist/moment/Moment.d.mts +86 -0
  68. package/dist/{Moment.mjs → moment/Moment.mjs} +44 -38
  69. package/dist/moment/Moment.mjs.map +1 -0
  70. package/dist/{Plan-DJ4hEEna.d.mts → plan/index.d.mts} +169 -64
  71. package/dist/{Plan-BG1WifW2.mjs → plan/index.mjs} +122 -199
  72. package/dist/plan/index.mjs.map +1 -0
  73. package/dist/{Policy-BGWjbqCl.d.mts → policy/Policy.d.mts} +16 -20
  74. package/dist/{Policy.mjs → policy/Policy.mjs} +11 -21
  75. package/dist/policy/Policy.mjs.map +1 -0
  76. package/dist/presentation/Motion.d.mts +12 -0
  77. package/dist/{Motion.mjs → presentation/Motion.mjs} +4 -27
  78. package/dist/presentation/Motion.mjs.map +1 -0
  79. package/dist/presentation/Presentation.d.mts +30 -0
  80. package/dist/presentation/Presentation.mjs +105 -0
  81. package/dist/presentation/Presentation.mjs.map +1 -0
  82. package/dist/{Stage-NHp8N81k.d.mts → presentation/Stage.d.mts} +12 -15
  83. package/dist/{Stage.mjs → presentation/Stage.mjs} +68 -76
  84. package/dist/presentation/Stage.mjs.map +1 -0
  85. package/dist/presentation/feed.d.mts +20 -0
  86. package/dist/presentation/feed.mjs +18 -0
  87. package/dist/presentation/feed.mjs.map +1 -0
  88. package/dist/providers/Cdp.d.mts +9 -0
  89. package/dist/{Cdp.mjs → providers/Cdp.mjs} +3 -8
  90. package/dist/providers/Cdp.mjs.map +1 -0
  91. package/dist/{Chromium.d.mts → providers/Chromium.d.mts} +6 -7
  92. package/dist/{Chromium.mjs → providers/Chromium.mjs} +6 -15
  93. package/dist/providers/Chromium.mjs.map +1 -0
  94. package/dist/providers/Released.d.mts +2 -0
  95. package/dist/providers/Released.mjs +12 -0
  96. package/dist/providers/Released.mjs.map +1 -0
  97. package/dist/stillness/Stillness.d.mts +12 -0
  98. package/dist/stillness/Stillness.mjs +2 -0
  99. package/dist/supervisor/Supervisor.d.mts +104 -0
  100. package/dist/supervisor/Supervisor.mjs +513 -0
  101. package/dist/supervisor/Supervisor.mjs.map +1 -0
  102. package/dist/testing/index.d.mts +337 -0
  103. package/dist/testing/index.mjs +515 -0
  104. package/dist/testing/index.mjs.map +1 -0
  105. package/dist/workerd/Cdp.d.mts +8 -3
  106. package/dist/workerd/Cdp.mjs +2 -7
  107. package/dist/workerd/Cdp.mjs.map +1 -1
  108. package/package.json +86 -36
  109. package/src/Action.ts +127 -0
  110. package/src/ActionPort.ts +128 -0
  111. package/src/Browser.ts +352 -201
  112. package/src/BrowserError.ts +63 -6
  113. package/src/BrowserEvent.ts +26 -25
  114. package/src/Change.ts +0 -2
  115. package/src/{internal/pictures/clock.ts → Clock.ts} +17 -6
  116. package/src/Frame.ts +14 -0
  117. package/src/Geometry.ts +48 -0
  118. package/src/{internal/reading/match.inpage.ts → Matching.ts} +34 -4
  119. package/src/Page.ts +111 -92
  120. package/src/Snapshot.ts +5 -0
  121. package/src/{internal/input/style.ts → Style.ts} +121 -14
  122. package/src/Window.ts +30 -0
  123. package/src/index.ts +15 -6
  124. package/src/internal/input/actions.ts +61 -119
  125. package/src/internal/input/dispatch.ts +3 -3
  126. package/src/internal/input/gate.ts +21 -18
  127. package/src/internal/input/guard.inpage.ts +25 -58
  128. package/src/internal/input/guard.ts +11 -20
  129. package/src/internal/input/keyboard.ts +12 -3
  130. package/src/internal/input/perform.ts +78 -60
  131. package/src/internal/input/pointer.ts +4 -2
  132. package/src/internal/input/settle.ts +7 -5
  133. package/src/internal/input/targets.inpage.ts +1 -1
  134. package/src/internal/input/targets.ts +4 -9
  135. package/src/internal/page/bridge.ts +209 -113
  136. package/src/internal/page/context.ts +12 -59
  137. package/src/internal/page/dialogs.ts +58 -0
  138. package/src/internal/page/lane.ts +14 -15
  139. package/src/internal/page/navigation.ts +50 -42
  140. package/src/internal/page/openings.ts +11 -5
  141. package/src/internal/page/page.ts +44 -81
  142. package/src/internal/page/port.ts +125 -0
  143. package/src/internal/{input → page}/replies.ts +1 -1
  144. package/src/internal/page/request-owner.ts +269 -0
  145. package/src/internal/page/requests.ts +357 -0
  146. package/src/internal/page/scripts.ts +124 -0
  147. package/src/internal/pictures/capture.ts +255 -332
  148. package/src/internal/pictures/dimensions.ts +162 -0
  149. package/src/internal/pictures/frame.ts +68 -0
  150. package/src/internal/pictures/pictures.ts +57 -23
  151. package/src/internal/pictures/quiescence.ts +1 -1
  152. package/src/internal/pictures/state.ts +26 -0
  153. package/src/internal/pictures/transport.ts +21 -4
  154. package/src/internal/reading/controls.inpage.ts +5 -70
  155. package/src/internal/reading/expect.inpage.ts +13 -17
  156. package/src/internal/reading/names.inpage.ts +89 -45
  157. package/src/internal/reading/outline.inpage.ts +6 -7
  158. package/src/internal/reading/reading.ts +144 -176
  159. package/src/internal/reading/ready.inpage.ts +6 -17
  160. package/src/internal/reading/ready.ts +13 -135
  161. package/src/internal/reading/subjects.inpage.ts +83 -43
  162. package/src/internal/reading/walk.inpage.ts +33 -13
  163. package/src/internal/timeline/changes.ts +55 -6
  164. package/src/internal/timeline/events.ts +15 -5
  165. package/src/internal/timeline/history.inpage.ts +1 -1
  166. package/src/internal/timeline/record.inpage.ts +4 -1
  167. package/src/internal/timeline/window.ts +2 -1
  168. package/src/{Moment.ts → moment/Moment.ts} +13 -31
  169. package/src/{internal/timeline → moment}/words.ts +2 -2
  170. package/src/{internal/reading → plan}/choose.ts +3 -3
  171. package/src/plan/data.ts +117 -0
  172. package/src/plan/execute.ts +411 -0
  173. package/src/plan/index.ts +36 -0
  174. package/src/plan/record.ts +71 -0
  175. package/src/plan/targets.ts +71 -0
  176. package/src/{Policy.ts → policy/Policy.ts} +13 -10
  177. package/src/{Motion.ts → presentation/Motion.ts} +12 -46
  178. package/src/presentation/Presentation.ts +176 -0
  179. package/src/{Stage.ts → presentation/Stage.ts} +147 -112
  180. package/src/presentation/feed.ts +21 -0
  181. package/src/{Cdp.ts → providers/Cdp.ts} +2 -2
  182. package/src/{Chromium.ts → providers/Chromium.ts} +7 -10
  183. package/src/providers/Released.ts +13 -0
  184. package/src/{internal/cdp.ts → providers/connection.ts} +2 -2
  185. package/src/{internal/pictures/motion.ts → stillness/Pixels.ts} +1 -1
  186. package/src/stillness/Stillness.ts +166 -0
  187. package/src/supervisor/Supervisor.ts +170 -0
  188. package/src/supervisor/contract.ts +105 -0
  189. package/src/supervisor/lifecycle.ts +272 -0
  190. package/src/supervisor/runtime.ts +234 -0
  191. package/src/testing/TestBrowser.ts +115 -0
  192. package/src/testing/TestPage.ts +10 -0
  193. package/src/testing/evidence.ts +154 -0
  194. package/src/testing/index.ts +3 -0
  195. package/src/testing/model.ts +222 -0
  196. package/src/testing/page.ts +360 -0
  197. package/src/workerd/Cdp.ts +2 -2
  198. package/dist/Browser-CxXUjxOp.mjs +0 -619
  199. package/dist/Browser-CxXUjxOp.mjs.map +0 -1
  200. package/dist/Cdp-CzCRnMlM.d.mts +0 -10
  201. package/dist/Cdp.d.mts +0 -11
  202. package/dist/Cdp.mjs.map +0 -1
  203. package/dist/Change-DNvztNLu.mjs +0 -138
  204. package/dist/Change-DNvztNLu.mjs.map +0 -1
  205. package/dist/Chromium.mjs.map +0 -1
  206. package/dist/Expect-u3P_ENLX.d.mts +0 -62
  207. package/dist/Expect.d.mts +0 -2
  208. package/dist/Expect.mjs +0 -114
  209. package/dist/Expect.mjs.map +0 -1
  210. package/dist/Moment.d.mts +0 -2
  211. package/dist/Moment.mjs.map +0 -1
  212. package/dist/Motion.d.mts +0 -2
  213. package/dist/Motion.mjs.map +0 -1
  214. package/dist/Page-BP02bmNv.mjs +0 -264
  215. package/dist/Page-BP02bmNv.mjs.map +0 -1
  216. package/dist/Plan-BG1WifW2.mjs.map +0 -1
  217. package/dist/Plan.d.mts +0 -2
  218. package/dist/Plan.mjs +0 -2
  219. package/dist/Policy.d.mts +0 -2
  220. package/dist/Policy.mjs.map +0 -1
  221. package/dist/Presentation-DxVikn9_.d.mts +0 -48
  222. package/dist/Presentation.d.mts +0 -2
  223. package/dist/Presentation.mjs +0 -118
  224. package/dist/Presentation.mjs.map +0 -1
  225. package/dist/Stage.d.mts +0 -2
  226. package/dist/Stage.mjs.map +0 -1
  227. package/dist/Supervisor-2mPjIYYs.mjs +0 -676
  228. package/dist/Supervisor-2mPjIYYs.mjs.map +0 -1
  229. package/dist/Supervisor-CfRxbaso.d.mts +0 -317
  230. package/dist/Supervisor.d.mts +0 -2
  231. package/dist/Supervisor.mjs +0 -2
  232. package/dist/cdp-BMpYMWYe.mjs.map +0 -1
  233. package/dist/context-EGhOqjNN.mjs +0 -335
  234. package/dist/context-EGhOqjNN.mjs.map +0 -1
  235. package/dist/page-PTM8m5wC.mjs +0 -4057
  236. package/dist/page-PTM8m5wC.mjs.map +0 -1
  237. package/dist/url-Bsp2y55M.mjs +0 -264
  238. package/dist/url-Bsp2y55M.mjs.map +0 -1
  239. package/dist/workerd/index.d.mts +0 -16
  240. package/dist/workerd/index.mjs +0 -17
  241. package/src/Expect.ts +0 -180
  242. package/src/Plan.ts +0 -674
  243. package/src/Presentation.ts +0 -196
  244. package/src/Supervisor.ts +0 -632
  245. package/src/internal/supervisor/lifecycle.ts +0 -484
  246. package/src/workerd/index.ts +0 -17
  247. /package/src/{internal/page/url.ts → Url.ts} +0 -0
  248. /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
- export 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 @@ export const install = (
133
161
  globalThis.__effectBrowser = api;
134
162
 
135
163
  return api;
136
- };
164
+ }
137
165
 
138
166
  /** The expression that installs the script and evaluates to its API; packaging freezes it. */
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(", ")})`;
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
 
@@ -19,13 +19,13 @@ import type { CDPSession, Page as PlaywrightPage } from "playwright-core";
19
19
  import type { CaptureSource } from "../../Browser.ts";
20
20
  import * as Errors from "../../BrowserError.ts";
21
21
  import type { BrowserEvent } from "../../BrowserEvent.ts";
22
+ import * as BrowserClock from "../../Clock.ts";
22
23
  import type { InputGuard, Point } from "../../Page.ts";
23
24
  import type { Gate } from "../input/gate.ts";
24
- import { Current } from "../input/replies.ts";
25
- import * as BrowserClock from "../pictures/clock.ts";
26
25
  import * as Lane from "./lane.ts";
27
26
  import type { Openings } from "./openings.ts";
28
- import * as Url from "./url.ts";
27
+ import * as Port from "./port.ts";
28
+ import { Current } from "./replies.ts";
29
29
 
30
30
  /** Why a page is gone. */
31
31
  export type ClosedCause = Errors.Closed["cause"];
@@ -51,6 +51,7 @@ export interface MakeOptions {
51
51
  readonly url: string;
52
52
  readonly playwright: PlaywrightPage;
53
53
  readonly cdp: CDPSession;
54
+ readonly nativePort?: Port.Hooks["native"] | undefined;
54
55
  /** A call's reply, or a failure as for a closed page once the browser is lost first. */
55
56
  readonly untilLost: <A>(reply: Promise<A>) => Promise<A>;
56
57
  readonly settings: Settings;
@@ -74,48 +75,8 @@ export interface MakeOptions {
74
75
  readonly capture?: CaptureSource | undefined;
75
76
  }
76
77
 
77
- const messageOf = (cause: unknown): string =>
78
- cause instanceof Error ? cause.message : typeof cause === "string" ? cause : "unknown error";
79
-
80
- const closedPattern =
81
- /has been closed|Target closed|Session closed|browser has disconnected|Target page, context or browser/i;
82
-
83
- /**
84
- * Map a Playwright or protocol failure to a reason, `Closed` with `closed` as its cause for a page
85
- * or browser that is gone. A call that gives Playwright a timeout passes the same bound, so its
86
- * `Timeout` reports it; without one, Playwright's own message stays.
87
- */
88
- export const reasonOf = (
89
- cause: unknown,
90
- timeoutMillis?: number,
91
- closed: ClosedCause = "connection",
92
- redact: (message: string) => string = Url.redactWithin,
93
- ): Errors.Reason => {
94
- const message = messageOf(cause);
95
-
96
- if (closedPattern.test(message)) return new Errors.Closed({ cause: closed });
97
- if (cause instanceof Error && cause.name === "TimeoutError" && timeoutMillis !== undefined)
98
- return new Errors.Timeout({ millis: timeoutMillis });
99
- const line = redact(message).split("\n")[0] ?? message;
100
-
101
- return new Errors.Failed({ detail: line.replace(/^[\w.]+: /, "") });
102
- };
103
-
104
- /**
105
- * One Playwright or protocol call, failing undispatched. A closed page says why it is gone as the
106
- * browser knows then: the library's own calls fail with the browser's loss, and Playwright fails
107
- * its calls on a dropped connection after reporting the context closed.
108
- */
109
- export const call = <A>(
110
- operation: string,
111
- run: () => Promise<A>,
112
- closedBy: () => ClosedCause,
113
- timeoutMillis?: number,
114
- ) =>
115
- Effect.tryPromise({
116
- try: run,
117
- catch: (cause) => undispatched(operation, reasonOf(cause, timeoutMillis, closedBy())),
118
- });
78
+ export { call, reasonOf, undispatched, failWith, refuse } from "../../BrowserError.ts";
79
+ import { call, failWith, undispatched } from "../../BrowserError.ts";
119
80
 
120
81
  export const contextGone = (error: Errors.BrowserError) =>
121
82
  error.reason._tag === "Failed" &&
@@ -151,18 +112,7 @@ const track = <A>(reply: Promise<A>) => Fiber.getCurrent()?.getRef(Current)?.tra
151
112
 
152
113
  // A message's size on the wire, give or take its envelope.
153
114
  const sizeOf = (value: unknown) =>
154
- value === undefined ? 0 : Buffer.byteLength(JSON.stringify(value));
155
-
156
- /** A failure of `operation` before any of its input reached the browser. */
157
- export const undispatched = (operation: string, reason: Errors.Reason) =>
158
- new Errors.BrowserError({ operation, reason, dispatched: false });
159
-
160
- export const failWith = (operation: string, reason: Errors.Reason) =>
161
- Effect.fail(undispatched(operation, reason));
162
-
163
- /** Refuse a request to `operation` that could never succeed, before sending anything. */
164
- export const refuse = (operation: string, detail: string) =>
165
- failWith(operation, new Errors.InvalidRequest({ detail }));
115
+ value === undefined ? 0 : new TextEncoder().encode(JSON.stringify(value)).byteLength;
166
116
 
167
117
  export const decodeWith =
168
118
  <A>(operation: string, schema: Schema.Codec<A, unknown>) =>
@@ -263,7 +213,9 @@ export const make = (options: MakeOptions, scope: Scope.Scope) => {
263
213
  // Every protocol or Playwright call. Errors are undispatched here; `perform` marks them
264
214
  // dispatched once input has gone out.
265
215
  const native = <A>(operation: string, run: () => Promise<A>, timeoutMillis?: number) =>
266
- 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
+ );
267
219
 
268
220
  /** Fail with `Timeout` once `duration` has passed, the action timeout unless another is given. */
269
221
  const within =
@@ -300,7 +252,8 @@ export const make = (options: MakeOptions, scope: Scope.Scope) => {
300
252
  documentAt: () => activity.documentAt,
301
253
  gone: (operation) => undispatched(operation, new Errors.Closed({ cause: options.closedBy() })),
302
254
  scope,
303
- inputGate: options.inputGate,
255
+ beforeWrite: options.inputGate?.check,
256
+ refusal: options.inputGate?.refused,
304
257
  });
305
258
 
306
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
+ });