foldkit-plus 0.18.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,8 +3,9 @@ import { RemoteJsonRequest } from "foldkit-remote";
3
3
  // src/testing/playwright.ts
4
4
  /**
5
5
  * `foldkit-plus/testing/playwright`: what a user sees, asserted on a running
6
- * page. A write shows before the server answers and stays after it; a step
7
- * never shows a given text, at any moment; the page logs no error.
6
+ * page. A write shows before the server answers, holds still until it is
7
+ * answered, and stays after; a step never shows a given text, at any moment;
8
+ * the page logs no error.
8
9
  *
9
10
  * Each checks the page as drawn, over the real network: it proves that the
10
11
  * whole application (server, hydration, persistence, the Worker) delivers a
@@ -16,13 +17,20 @@ import { RemoteJsonRequest } from "foldkit-remote";
16
17
  * this module calls nothing but the `Page` it is given.
17
18
  */
18
19
  const decodeRequest = Schema.decodeUnknownOption(Schema.fromJsonString(RemoteJsonRequest));
19
- /** A Remote mutation over HTTP, by the JSON request `Remote.http` sends. */
20
- const isRemoteMutation = (request) => {
21
- const body = request.postData();
22
- return request.method() === "POST" && body !== null && Option.exists(decodeRequest(body), (sent) => sent.operation === "mutate");
20
+ /** The operation of a Remote request over HTTP, by the JSON request `Remote.http` sends. */
21
+ const remoteOperation = (request) => {
22
+ const body = request.method() === "POST" ? request.postData() : null;
23
+ return body === null ? Option.none() : Option.map(decodeRequest(body), (sent) => sent.operation);
23
24
  };
25
+ const isRemoteMutation = (request) => Option.contains(remoteOperation(request), "mutate");
24
26
  const millis = (input) => Duration.toMillis(Duration.fromInputUnsafe(input));
25
27
  /**
28
+ * How long `act` may take at least before it is taken to wait for its own
29
+ * write's answer. Only that case needs a limit, so it is far longer than a
30
+ * click takes on a loaded runner, whatever `hold` is.
31
+ */
32
+ const ACT_LIMIT = 1e4;
33
+ /**
26
34
  * Resolves once three frames in a row pass with no change to the document,
27
35
  * or after two seconds of changes: a Message an answer caused has been drawn.
28
36
  */
@@ -49,20 +57,132 @@ const quiet = (page) => page.evaluate(() => new Promise((resolve) => {
49
57
  };
50
58
  requestAnimationFrame(frame);
51
59
  }));
60
+ const watchStill = (elements, { key }) => {
61
+ const started = performance.now();
62
+ const where = (element) => {
63
+ const box = element.getBoundingClientRect();
64
+ return {
65
+ x: box.left + window.scrollX,
66
+ y: box.top + window.scrollY
67
+ };
68
+ };
69
+ const named = (element) => {
70
+ const html = element.outerHTML.replace(/\s+/g, " ");
71
+ return html.length > 80 ? `${html.slice(0, 77)}...` : html;
72
+ };
73
+ const watched = elements.map((element) => {
74
+ const lineage = /* @__PURE__ */ new Set();
75
+ for (let node = element; node !== null; node = node.parentNode) lineage.add(node);
76
+ return {
77
+ element,
78
+ lineage,
79
+ first: where(element),
80
+ faults: /* @__PURE__ */ new Map()
81
+ };
82
+ });
83
+ const fault = (each, kind, words) => {
84
+ if (!each.faults.has(kind)) each.faults.set(kind, `${named(each.element)} ${words}, ${Math.round(performance.now() - started)} ms after it showed`);
85
+ };
86
+ const observer = new MutationObserver((records) => {
87
+ for (const record of records) for (const each of watched) {
88
+ if ([...record.removedNodes].some((node) => each.lineage.has(node))) fault(each, "removed", "was taken out of the page");
89
+ if (record.type === "attributes" && record.attributeName === "hidden" && record.oldValue === null && each.lineage.has(record.target)) fault(each, "hidden", "was hidden");
90
+ }
91
+ for (const each of watched) if (each.faults.has("removed") && each.element.isConnected) fault(each, "moved", "was taken out and put back");
92
+ });
93
+ observer.observe(document, {
94
+ childList: true,
95
+ subtree: true,
96
+ attributes: true,
97
+ attributeFilter: ["hidden"],
98
+ attributeOldValue: true
99
+ });
100
+ let frame = 0;
101
+ const sample = () => {
102
+ for (const each of watched) {
103
+ if (!each.element.isConnected) continue;
104
+ if (!each.element.checkVisibility({ visibilityProperty: true })) fault(each, "hidden", "was hidden");
105
+ const now = where(each.element);
106
+ const dx = now.x - each.first.x;
107
+ const dy = now.y - each.first.y;
108
+ const away = [...Math.abs(dx) > 1 ? [`${Math.round(Math.abs(dx))}px ${dx < 0 ? "left" : "right"}`] : [], ...Math.abs(dy) > 1 ? [`${Math.round(Math.abs(dy))}px ${dy < 0 ? "up" : "down"}`] : []];
109
+ if (away.length > 0) fault(each, "shifted", `moved ${away.join(" and ")}`);
110
+ }
111
+ frame = requestAnimationFrame(sample);
112
+ };
113
+ sample();
114
+ Reflect.set(window, key, () => {
115
+ Reflect.deleteProperty(window, key);
116
+ observer.disconnect();
117
+ cancelAnimationFrame(frame);
118
+ return watched.map((each) => ({
119
+ element: each.element,
120
+ name: named(each.element),
121
+ faults: each.faults
122
+ }));
123
+ });
124
+ return elements.length;
125
+ };
52
126
  /**
53
- * The write shows before the server answers, and still shows once it has.
54
- * Every Remote mutation the page sends is held at the network for `hold`;
55
- * `shows` must be visible within `within` of `act` while they are held, and
56
- * again after every answer has landed and been drawn. Throws otherwise, and
57
- * when `act` sent no Remote mutation, since nothing was then held.
127
+ * Stops the watch and lists what went wrong. `now` is what the locator
128
+ * resolves to once settled: a watched element gone from the page while one
129
+ * that was not watched stands there was replaced, not only removed.
130
+ */
131
+ const stopStill = (now, { key }) => {
132
+ const report = Reflect.apply(Reflect.get(window, key), void 0, []);
133
+ const newcomer = now.some((element) => !report.some((each) => each.element === element));
134
+ return report.flatMap((each) => {
135
+ const replaced = newcomer && !each.element.isConnected;
136
+ return [...[...each.faults].flatMap(([kind, words]) => replaced && kind === "removed" ? [] : [words]), ...replaced ? [`${each.name} was replaced by a new element`] : []];
137
+ });
138
+ };
139
+ const stopIfWatching = ({ key }) => {
140
+ const stop = Reflect.get(window, key);
141
+ if (typeof stop === "function") stop();
142
+ };
143
+ /**
144
+ * The write shows before the server answers, holds still until it has been
145
+ * answered and drawn, and still shows after.
146
+ *
147
+ * Every Remote mutation the page sends is held at the network until `act`
148
+ * has ended and `shows` has been looked for, and for `hold` at least, so
149
+ * what shows was drawn before any answer however long `act` takes;
150
+ * `shows` must be visible within `within` of `act` beginning. From
151
+ * then until settled, what `stays` names must stay in the page as the same
152
+ * nodes, in the same place in their parent, within 1px of where they were
153
+ * drawn, and visible. Settled is evidence, not a wait: no Remote request of
154
+ * the page in flight (an answer can lead to more, such as a placed list's
155
+ * first page under `verifyPredictions`), or `writes.answered`, then the page
156
+ * quiet for three frames. An error the page logs meanwhile fails it too: a
157
+ * `PredictionMismatch` is logged as one. Throws otherwise, when `act` sent
158
+ * no Remote mutation over HTTP, since nothing was then held, and when `act`
159
+ * has not ended 10 seconds (or `hold`, if longer) after it began: one that
160
+ * waits for its own write's answer would wait for good.
58
161
  */
59
162
  const optimistic = async (page, options) => {
163
+ const writes = options.writes ?? "http";
60
164
  const hold = millis(options.hold ?? "3 seconds");
61
165
  const within = millis(options.within ?? "1 second");
62
- if (within >= hold) throw new Error(`optimistic: within (${within} ms) must be shorter than hold (${hold} ms), or what shows could be the answer`);
166
+ let release = () => {};
167
+ const looked = new Promise((resolve) => {
168
+ release = resolve;
169
+ });
63
170
  const held = [];
171
+ const inFlight = /* @__PURE__ */ new Set();
172
+ const sent = (request) => {
173
+ if (Option.isSome(remoteOperation(request))) inFlight.add(request);
174
+ };
175
+ let answers = 0;
176
+ const done = (request) => {
177
+ if (inFlight.delete(request)) answers += 1;
178
+ };
179
+ const errors = [];
180
+ const logged = (message) => {
181
+ if (message.type() === "error") errors.push(message.text());
182
+ };
183
+ const thrown = (error) => errors.push(String(error));
64
184
  const letThrough = async (route) => {
65
- await new Promise((resume) => setTimeout(resume, hold));
185
+ await Promise.all([new Promise((resume) => setTimeout(resume, hold)), looked]);
66
186
  await route.fallback();
67
187
  };
68
188
  const answered = async (request) => {
@@ -70,25 +190,61 @@ const optimistic = async (page, options) => {
70
190
  if (response !== null) await response.finished();
71
191
  };
72
192
  const route = await page.route("**/*", (route, request) => {
73
- if (!isRemoteMutation(request)) return route.fallback();
193
+ if (writes !== "http" || !isRemoteMutation(request)) return route.fallback();
74
194
  held.push(answered(request));
75
195
  return letThrough(route);
76
196
  });
197
+ page.on("request", sent);
198
+ page.on("requestfinished", done);
199
+ page.on("requestfailed", done);
200
+ page.on("console", logged);
201
+ page.on("pageerror", thrown);
77
202
  const shows = String(options.shows);
203
+ const stays = options.stays ?? "put";
204
+ const watched = stays === "shown" ? Option.none() : Option.some(stays === "put" ? options.shows : stays);
205
+ const watch = { key: `__foldkitStill${crypto.randomUUID().replaceAll("-", "")}` };
206
+ let overdue;
78
207
  try {
79
- const started = Date.now();
80
- await options.act();
81
- await options.shows.waitFor({
208
+ const shown = options.shows.waitFor({
82
209
  state: "visible",
83
- timeout: Math.max(1, within - (Date.now() - started))
84
- }).catch((error) => {
85
- throw new Error(`optimistic: ${shows} did not show within ${within} ms of the action`, { cause: error });
86
- });
87
- if (held.length === 0) throw new Error(`optimistic: ${shows} showed, but the action sent no Remote mutation`);
88
- await Promise.all(held);
89
- await quiet(page);
210
+ timeout: within
211
+ }).then(() => Option.none(), (error) => Option.some(error));
212
+ const acted = Promise.resolve().then(options.act);
213
+ const deadline = writes === "http" ? new Promise((resolve) => {
214
+ overdue = setTimeout(resolve, Math.max(hold, ACT_LIMIT), false);
215
+ }) : new Promise(() => {});
216
+ if (!await Promise.race([acted.then(() => true), deadline])) {
217
+ release();
218
+ acted.catch(() => {});
219
+ throw new Error(`optimistic: the action did not end within ${Math.max(hold, ACT_LIMIT)} ms, and every write is held until it does: does it wait for its own write's answer?`);
220
+ }
221
+ const missed = await shown;
222
+ if (Option.isSome(missed)) throw new Error(`optimistic: ${shows} did not show within ${within} ms of the action`, { cause: missed.value });
223
+ if (Option.isSome(watched) && await watched.value.evaluateAll(watchStill, watch) === 0) throw new Error(`optimistic: ${String(watched.value)}, what stays, matches nothing`);
224
+ release();
225
+ if (writes === "http") {
226
+ if (held.length === 0) throw new Error(`optimistic: ${shows} showed, but the action sent no Remote mutation`);
227
+ } else await writes.answered();
228
+ for (;;) {
229
+ const before = answers;
230
+ await quiet(page);
231
+ if (inFlight.size === 0 && answers === before) break;
232
+ }
233
+ if (Option.isSome(watched)) {
234
+ const faults = await watched.value.evaluateAll(stopStill, watch);
235
+ if (faults.length > 0) throw new Error(`optimistic: ${String(watched.value)} did not hold still until the write settled:\n ${faults.join("\n ")}`);
236
+ }
90
237
  if (!await options.shows.isVisible()) throw new Error(`optimistic: ${shows} showed while the write was held, but not after its answer`);
238
+ if (errors.length > 0) throw new Error(`optimistic: the page logged an error while the write settled:\n ${errors.join("\n ")}`);
91
239
  } finally {
240
+ clearTimeout(overdue);
241
+ release();
242
+ if (!page.isClosed()) await page.evaluate(stopIfWatching, watch);
243
+ page.off("request", sent);
244
+ page.off("requestfinished", done);
245
+ page.off("requestfailed", done);
246
+ page.off("console", logged);
247
+ page.off("pageerror", thrown);
92
248
  await route.dispose();
93
249
  await Promise.allSettled(held);
94
250
  }
@@ -1 +1 @@
1
- {"version":3,"file":"playwright.mjs","names":[],"sources":["../../src/testing/playwright.ts"],"sourcesContent":["/**\n * `foldkit-plus/testing/playwright`: what a user sees, asserted on a running\n * page. A write shows before the server answers and stays after it; a step\n * never shows a given text, at any moment; the page logs no error.\n *\n * Each checks the page as drawn, over the real network: it proves that the\n * whole application (server, hydration, persistence, the Worker) delivers a\n * property. Which Message breaks a read's property is\n * `foldkit-plus/remote/testing`'s `Trace`, which records every Model without\n * a browser; reach for it once one of these fails.\n *\n * Playwright is an optional peer of `foldkit-plus`, needed only for its types:\n * this module calls nothing but the `Page` it is given.\n */\nimport { Duration, Option, Schema } from 'effect'\nimport { RemoteJsonRequest } from 'foldkit-remote'\nimport type { Locator, Page, Request, Route } from 'playwright'\n\nconst decodeRequest = Schema.decodeUnknownOption(Schema.fromJsonString(RemoteJsonRequest))\n\n/** A Remote mutation over HTTP, by the JSON request `Remote.http` sends. */\nconst isRemoteMutation = (request: Request): boolean => {\n const body = request.postData()\n return (\n request.method() === 'POST' &&\n body !== null &&\n Option.exists(decodeRequest(body), sent => sent.operation === 'mutate')\n )\n}\n\nconst millis = (input: Duration.Input) => Duration.toMillis(Duration.fromInputUnsafe(input))\n\n/**\n * Resolves once three frames in a row pass with no change to the document,\n * or after two seconds of changes: a Message an answer caused has been drawn.\n */\nconst quiet = (page: Page): Promise<void> =>\n page.evaluate(\n () =>\n new Promise<void>(resolve => {\n let calm = 0\n const observer = new MutationObserver(() => {\n calm = 0\n })\n const done = () => {\n observer.disconnect()\n resolve()\n }\n observer.observe(document, {\n childList: true,\n subtree: true,\n characterData: true,\n attributes: true,\n })\n setTimeout(done, 2000)\n const frame = () => {\n calm += 1\n if (calm >= 3) done()\n else requestAnimationFrame(frame)\n }\n requestAnimationFrame(frame)\n }),\n )\n\nexport interface OptimisticOptions {\n /** The user's action that writes: a click, a key. */\n readonly act: () => Promise<unknown>\n /** What the page shows once the write is made. */\n readonly shows: Locator\n /** How long each Remote mutation is held at the network. `'3 seconds'` unless given. */\n readonly hold?: Duration.Input\n /** How soon after `act` begins `shows` must show, while every write is held. `'1 second'` unless given. */\n readonly within?: Duration.Input\n}\n\n/**\n * The write shows before the server answers, and still shows once it has.\n * Every Remote mutation the page sends is held at the network for `hold`;\n * `shows` must be visible within `within` of `act` while they are held, and\n * again after every answer has landed and been drawn. Throws otherwise, and\n * when `act` sent no Remote mutation, since nothing was then held.\n */\nconst optimistic = async (page: Page, options: OptimisticOptions): Promise<void> => {\n const hold = millis(options.hold ?? '3 seconds')\n const within = millis(options.within ?? '1 second')\n if (within >= hold)\n throw new Error(\n `optimistic: within (${within} ms) must be shorter than hold (${hold} ms), ` +\n 'or what shows could be the answer',\n )\n const held: Array<Promise<void>> = []\n // Let through after `hold`. The answer is awaited apart from the handler:\n // Playwright passes a request on to the next handler only once this one returns.\n const letThrough = async (route: Route) => {\n await new Promise(resume => setTimeout(resume, hold))\n await route.fallback()\n }\n const answered = async (request: Request) => {\n const response = await request.response()\n if (response !== null) await response.finished()\n }\n const route = await page.route('**/*', (route, request) => {\n if (!isRemoteMutation(request)) return route.fallback()\n held.push(answered(request))\n return letThrough(route)\n })\n const shows = String(options.shows)\n try {\n const started = Date.now()\n await options.act()\n // A write is let through `hold` after it was sent, which was after `act`\n // began, so whatever shows by this deadline was drawn before any answer.\n await options.shows\n .waitFor({ state: 'visible', timeout: Math.max(1, within - (Date.now() - started)) })\n .catch((error: unknown) => {\n throw new Error(`optimistic: ${shows} did not show within ${within} ms of the action`, {\n cause: error,\n })\n })\n if (held.length === 0)\n throw new Error(`optimistic: ${shows} showed, but the action sent no Remote mutation`)\n await Promise.all(held)\n await quiet(page)\n if (!(await options.shows.isVisible()))\n throw new Error(\n `optimistic: ${shows} showed while the write was held, but not after its answer`,\n )\n } finally {\n await route.dispose()\n await Promise.allSettled(held)\n }\n}\n\nexport interface NeverShowsOptions {\n /** What the page must not show at any moment of `during`. */\n readonly text: string | RegExp\n /**\n * The steps to watch: a reload, a navigation away and back. End it on what\n * the page waits for (an answer, a row), since watching stops once it ends\n * and the page is quiet.\n */\n readonly during: () => Promise<unknown>\n}\n\n/** What the page script needs: the binding to report through, and the text as a pattern. */\ninterface Watch {\n readonly key: string\n readonly source: string\n readonly flags: string\n}\n\n// Runs in the page, in the open document and in each one loaded after: after\n// every change to the document, the rendered text (`innerText` leaves hidden\n// text out) is searched, so a text shown for one frame is seen, not sampled.\nconst watchText = ({ key, source, flags }: Watch) => {\n if (window !== window.top) return\n const pattern = new RegExp(source, flags)\n let reported = false\n const check = () => {\n if (reported) return\n const line = (document.body?.innerText ?? '').split('\\n').find(each => pattern.test(each))\n if (line === undefined) return\n reported = true\n Reflect.apply(Reflect.get(window, key), undefined, [line])\n }\n const observer = new MutationObserver(check)\n observer.observe(document, {\n childList: true,\n subtree: true,\n characterData: true,\n attributes: true,\n })\n Reflect.set(window, `${key}Stop`, () => observer.disconnect())\n check()\n}\n\nconst stopWatching = (key: string) =>\n Reflect.apply(Reflect.get(window, `${key}Stop`), undefined, [])\n\n/**\n * The page never shows `text` while `during` runs, nor until the page is\n * quiet after it: a cached page revisited never reads \"Loading…\", even for\n * one frame. Throws with the line that showed.\n */\nconst neverShows = async (page: Page, options: NeverShowsOptions): Promise<void> => {\n const key = `__foldkitNeverShows${crypto.randomUUID().replaceAll('-', '')}`\n const { text } = options\n const watch: Watch =\n typeof text === 'string'\n ? { key, source: text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'), flags: '' }\n : { key, source: text.source, flags: text.flags }\n const shown: Array<string> = []\n const binding = await page.exposeBinding(key, (_, line: string) => {\n shown.push(line)\n })\n const script = await page.addInitScript(watchText, watch)\n try {\n await page.evaluate(watchText, watch)\n await options.during()\n await quiet(page)\n } finally {\n await script.dispose()\n if (!page.isClosed()) await page.evaluate(stopWatching, key)\n await binding.dispose()\n }\n if (shown.length > 0)\n throw new Error(`neverShows: the page showed ${String(text)}: \"${shown[0]}\"`)\n}\n\n/**\n * Collects every error the page logs (`console.error`) and every exception it\n * does not catch, from now until the page closes. Read the list at the end.\n */\nconst consoleErrors = (page: Page): (() => ReadonlyArray<string>) => {\n const errors: Array<string> = []\n page.on('console', message => {\n if (message.type() === 'error') errors.push(message.text())\n })\n page.on('pageerror', error => errors.push(String(error)))\n return () => [...errors]\n}\n\n/** Assertions on what a running page shows, for Playwright. */\nexport const Behaviors = { optimistic, neverShows, consoleErrors } as const\n"],"mappings":";;;;;;;;;;;;;;;;;AAkBA,MAAM,gBAAgB,OAAO,oBAAoB,OAAO,eAAe,iBAAiB,CAAC;;AAGzF,MAAM,oBAAoB,YAA8B;CACtD,MAAM,OAAO,QAAQ,SAAS;CAC9B,OACE,QAAQ,OAAO,MAAM,UACrB,SAAS,QACT,OAAO,OAAO,cAAc,IAAI,IAAG,SAAQ,KAAK,cAAc,QAAQ;AAE1E;AAEA,MAAM,UAAU,UAA0B,SAAS,SAAS,SAAS,gBAAgB,KAAK,CAAC;;;;;AAM3F,MAAM,SAAS,SACb,KAAK,eAED,IAAI,SAAc,YAAW;CAC3B,IAAI,OAAO;CACX,MAAM,WAAW,IAAI,uBAAuB;EAC1C,OAAO;CACT,CAAC;CACD,MAAM,aAAa;EACjB,SAAS,WAAW;EACpB,QAAQ;CACV;CACA,SAAS,QAAQ,UAAU;EACzB,W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KAAK;EAAQ,OAAO,KAAK;CAAM;CACpD,MAAM,QAAuB,CAAC;CAC9B,MAAM,UAAU,MAAM,KAAK,cAAc,MAAM,GAAG,SAAiB;EACjE,MAAM,KAAK,IAAI;CACjB,CAAC;CACD,MAAM,SAAS,MAAM,KAAK,cAAc,WAAW,KAAK;CACxD,IAAI;EACF,MAAM,KAAK,SAAS,WAAW,KAAK;EACpC,MAAM,QAAQ,OAAO;EACrB,MAAM,MAAM,IAAI;CAClB,UAAU;EACR,MAAM,OAAO,QAAQ;EACrB,IAAI,CAAC,KAAK,SAAS,GAAG,MAAM,KAAK,SAAS,cAAc,GAAG;EAC3D,MAAM,QAAQ,QAAQ;CACxB;CACA,IAAI,MAAM,SAAS,GACjB,MAAM,IAAI,MAAM,+BAA+B,OAAO,IAAI,EAAE,KAAK,MAAM,GAAG,EAAE;AAChF;;;;;AAMA,MAAM,iBAAiB,SAA8C;CACnE,MAAM,SAAwB,CAAC;CAC/B,KAAK,GAAG,YAAW,YAAW;EAC5B,IAAI,QAAQ,KAAK,MAAM,SAAS,OAAO,KAAK,QAAQ,KAAK,CAAC;CAC5D,CAAC;CACD,KAAK,GAAG,cAAa,UAAS,OAAO,KAAK,OAAO,KAAK,CAAC,CAAC;CACxD,aAAa,CAAC,GAAG,MAAM;AACzB;;AAGA,MAAa,YAAY;CAAE;CAAY;CAAY;AAAc"}
1
+ {"version":3,"file":"playwright.mjs","names":[],"sources":["../../src/testing/playwright.ts"],"sourcesContent":["/**\n * `foldkit-plus/testing/playwright`: what a user sees, asserted on a running\n * page. A write shows before the server answers, holds still until it is\n * answered, and stays after; a step never shows a given text, at any moment;\n * the page logs no error.\n *\n * Each checks the page as drawn, over the real network: it proves that the\n * whole application (server, hydration, persistence, the Worker) delivers a\n * property. Which Message breaks a read's property is\n * `foldkit-plus/remote/testing`'s `Trace`, which records every Model without\n * a browser; reach for it once one of these fails.\n *\n * Playwright is an optional peer of `foldkit-plus`, needed only for its types:\n * this module calls nothing but the `Page` it is given.\n */\nimport { Duration, Option, Schema } from 'effect'\nimport { RemoteJsonRequest } from 'foldkit-remote'\nimport type { ConsoleMessage, Locator, Page, Request, Route } from 'playwright'\n\nconst decodeRequest = Schema.decodeUnknownOption(Schema.fromJsonString(RemoteJsonRequest))\n\n/** The operation of a Remote request over HTTP, by the JSON request `Remote.http` sends. */\nconst remoteOperation = (request: Request): Option.Option<RemoteJsonRequest['operation']> => {\n const body = request.method() === 'POST' ? request.postData() : null\n return body === null ? Option.none() : Option.map(decodeRequest(body), sent => sent.operation)\n}\n\nconst isRemoteMutation = (request: Request): boolean =>\n Option.contains(remoteOperation(request), 'mutate')\n\nconst millis = (input: Duration.Input) => Duration.toMillis(Duration.fromInputUnsafe(input))\n\n/**\n * How long `act` may take at least before it is taken to wait for its own\n * write's answer. Only that case needs a limit, so it is far longer than a\n * click takes on a loaded runner, whatever `hold` is.\n */\nconst ACT_LIMIT = 10_000\n\n/**\n * Resolves once three frames in a row pass with no change to the document,\n * or after two seconds of changes: a Message an answer caused has been drawn.\n */\nconst quiet = (page: Page): Promise<void> =>\n page.evaluate(\n () =>\n new Promise<void>(resolve => {\n let calm = 0\n const observer = new MutationObserver(() => {\n calm = 0\n })\n const done = () => {\n observer.disconnect()\n resolve()\n }\n observer.observe(document, {\n childList: true,\n subtree: true,\n characterData: true,\n attributes: true,\n })\n setTimeout(done, 2000)\n const frame = () => {\n calm += 1\n if (calm >= 3) done()\n else requestAnimationFrame(frame)\n }\n requestAnimationFrame(frame)\n }),\n )\n\n/**\n * Writes that reach the server some way other than `Remote.http` (a port to a\n * SharedWorker, a sandbox in the page). The page holds its own answers (the\n * test opened it so), and `answered` resolves on the page's own evidence that\n * nothing it wrote is pending: an outbox emptied, a status gone.\n */\nexport interface PageWrites {\n readonly answered: () => Promise<unknown>\n}\n\nexport interface OptimisticOptions {\n /** The user's action that writes: a click, a key. */\n readonly act: () => Promise<unknown>\n /** What the page shows once the write is made. */\n readonly shows: Locator\n /**\n * What must hold still from the moment `shows` shows until the write is\n * answered and drawn: `'put'` (the default), each element `shows` resolves\n * to; a `Locator`, what it resolves to instead (the list around a row its\n * answer deliberately draws again); `'shown'`, nothing, so only that\n * `shows` shows again after the answer.\n */\n readonly stays?: 'put' | 'shown' | Locator\n /** How the writes travel: `'http'` (the default), `Remote.http`'s requests, held at the network. */\n readonly writes?: 'http' | PageWrites\n /**\n * How long each Remote mutation is held at the network at least: it is held\n * on until `act` has ended and `shows` has been looked for. `'3 seconds'`\n * unless given.\n */\n readonly hold?: Duration.Input\n /** How soon after `act` begins `shows` must show, while every write is held. `'1 second'` unless given. */\n readonly within?: Duration.Input\n}\n\n/** What the page script needs to keep what it watches apart from another watch's. */\ninterface StillWatch {\n readonly key: string\n}\n\n// Runs in the page over the elements to keep still. A node removed and put\n// back in one batch reads as attached in the callback, so removals and\n// `hidden` are replayed from the records; layout and visibility are sampled\n// every frame, as a reader sees them. Each element reports each kind of fault once.\nconst watchStill = (elements: ReadonlyArray<Element>, { key }: StillWatch): number => {\n const started = performance.now()\n const where = (element: Element) => {\n const box = element.getBoundingClientRect()\n return { x: box.left + window.scrollX, y: box.top + window.scrollY }\n }\n const named = (element: Element) => {\n const html = element.outerHTML.replace(/\\s+/g, ' ')\n return html.length > 80 ? `${html.slice(0, 77)}...` : html\n }\n const watched = elements.map(element => {\n const lineage = new Set<Node>()\n for (let node: Node | null = element; node !== null; node = node.parentNode) lineage.add(node)\n return { element, lineage, first: where(element), faults: new Map<string, string>() }\n })\n const fault = (each: (typeof watched)[number], kind: string, words: string) => {\n if (!each.faults.has(kind))\n each.faults.set(\n kind,\n `${named(each.element)} ${words}, ${Math.round(performance.now() - started)} ms after it showed`,\n )\n }\n const observer = new MutationObserver(records => {\n for (const record of records)\n for (const each of watched) {\n if ([...record.removedNodes].some(node => each.lineage.has(node)))\n fault(each, 'removed', 'was taken out of the page')\n if (\n record.type === 'attributes' &&\n record.attributeName === 'hidden' &&\n record.oldValue === null &&\n each.lineage.has(record.target)\n )\n fault(each, 'hidden', 'was hidden')\n }\n for (const each of watched)\n if (each.faults.has('removed') && each.element.isConnected)\n fault(each, 'moved', 'was taken out and put back')\n })\n observer.observe(document, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: ['hidden'],\n attributeOldValue: true,\n })\n let frame = 0\n const sample = () => {\n for (const each of watched) {\n if (!each.element.isConnected) continue\n if (!each.element.checkVisibility({ visibilityProperty: true }))\n fault(each, 'hidden', 'was hidden')\n const now = where(each.element)\n const dx = now.x - each.first.x\n const dy = now.y - each.first.y\n const away = [\n ...(Math.abs(dx) > 1 ? [`${Math.round(Math.abs(dx))}px ${dx < 0 ? 'left' : 'right'}`] : []),\n ...(Math.abs(dy) > 1 ? [`${Math.round(Math.abs(dy))}px ${dy < 0 ? 'up' : 'down'}`] : []),\n ]\n if (away.length > 0) fault(each, 'shifted', `moved ${away.join(' and ')}`)\n }\n frame = requestAnimationFrame(sample)\n }\n sample()\n Reflect.set(window, key, () => {\n Reflect.deleteProperty(window, key)\n observer.disconnect()\n cancelAnimationFrame(frame)\n return watched.map(each => ({\n element: each.element,\n name: named(each.element),\n faults: each.faults,\n }))\n })\n return elements.length\n}\n\n/**\n * Stops the watch and lists what went wrong. `now` is what the locator\n * resolves to once settled: a watched element gone from the page while one\n * that was not watched stands there was replaced, not only removed.\n */\nconst stopStill = (now: ReadonlyArray<Element>, { key }: StillWatch): ReadonlyArray<string> => {\n const report: ReadonlyArray<{\n readonly element: Element\n readonly name: string\n readonly faults: ReadonlyMap<string, string>\n }> = Reflect.apply(Reflect.get(window, key), undefined, [])\n const newcomer = now.some(element => !report.some(each => each.element === element))\n return report.flatMap(each => {\n const replaced = newcomer && !each.element.isConnected\n return [\n ...[...each.faults].flatMap(([kind, words]) =>\n replaced && kind === 'removed' ? [] : [words],\n ),\n ...(replaced ? [`${each.name} was replaced by a new element`] : []),\n ]\n })\n}\n\nconst stopIfWatching = ({ key }: StillWatch) => {\n const stop: unknown = Reflect.get(window, key)\n if (typeof stop === 'function') stop()\n}\n\n/**\n * The write shows before the server answers, holds still until it has been\n * answered and drawn, and still shows after.\n *\n * Every Remote mutation the page sends is held at the network until `act`\n * has ended and `shows` has been looked for, and for `hold` at least, so\n * what shows was drawn before any answer however long `act` takes;\n * `shows` must be visible within `within` of `act` beginning. From\n * then until settled, what `stays` names must stay in the page as the same\n * nodes, in the same place in their parent, within 1px of where they were\n * drawn, and visible. Settled is evidence, not a wait: no Remote request of\n * the page in flight (an answer can lead to more, such as a placed list's\n * first page under `verifyPredictions`), or `writes.answered`, then the page\n * quiet for three frames. An error the page logs meanwhile fails it too: a\n * `PredictionMismatch` is logged as one. Throws otherwise, when `act` sent\n * no Remote mutation over HTTP, since nothing was then held, and when `act`\n * has not ended 10 seconds (or `hold`, if longer) after it began: one that\n * waits for its own write's answer would wait for good.\n */\nconst optimistic = async (page: Page, options: OptimisticOptions): Promise<void> => {\n const writes = options.writes ?? 'http'\n const hold = millis(options.hold ?? '3 seconds')\n const within = millis(options.within ?? '1 second')\n // Opened once `shows` has been looked for and is watched: no write is\n // answered before, so nothing shown by then is an answer.\n let release = () => {}\n const looked = new Promise<void>(resolve => {\n release = resolve\n })\n const held: Array<Promise<void>> = []\n // Every Remote request from `act` on that is not yet answered.\n const inFlight = new Set<Request>()\n const sent = (request: Request) => {\n if (Option.isSome(remoteOperation(request))) inFlight.add(request)\n }\n // How many have been answered: a quiet that began before the last answer\n // may have ended before the page drew it.\n let answers = 0\n const done = (request: Request) => {\n if (inFlight.delete(request)) answers += 1\n }\n const errors: Array<string> = []\n const logged = (message: ConsoleMessage) => {\n if (message.type() === 'error') errors.push(message.text())\n }\n const thrown = (error: Error) => errors.push(String(error))\n // Let through after `hold`, once looked. The answer is awaited apart from the\n // handler: Playwright passes a request on to the next handler only once this one returns.\n const letThrough = async (route: Route) => {\n await Promise.all([new Promise(resume => setTimeout(resume, hold)), looked])\n await route.fallback()\n }\n const answered = async (request: Request) => {\n const response = await request.response()\n if (response !== null) await response.finished()\n }\n const route = await page.route('**/*', (route, request) => {\n if (writes !== 'http' || !isRemoteMutation(request)) return route.fallback()\n held.push(answered(request))\n return letThrough(route)\n })\n page.on('request', sent)\n page.on('requestfinished', done)\n page.on('requestfailed', done)\n page.on('console', logged)\n page.on('pageerror', thrown)\n const shows = String(options.shows)\n const stays = options.stays ?? 'put'\n const watched =\n stays === 'shown'\n ? Option.none<Locator>()\n : Option.some(stays === 'put' ? options.shows : stays)\n const watch: StillWatch = { key: `__foldkitStill${crypto.randomUUID().replaceAll('-', '')}` }\n let overdue: ReturnType<typeof setTimeout> | undefined\n try {\n const shown = options.shows.waitFor({ state: 'visible', timeout: within }).then(\n () => Option.none<unknown>(),\n (error: unknown) => Option.some(error),\n )\n const acted = Promise.resolve().then(options.act)\n // An action waiting for its own write's answer would wait for good.\n const deadline =\n writes === 'http'\n ? new Promise<false>(resolve => {\n overdue = setTimeout(resolve, Math.max(hold, ACT_LIMIT), false)\n })\n : new Promise<never>(() => {})\n const ended = await Promise.race([acted.then(() => true), deadline])\n if (!ended) {\n release()\n // The action is left running, so its eventual outcome is unobserved\n // here: a rejection after the deadline must not surface as an\n // unhandled rejection.\n void acted.catch(() => {})\n throw new Error(\n `optimistic: the action did not end within ${Math.max(hold, ACT_LIMIT)} ms, and every write is held until it does: does it wait for its own write's answer?`,\n )\n }\n const missed = await shown\n if (Option.isSome(missed))\n throw new Error(`optimistic: ${shows} did not show within ${within} ms of the action`, {\n cause: missed.value,\n })\n if (Option.isSome(watched) && (await watched.value.evaluateAll(watchStill, watch)) === 0)\n throw new Error(`optimistic: ${String(watched.value)}, what stays, matches nothing`)\n release()\n if (writes === 'http') {\n if (held.length === 0)\n throw new Error(`optimistic: ${shows} showed, but the action sent no Remote mutation`)\n } else {\n await writes.answered()\n }\n // Every held write is in flight until answered, and an answer drawn can ask\n // for more: settled once the page asks nothing and stays quiet from after\n // the last answer. The network finishes before the page reads the answer,\n // and an app draws it on a later frame.\n for (;;) {\n const before = answers\n await quiet(page)\n if (inFlight.size === 0 && answers === before) break\n }\n if (Option.isSome(watched)) {\n const faults = await watched.value.evaluateAll(stopStill, watch)\n if (faults.length > 0)\n throw new Error(\n `optimistic: ${String(watched.value)} did not hold still until the write settled:\\n ${faults.join('\\n ')}`,\n )\n }\n if (!(await options.shows.isVisible()))\n throw new Error(\n `optimistic: ${shows} showed while the write was held, but not after its answer`,\n )\n if (errors.length > 0)\n throw new Error(\n `optimistic: the page logged an error while the write settled:\\n ${errors.join('\\n ')}`,\n )\n } finally {\n clearTimeout(overdue)\n release()\n // A check that failed before reading the watch leaves it sampling every frame.\n if (!page.isClosed()) await page.evaluate(stopIfWatching, watch)\n page.off('request', sent)\n page.off('requestfinished', done)\n page.off('requestfailed', done)\n page.off('console', logged)\n page.off('pageerror', thrown)\n await route.dispose()\n await Promise.allSettled(held)\n }\n}\n\nexport interface NeverShowsOptions {\n /** What the page must not show at any moment of `during`. */\n readonly text: string | RegExp\n /**\n * The steps to watch: a reload, a navigation away and back. End it on what\n * the page waits for (an answer, a row), since watching stops once it ends\n * and the page is quiet.\n */\n readonly during: () => Promise<unknown>\n}\n\n/** What the page script needs: the binding to report through, and the text as a pattern. */\ninterface Watch {\n readonly key: string\n readonly source: string\n readonly flags: string\n}\n\n// Runs in the page, in the open document and in each one loaded after: after\n// every change to the document, the rendered text (`innerText` leaves hidden\n// text out) is searched, so a text shown for one frame is seen, not sampled.\nconst watchText = ({ key, source, flags }: Watch) => {\n if (window !== window.top) return\n const pattern = new RegExp(source, flags)\n let reported = false\n const check = () => {\n if (reported) return\n const line = (document.body?.innerText ?? '').split('\\n').find(each => pattern.test(each))\n if (line === undefined) return\n reported = true\n Reflect.apply(Reflect.get(window, key), undefined, [line])\n }\n const observer = new MutationObserver(check)\n observer.observe(document, {\n childList: true,\n subtree: true,\n characterData: true,\n attributes: true,\n })\n Reflect.set(window, `${key}Stop`, () => observer.disconnect())\n check()\n}\n\nconst stopWatching = (key: string) =>\n Reflect.apply(Reflect.get(window, `${key}Stop`), undefined, [])\n\n/**\n * The page never shows `text` while `during` runs, nor until the page is\n * quiet after it: a cached page revisited never reads \"Loading…\", even for\n * one frame. Throws with the line that showed.\n */\nconst neverShows = async (page: Page, options: NeverShowsOptions): Promise<void> => {\n const key = `__foldkitNeverShows${crypto.randomUUID().replaceAll('-', '')}`\n const { text } = options\n const watch: Watch =\n typeof text === 'string'\n ? { key, source: text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'), flags: '' }\n : { key, source: text.source, flags: text.flags }\n const shown: Array<string> = []\n const binding = await page.exposeBinding(key, (_, line: string) => {\n shown.push(line)\n })\n const script = await page.addInitScript(watchText, watch)\n try {\n await page.evaluate(watchText, watch)\n await options.during()\n await quiet(page)\n } finally {\n await script.dispose()\n if (!page.isClosed()) await page.evaluate(stopWatching, key)\n await binding.dispose()\n }\n if (shown.length > 0)\n throw new Error(`neverShows: the page showed ${String(text)}: \"${shown[0]}\"`)\n}\n\n/**\n * Collects every error the page logs (`console.error`) and every exception it\n * does not catch, from now until the page closes. Read the list at the end.\n */\nconst consoleErrors = (page: Page): (() => ReadonlyArray<string>) => {\n const errors: Array<string> = []\n page.on('console', message => {\n if (message.type() === 'error') errors.push(message.text())\n })\n page.on('pageerror', error => errors.push(String(error)))\n return () => [...errors]\n}\n\n/** Assertions on what a running page shows, for Playwright. */\nexport const Behaviors = { optimistic, neverShows, consoleErrors } as const\n"],"mappings":";;;;;;;;;;;;;;;;;;AAmBA,MAAM,gBAAgB,OAAO,oBAAoB,OAAO,eAAe,iBAAiB,CAAC;;AAGzF,MAAM,mBAAmB,YAAoE;CAC3F,MAAM,OAAO,QAAQ,OAAO,MAAM,SAAS,QAAQ,SAAS,IAAI;CAChE,OAAO,SAAS,OAAO,OAAO,KAAK,IAAI,OAAO,IAAI,cAAc,IAAI,IAAG,SAAQ,KAAK,SAAS;AAC/F;AAEA,MAAM,oBAAoB,YACxB,OAAO,SAAS,gBAAgB,OAAO,GAAG,QAAQ;AAEpD,MAAM,UAAU,UAA0B,SAAS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KAAK,GAAG,cAAa,UAAS,OAAO,KAAK,OAAO,KAAK,CAAC,CAAC;CACxD,aAAa,CAAC,GAAG,MAAM;AACzB;;AAGA,MAAa,YAAY;CAAE;CAAY;CAAY;AAAc"}
@@ -13,8 +13,17 @@ export interface StackOptions {
13
13
  readonly vars?: Vars | ((origin: string) => Vars);
14
14
  /** Local values for secrets, over any in `.dev.vars`. */
15
15
  readonly secrets?: Readonly<Record<string, string>>;
16
- /** esbuild plugins for the bundle, the deploy's and the stack's alike. */
16
+ /**
17
+ * esbuild plugins for the bundle, the deploy's and the stack's alike. A
18
+ * module one loads is branded with view identities as one read from disk is.
19
+ */
17
20
  readonly plugins?: ReadonlyArray<Plugin>;
21
+ /**
22
+ * The Vite root of the page the Worker renders; by default the folder of
23
+ * the Wrangler configuration. Each view is named by its module's path from
24
+ * here, as `@foldkit/vite-plugin` names the page's.
25
+ */
26
+ readonly pageRoot?: string;
18
27
  /**
19
28
  * Whether each line the Worker writes to its console is printed here, by
20
29
  * its level, as it arrives (`'print'`, the default). `logs()` keeps them either way.
@@ -67,6 +76,14 @@ export interface Stack<Env> {
67
76
  * line written for a request may arrive after it: poll.
68
77
  */
69
78
  readonly logs: () => ReadonlyArray<WorkerLog>;
79
+ /**
80
+ * Requests sent straight to the Worker, metered for `Cpu.budget` by how
81
+ * long workerd's main thread runs, read from the operating system since
82
+ * workerd reports no CPU (Linux and Windows). That counts the Worker's code
83
+ * and what workerd does on the thread around it, D1's SQLite included,
84
+ * which a deployed Worker's CPU time leaves out.
85
+ */
86
+ readonly cpu: CpuMeter;
70
87
  /**
71
88
  * Rebuilds on every change to a file the bundle read, and rereads the
72
89
  * Wrangler configuration when it changes. Each change is first started on
@@ -82,6 +99,72 @@ export interface Stack<Env> {
82
99
  */
83
100
  readonly stop: () => Promise<void>;
84
101
  }
102
+ /** What a meter answers: a `Response`, or Miniflare's own. */
103
+ export type CpuAnswer = Pick<Response, 'status' | 'arrayBuffer'>;
104
+ /** Answers requests, and reads how much CPU time the code answering them has spent. */
105
+ export interface CpuMeter {
106
+ /** What a route given as a path is resolved against. */
107
+ readonly origin: string;
108
+ readonly fetch: (request: Request) => Promise<CpuAnswer>;
109
+ /** Milliseconds of CPU time spent so far, from a fixed point of the meter's own. */
110
+ readonly spent: () => Promise<number>;
111
+ }
112
+ /**
113
+ * A route `Cpu.budget` asks: a path or URL to `GET`, or a function making
114
+ * a new request for each run, since a request's body is read once.
115
+ */
116
+ export type CpuRoute = string | (() => Request);
117
+ /** What one route cost, in milliseconds of CPU time. */
118
+ export interface CpuReading {
119
+ readonly route: string;
120
+ /** The last response's status. */
121
+ readonly status: number;
122
+ /** The route's first request in this call: in a fresh stack, a cold isolate's. */
123
+ readonly cold: number;
124
+ /**
125
+ * The most a request after the first spent, in milliseconds. A deployed
126
+ * Worker's limit applies to each request, not to their mean.
127
+ */
128
+ readonly warm: number;
129
+ }
130
+ export interface CpuBudget {
131
+ /** The routes, by the name a failure reports them with. */
132
+ readonly routes: Readonly<Record<string, CpuRoute>>;
133
+ /**
134
+ * Milliseconds each request after the first may spend. A meter's own
135
+ * resolution bounds how small this can be: Windows books a thread's CPU
136
+ * time in 15.6 ms ticks, so a budget near that reads one request's cost
137
+ * as a tick whether it spent it or not.
138
+ */
139
+ readonly warm: number;
140
+ /** Milliseconds the first request may spend; unchecked when not given. */
141
+ readonly cold?: number;
142
+ /** Requests after the first, each answered in full before the next; default 5. */
143
+ readonly runs?: number;
144
+ }
145
+ /**
146
+ * Asks each route once, then `runs` times more, one request at a time, each
147
+ * response read in full, and reads what each cost. Every warm request is
148
+ * checked, since a deployed Worker's limit applies to each rather than to
149
+ * their mean. Throws listing every reading when a route spends more than
150
+ * the budget, or answers a 5xx, whose cost says nothing of the route's.
151
+ */
152
+ declare const budget: (meter: CpuMeter, { routes, warm, cold, runs }: CpuBudget) => Promise<ReadonlyArray<CpuReading>>;
153
+ /**
154
+ * A meter over `answer` run in this process, by this thread's CPU time: for
155
+ * a Worker's handler Node can run (no D1 or other binding of workerd's),
156
+ * whose work happens on the thread that awaits it.
157
+ */
158
+ declare const inThread: (answer: (request: Request) => Promise<CpuAnswer>, origin?: string) => CpuMeter;
159
+ /**
160
+ * What a request costs in CPU time, which Miniflare neither limits nor
161
+ * reports, while a deployed Worker fails past its plan's limit (error 1102).
162
+ * `Cpu.budget` reads routes through a meter: a stack's `cpu`, or `Cpu.inThread`.
163
+ */
164
+ export declare const Cpu: {
165
+ readonly budget: typeof budget;
166
+ readonly inThread: typeof inThread;
167
+ };
85
168
  /** Writes the bundle where `main` says, for `wrangler deploy`. */
86
169
  declare const writeBundle: (options: Omit<StackOptions, 'vars' | 'secrets'>) => Promise<void>;
87
170
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"workers.d.mts","names":[],"sources":["../../src/testing/workers.ts"],"mappings":";;iBA8BiB;;WAEN;;WAEA;;;;;;WAMA,OAAO,SAAS,mBAAmB;;WAEnC,UAAU,SAAS;;WAEnB,UAAU,cAAc;;;;;WAKxB;;KAGN,OAAO,SAAS;;iBAGJ;;WAEN;WACA;WACA;;;;;;iBAOM;;WAEN;;;;;;;;WAQA,YAAY;;;;;;WAMZ,YAAY;;iBAGN,MAAM;;WAEZ;;;;;WAKA,WAAW,QAAQ;;WAEnB,UAAU;;;;;;WAMV,YAAY,cAAc;;;;;;;WAO1B,QAAQ,UAAU,kBAAkB;;;;;;;WAOpC,YAAY;;;cA6FjB,cAAW,SAAmB,KAAK,sCAAoC;;;;;;cAyBvE,QAAe,KAAG,SAAW,iBAAe,QAAQ,MAAM;;;;;;qBA4OnD"}
1
+ {"version":3,"file":"workers.d.mts","names":[],"sources":["../../src/testing/workers.ts"],"mappings":";;iBA2CiB;;WAEN;;WAEA;;;;;;WAMA,OAAO,SAAS,mBAAmB;;WAEnC,UAAU,SAAS;;;;;WAKnB,UAAU,cAAc;;;;;;WAMxB;;;;;WAKA;;KAGN,OAAO,SAAS;;iBAGJ;;WAEN;WACA;WACA;;;;;;iBAOM;;WAEN;;;;;;;;W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