pomerado 0.4.0-canary.708 → 0.4.0-canary.709
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.
- package/CHANGELOG.md +5 -0
- package/dist/runtime-sources.json +4 -4
- package/dist/typescript/authoring/core/SKILL.md +3 -2
- package/dist/typescript/authoring/workspace/AGENTS.md +4 -3
- package/dist/typescript/authoring/writes/SKILL.md +5 -2
- package/dist/typescript/src/browser/action-waits.d.ts +2 -0
- package/dist/typescript/src/browser/wait.d.ts +18 -6
- package/dist/typescript/src/browser/wait.js +73 -12
- package/dist/typescript/src/runtime/browser-action-timeout.d.ts +2 -2
- package/dist/typescript/src/runtime/browser-action-timeout.js +3 -3
- package/dist/typescript/src/runtime/deadline.d.ts +3 -0
- package/dist/typescript/src/runtime/deadline.js +3 -0
- package/dist/typescript/src/runtime/kernel-operation.js +5 -2
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
### Breaking changes
|
|
6
6
|
|
|
7
|
+
- `waitForRows` and `waitForValues` fail as `page_mismatch`, in place of `values_loading`, when the page stopped progressing and the only fields holding them back are needed ones it lacks, such as a row with no title. The message is otherwise the same and names each missing field, and its rows. A field still empty or loading keeps `values_loading`, as does a row field `waitForRows` reads as hidden, and the wait keeps its timing: the no-progress window still decides that the page has stopped. `nativeActionTimeout` reads `page_mismatch` as a page wait's failure, so a host still gets a `BrowserActionTimeout`. Migrate a host or a tool that matches `values_loading` to tell a still-loading page from one the code does not match by also matching `page_mismatch`. The core skill names it; a recorded minter response keyed on the exact skill text needs recording again.
|
|
7
8
|
- The auth skill says to prefer a hand-off sign-in, `signInStep: { approval: "handoff" }` with no popup or `matchSelector` on the site's sign-in page, when the request asks for a person to sign in, even when that page also shows a password form. A recorded minter response keyed on the exact skill text needs recording again.
|
|
8
9
|
- A picker's match now depends on what a wrong pick costs. In a read, `pickValue` and `pickValues` pick the best match at any rank again, as before they picked only a clean one, and a match looser than a clean one returns `loose: true`. In a write, they still pick only a clean match and return a looser one as `option_unclear`. Before, every run picked only a clean match, as the entry below on clean matches says; that entry now holds for writes.
|
|
9
10
|
- The runtime declares the run's effect ahead of each Kernel call's code, which `pickerCode` reads; `withRunEffect` in `pomerado/core/runtime/kernel-operation` declares it the same way for code run another way, such as in a test. A script that declares `write` writes, and any other reads. `executeKernelOperation`'s browser and `runLocalOperation` take an optional `effect`, which a host passes for a build's or repair's steps, so every step follows the build's effect. The local host passes it. Code run without the runtime picks only a clean match. A tool keeps its behavior until it is published again on this release.
|
|
@@ -333,6 +334,10 @@
|
|
|
333
334
|
- `pomerado.hostProtocol` stays 1: no `./core/*` export is removed. A host that cannot show its browser to a person must fail a hand-off request with `Unavailable` before showing it, without calling `opened`, and never answer it itself. Migrate a host that maps each question type, such as in an exhaustive check or its own request decoder, by handling `browser_handoff`; a host's renderer by wording `handoff_state_changed`; a host that stores the failure reason by accepting `handoff_state_changed`; a hosted runner by passing `HandoffStateChanged` through as it passes `InputNotApplied`, and its script question handler by calling `opened` once the hand-off shows, as the asker's `AskBounds.opened` says; a host that already passes `AskBounds.opened` to `makeInputAsker` by expecting the call it now makes; and a host that bounds requests itself by taking `inputWaitMs`. A tool minted with a hand-off fails as an ordinary script error on a runtime from before this change, so upgrade a host's runners before its minter. A recorded Guardian or minter response keyed on the exact publication, execution or question policy, `provide_input` description, caller-input skill or workspace guide text needs recording again.
|
|
334
335
|
### Other changes
|
|
335
336
|
|
|
337
|
+
- `waitForOutcome` and `waitForOutcomeResult` take `pending`, naming the outcomes, one key or a list, that are the site's in-between answers to the action, such as a save the site is still processing: outcomes the page shows, never a response, dialog or popup, each counting only once new or changed since the action. One never decides the wait while it shows: from the first look that shows one, the wait holds for a final outcome up to `timeoutDefaults.pending` (60 s) past it, or to `timeout` when that ends later, never past `deadline` nor later than 5 s before the call's own end. A final outcome wins at once. One still showing when the hold ends is the answer, with `pending: true` on `OutcomeResult`, and its summary says when it first showed. A wait without `pending` behaves as before.
|
|
338
|
+
- The runtime declares each Kernel call's end, a second before its `timeout_sec`, as `__pomeradoCallEnds` ahead of the call's code, where the hold ends. Code run another way holds up to `deadline`.
|
|
339
|
+
- `confirmCommit` reports a `pending` answer with no commit response as `done` with the new status `pending`, and its text as `status_label`, when the page shows no new error and no new message other than an alert. Before, any answer with no commit response that showed no error was `unclear`. `CommitConfirmation`'s `status` adds `pending`; `queued` still means a 202, or a body whose status says the work is queued. Migrate code that maps each status, such as in an exhaustive check, by handling `pending`.
|
|
340
|
+
- The workspace rules and the writes skill say to wait for the site's final answer to an in-between state, and to name that state in the commit wait's `pending`; one still showing after the wait is pending, not completed. A recorded minter response keyed on the exact skill text needs recording again.
|
|
336
341
|
- Guardian's execution review reads the commit marks each listed earlier write's step sent, when the host gives them. A step that enters a mark no listed write sent makes that mark's change for the first time, unless a listed write's own source could have made the same change without that mark. Before, an earlier step that only opened an item's options and sent no mark, once the outcome review found it done, made the first add after it read as a repeat, and Guardian denied it.
|
|
337
342
|
- Each entry of `PendingExecution`'s `mintContext.writes` (`trusted_execution_context.writes`) takes an optional `sent`, the names of the commit marks the write's step sent (entered `sent` or `confirmed`), empty when it sent none. A host leaves it out unless the step's own commit report was read and nothing the step did could have sent past its marks, and a host that leaves it out keeps the rule as it was. The local host leaves it out for now. No other type or signature changes, and `pomerado.hostProtocol` stays 1.
|
|
338
343
|
- A recorded Guardian response keyed on the exact execution policy needs recording again.
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
},
|
|
14
14
|
{
|
|
15
15
|
"path": "runtime/deadline.js",
|
|
16
|
-
"text": "import { Effect } from \"effect\";\n/**\n * The one set of budgets the runtime's waits apply and the authoring skills quote.\n *\n * - `navigation`: a `goto` or URL wait, to document commit.\n * - `action`: a click, fill, press or select on an element a wait has shown ready, and every action\n * in an exploration probe.\n * - `answer`: how long a wait goes on with no visible progress before it fails.\n * - `answerCap`: the hard cap on an answer wait while the page keeps progressing.\n * - `settle`: the gap between the two looks that must agree on the values a tool returns.\n * - `unchanged`: how long an answer or value from before an action must hold to count as unchanged.\n * - `lateFillCap`: the cap on waiting for values the site fills in after its answer.\n * - `http`: an HTTP request that names no `timeoutMs` of its own, to its whole body.\n * - `httpRead`: a read's request that names none, such as each of `batchRead`'s and\n * `batchFetch`'s. A site answers a read within a few seconds, and one that holds a read longer\n * has stalled, so this ends it while the call can still try another way. A write's request\n * keeps `http`, since one cut short after it was sent may still have reached the site.\n */\nexport const timeoutDefaults = {\n execution: 20 * 60_000,\n action: 5_000,\n readiness: 5_000,\n navigation: 30_000,\n answer: 8_000,\n answerCap: 30_000,\n settle: 500,\n unchanged: 2_000,\n lateFillCap: 15_000,\n http: 60_000,\n httpRead: 8_000,\n};\nexport class Deadline {\n activeExpiresAt;\n now;\n parentRemaining;\n pausedAt;\n pausedMilliseconds = 0;\n suspensionCount = 0;\n constructor(activeExpiresAt, now, parentRemaining) {\n this.activeExpiresAt = activeExpiresAt;\n this.now = now;\n this.parentRemaining = parentRemaining;\n }\n get expiresAt() {\n return this.now() + this.remainingMs();\n }\n /** Trusted holds pause the active budget; each caller owns and releases its suspension. */\n suspend() {\n if (this.suspensionCount === 0)\n this.pausedAt = this.now();\n this.suspensionCount += 1;\n let resumed = false;\n return () => {\n if (resumed)\n return;\n resumed = true;\n this.suspensionCount -= 1;\n if (this.suspensionCount === 0 && this.pausedAt !== undefined) {\n this.pausedMilliseconds += Math.max(0, this.now() - this.pausedAt);\n this.pausedAt = undefined;\n }\n };\n }\n /** Observe changes made by challenge suspension instead of freezing a wall timeout. */\n awaitExpiry = Effect.suspend(() => {\n const remaining = this.remainingMs();\n return remaining <= 0\n ? Effect.void\n : Effect.sleep(Math.min(remaining, 100)).pipe(Effect.zipRight(this.awaitExpiry));\n });\n static after(milliseconds = timeoutDefaults.execution, now = () => performance.now()) {\n if (!Number.isFinite(milliseconds) || milliseconds <= 0) {\n throw new RangeError(\"A deadline requires a positive finite duration\");\n }\n return new Deadline(now() + milliseconds, now);\n }\n remainingMs() {\n const now = this.now();\n const pause = this.pausedMilliseconds +\n (this.pausedAt === undefined ? 0 : Math.max(0, now - this.pausedAt));\n return Math.max(0, Math.min(this.activeExpiresAt + pause - now, this.parentRemaining?.() ?? Infinity));\n }\n limitTo(other) {\n return new Deadline(Infinity, this.now, () => Math.min(this.remainingMs(), other.remainingMs()));\n }\n child(milliseconds) {\n if (!Number.isFinite(milliseconds) || milliseconds <= 0) {\n throw new RangeError(\"A deadline requires a positive finite duration\");\n }\n return new Deadline(this.now() + milliseconds, this.now, () => this.remainingMs());\n }\n}\n"
|
|
16
|
+
"text": "import { Effect } from \"effect\";\n/**\n * The one set of budgets the runtime's waits apply and the authoring skills quote.\n *\n * - `navigation`: a `goto` or URL wait, to document commit.\n * - `action`: a click, fill, press or select on an element a wait has shown ready, and every action\n * in an exploration probe.\n * - `answer`: how long a wait goes on with no visible progress before it fails.\n * - `answerCap`: the hard cap on an answer wait while the page keeps progressing.\n * - `settle`: the gap between the two looks that must agree on the values a tool returns.\n * - `unchanged`: how long an answer or value from before an action must hold to count as unchanged.\n * - `lateFillCap`: the cap on waiting for values the site fills in after its answer.\n * - `pending`: how long an answer wait holds, from the first look that shows an in-between answer\n * the code named (`pending`), for the site's final answer.\n * - `http`: an HTTP request that names no `timeoutMs` of its own, to its whole body.\n * - `httpRead`: a read's request that names none, such as each of `batchRead`'s and\n * `batchFetch`'s. A site answers a read within a few seconds, and one that holds a read longer\n * has stalled, so this ends it while the call can still try another way. A write's request\n * keeps `http`, since one cut short after it was sent may still have reached the site.\n */\nexport const timeoutDefaults = {\n execution: 20 * 60_000,\n action: 5_000,\n readiness: 5_000,\n navigation: 30_000,\n answer: 8_000,\n answerCap: 30_000,\n settle: 500,\n unchanged: 2_000,\n lateFillCap: 15_000,\n pending: 60_000,\n http: 60_000,\n httpRead: 8_000,\n};\nexport class Deadline {\n activeExpiresAt;\n now;\n parentRemaining;\n pausedAt;\n pausedMilliseconds = 0;\n suspensionCount = 0;\n constructor(activeExpiresAt, now, parentRemaining) {\n this.activeExpiresAt = activeExpiresAt;\n this.now = now;\n this.parentRemaining = parentRemaining;\n }\n get expiresAt() {\n return this.now() + this.remainingMs();\n }\n /** Trusted holds pause the active budget; each caller owns and releases its suspension. */\n suspend() {\n if (this.suspensionCount === 0)\n this.pausedAt = this.now();\n this.suspensionCount += 1;\n let resumed = false;\n return () => {\n if (resumed)\n return;\n resumed = true;\n this.suspensionCount -= 1;\n if (this.suspensionCount === 0 && this.pausedAt !== undefined) {\n this.pausedMilliseconds += Math.max(0, this.now() - this.pausedAt);\n this.pausedAt = undefined;\n }\n };\n }\n /** Observe changes made by challenge suspension instead of freezing a wall timeout. */\n awaitExpiry = Effect.suspend(() => {\n const remaining = this.remainingMs();\n return remaining <= 0\n ? Effect.void\n : Effect.sleep(Math.min(remaining, 100)).pipe(Effect.zipRight(this.awaitExpiry));\n });\n static after(milliseconds = timeoutDefaults.execution, now = () => performance.now()) {\n if (!Number.isFinite(milliseconds) || milliseconds <= 0) {\n throw new RangeError(\"A deadline requires a positive finite duration\");\n }\n return new Deadline(now() + milliseconds, now);\n }\n remainingMs() {\n const now = this.now();\n const pause = this.pausedMilliseconds +\n (this.pausedAt === undefined ? 0 : Math.max(0, now - this.pausedAt));\n return Math.max(0, Math.min(this.activeExpiresAt + pause - now, this.parentRemaining?.() ?? Infinity));\n }\n limitTo(other) {\n return new Deadline(Infinity, this.now, () => Math.min(this.remainingMs(), other.remainingMs()));\n }\n child(milliseconds) {\n if (!Number.isFinite(milliseconds) || milliseconds <= 0) {\n throw new RangeError(\"A deadline requires a positive finite duration\");\n }\n return new Deadline(this.now() + milliseconds, this.now, () => this.remainingMs());\n }\n}\n"
|
|
17
17
|
},
|
|
18
18
|
{
|
|
19
19
|
"path": "runtime/operation.js",
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
},
|
|
22
22
|
{
|
|
23
23
|
"path": "runtime/kernel-operation.js",
|
|
24
|
-
"text": "import { BrowserActionTimeout, nativeActionTimeout } from \"./browser-action-timeout.js\";\nimport { Effect, Either, Schema } from \"effect\";\nimport { DialogChoice, DialogFailure, DialogType } from \"./dialogs.js\";\nimport { ChallengeFailure, challengeSolverWaitMs } from \"./challenge.js\";\nimport { handsOff } from \"./input-request.js\";\nimport { ScriptInput, ScriptInputFailure } from \"./script-input.js\";\nimport { timeoutDefaults } from \"./deadline.js\";\nimport { CommitAlreadySent, WriteConfirmationRefused } from \"./errors.js\";\nimport { kernelTimeoutSec } from \"./kernel-execute-client.js\";\nimport { inspectSignInRejection } from \"./sign-in-rejection.js\";\nimport { FileField, FileRefused, ScreenshotTarget, SiteFileLimits, } from \"./files.js\";\nimport { ScriptCardFillAnswer, ScriptCardFillRequest } from \"./script-card-fill.js\";\nimport { CredentialsRejected, OperationFailure, operationErrors, scriptFailure, } from \"./operation-failure.js\";\nexport { OperationFailure, operationErrors };\n/** Longest dialog message the host is sent. */\nexport const dialogMessageLimit = 16_384;\n/**\n * A native dialog a call left open on Kernel's page, as the script reports it to the host.\n * `step` is the script's name for the step that raised it, the same on every run, and `url` is\n * the page's URL when it showed.\n */\nexport const DialogReport = Schema.Struct({\n step: Schema.String.pipe(Schema.pattern(/^[A-Za-z0-9_-]{1,100}$/)),\n type: DialogType,\n message: Schema.String,\n url: Schema.String.pipe(Schema.maxLength(8_192)),\n});\n/** Runs a host exchange and throws its own typed failure, not Effect's wrapper. */\nconst settle = async (effect) => {\n const outcome = await Effect.runPromise(Effect.either(effect));\n if (Either.isLeft(outcome))\n throw outcome.left;\n return outcome.right;\n};\nexport { kernelTimeoutSec } from \"./kernel-execute-client.js\";\nconst WaitResult = Schema.Struct({ cleared: Schema.Boolean, waitedMs: Schema.Number });\n/** The solver wait as one call on Kernel's page, polling the script's own readiness check. */\nconst waitPastChallengeCode = (ready, limitMs) => `const started = Date.now();\nconst ready = async () => {\n${ready}\n};\nwhile (true) {\n try { if (await ready()) return { cleared: true, waitedMs: Date.now() - started }; } catch {}\n if (Date.now() - started >= ${limitMs}) return { cleared: false, waitedMs: Date.now() - started };\n await new Promise((resolve) => setTimeout(resolve, 250));\n}`;\n/** The declared question an ask of exactly one id puts, if it is a browser hand-off. */\nconst handOffAsked = (questions, input) => {\n const ids = typeof input === \"string\" ? [input] : Array.isArray(input) ? input : Object.keys(input);\n const [id] = ids;\n if (ids.length !== 1 || id === undefined || questions === undefined)\n return undefined;\n const declaration = Object.hasOwn(questions, id) ? questions[id] : undefined;\n return handsOff({ [id]: declaration }) ? id : undefined;\n};\n/**\n * Once a write's browser is handed to a person, who may submit it: every declared commit step\n * still unsent reads sent, entered from unsent, so the script may put back with `notCommitted`\n * one the person left unsubmitted. A confirmed step stays confirmed, and a step maintenance\n * settled stays as it is. A write that declares no steps marks a possible dispatch, unless it\n * already recorded its confirmation, which then stands as a confirmed step does.\n */\nconst markHandOff = (journal, write) => {\n if (journal === undefined || write === undefined)\n return;\n const declared = write.commits;\n const names = Array.isArray(declared)\n ? declared.filter((name) => typeof name === \"string\")\n : [];\n if (names.length === 0) {\n if (Effect.runSync(journal.confirmation) === undefined)\n Effect.runSync(journal.enteringDispatch);\n return;\n }\n const marks = Effect.runSync(journal.commits);\n for (const name of names)\n if ((marks.find((mark) => mark.name === name)?.state ?? \"not_sent\") === \"not_sent\")\n Effect.runSync(Effect.ignore(journal.enteringCommit(name)));\n};\n/**\n * Failures after which a hand-off may have been shown to the person: it went unanswered, or the\n * caller's access ended while it waited. Any other failure means the host could not show it, or\n * says so by calling `opened` first.\n */\nconst shownBefore = new Set([\"NoResponse\", \"Unauthorized\"]);\n/**\n * The context's `ask` over the runner's script input. The runtime checks every id and option\n * against the contract's declarations; the declared types only guide the script's author. A\n * browser hand-off marks a write's commit steps sent (`markHandOff`) once the host opens it, and,\n * for a host that never says so, once the person answers or the request ends unanswered. A\n * hand-off the host refused before showing it marks nothing.\n */\nconst scriptAsk = (scriptInput, handingOff = {}) => {\n function ask(input) {\n if (scriptInput === undefined)\n return settle(Effect.fail(new ScriptInputFailure({ code: \"Unavailable\" })));\n if (handOffAsked(handingOff.questions, input) === undefined)\n return settle(scriptInput.ask(input));\n let marked = false;\n const mark = () => {\n if (marked)\n return;\n marked = true;\n markHandOff(handingOff.journal, handingOff.write);\n };\n return settle(scriptInput.ask(input, { opened: mark })).then((answer) => {\n mark();\n return answer;\n }, (error) => {\n if (error instanceof ScriptInputFailure && shownBefore.has(error.code))\n mark();\n throw error;\n });\n }\n return ask;\n};\n/** The context's `askOne`, a thin wrapper over `ask` that unwraps the one answer. */\nconst scriptAskOne = (ask) => async (id, question = {}) => {\n const answer = (await ask({ [id]: question }))[id];\n if (answer === undefined)\n throw new ScriptInputFailure({ code: \"Unavailable\" });\n return answer;\n};\n/** The context's `handOff`: `ask` for one declared hand-off, which resolves once it is done. */\nconst scriptHandOff = (ask, questions) => async (id) => {\n if (handOffAsked(questions, id) === undefined)\n throw new ScriptInputFailure({ code: \"Undeclared\" });\n const answer = await ask(id);\n if (typeof answer !== \"object\" || !(\"done\" in answer) || answer.done !== true)\n throw new ScriptInputFailure({ code: \"Unavailable\" });\n};\n/** The default wait for a download to finish after its trigger. */\nexport const downloadWaitMs = 30_000;\n/** Refusals the caller's file causes when placed, which the caller fixes with another file. */\nconst callerFileReasons = new Set([\n \"too_large\",\n \"run_limit\",\n \"type_mismatch\",\n \"executable\",\n \"not_accepted\",\n]);\n/**\n * A download the host refused over its size caps, as the script's failure: the page made the\n * file, so it is the host's limit, never the caller's input, and the message names the cap.\n */\nexport const downloadCapFailures = {\n too_large: \"The downloaded file is over the host's size limit for one file (too_large)\",\n run_limit: \"The downloaded file is over the host's limit for one run's files (run_limit)\",\n};\n/**\n * A file refusal, or the host's file service failing, as the script's own failure: the caller's\n * file refused is `InvalidInput`, naming the reason, and anything else an `OperationFailure`.\n * Only a refusal after the host set the input, or after a trigger's own calls, may have sent\n * anything.\n */\nconst fileFailure = (error, afterCalls = false) => {\n const refused = error instanceof FileRefused ? error : undefined;\n if (refused !== undefined && callerFileReasons.has(refused.reason))\n return new operationErrors.InvalidInput(refused.message);\n return new OperationFailure(refused?.message ?? \"The host's file service failed\", {\n cause: error,\n dispatch: afterCalls || refused === undefined || refused.dispatched === true ? \"unknown\" : \"not_sent\",\n });\n};\n/**\n * A failed take of a trigger's downloads, by `files.collect` or `files.collectAll`: a download\n * over the host's caps fails with the cap's own wording, which a build's host reads as its file\n * cap; any other refusal as `fileFailure` after the trigger's calls.\n */\nconst collectFailure = (error) => {\n const overCap = error instanceof FileRefused ? downloadCapFailures[error.reason] : undefined;\n return overCap === undefined\n ? fileFailure(error, true)\n : new OperationFailure(overCap, { cause: error, dispatch: \"unknown\" });\n};\n/**\n * The context's `files` over the host's channel. A live run marks a possible dispatch once a\n * placement set the file input, or may have, as an execute call does; a refusal before that\n * reached no page. Collecting only reads what the trigger's own calls made the page download.\n */\nconst scriptFiles = (options) => {\n const channel = () => {\n if (options.files === undefined || options.offline === true)\n throw new OperationFailure(\"This run has no file service\", { dispatch: \"not_sent\" });\n return options.files;\n };\n const dispatched = () => {\n if (options.journal !== undefined)\n Effect.runSync(options.journal.enteringDispatch);\n };\n return {\n place: async (reference, { field, timeoutSec, maxBytes, extensions }) => {\n const files = channel();\n if (typeof reference !== \"string\")\n throw new OperationFailure(\"files.place takes the input's file reference\", {\n dispatch: \"not_sent\",\n });\n // A field is data naming one input; anything else, such as page code, names none.\n if (Either.isLeft(Schema.decodeUnknownEither(FileField)(field)))\n throw fileFailure(new FileRefused({ reason: \"field_not_found\" }));\n // The site's limits go to the host only when the script names them, and only as limits.\n const limits = Schema.decodeUnknownEither(SiteFileLimits)({\n ...(maxBytes === undefined ? {} : { maxBytes }),\n ...(extensions === undefined ? {} : { extensions }),\n });\n if (Either.isLeft(limits))\n throw new OperationFailure('files.place takes maxBytes as a positive whole number of bytes and extensions as file name endings such as \".pdf\"', { dispatch: \"not_sent\" });\n try {\n const placed = await settle(files.place({\n reference,\n field,\n timeoutSec: kernelTimeoutSec(Math.min((timeoutSec ?? 30) * 1000, options.deadline.remainingMs())),\n ...limits.right,\n }));\n dispatched();\n return placed;\n }\n catch (error) {\n if (!(error instanceof FileRefused) || error.dispatched === true)\n dispatched();\n throw fileFailure(error);\n }\n },\n collect: async (trigger, collectOptions) => {\n const files = channel();\n let slot;\n try {\n slot = await settle(files.arm());\n }\n catch (error) {\n throw fileFailure(error);\n }\n try {\n await trigger();\n }\n catch (error) {\n // The capture ends with the trigger, so nothing it armed outlives the failure.\n await Effect.runPromise(Effect.ignore(files.collect({ slot, timeoutMs: 0 })));\n throw error;\n }\n const timeoutMs = Math.min(collectOptions?.timeoutMs ?? downloadWaitMs, Math.max(0, options.deadline.remainingMs()));\n try {\n return await settle(files.collect({ slot, timeoutMs }));\n }\n catch (error) {\n throw collectFailure(error);\n }\n },\n collectAll: async (trigger, collectOptions) => {\n const files = channel();\n const collectAll = files.collectAll;\n if (collectAll === undefined)\n throw new OperationFailure(\"This host cannot collect every download a trigger starts (files.collectAll); use files.collect for one download\", { dispatch: \"not_sent\" });\n const max = collectOptions?.max;\n if (max !== undefined && !(Number.isSafeInteger(max) && max >= 1))\n throw new OperationFailure(\"files.collectAll takes max as a positive whole number\", {\n dispatch: \"not_sent\",\n });\n let slot;\n try {\n slot = await settle(files.arm());\n }\n catch (error) {\n throw fileFailure(error);\n }\n try {\n await trigger();\n }\n catch (error) {\n // The capture ends with the trigger, so nothing it armed outlives the failure.\n await Effect.runPromise(Effect.ignore(collectAll({ slot, timeoutMs: 0, max: 1 })));\n throw error;\n }\n const timeoutMs = Math.min(collectOptions?.timeoutMs ?? downloadWaitMs, Math.max(0, options.deadline.remainingMs()));\n try {\n return await settle(collectAll({ slot, timeoutMs, ...(max === undefined ? {} : { max }) }));\n }\n catch (error) {\n throw collectFailure(error);\n }\n },\n screenshot: async (shot = {}) => {\n const files = channel();\n if (files.screenshot === undefined)\n throw new OperationFailure(\"This run's host takes no screenshots\", { dispatch: \"not_sent\" });\n // The target is data the host writes into its own locator; anything else names no element.\n // An option left undefined is no option; anything but an options object still names no\n // target.\n const given = typeof shot === \"object\" && shot !== null && !Array.isArray(shot)\n ? Object.fromEntries(Object.entries(shot).filter(([, value]) => value !== undefined))\n : shot;\n const target = Schema.decodeUnknownEither(ScreenshotTarget)(given);\n if (Either.isLeft(target))\n throw fileFailure(new FileRefused({ reason: \"field_not_found\" }));\n try {\n return await settle(files.screenshot({\n ...target.right,\n timeoutMs: Math.min(shot.timeoutMs ?? downloadWaitMs, Math.max(0, options.deadline.remainingMs())),\n }));\n }\n catch (error) {\n // A picture over the caps is the host's limit, as a download's is; it sent nothing.\n const overCap = error instanceof FileRefused ? downloadCapFailures[error.reason] : undefined;\n if (overCap !== undefined)\n throw new OperationFailure(overCap.replace(\"downloaded file\", \"screenshot\"), {\n cause: error,\n dispatch: \"not_sent\",\n });\n throw fileFailure(error);\n }\n },\n };\n};\n/**\n * The context's `fillCard` over the host's card fill. A refusal typed nothing; once a value may\n * have reached the page, a live run marks a possible dispatch, as a file placement does.\n */\nconst scriptFillCard = (options) => async (step) => {\n const cardFill = options.cardFill;\n if (cardFill === undefined || options.offline === true)\n throw new OperationFailure(\"This run has no card fill\", { dispatch: \"not_sent\" });\n const request = Schema.decodeUnknownEither(ScriptCardFillRequest)(step, {\n onExcessProperty: \"error\",\n });\n if (Either.isLeft(request))\n throw new OperationFailure(\"fillCard takes one to four fields, each its own selector and a card handle ask returned, each handle once, or card slots with the checkout's total\", { dispatch: \"not_sent\" });\n const resume = options.deadline.suspend();\n try {\n const answer = Schema.decodeUnknownSync(ScriptCardFillAnswer)(await cardFill(request.right));\n const typed = answer.outcome === \"filled\" || answer.typed;\n if (typed && options.journal !== undefined)\n Effect.runSync(options.journal.enteringDispatch);\n if (answer.outcome === \"filled\")\n return { outcome: answer.outcome, fields: answer.fields };\n throw new OperationFailure(answer.message, { dispatch: typed ? \"unknown\" : \"not_sent\" });\n }\n finally {\n resume();\n }\n};\n/** Builds the context the runtime hands a Kernel script. */\nconst makeKernelOperationContext = (options) => {\n const ask = scriptAsk(options.scriptInput, options);\n return {\n kernel: options.kernel,\n sessionId: options.sessionId,\n siteOrigin: options.siteOrigin,\n siteDomain: options.siteDomain,\n input: options.input,\n // Records how the run proved its effect, a read-back unless the site's message says so.\n verified: (proof) => {\n const kind = proof?.confirmation ?? \"readback\";\n if (options.write?.confirmation === \"unverifiable\")\n throw new WriteConfirmationRefused({ declared: \"unverifiable\", recorded: kind });\n if (options.journal !== undefined)\n Effect.runSync(options.journal.confirmed(kind));\n },\n // Marks a named commit step sent just before the execute call that dispatches it.\n enteringCommit: (name) => {\n if (options.journal === undefined)\n return;\n const entered = Effect.runSync(Effect.either(options.journal.enteringCommit(name)));\n if (entered._tag === \"Left\")\n throw entered.left;\n },\n // A host journal without it cannot record the click unsent, so the step stays sent.\n // `siteRefused` goes to the host only as the script's own word, so a host that checks each\n // step's proof can tell it from a bare call.\n notCommitted: (name, said) => {\n if (options.journal === undefined)\n return;\n const revert = options.journal.notCommitted;\n if (revert === undefined)\n throw new CommitAlreadySent({ name });\n const reverted = Effect.runSync(Effect.either(said?.siteRefused === true ? revert(name, { siteRefused: true }) : revert(name)));\n if (reverted._tag === \"Left\")\n throw reverted.left;\n },\n remainingMs: () => options.deadline.remainingMs(),\n errors: operationErrors,\n rejectedSignIn: (request) => settle(inspectSignInRejection(options, request)),\n ensureSignedIn: options.ensureSignedIn,\n decideDialog: async (shown) => {\n const decide = options.dialogs;\n if (decide === undefined)\n throw new DialogFailure({ reason: \"unavailable\" });\n const report = Schema.decodeUnknownEither(DialogReport)(shown);\n if (Either.isLeft(report))\n throw new DialogFailure({ reason: \"invalid_request\" });\n const resume = options.deadline.suspend();\n try {\n const choice = await settle(decide({\n interactionId: crypto.randomUUID(),\n ...report.right,\n message: report.right.message.slice(0, dialogMessageLimit),\n }));\n return Schema.decodeUnknownSync(DialogChoice)(choice, { onExcessProperty: \"error\" });\n }\n finally {\n resume();\n }\n },\n // The runtime checks every id and option against the declarations; the types only guide.\n ask,\n askOne: scriptAskOne(ask),\n handOff: scriptHandOff(ask, options.questions),\n fillCard: scriptFillCard(options),\n files: scriptFiles(options),\n waitPastChallenge: async ({ ready }) => {\n // The SDK accepts only a whole-millisecond request timeout.\n const limitMs = Math.floor(Math.min(challengeSolverWaitMs, options.deadline.remainingMs()));\n const answer = await options.kernel.browsers.playwright.execute(options.sessionId, {\n code: waitPastChallengeCode(ready, limitMs),\n timeout_sec: kernelTimeoutSec(Math.min(limitMs + 10_000, options.deadline.remainingMs())),\n }, { maxRetries: 0, timeout: limitMs + 20_000 });\n if (answer.success !== true)\n throw new OperationFailure(`waitPastChallenge failed: ${String(answer.error)}`, {\n stderr: answer.stderr,\n });\n const result = Schema.decodeUnknownSync(WaitResult)(answer.result);\n if (!result.cleared)\n throw new ChallengeFailure({\n code: \"Unavailable\",\n solverWaitMs: Math.max(0, Math.round(result.waitedMs)),\n });\n },\n };\n};\nexport const isKernelOperation = (value) => typeof value === \"object\" &&\n value !== null &&\n Reflect.get(value, \"kind\") === \"kernel\" &&\n typeof Reflect.get(value, \"run\") === \"function\";\n/**\n * Page code that wraps the page's and locators' `click` for one call. A click Playwright made that\n * timed out only waiting for the page load it started counts as done once the main frame next\n * commits, within the navigation budget from the click and before the call's own limit. Only a\n * commit after the timeout counts, so a URL the click's own handler changed in place doesn't. A\n * page that doesn't commit by then leaves the click's own timeout, as before. Every other click\n * is Playwright's own, and a `page` that isn't Playwright's is left as it is. Each wrapper holds\n * Playwright's own click, which the next call wraps instead of a wrapper a call left behind. It is\n * one line, so the call's code keeps its line numbers.\n */\nconst clickNavigationWait = String.raw `(until) => {\n if (typeof page === \"undefined\" || typeof page?.mainFrame !== \"function\" || typeof page.locator !== \"function\") return () => {};\n const own = Symbol.for(\"pomerado.clickNavigation.original\");\n const wrap = (prototype) => {\n const click = prototype.click?.[own] ?? prototype.click;\n const waited = async function (...args) {\n const tab = typeof this.mainFrame === \"function\" ? this : this.page();\n const startedAt = Date.now();\n try {\n return await click.apply(this, args);\n } catch (error) {\n if (error?.name !== \"TimeoutError\" || !/-\\s+click action done[^\\n]*\\n[^\\n]*-\\s+waiting for scheduled navigations to finish[^\\n]*\\s*$/u.test(String(error.message))) throw error;\n let seen;\n let timer;\n const committed = await new Promise((resolve) => {\n seen = (frame) => {\n if (frame === tab.mainFrame()) resolve(true);\n };\n tab.on(\"framenavigated\", seen);\n timer = setTimeout(resolve, Math.min(startedAt + ${timeoutDefaults.navigation}, until) - Date.now(), false);\n });\n tab.off(\"framenavigated\", seen);\n clearTimeout(timer);\n if (!committed) throw error;\n }\n };\n waited[own] = click;\n prototype.click = waited;\n return () => {\n if (prototype.click === waited) prototype.click = click;\n };\n };\n const restores = [wrap(Object.getPrototypeOf(page)), wrap(Object.getPrototypeOf(page.locator(\":root\")))];\n return () => restores.forEach((restore) => restore());\n}`.replace(/\\n\\s*/gu, \" \");\n/**\n * A call's code with the run's effect declared ahead of it, on the same line, as `pickerCode`\n * reads it (`__pomeradoEffect`).\n */\nexport const withRunEffect = (code, effect) => `const __pomeradoEffect = ${JSON.stringify(effect)};${code}`;\n/** A call's code inside `clickNavigationWait`, which ends a second before its `timeout_sec`. */\nconst withClickNavigationWait = (code, timeoutSec = 60) => `const __pomeradoClickNavigation = (${clickNavigationWait})(Date.now() + ${timeoutSec * 1000 - 1000}); try {${code}\n} finally { __pomeradoClickNavigation(); }`;\n/**\n * One run of a script's function against a Kernel client: Kernel's own, or the saved-DOM stand-in.\n * A throw that is not one of its typed errors becomes an `OperationFailure`.\n */\nexport const runKernelScript = (operation, input, browser) => Effect.suspend(() => {\n let actionTimeout;\n let calls = 0;\n const effect = browser.effect ?? (operation.write === undefined ? \"read\" : \"write\");\n // The host's sign-in under way. Every browser call the script starts meanwhile, from a timer\n // or an un-awaited promise too, waits for it and is only then sent, in order, so its own\n // timeout starts then. A failed sign-in releases them as well.\n let signingIn;\n const afterSignIn = (call) => signingIn === undefined ? call() : signingIn.then(call, call);\n const kernel = {\n browsers: {\n playwright: {\n execute: (sessionId, body, options) => {\n // Counted when made: a held call goes out later, even after the script ends.\n calls += 1;\n return afterSignIn(() => settle(Effect.sync(() => {\n actionTimeout = undefined;\n }).pipe(Effect.flatMap(() => Effect.tryPromise({\n try: () => browser.kernel.browsers.playwright.execute(sessionId, {\n ...body,\n code: withClickNavigationWait(withRunEffect(body.code, effect), body.timeout_sec),\n }, options),\n catch: (error) => error instanceof Error ? error : new Error(String(error), { cause: error }),\n })), Effect.tap((answer) => Effect.sync(() => {\n actionTimeout = nativeActionTimeout(answer);\n })))));\n },\n },\n },\n };\n // The host's sign-in, with the deadline paused. A refusal before the script's first call\n // sent nothing; after it, the script's own calls may have.\n const signInOnce = async (signIn) => {\n const resume = browser.deadline.suspend();\n try {\n const { signedInAgain } = await signIn();\n return { signedInAgain: signedInAgain === true };\n }\n catch (error) {\n if (error instanceof CredentialsRejected)\n throw error;\n throw new OperationFailure(\"The host could not sign the site in again\", {\n cause: error,\n dispatch: calls === 0 ? \"not_sent\" : \"unknown\",\n sessionLoss: \"session_not_kept\",\n });\n }\n finally {\n resume();\n }\n };\n // A call while one is under way joins it rather than signing in again.\n const ensureSignedIn = async () => {\n const signIn = browser.signIn;\n if (signIn === undefined || browser.offline === true)\n return { signedInAgain: false };\n signingIn ??= signInOnce(signIn).finally(() => {\n signingIn = undefined;\n });\n return signingIn;\n };\n return Effect.tryPromise({\n try: async () => {\n // A page that lost its session since the host signed in is signed in again first.\n await ensureSignedIn();\n const context = makeKernelOperationContext({\n ...browser,\n kernel,\n input,\n ensureSignedIn,\n ...(operation.write === undefined ? {} : { write: operation.write }),\n ...(operation.questions === undefined ? {} : { questions: operation.questions }),\n });\n const output = await operation.run({\n ...context,\n decideDialog: (report) => afterSignIn(() => context.decideDialog(report)),\n // Typing a card is a browser call too.\n fillCard: (step) => {\n calls += 1;\n return afterSignIn(() => context.fillCard(step));\n },\n // Placing a file is a browser call: it waits for a sign-in under way and counts as one.\n files: {\n ...context.files,\n place: (reference, options) => {\n calls += 1;\n return afterSignIn(() => context.files.place(reference, options));\n },\n },\n });\n // A returned Effect never ran, so only the script's own execute calls may have sent.\n if (Effect.isEffect(output))\n throw scriptFailure(output, browser.scriptError, calls === 0 ? \"not_sent\" : \"unknown\");\n return output;\n },\n catch: (error) => {\n const failure = scriptFailure(error, browser.scriptError);\n return failure instanceof OperationFailure &&\n actionTimeout !== undefined &&\n failure.message === actionTimeout.slice(0, 4096)\n ? new BrowserActionTimeout(failure)\n : failure;\n },\n });\n});\n"
|
|
24
|
+
"text": "import { BrowserActionTimeout, nativeActionTimeout } from \"./browser-action-timeout.js\";\nimport { Effect, Either, Schema } from \"effect\";\nimport { DialogChoice, DialogFailure, DialogType } from \"./dialogs.js\";\nimport { ChallengeFailure, challengeSolverWaitMs } from \"./challenge.js\";\nimport { handsOff } from \"./input-request.js\";\nimport { ScriptInput, ScriptInputFailure } from \"./script-input.js\";\nimport { timeoutDefaults } from \"./deadline.js\";\nimport { CommitAlreadySent, WriteConfirmationRefused } from \"./errors.js\";\nimport { kernelTimeoutSec } from \"./kernel-execute-client.js\";\nimport { inspectSignInRejection } from \"./sign-in-rejection.js\";\nimport { FileField, FileRefused, ScreenshotTarget, SiteFileLimits, } from \"./files.js\";\nimport { ScriptCardFillAnswer, ScriptCardFillRequest } from \"./script-card-fill.js\";\nimport { CredentialsRejected, OperationFailure, operationErrors, scriptFailure, } from \"./operation-failure.js\";\nexport { OperationFailure, operationErrors };\n/** Longest dialog message the host is sent. */\nexport const dialogMessageLimit = 16_384;\n/**\n * A native dialog a call left open on Kernel's page, as the script reports it to the host.\n * `step` is the script's name for the step that raised it, the same on every run, and `url` is\n * the page's URL when it showed.\n */\nexport const DialogReport = Schema.Struct({\n step: Schema.String.pipe(Schema.pattern(/^[A-Za-z0-9_-]{1,100}$/)),\n type: DialogType,\n message: Schema.String,\n url: Schema.String.pipe(Schema.maxLength(8_192)),\n});\n/** Runs a host exchange and throws its own typed failure, not Effect's wrapper. */\nconst settle = async (effect) => {\n const outcome = await Effect.runPromise(Effect.either(effect));\n if (Either.isLeft(outcome))\n throw outcome.left;\n return outcome.right;\n};\nexport { kernelTimeoutSec } from \"./kernel-execute-client.js\";\nconst WaitResult = Schema.Struct({ cleared: Schema.Boolean, waitedMs: Schema.Number });\n/** The solver wait as one call on Kernel's page, polling the script's own readiness check. */\nconst waitPastChallengeCode = (ready, limitMs) => `const started = Date.now();\nconst ready = async () => {\n${ready}\n};\nwhile (true) {\n try { if (await ready()) return { cleared: true, waitedMs: Date.now() - started }; } catch {}\n if (Date.now() - started >= ${limitMs}) return { cleared: false, waitedMs: Date.now() - started };\n await new Promise((resolve) => setTimeout(resolve, 250));\n}`;\n/** The declared question an ask of exactly one id puts, if it is a browser hand-off. */\nconst handOffAsked = (questions, input) => {\n const ids = typeof input === \"string\" ? [input] : Array.isArray(input) ? input : Object.keys(input);\n const [id] = ids;\n if (ids.length !== 1 || id === undefined || questions === undefined)\n return undefined;\n const declaration = Object.hasOwn(questions, id) ? questions[id] : undefined;\n return handsOff({ [id]: declaration }) ? id : undefined;\n};\n/**\n * Once a write's browser is handed to a person, who may submit it: every declared commit step\n * still unsent reads sent, entered from unsent, so the script may put back with `notCommitted`\n * one the person left unsubmitted. A confirmed step stays confirmed, and a step maintenance\n * settled stays as it is. A write that declares no steps marks a possible dispatch, unless it\n * already recorded its confirmation, which then stands as a confirmed step does.\n */\nconst markHandOff = (journal, write) => {\n if (journal === undefined || write === undefined)\n return;\n const declared = write.commits;\n const names = Array.isArray(declared)\n ? declared.filter((name) => typeof name === \"string\")\n : [];\n if (names.length === 0) {\n if (Effect.runSync(journal.confirmation) === undefined)\n Effect.runSync(journal.enteringDispatch);\n return;\n }\n const marks = Effect.runSync(journal.commits);\n for (const name of names)\n if ((marks.find((mark) => mark.name === name)?.state ?? \"not_sent\") === \"not_sent\")\n Effect.runSync(Effect.ignore(journal.enteringCommit(name)));\n};\n/**\n * Failures after which a hand-off may have been shown to the person: it went unanswered, or the\n * caller's access ended while it waited. Any other failure means the host could not show it, or\n * says so by calling `opened` first.\n */\nconst shownBefore = new Set([\"NoResponse\", \"Unauthorized\"]);\n/**\n * The context's `ask` over the runner's script input. The runtime checks every id and option\n * against the contract's declarations; the declared types only guide the script's author. A\n * browser hand-off marks a write's commit steps sent (`markHandOff`) once the host opens it, and,\n * for a host that never says so, once the person answers or the request ends unanswered. A\n * hand-off the host refused before showing it marks nothing.\n */\nconst scriptAsk = (scriptInput, handingOff = {}) => {\n function ask(input) {\n if (scriptInput === undefined)\n return settle(Effect.fail(new ScriptInputFailure({ code: \"Unavailable\" })));\n if (handOffAsked(handingOff.questions, input) === undefined)\n return settle(scriptInput.ask(input));\n let marked = false;\n const mark = () => {\n if (marked)\n return;\n marked = true;\n markHandOff(handingOff.journal, handingOff.write);\n };\n return settle(scriptInput.ask(input, { opened: mark })).then((answer) => {\n mark();\n return answer;\n }, (error) => {\n if (error instanceof ScriptInputFailure && shownBefore.has(error.code))\n mark();\n throw error;\n });\n }\n return ask;\n};\n/** The context's `askOne`, a thin wrapper over `ask` that unwraps the one answer. */\nconst scriptAskOne = (ask) => async (id, question = {}) => {\n const answer = (await ask({ [id]: question }))[id];\n if (answer === undefined)\n throw new ScriptInputFailure({ code: \"Unavailable\" });\n return answer;\n};\n/** The context's `handOff`: `ask` for one declared hand-off, which resolves once it is done. */\nconst scriptHandOff = (ask, questions) => async (id) => {\n if (handOffAsked(questions, id) === undefined)\n throw new ScriptInputFailure({ code: \"Undeclared\" });\n const answer = await ask(id);\n if (typeof answer !== \"object\" || !(\"done\" in answer) || answer.done !== true)\n throw new ScriptInputFailure({ code: \"Unavailable\" });\n};\n/** The default wait for a download to finish after its trigger. */\nexport const downloadWaitMs = 30_000;\n/** Refusals the caller's file causes when placed, which the caller fixes with another file. */\nconst callerFileReasons = new Set([\n \"too_large\",\n \"run_limit\",\n \"type_mismatch\",\n \"executable\",\n \"not_accepted\",\n]);\n/**\n * A download the host refused over its size caps, as the script's failure: the page made the\n * file, so it is the host's limit, never the caller's input, and the message names the cap.\n */\nexport const downloadCapFailures = {\n too_large: \"The downloaded file is over the host's size limit for one file (too_large)\",\n run_limit: \"The downloaded file is over the host's limit for one run's files (run_limit)\",\n};\n/**\n * A file refusal, or the host's file service failing, as the script's own failure: the caller's\n * file refused is `InvalidInput`, naming the reason, and anything else an `OperationFailure`.\n * Only a refusal after the host set the input, or after a trigger's own calls, may have sent\n * anything.\n */\nconst fileFailure = (error, afterCalls = false) => {\n const refused = error instanceof FileRefused ? error : undefined;\n if (refused !== undefined && callerFileReasons.has(refused.reason))\n return new operationErrors.InvalidInput(refused.message);\n return new OperationFailure(refused?.message ?? \"The host's file service failed\", {\n cause: error,\n dispatch: afterCalls || refused === undefined || refused.dispatched === true ? \"unknown\" : \"not_sent\",\n });\n};\n/**\n * A failed take of a trigger's downloads, by `files.collect` or `files.collectAll`: a download\n * over the host's caps fails with the cap's own wording, which a build's host reads as its file\n * cap; any other refusal as `fileFailure` after the trigger's calls.\n */\nconst collectFailure = (error) => {\n const overCap = error instanceof FileRefused ? downloadCapFailures[error.reason] : undefined;\n return overCap === undefined\n ? fileFailure(error, true)\n : new OperationFailure(overCap, { cause: error, dispatch: \"unknown\" });\n};\n/**\n * The context's `files` over the host's channel. A live run marks a possible dispatch once a\n * placement set the file input, or may have, as an execute call does; a refusal before that\n * reached no page. Collecting only reads what the trigger's own calls made the page download.\n */\nconst scriptFiles = (options) => {\n const channel = () => {\n if (options.files === undefined || options.offline === true)\n throw new OperationFailure(\"This run has no file service\", { dispatch: \"not_sent\" });\n return options.files;\n };\n const dispatched = () => {\n if (options.journal !== undefined)\n Effect.runSync(options.journal.enteringDispatch);\n };\n return {\n place: async (reference, { field, timeoutSec, maxBytes, extensions }) => {\n const files = channel();\n if (typeof reference !== \"string\")\n throw new OperationFailure(\"files.place takes the input's file reference\", {\n dispatch: \"not_sent\",\n });\n // A field is data naming one input; anything else, such as page code, names none.\n if (Either.isLeft(Schema.decodeUnknownEither(FileField)(field)))\n throw fileFailure(new FileRefused({ reason: \"field_not_found\" }));\n // The site's limits go to the host only when the script names them, and only as limits.\n const limits = Schema.decodeUnknownEither(SiteFileLimits)({\n ...(maxBytes === undefined ? {} : { maxBytes }),\n ...(extensions === undefined ? {} : { extensions }),\n });\n if (Either.isLeft(limits))\n throw new OperationFailure('files.place takes maxBytes as a positive whole number of bytes and extensions as file name endings such as \".pdf\"', { dispatch: \"not_sent\" });\n try {\n const placed = await settle(files.place({\n reference,\n field,\n timeoutSec: kernelTimeoutSec(Math.min((timeoutSec ?? 30) * 1000, options.deadline.remainingMs())),\n ...limits.right,\n }));\n dispatched();\n return placed;\n }\n catch (error) {\n if (!(error instanceof FileRefused) || error.dispatched === true)\n dispatched();\n throw fileFailure(error);\n }\n },\n collect: async (trigger, collectOptions) => {\n const files = channel();\n let slot;\n try {\n slot = await settle(files.arm());\n }\n catch (error) {\n throw fileFailure(error);\n }\n try {\n await trigger();\n }\n catch (error) {\n // The capture ends with the trigger, so nothing it armed outlives the failure.\n await Effect.runPromise(Effect.ignore(files.collect({ slot, timeoutMs: 0 })));\n throw error;\n }\n const timeoutMs = Math.min(collectOptions?.timeoutMs ?? downloadWaitMs, Math.max(0, options.deadline.remainingMs()));\n try {\n return await settle(files.collect({ slot, timeoutMs }));\n }\n catch (error) {\n throw collectFailure(error);\n }\n },\n collectAll: async (trigger, collectOptions) => {\n const files = channel();\n const collectAll = files.collectAll;\n if (collectAll === undefined)\n throw new OperationFailure(\"This host cannot collect every download a trigger starts (files.collectAll); use files.collect for one download\", { dispatch: \"not_sent\" });\n const max = collectOptions?.max;\n if (max !== undefined && !(Number.isSafeInteger(max) && max >= 1))\n throw new OperationFailure(\"files.collectAll takes max as a positive whole number\", {\n dispatch: \"not_sent\",\n });\n let slot;\n try {\n slot = await settle(files.arm());\n }\n catch (error) {\n throw fileFailure(error);\n }\n try {\n await trigger();\n }\n catch (error) {\n // The capture ends with the trigger, so nothing it armed outlives the failure.\n await Effect.runPromise(Effect.ignore(collectAll({ slot, timeoutMs: 0, max: 1 })));\n throw error;\n }\n const timeoutMs = Math.min(collectOptions?.timeoutMs ?? downloadWaitMs, Math.max(0, options.deadline.remainingMs()));\n try {\n return await settle(collectAll({ slot, timeoutMs, ...(max === undefined ? {} : { max }) }));\n }\n catch (error) {\n throw collectFailure(error);\n }\n },\n screenshot: async (shot = {}) => {\n const files = channel();\n if (files.screenshot === undefined)\n throw new OperationFailure(\"This run's host takes no screenshots\", { dispatch: \"not_sent\" });\n // The target is data the host writes into its own locator; anything else names no element.\n // An option left undefined is no option; anything but an options object still names no\n // target.\n const given = typeof shot === \"object\" && shot !== null && !Array.isArray(shot)\n ? Object.fromEntries(Object.entries(shot).filter(([, value]) => value !== undefined))\n : shot;\n const target = Schema.decodeUnknownEither(ScreenshotTarget)(given);\n if (Either.isLeft(target))\n throw fileFailure(new FileRefused({ reason: \"field_not_found\" }));\n try {\n return await settle(files.screenshot({\n ...target.right,\n timeoutMs: Math.min(shot.timeoutMs ?? downloadWaitMs, Math.max(0, options.deadline.remainingMs())),\n }));\n }\n catch (error) {\n // A picture over the caps is the host's limit, as a download's is; it sent nothing.\n const overCap = error instanceof FileRefused ? downloadCapFailures[error.reason] : undefined;\n if (overCap !== undefined)\n throw new OperationFailure(overCap.replace(\"downloaded file\", \"screenshot\"), {\n cause: error,\n dispatch: \"not_sent\",\n });\n throw fileFailure(error);\n }\n },\n };\n};\n/**\n * The context's `fillCard` over the host's card fill. A refusal typed nothing; once a value may\n * have reached the page, a live run marks a possible dispatch, as a file placement does.\n */\nconst scriptFillCard = (options) => async (step) => {\n const cardFill = options.cardFill;\n if (cardFill === undefined || options.offline === true)\n throw new OperationFailure(\"This run has no card fill\", { dispatch: \"not_sent\" });\n const request = Schema.decodeUnknownEither(ScriptCardFillRequest)(step, {\n onExcessProperty: \"error\",\n });\n if (Either.isLeft(request))\n throw new OperationFailure(\"fillCard takes one to four fields, each its own selector and a card handle ask returned, each handle once, or card slots with the checkout's total\", { dispatch: \"not_sent\" });\n const resume = options.deadline.suspend();\n try {\n const answer = Schema.decodeUnknownSync(ScriptCardFillAnswer)(await cardFill(request.right));\n const typed = answer.outcome === \"filled\" || answer.typed;\n if (typed && options.journal !== undefined)\n Effect.runSync(options.journal.enteringDispatch);\n if (answer.outcome === \"filled\")\n return { outcome: answer.outcome, fields: answer.fields };\n throw new OperationFailure(answer.message, { dispatch: typed ? \"unknown\" : \"not_sent\" });\n }\n finally {\n resume();\n }\n};\n/** Builds the context the runtime hands a Kernel script. */\nconst makeKernelOperationContext = (options) => {\n const ask = scriptAsk(options.scriptInput, options);\n return {\n kernel: options.kernel,\n sessionId: options.sessionId,\n siteOrigin: options.siteOrigin,\n siteDomain: options.siteDomain,\n input: options.input,\n // Records how the run proved its effect, a read-back unless the site's message says so.\n verified: (proof) => {\n const kind = proof?.confirmation ?? \"readback\";\n if (options.write?.confirmation === \"unverifiable\")\n throw new WriteConfirmationRefused({ declared: \"unverifiable\", recorded: kind });\n if (options.journal !== undefined)\n Effect.runSync(options.journal.confirmed(kind));\n },\n // Marks a named commit step sent just before the execute call that dispatches it.\n enteringCommit: (name) => {\n if (options.journal === undefined)\n return;\n const entered = Effect.runSync(Effect.either(options.journal.enteringCommit(name)));\n if (entered._tag === \"Left\")\n throw entered.left;\n },\n // A host journal without it cannot record the click unsent, so the step stays sent.\n // `siteRefused` goes to the host only as the script's own word, so a host that checks each\n // step's proof can tell it from a bare call.\n notCommitted: (name, said) => {\n if (options.journal === undefined)\n return;\n const revert = options.journal.notCommitted;\n if (revert === undefined)\n throw new CommitAlreadySent({ name });\n const reverted = Effect.runSync(Effect.either(said?.siteRefused === true ? revert(name, { siteRefused: true }) : revert(name)));\n if (reverted._tag === \"Left\")\n throw reverted.left;\n },\n remainingMs: () => options.deadline.remainingMs(),\n errors: operationErrors,\n rejectedSignIn: (request) => settle(inspectSignInRejection(options, request)),\n ensureSignedIn: options.ensureSignedIn,\n decideDialog: async (shown) => {\n const decide = options.dialogs;\n if (decide === undefined)\n throw new DialogFailure({ reason: \"unavailable\" });\n const report = Schema.decodeUnknownEither(DialogReport)(shown);\n if (Either.isLeft(report))\n throw new DialogFailure({ reason: \"invalid_request\" });\n const resume = options.deadline.suspend();\n try {\n const choice = await settle(decide({\n interactionId: crypto.randomUUID(),\n ...report.right,\n message: report.right.message.slice(0, dialogMessageLimit),\n }));\n return Schema.decodeUnknownSync(DialogChoice)(choice, { onExcessProperty: \"error\" });\n }\n finally {\n resume();\n }\n },\n // The runtime checks every id and option against the declarations; the types only guide.\n ask,\n askOne: scriptAskOne(ask),\n handOff: scriptHandOff(ask, options.questions),\n fillCard: scriptFillCard(options),\n files: scriptFiles(options),\n waitPastChallenge: async ({ ready }) => {\n // The SDK accepts only a whole-millisecond request timeout.\n const limitMs = Math.floor(Math.min(challengeSolverWaitMs, options.deadline.remainingMs()));\n const answer = await options.kernel.browsers.playwright.execute(options.sessionId, {\n code: waitPastChallengeCode(ready, limitMs),\n timeout_sec: kernelTimeoutSec(Math.min(limitMs + 10_000, options.deadline.remainingMs())),\n }, { maxRetries: 0, timeout: limitMs + 20_000 });\n if (answer.success !== true)\n throw new OperationFailure(`waitPastChallenge failed: ${String(answer.error)}`, {\n stderr: answer.stderr,\n });\n const result = Schema.decodeUnknownSync(WaitResult)(answer.result);\n if (!result.cleared)\n throw new ChallengeFailure({\n code: \"Unavailable\",\n solverWaitMs: Math.max(0, Math.round(result.waitedMs)),\n });\n },\n };\n};\nexport const isKernelOperation = (value) => typeof value === \"object\" &&\n value !== null &&\n Reflect.get(value, \"kind\") === \"kernel\" &&\n typeof Reflect.get(value, \"run\") === \"function\";\n/**\n * Page code that wraps the page's and locators' `click` for one call. A click Playwright made that\n * timed out only waiting for the page load it started counts as done once the main frame next\n * commits, within the navigation budget from the click and before the call's own limit. Only a\n * commit after the timeout counts, so a URL the click's own handler changed in place doesn't. A\n * page that doesn't commit by then leaves the click's own timeout, as before. Every other click\n * is Playwright's own, and a `page` that isn't Playwright's is left as it is. Each wrapper holds\n * Playwright's own click, which the next call wraps instead of a wrapper a call left behind. It is\n * one line, so the call's code keeps its line numbers.\n */\nconst clickNavigationWait = String.raw `(until) => {\n if (typeof page === \"undefined\" || typeof page?.mainFrame !== \"function\" || typeof page.locator !== \"function\") return () => {};\n const own = Symbol.for(\"pomerado.clickNavigation.original\");\n const wrap = (prototype) => {\n const click = prototype.click?.[own] ?? prototype.click;\n const waited = async function (...args) {\n const tab = typeof this.mainFrame === \"function\" ? this : this.page();\n const startedAt = Date.now();\n try {\n return await click.apply(this, args);\n } catch (error) {\n if (error?.name !== \"TimeoutError\" || !/-\\s+click action done[^\\n]*\\n[^\\n]*-\\s+waiting for scheduled navigations to finish[^\\n]*\\s*$/u.test(String(error.message))) throw error;\n let seen;\n let timer;\n const committed = await new Promise((resolve) => {\n seen = (frame) => {\n if (frame === tab.mainFrame()) resolve(true);\n };\n tab.on(\"framenavigated\", seen);\n timer = setTimeout(resolve, Math.min(startedAt + ${timeoutDefaults.navigation}, until) - Date.now(), false);\n });\n tab.off(\"framenavigated\", seen);\n clearTimeout(timer);\n if (!committed) throw error;\n }\n };\n waited[own] = click;\n prototype.click = waited;\n return () => {\n if (prototype.click === waited) prototype.click = click;\n };\n };\n const restores = [wrap(Object.getPrototypeOf(page)), wrap(Object.getPrototypeOf(page.locator(\":root\")))];\n return () => restores.forEach((restore) => restore());\n}`.replace(/\\n\\s*/gu, \" \");\n/**\n * A call's code with the run's effect declared ahead of it, on the same line, as `pickerCode`\n * reads it (`__pomeradoEffect`).\n */\nexport const withRunEffect = (code, effect) => `const __pomeradoEffect = ${JSON.stringify(effect)};${code}`;\n/**\n * A call's code inside `clickNavigationWait`, which ends a second before its `timeout_sec`, with\n * that end declared as `__pomeradoCallEnds`, where a pending `waitForOutcome` ends its hold.\n */\nconst withClickNavigationWait = (code, timeoutSec = 60) => `const __pomeradoCallEnds = Date.now() + ${timeoutSec * 1000 - 1000}; const __pomeradoClickNavigation = (${clickNavigationWait})(__pomeradoCallEnds); try {${code}\n} finally { __pomeradoClickNavigation(); }`;\n/**\n * One run of a script's function against a Kernel client: Kernel's own, or the saved-DOM stand-in.\n * A throw that is not one of its typed errors becomes an `OperationFailure`.\n */\nexport const runKernelScript = (operation, input, browser) => Effect.suspend(() => {\n let actionTimeout;\n let calls = 0;\n const effect = browser.effect ?? (operation.write === undefined ? \"read\" : \"write\");\n // The host's sign-in under way. Every browser call the script starts meanwhile, from a timer\n // or an un-awaited promise too, waits for it and is only then sent, in order, so its own\n // timeout starts then. A failed sign-in releases them as well.\n let signingIn;\n const afterSignIn = (call) => signingIn === undefined ? call() : signingIn.then(call, call);\n const kernel = {\n browsers: {\n playwright: {\n execute: (sessionId, body, options) => {\n // Counted when made: a held call goes out later, even after the script ends.\n calls += 1;\n return afterSignIn(() => settle(Effect.sync(() => {\n actionTimeout = undefined;\n }).pipe(Effect.flatMap(() => Effect.tryPromise({\n try: () => browser.kernel.browsers.playwright.execute(sessionId, {\n ...body,\n code: withClickNavigationWait(withRunEffect(body.code, effect), body.timeout_sec),\n }, options),\n catch: (error) => error instanceof Error ? error : new Error(String(error), { cause: error }),\n })), Effect.tap((answer) => Effect.sync(() => {\n actionTimeout = nativeActionTimeout(answer);\n })))));\n },\n },\n },\n };\n // The host's sign-in, with the deadline paused. A refusal before the script's first call\n // sent nothing; after it, the script's own calls may have.\n const signInOnce = async (signIn) => {\n const resume = browser.deadline.suspend();\n try {\n const { signedInAgain } = await signIn();\n return { signedInAgain: signedInAgain === true };\n }\n catch (error) {\n if (error instanceof CredentialsRejected)\n throw error;\n throw new OperationFailure(\"The host could not sign the site in again\", {\n cause: error,\n dispatch: calls === 0 ? \"not_sent\" : \"unknown\",\n sessionLoss: \"session_not_kept\",\n });\n }\n finally {\n resume();\n }\n };\n // A call while one is under way joins it rather than signing in again.\n const ensureSignedIn = async () => {\n const signIn = browser.signIn;\n if (signIn === undefined || browser.offline === true)\n return { signedInAgain: false };\n signingIn ??= signInOnce(signIn).finally(() => {\n signingIn = undefined;\n });\n return signingIn;\n };\n return Effect.tryPromise({\n try: async () => {\n // A page that lost its session since the host signed in is signed in again first.\n await ensureSignedIn();\n const context = makeKernelOperationContext({\n ...browser,\n kernel,\n input,\n ensureSignedIn,\n ...(operation.write === undefined ? {} : { write: operation.write }),\n ...(operation.questions === undefined ? {} : { questions: operation.questions }),\n });\n const output = await operation.run({\n ...context,\n decideDialog: (report) => afterSignIn(() => context.decideDialog(report)),\n // Typing a card is a browser call too.\n fillCard: (step) => {\n calls += 1;\n return afterSignIn(() => context.fillCard(step));\n },\n // Placing a file is a browser call: it waits for a sign-in under way and counts as one.\n files: {\n ...context.files,\n place: (reference, options) => {\n calls += 1;\n return afterSignIn(() => context.files.place(reference, options));\n },\n },\n });\n // A returned Effect never ran, so only the script's own execute calls may have sent.\n if (Effect.isEffect(output))\n throw scriptFailure(output, browser.scriptError, calls === 0 ? \"not_sent\" : \"unknown\");\n return output;\n },\n catch: (error) => {\n const failure = scriptFailure(error, browser.scriptError);\n return failure instanceof OperationFailure &&\n actionTimeout !== undefined &&\n failure.message === actionTimeout.slice(0, 4096)\n ? new BrowserActionTimeout(failure)\n : failure;\n },\n });\n});\n"
|
|
25
25
|
},
|
|
26
26
|
{
|
|
27
27
|
"path": "runtime/variants.js",
|
|
@@ -89,7 +89,7 @@
|
|
|
89
89
|
},
|
|
90
90
|
{
|
|
91
91
|
"path": "browser/wait.js",
|
|
92
|
-
"text": "import { timeoutDefaults } from \"../runtime/deadline.js\";\nimport { outcomeKindsCode, readyWaitCode } from \"./action-waits.js\";\n/**\n * The page-progress tracker every wait shares. A wait keeps going while the page shows progress\n * and fails once it has shown none for `noProgressMs`. Progress is any of:\n *\n * - the author's `loading` locator showing (for as long as it shows);\n * - a generic loading sign, within `region` when one is named, coming, going, or new: a busy\n * region, an indeterminate progress bar, or a skeleton, shimmer, spinner or loader class (never\n * on a form control) counts while it shows until it has held for `noProgressMs`, or in\n * `waitForOutcome` after an action, for as long as it shows. Determinate\n * bars (ratings, steps, meters) never count, and signs showing before the action in the same\n * number, or class hints already there at the first look, are the page's own decoration. One\n * page call counts them at each look; a sign element in content the browser skips rendering\n * does not show, and a look whose count runs out of time takes the class hints as unchanged.\n * `waitForRows` also counts a sign beside its rows (in their container or the element around\n * it, never inside a row, and only when it is visible): one there before the action, in the\n * same number, is the page's own; any other counts while it shows, until it and the rows have\n * held for `noProgressMs` with no request the action started in flight;\n * - in `waitForOutcome` after an action, a countdown ticking, within `region` when one is named:\n * a visible element whose own short text keeps its words while its numbers fall, read as a\n * clock (0:10 to 0:09), such as a review step that submits on its own at zero. One showing\n * before the action is the page's own, such as a hold timer, and never counts;\n * - DOM changes inside the author's `region` (never the whole page: carousels and ads never stop);\n * - one of the site's own `document`, `xhr` or `fetch` requests in flight (the site is\n * `siteDomain`, else a conservative guess from the page's host). A request the action started\n * counts until it ends, up to `lateFillCap`, and the page then gets `unchangedMs` to render its\n * answer; any other counts for 10 s and keeps the page busy for 4 s, since long-polls and\n * streams stay open. Beacons, images, fonts and media never count, and a request repeated with\n * the same method, URL and body (numbers aside) at a steady interval is a poll and is ignored;\n * - the page's URL changing, or the page being replaced;\n * - the wait's own reads changing: an outcome's matches, rows or values filling or changing.\n *\n * Network activity alone never proves the content is coming; it only keeps a wait alive.\n */\nconst progressCode = String.raw `\nconst waitLimits = Object.freeze(${JSON.stringify({\n navigation: timeoutDefaults.navigation,\n action: timeoutDefaults.action,\n answer: timeoutDefaults.answer,\n answerCap: timeoutDefaults.answerCap,\n settle: timeoutDefaults.settle,\n unchanged: timeoutDefaults.unchanged,\n lateFillCap: timeoutDefaults.lateFillCap,\n})});\nconst waitRecords = [];\n// Every wait this call ran, oldest first, each with a sentence saying how it ended.\nconst waitReport = () => waitRecords.map((record) => ({ ...record }));\nconst waitSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n// A promise, or fallback once ms have passed without it settling; its timer never outlives it.\nconst waitBounded = (promise, ms, fallback = undefined) => {\n let timer;\n return Promise.race([\n promise,\n new Promise((resolve) => {\n timer = setTimeout(() => resolve(fallback), Math.max(0, ms));\n }),\n ]).finally(() => clearTimeout(timer));\n};\nconst waitSeconds = (ms) => (Math.max(0, ms) / 1000).toFixed(1) + \" s\";\n// How many reads in a row the running wait lost to a closed target. waitProgress sets it to 0 as a\n// wait starts, and again at the sample after a look that lost none.\nlet waitClosedLosses = 0;\n// A read the page cut short by replacing or removing what it read, so the next look reads again.\n// A cross-site frame runs as a target of its own, and a read of one that went reports a closed\n// target. While the call's page is open, that target was a frame of it, which goes once. A page\n// that closed, such as a popup the wait reads, fails every look instead, so the third such read in\n// a row throws.\nconst waitContextLost = (error) => {\n const message = String(error?.message);\n if (/Execution context was destroyed|Frame was detached/.test(message)) return true;\n if (!/Target page, context or browser has been closed|Target closed/.test(message) || page.isClosed()) return false;\n waitClosedLosses += 1;\n return waitClosedLosses < 3;\n};\n// Generic loading signs. A busy region or an indeterminate progress bar says the page is loading;\n// a determinate bar (one with a value) is a rating, a step or a meter. A class that names a\n// skeleton, shimmer, spinner or loader is only a hint, and never on a form control.\nconst waitLoadingSigns = '[aria-busy=\"true\"], [role=\"progressbar\"]:not([aria-valuenow], [aria-valuetext])';\nconst waitLoadingClasses =\n ':is([class*=\"skeleton\" i], [class*=\"shimmer\" i], [class*=\"spinner\" i], [class*=\"loader\" i]):not(input, select, textarea, button, option, [role=\"progressbar\"])';\n// How long one look's sign count may run in the page, which runs one call at a time, before it\n// leaves the class hints uncounted.\nconst waitClassesBudgetMs = 250;\n// Runs in the page, as page.evaluate(spec) or region.evaluateAll(elements, spec): how many generic\n// loading signs and class hints show in the document or the region's elements, through open\n// shadow roots, in one call, since a locator's count can cost a protocol call for each element it\n// matches. A sign shows as a visible locator match does: rendered, not hidden by visibility, with\n// a box, or for display: contents, a child element or text that shows. An element in content the\n// browser skips rendering (content-visibility) does not show, and its box is never read: reading\n// it would lay that content out, one element at a time. A display: contents sign is judged by its\n// children even there, its text by a range's box, as the visible check judges it. A closed shadow\n// root is out of page code's reach, so a sign inside one, which a Patchright locator could count,\n// is not counted. Class hints left uncounted after the budget are null.\nconst waitSignsInPage = (first, second) => {\n const [roots, spec] = second === undefined ? [[document], first] : [first, second];\n const started = performance.now();\n const scopes = new Set(roots);\n for (const scope of scopes) {\n if (scope.shadowRoot) scopes.add(scope.shadowRoot);\n for (const node of scope.querySelectorAll(\"*\")) if (node.shadowRoot) scopes.add(node.shadowRoot);\n }\n const boxed = (box) => box.width > 0 && box.height > 0;\n const textShows = (text) => {\n const range = text.ownerDocument.createRange();\n range.selectNode(text);\n return boxed(range.getBoundingClientRect());\n };\n const shows = (element) => {\n const rendered = typeof element.checkVisibility !== \"function\" ||\n element.checkVisibility({ visibilityProperty: true, contentVisibilityAuto: true });\n // Without a box: display: contents shows when a child element or text does; hidden or skipped\n // content does not.\n if (!rendered)\n return !element.checkVisibility() && getComputedStyle(element).display === \"contents\" &&\n [...element.childNodes].some((child) =>\n child.nodeType === Node.ELEMENT_NODE ? shows(child) : child.nodeType === Node.TEXT_NODE && textShows(child));\n return boxed(element.getBoundingClientRect());\n };\n const count = (selector, budgetMs) => {\n const seen = new Set();\n let shown = 0;\n for (const scope of scopes)\n for (const element of scope.querySelectorAll(selector)) {\n if (seen.has(element)) continue;\n seen.add(element);\n if (shows(element)) shown += 1;\n if (performance.now() - started > budgetMs) return null;\n }\n return shown;\n };\n // Countdown ticks, read when spec.countdown: an element whose own text is short and holds a\n // number is kept between looks. The same text with its numbers lower, read as a clock (0:10 to\n // 0:09), is a tick. The baseline look reads every element, however long that takes, and marks\n // what shows as the wait's own, such as a hold timer from before the action, which never ticks\n // for it and is not measured again while its text keeps its words. A later look reads no\n // further once past the budget.\n const ticks = () => {\n const timers = (globalThis[Symbol.for(\"pomerado.waitCountdowns\")] ??= new WeakMap());\n const begun = performance.now();\n const seen = new Set();\n let ticked = 0;\n for (const scope of scopes) {\n const walker = document.createTreeWalker(scope, NodeFilter.SHOW_TEXT);\n for (let text = walker.nextNode(); text !== null; text = walker.nextNode()) {\n if (!spec.baseline && performance.now() - begun > spec.budgetMs) return ticked;\n const element = text.parentElement;\n if (element === null || seen.has(element) || !/\\d/.test(text.data)) continue;\n seen.add(element);\n let own = \"\";\n for (const child of element.childNodes) if (child.nodeType === Node.TEXT_NODE) own += child.data;\n own = own.trim();\n if (own.length > 80) continue;\n const shape = own.replace(/\\d+/g, \"#\");\n const last = timers.get(element);\n const same = last?.shape === shape;\n if ((!spec.baseline && same && last.wait === spec.key) || !shows(element)) continue;\n const numbers = own.match(/\\d+/g).map(Number);\n if (!spec.baseline && same) {\n const at = numbers.findIndex((value, index) => value !== last.numbers[index]);\n if (at >= 0 && numbers[at] < last.numbers[at]) ticked += 1;\n }\n timers.set(element, { shape, numbers, wait: spec.baseline ? spec.key : undefined });\n }\n }\n return ticked;\n };\n const counted = { signs: count(spec.signs, Infinity), classes: count(spec.classes, spec.budgetMs) };\n if (spec.countdown) counted.ticks = ticks();\n return counted;\n};\nconst waitSignsSpec = { signs: waitLoadingSigns, classes: waitLoadingClasses, budgetMs: waitClassesBudgetMs };\n// A request the wait's action started, while it ran or in the second after, is the answer on its\n// way: it counts as progress and keeps the page busy until it ends, up to\n// lateFillCap. Any other request counts as progress for up to 10 s, and keeps the page busy for up\n// to 4 s (or the no-progress window when shorter): a long-poll or a stream stays open with nothing\n// to come, and starts on its own.\nconst waitCausedMs = 1000;\nconst waitInflightMs = 10000;\nconst waitBusyRequestMs = 4000;\n// The site's registrable domain, when the code gave none: the last two labels of the page's host,\n// or three under a country's shared second level (example.co.uk, never co.uk). Pass the context's\n// siteDomain, which the host computed with the public suffix list, to be exact.\nconst waitSiteDomain = (host) => {\n const labels = host.split(\".\");\n if (labels.length <= 2 || /^\\d+$/.test(labels.at(-1))) return host;\n const shared = labels.at(-1).length === 2 &&\n /^(?:ac|co|com|edu|gen|go|gob|gov|gv|in|ind|info|int|lg|ltd|me|mil|ne|net|nhs|nic|nom|or|org|plc|sch|web)$/.test(labels.at(-2));\n return labels.slice(shared ? -3 : -2).join(\".\");\n};\n// What makes two requests the same one again: method, path, query and body, with every number\n// (counters, timestamps, cache busters) read as the same.\nconst waitRequestKey = (request) => {\n const url = new URL(request.url());\n const body = String(request.postData() ?? \"\").slice(0, 4096).replace(/\\d+/g, \"#\");\n let hash = 2166136261;\n for (let i = 0; i < body.length; i += 1) hash = Math.imul(hash ^ body.charCodeAt(i), 16777619);\n return request.method() + \" \" + url.origin + url.pathname + url.search.replace(/\\d+/g, \"#\") + \" \" + (hash >>> 0).toString(36);\n};\nconst waitProgress = (options = {}) => {\n const noProgressMs = options.noProgressMs ?? waitLimits.answer;\n const key = \"pomerado.waitProgress.\" + Date.now() + \".\" + Math.random();\n waitClosedLosses = 0;\n let closedAtSample = 0;\n let started = Date.now();\n // Requests that start before this are the action's: from the baseline look, taken just before\n // the action, to a second after it returned. A wait without an action causes none.\n let causedUntil = -Infinity;\n let acted = false;\n let lastProgress = started;\n let signs = {};\n const mark = (kind, at = Date.now()) => {\n const sign = (signs[kind] ??= { first: at - started, last: at - started });\n sign.last = at - started;\n if (at > lastProgress) lastProgress = at;\n };\n const sameSite = (url) => {\n try {\n const host = new URL(url).hostname;\n const domain = options.siteDomain ?? waitSiteDomain(new URL(page.url()).hostname);\n return domain !== \"\" && (host === domain || host.endsWith(\".\" + domain));\n } catch {\n return false;\n }\n };\n // The site's requests in flight, by request: when each started and what makes it the same again.\n const pending = new Map();\n const starts = new Map();\n const polls = new Set();\n let ignoredRepeats = 0;\n const onRequest = (request) => {\n if (![\"document\", \"xhr\", \"fetch\"].includes(request.resourceType()) || !sameSite(request.url())) return;\n const key = waitRequestKey(request);\n const now = Date.now();\n // A poll repeats the same request at a steady interval: from its third start, once two\n // intervals of at least 50 ms agree within half, it is ignored with every copy in flight.\n // Requests to one path that differ, such as an API's different queries, never are.\n const times = [...(starts.get(key) ?? []), now].slice(-3);\n starts.set(key, times);\n if (!polls.has(key) && times.length === 3) {\n const [first, second] = [times[1] - times[0], times[2] - times[1]];\n if (Math.min(first, second) >= 50 && Math.abs(first - second) <= Math.max(first, second) / 2) {\n polls.add(key);\n for (const [other, entry] of pending) if (entry.key === key) pending.delete(other);\n }\n }\n if (polls.has(key)) {\n ignoredRepeats += 1;\n return;\n }\n pending.set(request, { at: now, key, caused: now <= causedUntil });\n mark(\"site request\");\n };\n // When the action's last request ended: the page then gets unchangedMs to render its answer.\n let causedEnded = -Infinity;\n const onDone = (request) => {\n const entry = pending.get(request);\n if (entry === undefined) return;\n pending.delete(request);\n if (entry.caused) causedEnded = Date.now();\n mark(\"site request\");\n };\n page.on(\"request\", onRequest);\n page.on(\"requestfinished\", onDone);\n page.on(\"requestfailed\", onDone);\n let url = page.url();\n // Generic signs, each kind with its count before the action (or, for class hints, at the first\n // look), its count at the last look and when that last changed. A sign counts while it shows\n // more than before, until its count has held for the no-progress window. A sign that stays is\n // part of the page. (waitForRows also judges the signs beside its rows: see listSigns.)\n const generic = {\n signs: { holdMs: noProgressMs, before: undefined, count: 0, changedAt: started, shows: false },\n classes: { holdMs: noProgressMs, before: undefined, count: 0, changedAt: started, shows: false, firstLook: true },\n };\n let loadingShows = false;\n let region = { count: 0, targets: 0 };\n // One look at the page's signs. The baseline look, taken before the action, notes them without\n // counting anything as progress.\n // Quiet time runs to the latest look that could see progress: the first look after the start\n // only installs the region's observer and notes the signs.\n let samples = 0;\n let sampledAt = started;\n const sample = async (changes = [], baseline = false) => {\n const now = Date.now();\n samples += 1;\n sampledAt = now;\n // A look that lost a read to a closed target saw no progress by it. One that lost none ends\n // the run of such losses.\n if (waitClosedLosses > closedAtSample) changes = changes.filter((kind) => kind !== \"page replaced\");\n else waitClosedLosses = 0;\n closedAtSample = waitClosedLosses;\n const note = (kind) => {\n if (!baseline) mark(kind, now);\n };\n for (const kind of changes) note(kind);\n if (page.url() !== url) {\n url = page.url();\n note(\"URL change\");\n }\n for (const { at, caused } of pending.values())\n if (now - at < (caused ? waitLimits.lateFillCap : waitInflightMs)) {\n note(\"site request\");\n break;\n }\n try {\n loadingShows = options.loading !== undefined && (await options.loading.filter({ visible: true }).count()) > 0;\n if (loadingShows) note(\"loading sign\");\n // A generic sign counts when it comes or goes, and while it is new: see generic above. Both\n // kinds are counted in one page call; class hints left uncounted are no news at this look.\n // After an action, waitForOutcome's call also reads countdowns.\n const spec = options.whileSending && acted ? { ...waitSignsSpec, key, countdown: true, baseline } : waitSignsSpec;\n const counted = await (options.region === undefined\n ? page.evaluate(waitSignsInPage, spec)\n : options.region.evaluateAll(waitSignsInPage, spec));\n if (counted.ticks > 0) note(\"countdown\");\n for (const [name, sign] of Object.entries(generic)) {\n // A count left undone is no news: the last count stands, so a sign showing keeps its\n // hold, and a baseline or first look notes nothing.\n const fresh = counted[name];\n if (fresh === null && (baseline || (sign.firstLook && sign.before === undefined))) continue;\n const count = fresh ?? sign.count;\n if (baseline || (sign.firstLook && sign.before === undefined)) {\n sign.before = count;\n sign.changedAt = now;\n } else {\n if (count !== sign.count) {\n sign.changedAt = now;\n note(\"loading sign\");\n }\n sign.shows = count > (sign.before ?? 0) && now - sign.changedAt < sign.holdMs;\n if (sign.shows) note(\"loading sign\");\n }\n sign.count = count;\n }\n if (options.region !== undefined) {\n const seen = await options.region.evaluateAll((elements, key) => {\n const state = (globalThis[Symbol.for(key)] ??= { count: 0, targets: new Set() });\n state.observer ??= new MutationObserver((records) => {\n state.count += records.length;\n });\n for (const element of elements)\n if (!state.targets.has(element)) {\n state.targets.add(element);\n state.observer.observe(element, {\n subtree: true,\n childList: true,\n characterData: true,\n attributes: true,\n attributeFilter: [\"class\", \"hidden\", \"aria-busy\", \"aria-hidden\", \"src\", \"value\", \"disabled\"],\n });\n }\n return { count: state.count, targets: state.targets.size };\n }, key);\n // The first look only installs the observer; a region that appears later is progress.\n if (seen.count !== region.count || (seen.targets !== region.targets && region.targets !== 0))\n note(\"region changes\");\n region = seen;\n }\n } catch (error) {\n const closedBefore = waitClosedLosses;\n if (!waitContextLost(error)) throw error;\n if (waitClosedLosses === closedBefore) note(\"page replaced\");\n }\n };\n return {\n // Before the action: what already shows is the page from before it.\n baseline: () => {\n acted = true;\n causedUntil = Infinity;\n // waitForOutcome counts a sign the action brought for as long as it shows: the page is\n // still sending.\n if (options.whileSending) for (const sign of Object.values(generic)) sign.holdMs = Infinity;\n return sample([], true);\n },\n // The budgets start once the action returns; requests it started stay in flight.\n begin: () => {\n started = Date.now();\n causedUntil = acted ? started + waitCausedMs : -Infinity;\n lastProgress = started;\n signs = {};\n samples = 0;\n },\n // Without a baseline, a sign already showing at the first look is the page still loading.\n sample: (changes) => sample(changes),\n quietMs: () => (samples < 2 ? 0 : sampledAt - lastProgress),\n // A loading sign showing or a site request in flight, at the last look. waitForRows judges the\n // generic signs itself, beside its rows (pageSigns false).\n busy: (pageSigns = true) => {\n const now = Date.now();\n const busyRequestMs = Math.min(noProgressMs, waitBusyRequestMs);\n return loadingShows || (pageSigns && (generic.signs.shows || generic.classes.shows)) ||\n now - causedEnded < (options.unchangedMs ?? waitLimits.unchanged) ||\n [...pending.values()].some(({ at, caused }) => now - at < (caused ? waitLimits.lateFillCap : busyRequestMs));\n },\n // A request the action started still in flight.\n causedInflight: () => {\n const now = Date.now();\n return [...pending.values()].some(({ at, caused }) => caused && now - at < waitLimits.lateFillCap);\n },\n diagnostics: () => ({\n signs: Object.fromEntries(Object.entries(signs).map(([kind, sign]) => [kind, { ...sign }])),\n quietSinceMs: lastProgress - started,\n inflight: pending.size,\n ignoredRepeats,\n }),\n describe: () => {\n const entries = Object.entries(signs);\n const seen = entries.length === 0\n ? \"no progress seen\"\n : \"progress seen: \" +\n entries\n .map(([kind, { first, last }]) =>\n kind + \" \" + (last > first ? waitSeconds(first) + \"–\" + waitSeconds(last) : \"at \" + waitSeconds(first)))\n .join(\", \") +\n \"; last progress at \" + waitSeconds(lastProgress - started);\n return seen + (ignoredRepeats > 0 ? \"; ignored \" + ignoredRepeats + \" repeating requests\" : \"\");\n },\n stop: async (inPage = true) => {\n page.off(\"request\", onRequest);\n page.off(\"requestfinished\", onDone);\n page.off(\"requestfailed\", onDone);\n if (inPage && options.region !== undefined) {\n const cleanup = options.region\n .evaluateAll((elements, key) => {\n globalThis[Symbol.for(key)]?.observer?.disconnect();\n delete globalThis[Symbol.for(key)];\n }, key)\n .catch(() => undefined);\n let timer;\n await Promise.race([cleanup, new Promise((resolve) => { timer = setTimeout(resolve, 250); })]);\n clearTimeout(timer);\n }\n },\n };\n};\nconst waitRecord = (record) => {\n waitRecords.push(record);\n return record;\n};\n`;\n/**\n * `waitForOutcome`, unchanged in what it decides, now with a progress budget: it fails as\n * `outcome_unknown` once the page shows no outcome and no progress for `noProgressMs`.\n */\nconst outcomeCode = String.raw `\nconst outcomeWaitSeen = (observations) =>\n Object.entries(observations)\n .map(([name, observation]) => {\n const { kind, count, visible, changed, matched, invalid, seen } = observation;\n if (kind === undefined || kind === \"gone\")\n return name + (kind === \"gone\" ? \" (gone) \" : \" \") + visible + \" visible of \" + count +\n (changed === 0 && visible > 0 ? \", unchanged\" : \"\");\n if (kind === \"invalid\") return name + \" \" + invalid + \" invalid fields\";\n if (kind === \"url\") return name + (matched ? \" URL matched\" : \" URL not matched\");\n if (kind === \"check\") return name + (matched ? \" check true\" : \" check not true\");\n if (kind === \"announced\") return name + (matched ? \" announced\" : \" no matching announcement of \" + seen + \" seen\");\n return name + (matched ? \" \" + kind + \" matched\" : \" no matching \" + kind + \" of \" + seen + \" seen\");\n })\n .join(\", \");\nconst outcomeWaitFailure = (reason, message, observations, extra) =>\n Object.assign(new Error(reason + message), {\n name: \"OutcomeWaitFailure\",\n reason,\n observations,\n ...extra,\n });\n// What each visible element showed before the action, kept in the page by a key of this wait's\n// own; a page the action replaced has none, so everything on it is new.\nconst outcomeWaitNote = (locator, key) =>\n locator.filter({ visible: true }).evaluateAll((elements, key) => {\n const noted = (globalThis[Symbol.for(key)] ??= new WeakMap());\n for (const element of elements) noted.set(element, element.innerText);\n }, key);\nconst outcomeWaitChanged = (locator, key) =>\n locator.filter({ visible: true }).evaluateAll((elements, key) => {\n const noted = globalThis[Symbol.for(key)];\n return elements.filter((element) => noted?.get(element) !== element.innerText).length;\n }, key);\n// Reads the outcomes highest priority last, so a look that sees one also sees a higher one drawn\n// in the same render. The observations keep the listed order.\nconst outcomeWaitObserve = async (outcomes, key, state, events) => {\n const candidates = Array.isArray(outcomes) ? outcomes\n : Object.entries(outcomes).map(([name, locator]) => ({ name, kind: \"locator\", locator }));\n const observations = {};\n for (const candidate of [...candidates].reverse())\n observations[candidate.name] = await outcomeWaitRead(candidate, state, key, events);\n return Object.fromEntries(candidates.map(({ name }) => [name, observations[name]]));\n};\n// How long a look the page holds up may still finish once a response or popup outcome arrived, and\n// once the deadline passed.\nconst outcomeWaitGraceMs = 1000;\nconst outcomeWaitLateMs = 500;\nconst waitForOutcomeResult = async (outcomes, options = {}) => {\n const names = Object.keys(outcomes ?? {});\n if (names.length === 0) throw new TypeError(\"waitForOutcome needs at least one outcome\");\n const candidates = names.map((name) => outcomeWaitCandidate(name, outcomes[name]));\n const timeout = options.timeout ?? waitLimits.answerCap;\n const noProgressMs = options.noProgressMs ?? waitLimits.answer;\n const progress = waitProgress({ ...options, noProgressMs, whileSending: true });\n const events = outcomeWaitEvents(candidates);\n const state = {\n goneSeen: new Set(),\n goneSince: new Map(),\n invalidFields: new Map(),\n invalidBefore: new Map(),\n checked: new Map(),\n announcedText: new Map(),\n announceKey: candidates.some((candidate) => candidate.kind === \"announced\")\n ? \"pomerado.outcomeAnnounce.\" + Date.now() + \".\" + Math.random() : undefined,\n urlBefore: undefined,\n actedAt: -Infinity,\n };\n let looks = 0;\n const finish = (fields, summary) =>\n waitRecord({\n wait: \"waitForOutcome\",\n ...fields,\n elapsedMs: Date.now() - begun,\n looks,\n progress: progress.describe(),\n summary: \"waitForOutcome: \" + summary + \"; \" + progress.describe(),\n });\n let begun = Date.now();\n let key;\n // How long the cleanup may take: 250 ms, and nothing past the wait's hard stop.\n let cleanupMs = () => 250;\n try {\n if (options.action !== undefined) {\n key = \"pomerado.outcomeWait.\" + Date.now() + \".\" + Math.random();\n for (const candidate of candidates) {\n if (candidate.kind === \"locator\") await outcomeWaitNote(candidate.locator, key);\n if (candidate.kind === \"gone\" && (await candidate.locator.filter({ visible: true }).count()) > 0)\n state.goneSeen.add(candidate.name);\n if (candidate.kind === \"invalid\")\n state.invalidBefore.set(candidate.name, outcomeWaitInvalidKey(await candidate.locator.evaluateAll(outcomeWaitInvalidInPage)));\n }\n state.urlBefore = page.url();\n if (state.announceKey !== undefined) await page.evaluate(outcomeWaitAnnounceInPage, { key: state.announceKey, seed: false });\n await progress.baseline();\n state.actedAt = Date.now();\n // A click whose handler opens a native dialog does not return until the dialog is handled,\n // and the wait's dialog listener keeps Playwright from dismissing it: with a dialog outcome,\n // the wait goes on once the action returns or a dialog opens.\n if (candidates.some((candidate) => candidate.kind === \"dialog\")) {\n const acting = Promise.resolve().then(() => options.action());\n acting.catch(() => undefined);\n const first = await Promise.race([acting.then(() => \"acted\"), events.dialogSignal.then(() => \"dialog\")]);\n if (first === \"acted\") await acting;\n } else await options.action();\n }\n progress.begin();\n begun = Date.now();\n // deadline, a Date.now() time such as the call's own, bounds the wait wherever the action left it.\n const until = Math.min(begun + timeout, options.deadline ?? Infinity);\n // Past the deadline, every page call shares outcomeWaitLateMs of grace and then ends: the wait\n // never outlasts hardStop, however long the page holds it.\n const hardStop = until + outcomeWaitLateMs;\n const beforeStop = () => Math.max(0, hardStop - Date.now());\n cleanupMs = () => Math.min(250, beforeStop());\n const unchangedMs = options.unchangedMs ?? waitLimits.unchanged;\n const unchangedFrom = begun + unchangedMs;\n // A page or frame the action is replacing or removing can drop a look midway; the next look\n // reads the page again.\n // The page cannot always be read: a native dialog stops its scripts, and while a navigation\n // is pending Playwright cannot evaluate in it. A look the page holds up ends at the deadline\n // (with outcomeWaitLateMs of grace, so a look begun just before it finishes), at once for a dialog,\n // and outcomeWaitGraceMs after a response or popup outcome arrived, which then decides on the\n // outcomes the page announced as events.\n const unblocked = (reading) => {\n reading.catch(() => undefined);\n const bounded = waitBounded(reading, beforeStop());\n if (!candidates.some((candidate) => [\"response\", \"dialog\", \"popup\"].includes(candidate.kind))) return bounded;\n return Promise.race([\n bounded,\n events.dialogSignal.then(() => undefined),\n events.hitSignal.then(() => waitBounded(reading, Math.min(outcomeWaitGraceMs, beforeStop()))),\n ]);\n };\n const look = () =>\n unblocked(outcomeWaitObserve(candidates, key, state, events).catch((error) => {\n if (waitContextLost(error)) return undefined;\n throw error;\n }));\n const result = (candidate, observations, evidence) => {\n const handles = events.hit(candidate.name)?.handles ?? {};\n // A native dialog stops the page, so the last look it allowed can predate an event outcome\n // that matched since, such as a save's response just before the dialog. Once a dialog opened,\n // each event outcome reads as it stands now, and those that matched besides the winner, the\n // dialog's own outcome included, are on the result and in the summary too.\n const evented = [\"response\", \"dialog\", \"popup\"];\n const dialogOpened = events.dialogOpen();\n const also = !dialogOpened ? []\n : candidates.filter((each) => each !== candidate && evented.includes(each.kind) && events.hit(each.name) !== undefined);\n const observed = !dialogOpened ? observations\n : Object.fromEntries(candidates.flatMap((each) =>\n evented.includes(each.kind) ? [[each.name, outcomeWaitEventRead(each, events)]]\n : observations[each.name] === undefined ? [] : [[each.name, observations[each.name]]]));\n const answer = {\n outcome: candidate.name,\n kind: candidate.kind,\n afterMs: Date.now() - begun,\n looks,\n evidence,\n observations: observed,\n };\n for (const [name, value] of Object.entries(handles)) outcomeWaitHidden(answer, name, value);\n for (const each of also)\n for (const [name, value] of Object.entries(events.hit(each.name).handles))\n if (answer[name] === undefined) outcomeWaitHidden(answer, name, value);\n // A dialog that opened while the wait listened stays open whichever outcome won, and the\n // summary says so.\n if (answer.dialog === undefined) outcomeWaitHidden(answer, \"dialog\", events.dialog());\n finish(\n { outcome: candidate.name },\n '\"' + candidate.name + '\"' + (candidate.kind === \"locator\" ? \"\" : \" (\" + candidate.kind + \")\") + \" showed after \" +\n answer.afterMs + \" ms (\" + looks + (looks === 1 ? \" look)\" : \" looks)\") +\n also.map((each) => '; \"' + each.name + '\" (' + each.kind + \") also matched\").join(\"\") +\n (answer.dialog === undefined ? \"\" : \"; a native \" + answer.dialog.type() + \" dialog is left open on the result's dialog\"),\n );\n return answer;\n };\n // The first look that shows an outcome decides: no second look confirms it. An answer from\n // before the action is kept out of that look by the stale rule below, not by a second look.\n let last;\n let signature;\n let quietBefore = false;\n while (true) {\n // A request the action started that was in flight as the look began counts as in flight for\n // that look's matches, even when it ends while the look runs.\n const inflightAtStart = progress.causedInflight();\n const observations = await look();\n events.rethrow();\n looks += 1;\n last = observations ?? last;\n // A match from before the action stays stale while a request the action started is in flight,\n // but only until the deadline less the unchanged window, so a match the wait returned before\n // such requests held it back still returns in time. One clock read serves this and the\n // deadline below, so the hold never outlasts the deadline even with no unchanged window.\n const now = Date.now();\n const stale = now < unchangedFrom ||\n (now < until - unchangedMs && (inflightAtStart || progress.causedInflight()));\n // With the page unreadable, a native dialog open included, only the outcomes the page\n // announced as events decide, in the listed order: a dialog outcome wins unless a response\n // or popup outcome listed before it already matched, and that one wins with the dialog held.\n const blocked = events.dialogOpen() || (observations === undefined && events.anyHit());\n // While a navigation the action set off is on its way, the elements shown are the old\n // document's, about to be replaced: a locator or invalid fields count only on the new one.\n const replacing = key !== undefined && events.navigating(state.actedAt);\n const shown = candidates.find((candidate) =>\n blocked ? [\"response\", \"dialog\", \"popup\"].includes(candidate.kind) && events.hit(candidate.name) !== undefined\n : !(replacing && (candidate.kind === \"locator\" || candidate.kind === \"invalid\")) &&\n outcomeWaitShows(candidate, observations?.[candidate.name], state, stale, now));\n if (shown !== undefined) {\n const observation = observations?.[shown.name];\n if (shown.kind === \"locator\" && observation.count > 1) {\n const failure = outcomeWaitFailure(\"outcome_ambiguous\", \": \" + outcomeWaitSeen(observations), observations, {\n outcome: shown.name,\n });\n finish({ reason: \"outcome_ambiguous\", outcome: shown.name }, failure.message);\n throw failure;\n }\n const evidence = await waitBounded(\n outcomeWaitEvidence(shown, observation, state, events, now),\n Math.max(250, until - Date.now()),\n {},\n );\n return result(shown, observations ?? last ?? {}, evidence);\n }\n if (events.unnamedDialog() !== undefined) {\n const opened = events.unnamedDialog();\n const failure = outcomeWaitFailure(\n \"outcome_unknown\",\n \" after \" + (now - begun) + \" ms: a native \" + opened.type() + \" dialog opened that no outcome names\",\n last ?? {},\n {},\n );\n outcomeWaitHidden(failure, \"dialog\", opened);\n finish({ reason: \"outcome_unknown\" }, failure.message);\n throw failure;\n }\n // Only a look that decides nothing samples the page's progress: the decision never uses it.\n const current = JSON.stringify(observations ?? null);\n await unblocked(progress.sample(\n observations === undefined ? [\"page replaced\"]\n : signature !== undefined && current !== signature ? [\"outcome matches changing\"] : [],\n ));\n // An outcome the page announced as an event during the sample decides at the next look.\n if (events.dialogOpen() || events.anyHit()) continue;\n signature = current;\n if (now >= until) {\n const seen = last ?? (beforeStop() > 0 ? await look().catch(() => undefined) : undefined) ?? {};\n const failure = outcomeWaitFailure(\n \"outcome_timeout\",\n \" after \" + Math.round(Math.max(0, until - begun)) + \" ms: \" +\n (Object.keys(seen).length === 0 ? \"the page could not be read\" : outcomeWaitSeen(seen)) + \"; \" + progress.describe(),\n seen,\n { progress: progress.diagnostics() },\n );\n finish({ reason: \"outcome_timeout\" }, failure.message);\n throw failure;\n }\n // Nothing shows, not even an answer from before the action, and the page went quiet.\n // A quiet page fails only when the next look agrees, since the page may have answered\n // between this look's outcomes and its progress sample.\n const anyShown = candidates.some((candidate) => outcomeWaitShowsAny(candidate, observations?.[candidate.name]));\n const quiet = !anyShown && progress.quietMs() >= noProgressMs;\n if (quiet && !quietBefore) quietBefore = true;\n else if (quiet) {\n const seen = last ?? {};\n const failure = outcomeWaitFailure(\n \"outcome_unknown\",\n \" after \" + (Date.now() - begun) + \" ms, \" + Math.round(noProgressMs) + \" ms without progress, no outcome showing: \" +\n outcomeWaitSeen(seen) + \"; \" + progress.describe(),\n seen,\n { progress: progress.diagnostics() },\n );\n finish({ reason: \"outcome_unknown\" }, failure.message);\n throw failure;\n } else quietBefore = false;\n await waitSleep(100);\n }\n } catch (error) {\n // A dialog that opened while the wait listened stays open: the failure carries it too.\n if (error !== null && typeof error === \"object\" && error.dialog === undefined) outcomeWaitHidden(error, \"dialog\", events.dialog());\n throw error;\n } finally {\n events.stop();\n // With a native dialog open the page cannot run the cleanup; what it leaves is inert.\n const inPage = !events.dialogOpen();\n // A page held up by a pending navigation gets a moment; what it keeps is inert.\n for (const each of [key, state.announceKey])\n if (each !== undefined && inPage)\n await waitBounded(\n page.evaluate((key) => {\n globalThis[Symbol.for(key)]?.observer?.disconnect?.();\n delete globalThis[Symbol.for(key)];\n }, each),\n cleanupMs(),\n ).catch(() => undefined);\n await progress.stop(inPage && cleanupMs() > 0);\n }\n};\nconst waitForOutcome = async (outcomes, options = {}) => (await waitForOutcomeResult(outcomes, options)).outcome;\n`;\n/**\n * `waitForRows`, `waitForValues` and `waitForChange`: wait for the values a tool returns to be\n * filled in and to read the same on two looks.\n */\nconst valueCode = String.raw `\n// Runs in the page: reads each element's value, or says it is absent or still loading. A value is\n// still loading when it is empty, reads as a loading word or only dots, matches the author's\n// placeholder, or sits in an aria-busy, skeleton or shimmer element (up to its row).\nconst waitReadInPage = (elements, spec) => {\n const loadingWords = /^(?:loading|updating|calculating|fetching|searching|please wait)\\b/i;\n const visible = (element) =>\n typeof element.checkVisibility === \"function\" ? element.checkVisibility()\n : element.getClientRects().length > 0;\n const busy = (element, stop) => {\n for (let node = element, depth = 0; node instanceof Element && depth < 8; node = node.parentElement, depth += 1) {\n if (node.getAttribute(\"aria-busy\") === \"true\") return true;\n if (/skeleton|shimmer/i.test(node.getAttribute(\"class\") ?? \"\")) return true;\n if (node === stop) break;\n }\n return false;\n };\n const read = (element, field, stop, identity) => {\n if (!(element instanceof Element)) return { state: \"absent\" };\n const raw = field.attribute ? element.getAttribute(field.attribute) : visible(element) ? element.innerText : \"\";\n const value = String(raw ?? \"\").trim();\n const placeholder = field.placeholder ? new RegExp(field.placeholder.source, field.placeholder.flags) : undefined;\n if (value === \"\" || loadingWords.test(value) || /^[.…\\s]+$/.test(value) || placeholder?.test(value))\n return { state: \"loading\" };\n if (!identity && busy(element, stop)) return { state: \"loading\" };\n return { state: \"filled\", value };\n };\n // How many loading signs show beside a list's rows: in the rows' container or the element around\n // it, never inside a row. A decoration lives in its card, while a list still loading shows its\n // spinner, skeleton or busy state beside the rows. A class hint that holds rows is their layout,\n // not a sign, and a sign kept in layout but invisible (visibility or opacity) does not show.\n const shown = (element) =>\n typeof element.checkVisibility === \"function\"\n ? element.checkVisibility({ visibilityProperty: true, opacityProperty: true })\n : element.getClientRects().length > 0;\n const listSigns = (rows, selectors) => {\n if (rows.length === 0) return 0;\n let common = rows[0].parentElement;\n while (common !== null && !rows.every((row) => common.contains(row))) common = common.parentElement;\n if (common === null) return 0;\n const outer = common.parentElement;\n const root = outer === null || outer === document.body || outer === document.documentElement ? common : outer;\n let count = 0;\n for (const element of [root, ...root.querySelectorAll(selectors.all)])\n if (\n element.matches(selectors.all) &&\n shown(element) &&\n !rows.some((row) => row.contains(element)) &&\n (element.matches(selectors.signs) || !rows.some((row) => element.contains(row)))\n )\n count += 1;\n return count;\n };\n if (spec.mode === \"rows\")\n return { signs: listSigns(elements, spec.signs), rows: elements.map((row) => {\n // A row's field is its first visible match, such as the price a responsive card shows\n // beside a hidden copy. Read text whose matches are all hidden is hidden, not loading: the\n // selector names the wrong copy, or the site shows it only on another layout.\n const at = (field) => {\n if (!field.selector) return row;\n const matches = [...row.querySelectorAll(field.selector)];\n return matches.find(visible) ?? (field.attribute || matches.length === 0 ? matches[0] : \"hidden\");\n };\n const take = (field, identity) => {\n const element = at(field);\n return element === \"hidden\" ? { state: \"hidden\" } : read(element, field, row, identity);\n };\n const fields = {};\n for (const [name, field] of Object.entries(spec.fields)) fields[name] = take(field, false);\n return { key: take(spec.key, true), fields };\n }) };\n const field = spec.field;\n const candidates = field.attribute ? elements : elements.filter(visible);\n if (candidates.length === 0) return { state: \"absent\" };\n if (field.all) {\n const values = candidates.map((element) => read(element, field, undefined, false));\n return values.some((value) => value.state !== \"filled\") ? { state: \"loading\" }\n : { state: \"filled\", value: values.map((value) => value.value) };\n }\n if (candidates.length > 1) return { state: \"ambiguous\", count: candidates.length };\n return read(candidates[0], field, undefined, false);\n};\n// A field as the page code reads it: a CSS selector inside the row (or the row itself), or for\n// waitForValues a Playwright locator, with an attribute to read instead of the text.\nconst waitFieldSpec = (field, where) => {\n const spec = typeof field === \"string\" ? { selector: field }\n : field !== null && typeof field === \"object\" && typeof field.evaluateAll === \"function\" ? { locator: field }\n : field !== null && typeof field === \"object\" ? field\n : undefined;\n if (spec === undefined) throw new TypeError(where + \" needs a selector, a locator or { selector | locator, attribute }\");\n const placeholder = spec.placeholder instanceof RegExp\n ? { source: spec.placeholder.source, flags: spec.placeholder.flags.replace(\"g\", \"\") }\n : undefined;\n return {\n ...(spec.selector === undefined ? {} : { selector: spec.selector }),\n ...(spec.locator === undefined ? {} : { locator: spec.locator }),\n ...(spec.attribute === undefined ? {} : { attribute: spec.attribute }),\n ...(spec.all === true ? { all: true } : {}),\n ...(spec.optional === true ? { optional: true } : {}),\n ...(placeholder === undefined ? {} : { placeholder }),\n };\n};\nconst valueWaitFailure = (reason, message, details) =>\n Object.assign(new Error(reason + message), { name: \"ValueWaitFailure\", reason, ...details });\nconst valueWaitRows = (list) =>\n list.length === 0 ? \"\" : (list.length === 1 ? \" in row \" : \" in rows \") + list.slice(0, 10).join(\", \") + (list.length > 10 ? \" and \" + (list.length - 10) + \" more\" : \"\");\n// Runs the shared loop for a value wait: look, note progress, return once ready on two agreeing\n// looks, fail once quiet or past the cap. evaluate() returns { ready, snapshot, filled, problems,\n// result, settleMs }.\nconst valueWaitLoop = async (wait, options, evaluate, timeoutDefault) => {\n const timeout = options.timeout ?? timeoutDefault;\n const noProgressMs = options.noProgressMs ?? waitLimits.answer;\n const progress = waitProgress({ ...options, noProgressMs });\n let looks = 0;\n let begun = Date.now();\n const finish = (fields, summary) =>\n waitRecord({\n wait,\n ...fields,\n elapsedMs: Date.now() - begun,\n looks,\n progress: progress.describe(),\n summary: wait + \": \" + summary + \"; \" + progress.describe(),\n });\n try {\n await options.prepare?.();\n if (options.action !== undefined) {\n await progress.baseline();\n await options.action();\n }\n progress.begin();\n begun = Date.now();\n const until = begun + timeout;\n let candidate;\n let candidateAt = begun;\n let filled = -1;\n let quietBefore = false;\n while (true) {\n let state;\n try {\n state = await evaluate(progress);\n } catch (error) {\n if (!waitContextLost(error)) throw error;\n state = undefined;\n }\n looks += 1;\n const changes = [];\n if (state === undefined) changes.push(\"page replaced\");\n else if (state.signs) changes.push(\"loading sign\");\n else if (candidate !== undefined && state.snapshot !== candidate) {\n changes.push(state.filled > filled ? \"values filling\" : \"values changing\");\n }\n await progress.sample(changes);\n const now = Date.now();\n if (state !== undefined) {\n if (state.snapshot !== candidate) {\n candidate = state.snapshot;\n candidateAt = now;\n }\n filled = state.filled;\n // Readiness that depends on progress is judged after this look's sample.\n state.ready = typeof state.ready === \"function\" ? state.ready() : state.ready;\n if (state.ready && now - candidateAt >= state.settleMs) {\n finish({ outcome: \"ready\" }, state.summary(now - begun, looks));\n return state.result;\n }\n }\n if (now >= until) {\n const problems = state?.problems ?? \"the page was being replaced\";\n const failure = valueWaitFailure(\n \"values_timeout\",\n \" after \" + Math.round(timeout) + \" ms: \" + problems + \"; \" + progress.describe(),\n { progress: progress.diagnostics() },\n );\n finish({ reason: \"values_timeout\" }, failure.message);\n throw failure;\n }\n // A quiet page fails only when the next look agrees, as in waitForOutcome.\n const quiet = progress.quietMs() >= noProgressMs && !state?.ready;\n if (quiet && !quietBefore) quietBefore = true;\n else if (quiet) {\n const reason = state?.reason ?? \"values_loading\";\n const failure = valueWaitFailure(\n reason,\n \" after \" + (now - begun) + \" ms, \" + Math.round(noProgressMs) + \" ms without progress: \" +\n (state?.problems ?? \"nothing read\") + \"; \" + progress.describe(),\n { progress: progress.diagnostics() },\n );\n finish({ reason }, failure.message);\n throw failure;\n } else quietBefore = false;\n await waitSleep(100);\n }\n } finally {\n await progress.stop();\n }\n};\nconst waitForRows = async (rows, fields, options = {}) => {\n const count = options.count;\n if (!Number.isInteger(count) || count < 1) throw new TypeError(\"waitForRows needs count, the number of rows you return\");\n if (options.key === undefined) throw new TypeError(\"waitForRows needs key, the field that identifies a row\");\n const key = waitFieldSpec(options.key, \"waitForRows key\");\n const spec = {\n mode: \"rows\",\n key,\n fields: Object.fromEntries(Object.entries(fields).map(([name, field]) => [name, waitFieldSpec(field, \"waitForRows field \" + name)])),\n };\n const settle = options.stableMs ?? waitLimits.settle;\n const fewSettle = Math.max(settle, options.unchangedMs ?? waitLimits.unchanged);\n spec.signs = { all: waitLoadingSigns + \", \" + waitLoadingClasses, signs: waitLoadingSigns };\n const noProgressMs = options.noProgressMs ?? waitLimits.answer;\n // The signs beside the rows. Those there before the action, in the same number, are the page's\n // own. One that came after it, or that shows without an action, counts while it shows, until it\n // and the rows have held unchanged for noProgressMs with no request the action started still in\n // flight: then it is decoration too, so a sign that never leaves costs one window, never the cap.\n let signsBefore = 0;\n let signsCount;\n let signsChangedAt = 0;\n let rowsSeen;\n let rowsChangedAt = 0;\n const prepare = async () => {\n await options.prepare?.();\n if (options.action !== undefined) signsBefore = (await rows.evaluateAll(waitReadInPage, spec)).signs;\n };\n return valueWaitLoop(\"waitForRows\", { ...options, prepare }, async (progress) => {\n const { rows: read, signs: listSigns } = await rows.evaluateAll(waitReadInPage, spec);\n const identified = read.filter((row) => row.key.state === \"filled\");\n const hiddenKeys = read.flatMap((row, index) => (row.key.state === \"hidden\" ? [index + 1] : []));\n const taken = identified.slice(0, count);\n const loading = {};\n const hidden = {};\n const missing = {};\n let filledCount = 0;\n taken.forEach((row, index) => {\n for (const [name, value] of Object.entries(row.fields)) {\n if (value.state === \"filled\") filledCount += 1;\n else if (value.state === \"loading\") (loading[name] ??= []).push(index + 1);\n else if (spec.fields[name].optional) continue;\n else if (value.state === \"hidden\") (hidden[name] ??= []).push(index + 1);\n else (missing[name] ??= []).push(index + 1);\n }\n });\n const problems = [\n ...Object.entries(loading).map(([name, list]) => name + \" still loading\" + valueWaitRows(list)),\n ...Object.entries(hidden).map(([name, list]) => name + \" hidden\" + valueWaitRows(list)),\n ...Object.entries(missing).map(([name, list]) => name + \" missing\" + valueWaitRows(list)),\n ];\n const complete = problems.length === 0;\n const few = taken.length < count;\n if (hiddenKeys.length > 0) problems.push(\"key hidden\" + valueWaitRows(hiddenKeys));\n const now = Date.now();\n if (listSigns !== signsCount) {\n signsCount = listSigns;\n signsChangedAt = now;\n }\n const rowsNow = JSON.stringify(taken);\n if (rowsNow !== rowsSeen) {\n rowsSeen = rowsNow;\n rowsChangedAt = now;\n }\n const listLoading = listSigns > signsBefore &&\n (now - Math.max(signsChangedAt, rowsChangedAt) < noProgressMs || progress.causedInflight());\n return {\n // No identified row is never an answer: an empty list is waitForOutcome's to decide. Fewer\n // rows than asked are an answer only once nothing shows the list is still loading.\n ready: () => complete && taken.length > 0 && (!few || (!listLoading && !progress.busy(false))),\n signs: listLoading,\n settleMs: few ? fewSettle : settle,\n filled: taken.length * 1000 + filledCount,\n // The rows are read before the signs beside them, so a loader leaving in between restarts\n // the settle, and the next look sees the rows it left for.\n snapshot: JSON.stringify([listSigns, taken]),\n reason: \"values_loading\",\n problems:\n identified.length + \" identified rows of \" + read.length + \", needed \" + count +\n (problems.length === 0 ? \"\" : \"; \" + problems.join(\"; \")),\n summary: (elapsed, looks) =>\n taken.length + \" of \" + count + \" rows filled and holding after \" + elapsed + \" ms (\" + looks + \" looks)\" +\n (few ? \", fewer rows than asked and the count held\" : \"\"),\n result: {\n rows: taken.map((row) => ({\n key: row.key.value,\n ...Object.fromEntries(Object.entries(row.fields).map(([name, value]) => [name, value.state === \"filled\" ? value.value : null])),\n })),\n more: identified.length > count,\n },\n };\n }, waitLimits.lateFillCap);\n};\n// Reads each named field once: its value, or that it is absent, ambiguous or still loading.\nconst valueWaitRead = async (specs) => {\n const read = {};\n for (const [name, spec] of Object.entries(specs))\n read[name] = await spec.locator.evaluateAll(waitReadInPage, { mode: \"field\", field: { ...spec, locator: undefined } });\n return read;\n};\nconst valueWaitState = (specs, read) => {\n const problems = [];\n let filled = 0;\n let absent = false;\n for (const [name, value] of Object.entries(read)) {\n if (value.state === \"filled\") filled += 1;\n else if (value.state === \"loading\") problems.push(name + \" still loading\");\n else if (value.state === \"ambiguous\") problems.push(name + \" matches \" + value.count + \" visible elements\");\n else if (!specs[name].optional) {\n absent = true;\n problems.push(name + \" missing\");\n }\n }\n const values = Object.fromEntries(Object.entries(read).map(([name, value]) => [name, value.state === \"filled\" ? value.value : null]));\n return { problems, filled, absent, values, complete: problems.length === 0 };\n};\nconst valueWaitSpecs = (fields, where) => {\n const specs = Object.fromEntries(Object.entries(fields).map(([name, field]) => [name, waitFieldSpec(field, where + \" field \" + name)]));\n for (const [name, spec] of Object.entries(specs))\n if (spec.locator === undefined) throw new TypeError(where + \" field \" + name + \" needs a Playwright locator\");\n if (Object.keys(specs).length === 0) throw new TypeError(where + \" needs at least one field\");\n return specs;\n};\nconst waitForValues = async (fields, options = {}) => {\n const specs = valueWaitSpecs(fields, \"waitForValues\");\n const settle = options.stableMs ?? waitLimits.settle;\n return valueWaitLoop(\"waitForValues\", options, async () => {\n const state = valueWaitState(specs, await valueWaitRead(specs));\n return {\n ready: state.complete,\n settleMs: settle,\n filled: state.filled,\n snapshot: JSON.stringify(state.values),\n reason: \"values_loading\",\n problems: state.problems.join(\"; \"),\n summary: (elapsed, looks) => Object.keys(specs).length + \" values filled and holding after \" + elapsed + \" ms (\" + looks + \" looks)\",\n result: { values: state.values },\n };\n }, waitLimits.lateFillCap);\n};\nconst waitForChange = async (fields, options = {}) => {\n const specs = valueWaitSpecs(fields, \"waitForChange\");\n if (options.before === undefined && options.action === undefined)\n throw new TypeError(\"waitForChange needs before (the values from before the choice) or action (the choice itself)\");\n let before = options.before;\n if (before !== undefined && (before === null || typeof before !== \"object\" || Array.isArray(before) ||\n Object.keys(before).sort().join() !== Object.keys(specs).sort().join()))\n throw new TypeError(\"waitForChange's before must be the values object an earlier wait returned, with the same field names\");\n const settle = options.stableMs ?? waitLimits.settle;\n const unchangedMs = options.unchangedMs ?? waitLimits.unchanged;\n const noProgressMs = options.noProgressMs ?? waitLimits.answer;\n return valueWaitLoop(\"waitForChange\", {\n ...options,\n prepare: async () => {\n if (before === undefined) before = valueWaitState(specs, await valueWaitRead(specs)).values;\n },\n }, async (progress) => {\n const state = valueWaitState(specs, await valueWaitRead(specs));\n const changed = JSON.stringify(state.values) !== JSON.stringify(before);\n // The same values count once nothing has shown progress for unchangedMs: a loading sign or\n // request that came after the choice must first go.\n return {\n ready: () => state.complete && (changed || progress.quietMs() >= Math.min(unchangedMs, noProgressMs)),\n settleMs: changed ? settle : 0,\n filled: state.filled,\n snapshot: JSON.stringify(state.values),\n reason: state.absent && state.problems.every((problem) => problem.endsWith(\" missing\")) ? \"change_unknown\" : \"values_loading\",\n problems: state.problems.length > 0 ? state.problems.join(\"; \") : changed ? \"values changed but not yet holding\" : \"values unchanged\",\n summary: (elapsed, looks) =>\n (changed ? \"values changed\" : \"values confirmed unchanged after \" + unchangedMs + \" ms without progress\") +\n \", after \" + elapsed + \" ms (\" + looks + \" looks)\",\n result: { values: state.values, changed },\n };\n }, waitLimits.answerCap);\n};\n`;\n/**\n * Page code for a Kernel call body, where `page` is in scope: paste it once at the top of the code\n * string, then wait with your verified Playwright locators. It declares the waits below, which share\n * one set of limits (`waitLimits`, from `timeoutDefaults`) and one progress budget, and\n * `waitReport()`.\n *\n * Every wait returns as soon as its condition holds: a ready page costs `waitForOutcome` one look,\n * and the value waits two looks `settle` (0.5 s) apart. While it waits it watches the page's\n * progress: the site's own loading sign passed as `loading`, for as long as it shows; a generic\n * sign (a busy region, an indeterminate progress bar, a skeleton, shimmer, spinner or loader class,\n * within `region` when named) only while it is new, so a decoration holds a wait for at most one\n * no-progress window, and one there before the action not at all (`waitForOutcome` counts one\n * its action brought for as long as it shows, and a countdown ticking that was not there before\n * the action, such as a review step that submits on its own at zero); DOM changes\n * inside the `region` you name; one of the site's own document or API requests in flight (beacons,\n * polls and long-open requests aside; pass the context's `siteDomain` to say which hosts are the\n * site's); the URL changing; and the wait's own reads filling or changing. It keeps waiting while progress\n * continues, up to `timeout`, and fails once nothing has progressed for `noProgressMs` (default\n * `answer`, 8 s). A failure is an `Error` with a `reason`, and a message that names the reason, what\n * each outcome or field showed (counts and states, never page text), which progress signs it saw\n * and when progress stopped. `waitReport()` returns one record per wait this call ran, each with a\n * `summary` sentence: return it from a probe to see how each wait ended.\n *\n * `waitForOutcome(outcomes, { action, loading, region, siteDomain, noProgressMs, timeout,\n * unchangedMs }?)` waits for whichever of the page's possible answers appears, after a step whose\n * answer can vary, such as a search, a filter, a date pick or a submit, and returns its key.\n * `outcomes` names one locator per answer, highest priority first, such as `{ refused, failed,\n * unavailable, empty, results }`: when several show at once, the first listed wins, so list a\n * refusal, the site's error or a greyed-out choice before an empty state, and an empty state before\n * results. Each locator names one element, such as the results list rather than its rows. It only\n * observes: about every 100 ms it counts each locator's matches and its visible ones, and never\n * clicks, types or navigates itself. It answers at the first look that shows an outcome.\n * `timeout` (default `answerCap`, 30 s) is the hard cap, reached only while the page keeps\n * progressing. `action` is the step itself, such as `() => apply.click()`, which it runs exactly\n * once, after noting what each outcome showed: a match that was visible before it, with the same\n * text, counts only once it has stayed so for `unchangedMs` (default 2000) and no request the\n * action started is still in flight, or was as the look began. Such a request holds it back for\n * at most `lateFillCap` (15 s), and never past `timeout` less `unchangedMs`, so the match still\n * counts before the timeout.\n * `timeout`, `noProgressMs` and `unchangedMs` start once the action returns; `deadline`, a\n * `Date.now()` time such as the call's own, ends the wait by then however long the action took. Its\n * `OutcomeWaitFailure` has `observations` (`OutcomeObservation` by key) and one of these reasons:\n *\n * - `outcome_ambiguous`, when the winning outcome's locator matches more than one element; its\n * `outcome` is that key. Scope the locator, for example with `.filter({ visible: true })`.\n * - `outcome_unknown`, when no outcome shows and the page made no progress for `noProgressMs`: a\n * challenge, the site's error or a layout the code does not handle, never slowness.\n * - `outcome_timeout`, when the page was still progressing at `timeout`.\n *\n * An outcome may also be an object naming one declared kind, raced beside the locators in the same\n * listed order, so a site that answers in a way the code did not expect still ends the wait:\n *\n * - `{ gone: locator, stableMs? }`: the element, visible before the action (or at a look), has\n * had no visible match for `stableMs` (default 300), such as a form or a modal closing. A form\n * redrawn in place within that time is not gone.\n * - `{ invalid: locator }`: a control inside it is marked invalid (`aria-invalid=\"true\"`, the\n * `is-invalid` class, or the browser's own check after a submit). Fields flagged before the\n * action, and unchanged, follow the same `unchangedMs` rule as a locator.\n * - `{ url }`: the page's URL matches a string (the whole URL, its path, or path and query), a\n * RegExp or a function of the `URL`. After an `action` it counts only once the page navigated,\n * by a document load or a route change, so an edit page whose URL already matched waits.\n * - `{ response }`: a response arrived, from before the action, that a function of the Playwright\n * `Response` accepts, or that matches `{ method, url, status, navigation }` (`status` a number,\n * `[low, high]` or a function). It races the page's answers, so a request the site batches,\n * caches or renames never hangs the wait: name one only for a write's commit request.\n * - `{ dialog: true | type | [types] }`: a native dialog opened, even one the action's own click\n * raised. Page scripts stop while it is open, so it decides at once, in the listed order: a\n * response or popup outcome listed before it that already matched still wins, else the dialog\n * does. Once a dialog opened, every other response, dialog or popup outcome that matched is on\n * the result too, such as `result.response`, and the summary says it also matched: prefer\n * checking a response before reading a dialog as a refusal. The wait never accepts or dismisses\n * it: a dialog that opened while it listened is on the result's or failure's `dialog`, whichever\n * won, and the result's summary names it. Until it is handled, reads of the page or of a\n * response's body wait, so prefer handing a dialog on `result.dialog` over before any other\n * read. A dialog of a type no outcome names fails as `outcome_unknown` only when no response or\n * popup outcome has already matched; otherwise that outcome wins with the dialog still open on\n * `result.dialog`. An action still waiting to click when a dialog opens clicks once the dialog\n * is handled, so handle it before ending the call.\n * - `{ popup: true | (page) => boolean }`: the page opened a new tab or window.\n * - `{ announced: string | RegExp }`: a live region (`aria-live`, or the role `alert`, `status`,\n * `log` or `alertdialog`) announced matching text after the action, as a screen reader hears\n * it. A toast that comes and goes between two looks still counts.\n * - `{ check: async () => value }`: a condition of your own, true once it returns a truthy value.\n * It has no stale rule: one already true before the action wins at the first look.\n *\n * `waitForOutcomeResult(outcomes, options?)` is the same wait returning `OutcomeResult`: the\n * winning `outcome` and its `kind`, `afterMs`, `looks`, the `observations`, and `evidence` of what\n * showed it (a locator's visible text, the invalid fields' labels and messages, the URL reached,\n * the response's method, URL and status, the dialog's type and message). The winning Playwright\n * `response`, `dialog` or popup `page` is on the result too, kept off its JSON. Every listener\n * the losing outcomes used is removed before it returns or throws.\n *\n * `waitForRows(rows, fields, { count, key, ...options })` waits until the first `count` identified\n * rows have every field filled and read the same on two looks `stableMs` apart (default `settle`,\n * 0.5 s), and returns `{ rows: [{ key, ...fields }], more }`. `rows` is a locator for every row;\n * `key` and each field are a CSS selector inside the row, or `{ selector, attribute, optional,\n * placeholder }` (no selector reads the row itself), read from its first visible match; a needed\n * text field whose matches are all hidden is reported `hidden`. A row without a key is a\n * placeholder slot and is skipped. When fewer identified rows than `count` exist, it returns them\n * once their count and values held for `unchangedMs`, no loading sign beside the rows still counts,\n * no request the action started is in flight, and no other site request started under 4 s ago is;\n * no identified row at all\n * is never an answer, so decide an empty list with `waitForOutcome` first. Options also take\n * `action` (run once first, such as a \"load more\" click), `loading`, `region`, `siteDomain`,\n * `noProgressMs` and `timeout` (default `lateFillCap`, 15 s).\n *\n * `waitForValues(fields, options?)` waits until each named field (a Playwright locator, or\n * `{ locator, attribute, all, optional, placeholder }`) is filled in and the values read the same\n * on two looks, and returns `{ values }`. `all` reads every visible match as a list.\n *\n * `waitForChange(fields, { before, action, ...options })` waits, after a choice, for the values\n * that depend on it: it returns `{ values, changed }` once they differ from `before` (or from what\n * they were before `action` ran) and hold, or once they stayed the same for `unchangedMs` with no\n * progress sign showing, so a loading sign or request the choice started must first go.\n *\n * `waitForReady(control, { overlays, expand, dismiss, pending, until, editable, stableMs,\n * dismissLimit, watch, deadline, ...options })` waits before an action until the control's one visible\n * match is attached, visible, enabled (and not read-only when `editable`), not busy (no\n * `aria-busy` around it, no spinner inside it), in the same place on two looks, and what a click\n * at its centre would hit is the control itself, not an overlay. It also waits while an `overlays`\n * locator shows, while `pending` (a function run in the page, such as\n * `() => window.jQuery?.active ?? 0`) returns a truthy count, and until `until()` is true. Once\n * anything held it back, ready must hold for `stableMs` (default `settle`), so a spinner that\n * flickers off between two requests does not count as gone. `expand` names the toggle of the\n * control's section: it clicks it once while the control is hidden and the toggle says the\n * section is collapsed (`aria-expanded` false, or the summary of a closed `details`), so it never\n * closes an open one. `dismiss`\n * names the close or skip controls of panels that open on their own, such as a tour, a what's-new\n * dialog or a cookie banner: it clicks one that shows, up to `dismissLimit` (5) times, and once\n * ready keeps a Playwright locator handler on each, so one that opens later is closed before the\n * next action, until `result.release()` or `dismissLimit` uses (`watch: false` skips it). It\n * returns `ReadyResult`, and fails as a `ReadyWaitFailure` with `blockers` and a message naming\n * what held it back last: `not_ready` once nothing progressed for `noProgressMs`, `ready_timeout`\n * at `timeout` (default `answerCap`), `ready_ambiguous` when more than one visible element\n * matches.\n *\n * A value is still loading, never absent, while it is empty, reads as a loading word or only dots,\n * matches the field's `placeholder` pattern, or sits in an `aria-busy`, skeleton or shimmer\n * element. An `optional` field may be absent and is then `null`; a needed one may not. A value\n * still loading when progress stops fails with `values_loading`, whether optional or not;\n * `change_unknown` when waitForChange's fields are missing; `values_timeout` at the cap. Each is a\n * `ValueWaitFailure`.\n */\nexport const waitCode = `${progressCode}${outcomeKindsCode}${outcomeCode}${valueCode}${readyWaitCode}`;\n/**\n * `waitForOutcome` alone, for code written against the first release of it: it declares only the\n * names that release declared (`waitForOutcome`, `outcomeWaitFailure`, `outcomeWaitNote`,\n * `outcomeWaitChanged` and `outcomeWaitObserve`), keeping every other helper inside, so code that\n * pastes it beside helpers of its own still parses. New code pastes `waitCode` instead; never both.\n */\nexport const outcomeOnlyWaitCode = `\nconst { outcomeWaitFailure, outcomeWaitNote, outcomeWaitChanged, outcomeWaitObserve, waitForOutcome } = (() => {\n${progressCode}${outcomeKindsCode}${outcomeCode}\nreturn { outcomeWaitFailure, outcomeWaitNote, outcomeWaitChanged, outcomeWaitObserve, waitForOutcome };\n})();\n`;\n/**\n * `confirmCommit(outcome, page)`, pasted after `waitCode` in a write's commit call, just before the\n * click's wait. It declares that one name, its helpers inside, so code that pastes `waitCode`\n * beside a `confirmCommit` of its own still parses. It uses `page`, and `waitCode`'s `waitLimits`,\n * `waitBounded`, `waitSleep`, `outcomeWaitClean` and `outcomeWaitInvalidInPage`. Pasting it notes\n * the page's address, how many messages show each text, and its flagged fields as they stand.\n * After, as many messages with a text as showed it then are stale, whatever element or page shows\n * them, so a page that draws its messages again, or a redirect to a page with the same banner,\n * adds no error, while one more message with an old text is new.\n *\n * It judges the commit from the `{ response }` answer of the click's `waitForOutcomeResult` and\n * the page, and returns `CommitConfirmation`, plain data a call can return. It never marks a write\n * done or not done without proof: whatever the response and the page leave open is `unclear`.\n *\n * - A 4xx response, or one below 200, is `not_done`; a 5xx is `unclear`, since a server can fail\n * after it saved; a 201 with a Location is `done` at once. A 3xx whose Location is the page that\n * posted (same path), or whose query names an error or failure, is `unclear` unless the page\n * shows an error.\n * - A 2xx body that reads as JSON is `not_done` for a success field (`success`, `succeeded`,\n * `isSuccess`, any case) that is false, `\"false\"`, 0 or `\"no\"` or holds an error word, `ok:\n * false`, an error field holding an error (not empty, and not a word for none such as \"No\n * error\"), a status of 400 or more, or an error word in a status or message. An error field is\n * any named for errors up to two levels down, and `error`, `errors` or `userErrors` up to four;\n * true counts only under `error`, `errors` or `hasError(s)`, and a setting such as\n * `notifyOnError` is never one. It is `unclear` for a success field holding anything but true,\n * `\"true\"`, 1, `\"yes\"`, `\"ok\"` or `\"success\"`, or a status or message that refuses a value\n * (\"required\", \"unable\", \"could not\") or says declined, rejected or denied, words a write may\n * itself have meant. A string holding JSON, as in `{ d: \"...\" }`, is read too. A body that is\n * neither JSON nor HTML, or can't be read within 1 s, is `unclear`; a 3xx's or an empty one is no\n * body.\n * - The page then gets the settle window (`settle`, 0.5 s). A field newly marked invalid, or a\n * message whose text is new with words of an error or a refusal, is `not_done`, whatever the\n * body's message said. A message is an alert, an assertive live region or anything styled as an\n * error, with letters, outside links, buttons and labels, and not one only a screen reader hears.\n * A new message styled as an error with no such words, one that mixes them with a success, one\n * that says declined, rejected or denied, an alert that says neither error nor success, or a\n * field still marked invalid as before, is `unclear`.\n * - Otherwise the commit is `done`: `queued` for a 202, or a body whose status says queued, pending\n * or processing, with that word as `status_label`, else `completed`. An outcome with no response\n * is `not_done` when the page shows a new error, else `unclear`. A native dialog that opened\n * during the wait and says the write failed is `not_done`, unless the response is a 5xx or\n * proves a record (a 201 with a Location): that is `unclear`, naming both. While one stays open\n * the page can't be read, which is `unclear`.\n *\n * It never clicks, and it reads the body for at most 1 s and the page for at most about 2 s.\n */\nexport const confirmCommitCode = String.raw `\nconst confirmCommit = await (async () => {\n // Words that say a write failed; \"no errors\" says none. Words that refuse a value prove nothing\n // on their own, nor do words a write may itself have meant, as declining or rejecting something.\n const errorWords = /\\b(?:errors?|fail(?:s|ed|ure)?|invalid|forbidden|unauthori[sz]ed)\\b/i;\n const noErrors = /\\b(?:no|without|zero|0)\\s+errors?\\b/i;\n const refusalWords = /\\b(?:required|must|cannot|can't|could not|couldn't|unable|not valid|please (?:enter|select|choose|provide|fill|complete|correct|try again))\\b/i;\n const openWords = /\\b(?:declined|rejected|denied)\\b/i;\n const successWords = /\\b(?:success(?:ful|fully)?|saved|created|updated|submitted|completed|confirmed|thank you)\\b/i;\n const queuedWords = /\\b(?:queued|enqueued|pending|processing|in progress)\\b/i;\n const words = (value) => String(value).replace(/[_-]+/g, \" \");\n const saysError = (value) => typeof value === \"string\" && errorWords.test(words(value)) && !noErrors.test(words(value));\n const saysRefusal = (value) => typeof value === \"string\" && refusalWords.test(words(value));\n const clip = (value) => outcomeWaitClean(typeof value === \"string\" ? value : JSON.stringify(value), 160);\n const list = (texts) => texts.slice(0, 3).map((text) => '\"' + clip(text) + '\"').join(\", \");\n // A success field's value: true, false, or anything else, which leaves it unclear.\n const truth = (value) => {\n const text = typeof value === \"string\" ? value.trim().toLowerCase() : value;\n if (text === true || text === 1 || [\"true\", \"1\", \"yes\", \"ok\", \"success\"].includes(text)) return true;\n if (text === false || text === 0 || [\"false\", \"0\", \"no\"].includes(text) || saysError(value)) return false;\n return undefined;\n };\n // Whether an error field holds an error: not empty, zero, false or a word for none, at any depth.\n const filled = (value, depth = 0) => {\n if (value === null || value === undefined || value === false || value === 0) return false;\n if (typeof value === \"string\")\n return !/^\\s*(?:0+|none|null|false|ok|success|n\\/a|no errors?(?: found)?)?\\s*\\.?\\s*$/i.test(value);\n if (typeof value !== \"object\" || depth > 3) return true;\n return (Array.isArray(value) ? value : Object.values(value)).some((each) => filled(each, depth + 1));\n };\n // Whether a field is an error field: up to two levels down, any named for errors, as in\n // { data: { save: { errors } } }; deeper, only error, errors and userErrors. A setting for what\n // to do on an error, such as notifyOnError, never is.\n const errorField = (name, depth) =>\n !/onerrors?$/.test(name) &&\n (depth <= 2 ? /errors?$|^error(?:message|msg|text|code)s?$/.test(name) : [\"error\", \"errors\", \"usererrors\"].includes(name));\n // Whether an error field holds an error; true does only under error, errors or hasError(s).\n const holdsError = (name, field) =>\n field === true ? [\"error\", \"errors\", \"haserror\", \"haserrors\"].includes(name) : filled(field);\n // What a JSON body says: the first sign the write failed, the first that leaves it unclear, and\n // the site's word for queued work. Error fields count up to four levels down (see errorField),\n // as in { data: { records: { save: { userErrors } } } }; success and ok fields up to two;\n // status and message words up to one. A string that holds JSON, as some frameworks wrap a body\n // in { d: \"...\" }, is read as one more level. It looks at 2,000 values at most.\n const judgeBody = (body) => {\n const found = {};\n let budget = 2000;\n const visit = (value, depth) => {\n if (depth > 4 || value === null || typeof value !== \"object\" || (budget -= 1) < 0) return;\n if (Array.isArray(value)) {\n for (const each of value.slice(0, 50)) visit(each, depth + 1);\n return;\n }\n for (const [key, field] of Object.entries(value)) {\n const name = key.toLowerCase().replace(/[_-]/g, \"\");\n const said = key + \" is \" + clip(field);\n if (depth <= 2 && /^(?:is)?succe(?:ss|ssful|eded)$/.test(name)) {\n const holds = truth(field);\n if (holds === false) found.failed ??= said;\n else if (holds === undefined) found.unclear ??= said + \", not true\";\n } else if (depth <= 2 && name === \"ok\" && field === false) found.failed ??= said;\n else if (errorField(name, depth)) {\n if (holdsError(name, field)) found.failed ??= said;\n } else if (depth <= 1 && (name === \"status\" || name === \"statuscode\") && typeof field === \"number\" && field >= 400)\n found.failed ??= said;\n else if (depth <= 1 && /^(?:status|state|result|outcome|message|msg|statusmessage|detail)$/.test(name) && typeof field === \"string\") {\n if (saysError(field)) found.failed ??= said;\n else if (saysRefusal(field) || openWords.test(field)) found.unclear ??= said;\n else if ((name === \"status\" || name === \"state\") && queuedWords.test(words(field)))\n found.queued ??= outcomeWaitClean(field, 100);\n }\n if (typeof field === \"string\" && depth <= 1 && /^\\s*[[{]/.test(field)) {\n try {\n visit(JSON.parse(field), depth + 1);\n } catch {}\n } else visit(field, depth + 1);\n }\n };\n visit(body, 0);\n return found;\n };\n // The body: JSON, HTML, none (empty, or a redirect's, which can't be read), or unclear when it\n // is something else or can't be read within 1 s.\n const readBody = async (response, status) => {\n const text = await waitBounded(Promise.resolve().then(() => response.text()).catch(() => null), 1000);\n if (text === undefined) return { unclear: \"its body could not be read within 1 s\" };\n if (text === null) return status >= 300 ? {} : { unclear: \"its body could not be read\" };\n if (text.trim() === \"\") return {};\n try {\n return { json: JSON.parse(text) };\n } catch {}\n const type = String(response.headers()[\"content-type\"] ?? \"\").toLowerCase();\n if (type.includes(\"html\") || /^\\s*(?:<!doctype html|<html[\\s>])/i.test(text)) return { html: true };\n return { unclear: \"its body is neither JSON nor HTML\" + (type === \"\" ? \"\" : \" (\" + clip(type) + \")\") };\n };\n // Elements that may hold the site's message: alerts, assertive live regions, and anything styled\n // as an error.\n const messages =\n '[role=\"alert\"], [role=\"alertdialog\"], [aria-live=\"assertive\"], [class*=\"error\" i], [class*=\"danger\" i], [class*=\"invalid\" i]';\n // Runs in the page: each visible message with letters, outside links, buttons and labels and\n // wider than a pixel, its text (500 characters at most), what its styling says (its own or up\n // to two elements around it), and whether it is an alert.\n const messagesInPage = (elements) => {\n const shows = (element) =>\n typeof element.checkVisibility === \"function\"\n ? element.checkVisibility({ visibilityProperty: true, opacityProperty: true })\n : element.getClientRects().length > 0;\n const styling = (element) => {\n const parts = [];\n for (let node = element, depth = 0; node instanceof Element && depth < 3; node = node.parentElement, depth += 1)\n for (const name of [\"class\", \"data-type\", \"data-status\", \"data-variant\", \"data-severity\"]) parts.push(node.getAttribute(name) ?? \"\");\n return parts.join(\" \");\n };\n return elements.flatMap((element) => {\n if (element.closest('a, button, label, summary, input, select, textarea, option, [role=\"button\"], [role=\"link\"]') || !shows(element))\n return [];\n const box = element.getBoundingClientRect();\n if (box.width <= 1 || box.height <= 1) return [];\n const text = String(element.innerText ?? \"\").replace(/\\s+/g, \" \").trim().slice(0, 500);\n if (!/\\p{L}/u.test(text)) return [];\n const style = styling(element);\n return [{\n text,\n errorStyle: /error|danger|invalid|fail/i.test(style),\n successStyle: /success/i.test(style),\n alert: element.matches('[role=\"alert\"], [role=\"alertdialog\"], [aria-live=\"assertive\"]'),\n }];\n });\n };\n const fieldKey = (field) => field.field + \"\\u0000\" + field.message;\n const fieldText = (field) => field.field + (field.message === \"\" ? \" is marked invalid\" : \": \" + field.message);\n // Notes the page as it stands now, before the click: its address, how many messages show each\n // text, and its flagged fields. After, as many messages with a text as showed it then are stale,\n // whatever element or page shows them, as a page that draws its messages again or a redirect to\n // a page with the same banner; one more with that text is new.\n const read = (promise) => waitBounded(promise.catch(() => undefined), 1000);\n const postedFrom = page.url();\n const shownBefore = await read(page.locator(messages).evaluateAll(messagesInPage));\n const staleCounts = new Map();\n for (const message of shownBefore ?? []) {\n const text = message.text.toLowerCase();\n staleCounts.set(text, (staleCounts.get(text) ?? 0) + 1);\n }\n const flaggedBefore = await read(page.locator(\"body\").evaluateAll(outcomeWaitInvalidInPage));\n const staleFields = new Set((flaggedBefore ?? []).map(fieldKey));\n // One look at the page: the new errors it shows, and what it shows that leaves the write open.\n const look = async (page) => {\n const fields = await page.locator(\"body\").evaluateAll(outcomeWaitInvalidInPage);\n const shown = await page.locator(messages).evaluateAll(messagesInPage);\n const errors = fields.filter((field) => !staleFields.has(fieldKey(field))).map(fieldText);\n const open = fields.filter((field) => staleFields.has(fieldKey(field))).map((field) => fieldText(field) + \", as before the click\");\n const counted = new Map();\n for (const message of shown) {\n const text = message.text.toLowerCase();\n counted.set(text, (counted.get(text) ?? 0) + 1);\n if (counted.get(text) <= (staleCounts.get(text) ?? 0)) continue;\n const refuses = saysError(message.text) || saysRefusal(message.text);\n const succeeds = message.successStyle || successWords.test(message.text);\n if (refuses && !succeeds) errors.push(message.text);\n else if (refuses) open.push(message.text + \" (a success beside a refusal)\");\n else if (openWords.test(message.text)) open.push(message.text);\n else if (message.errorStyle && !message.successStyle) open.push(message.text + \" (styled as an error, with no words of one)\");\n else if (message.alert && !succeeds) open.push(message.text + \" (an alert that says neither error nor success)\");\n }\n return { errors: [...new Set(errors)], open: [...new Set(open)] };\n };\n // Looks for the settle window, so an error the page draws just after the response counts, and\n // returns at the first look that shows one. Undefined when no look could read the page.\n const watch = async (page) => {\n const begun = Date.now();\n const capMs = 2000;\n let seen;\n while (true) {\n const each = await waitBounded(look(page).catch(() => undefined), Math.max(0, begun + capMs - Date.now()));\n if (each !== undefined) {\n seen = each;\n if (each.errors.length > 0) return each;\n }\n const elapsed = Date.now() - begun;\n if ((seen !== undefined && elapsed >= waitLimits.settle) || elapsed >= capMs) return seen;\n await waitSleep(100);\n }\n };\n // A redirect gives no body, so one back to the page that posted, or to an address whose query\n // names an error or failure, may carry a refusal the page check can't see: why, or undefined.\n const redirectedBack = (response) => {\n const location = String(response.headers()[\"location\"] ?? \"\").trim();\n if (location === \"\") return undefined;\n try {\n const to = new URL(location, response.url());\n const from = new URL(postedFrom);\n let query = to.search + to.hash;\n try {\n query = decodeURIComponent(query);\n } catch {}\n if (/error|fail/i.test(query)) return \"it redirected to \" + clip(location) + \", whose query names an error\";\n if (to.origin === from.origin && to.pathname === from.pathname)\n return \"it redirected back to the page that posted, \" + clip(to.pathname);\n } catch {}\n return undefined;\n };\n return async (outcome, page) => {\n const done = (reason, queued, label) => ({\n state: \"done\",\n status: queued ? \"queued\" : \"completed\",\n ...(label === undefined ? {} : { status_label: label }),\n reason,\n });\n const notDone = (reason) => ({ state: \"not_done\", status: \"failed\", reason });\n const unclear = (reason) => ({ state: \"unclear\", status: \"unconfirmed\", reason });\n // A native dialog that opened during the wait and says the write failed is the page's answer,\n // unless the response is a server error or proves a record (below). While one stays open the\n // page can't be read, and the look below finds it unclear.\n const dialog = outcome?.dialog;\n const dialogFailed =\n dialog !== undefined && dialog !== null && saysError(dialog.message())\n ? \"a native \" + dialog.type() + ' dialog said \"' + clip(dialog.message()) + '\"'\n : undefined;\n const response = outcome?.response;\n if (response === undefined || response === null) {\n if (dialogFailed !== undefined) return notDone(dialogFailed);\n const seen = await watch(page);\n const answered = outcome?.outcome === undefined ? \"\" : '; \"' + outcome.outcome + '\" answered the wait';\n if (seen !== undefined && seen.errors.length > 0)\n return notDone(\"no commit response\" + answered + \"; the page shows \" + list(seen.errors));\n return unclear(\"no commit response to confirm\" + answered);\n }\n const status = response.status();\n const where = response.request().method() + \" \" + new URL(response.url()).pathname + \" answered \" + status;\n // A server can fail after it saved, so a 5xx never proves the write did not go through.\n if (status >= 500)\n return unclear(where + \", a server error, which can come after a save\" + (dialogFailed === undefined ? \"\" : \"; \" + dialogFailed));\n const location = String(response.headers()[\"location\"] ?? \"\").trim();\n // A 201 with a Location names the record the commit created, so a dialog's words alone can't\n // make it not done.\n const created = status === 201 && location !== \"\" ? where + \" with Location \" + clip(location) : undefined;\n if (created !== undefined && dialogFailed !== undefined) return unclear(created + \", which proves a record, but \" + dialogFailed);\n if (dialogFailed !== undefined) return notDone(dialogFailed);\n if (status < 200 || status >= 400) return notDone(where);\n if (created !== undefined) return done(created, false);\n const body = await readBody(response, status);\n const found = body.json === undefined ? {} : judgeBody(body.json);\n if (found.failed !== undefined) return notDone(where + \"; its body's \" + found.failed);\n const seen = await watch(page);\n if (seen !== undefined && seen.errors.length > 0) return notDone(where + \"; the page shows \" + list(seen.errors));\n const back = status >= 300 ? redirectedBack(response) : undefined;\n if (back !== undefined) return unclear(where + \"; \" + back);\n if (body.unclear !== undefined) return unclear(where + \"; \" + body.unclear);\n if (found.unclear !== undefined) return unclear(where + \"; its body's \" + found.unclear);\n if (seen === undefined) return unclear(where + \"; the page could not be read after it\");\n if (seen.open.length > 0) return unclear(where + \"; the page shows \" + list(seen.open));\n return done(\n where + (body.json === undefined ? \"\" : \"; its body shows no error\") + \"; the page shows no error\",\n status === 202 || found.queued !== undefined,\n found.queued,\n );\n };\n})();\n`;\n"
|
|
92
|
+
"text": "import { timeoutDefaults } from \"../runtime/deadline.js\";\nimport { outcomeKindsCode, readyWaitCode } from \"./action-waits.js\";\n/**\n * The page-progress tracker every wait shares. A wait keeps going while the page shows progress\n * and fails once it has shown none for `noProgressMs`. Progress is any of:\n *\n * - the author's `loading` locator showing (for as long as it shows);\n * - a generic loading sign, within `region` when one is named, coming, going, or new: a busy\n * region, an indeterminate progress bar, or a skeleton, shimmer, spinner or loader class (never\n * on a form control) counts while it shows until it has held for `noProgressMs`, or in\n * `waitForOutcome` after an action, for as long as it shows. Determinate\n * bars (ratings, steps, meters) never count, and signs showing before the action in the same\n * number, or class hints already there at the first look, are the page's own decoration. One\n * page call counts them at each look; a sign element in content the browser skips rendering\n * does not show, and a look whose count runs out of time takes the class hints as unchanged.\n * `waitForRows` also counts a sign beside its rows (in their container or the element around\n * it, never inside a row, and only when it is visible): one there before the action, in the\n * same number, is the page's own; any other counts while it shows, until it and the rows have\n * held for `noProgressMs` with no request the action started in flight;\n * - in `waitForOutcome` after an action, a countdown ticking, within `region` when one is named:\n * a visible element whose own short text keeps its words while its numbers fall, read as a\n * clock (0:10 to 0:09), such as a review step that submits on its own at zero. One showing\n * before the action is the page's own, such as a hold timer, and never counts;\n * - DOM changes inside the author's `region` (never the whole page: carousels and ads never stop);\n * - one of the site's own `document`, `xhr` or `fetch` requests in flight (the site is\n * `siteDomain`, else a conservative guess from the page's host). A request the action started\n * counts until it ends, up to `lateFillCap`, and the page then gets `unchangedMs` to render its\n * answer; any other counts for 10 s and keeps the page busy for 4 s, since long-polls and\n * streams stay open. Beacons, images, fonts and media never count, and a request repeated with\n * the same method, URL and body (numbers aside) at a steady interval is a poll and is ignored;\n * - the page's URL changing, or the page being replaced;\n * - the wait's own reads changing: an outcome's matches, rows or values filling or changing.\n *\n * Network activity alone never proves the content is coming; it only keeps a wait alive.\n */\nconst progressCode = String.raw `\nconst waitLimits = Object.freeze(${JSON.stringify({\n navigation: timeoutDefaults.navigation,\n action: timeoutDefaults.action,\n answer: timeoutDefaults.answer,\n answerCap: timeoutDefaults.answerCap,\n settle: timeoutDefaults.settle,\n unchanged: timeoutDefaults.unchanged,\n lateFillCap: timeoutDefaults.lateFillCap,\n pending: timeoutDefaults.pending,\n})});\nconst waitRecords = [];\n// Every wait this call ran, oldest first, each with a sentence saying how it ended.\nconst waitReport = () => waitRecords.map((record) => ({ ...record }));\nconst waitSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n// A promise, or fallback once ms have passed without it settling; its timer never outlives it.\nconst waitBounded = (promise, ms, fallback = undefined) => {\n let timer;\n return Promise.race([\n promise,\n new Promise((resolve) => {\n timer = setTimeout(() => resolve(fallback), Math.max(0, ms));\n }),\n ]).finally(() => clearTimeout(timer));\n};\nconst waitSeconds = (ms) => (Math.max(0, ms) / 1000).toFixed(1) + \" s\";\n// How many reads in a row the running wait lost to a closed target. waitProgress sets it to 0 as a\n// wait starts, and again at the sample after a look that lost none.\nlet waitClosedLosses = 0;\n// A read the page cut short by replacing or removing what it read, so the next look reads again.\n// A cross-site frame runs as a target of its own, and a read of one that went reports a closed\n// target. While the call's page is open, that target was a frame of it, which goes once. A page\n// that closed, such as a popup the wait reads, fails every look instead, so the third such read in\n// a row throws.\nconst waitContextLost = (error) => {\n const message = String(error?.message);\n if (/Execution context was destroyed|Frame was detached/.test(message)) return true;\n if (!/Target page, context or browser has been closed|Target closed/.test(message) || page.isClosed()) return false;\n waitClosedLosses += 1;\n return waitClosedLosses < 3;\n};\n// Generic loading signs. A busy region or an indeterminate progress bar says the page is loading;\n// a determinate bar (one with a value) is a rating, a step or a meter. A class that names a\n// skeleton, shimmer, spinner or loader is only a hint, and never on a form control.\nconst waitLoadingSigns = '[aria-busy=\"true\"], [role=\"progressbar\"]:not([aria-valuenow], [aria-valuetext])';\nconst waitLoadingClasses =\n ':is([class*=\"skeleton\" i], [class*=\"shimmer\" i], [class*=\"spinner\" i], [class*=\"loader\" i]):not(input, select, textarea, button, option, [role=\"progressbar\"])';\n// How long one look's sign count may run in the page, which runs one call at a time, before it\n// leaves the class hints uncounted.\nconst waitClassesBudgetMs = 250;\n// Runs in the page, as page.evaluate(spec) or region.evaluateAll(elements, spec): how many generic\n// loading signs and class hints show in the document or the region's elements, through open\n// shadow roots, in one call, since a locator's count can cost a protocol call for each element it\n// matches. A sign shows as a visible locator match does: rendered, not hidden by visibility, with\n// a box, or for display: contents, a child element or text that shows. An element in content the\n// browser skips rendering (content-visibility) does not show, and its box is never read: reading\n// it would lay that content out, one element at a time. A display: contents sign is judged by its\n// children even there, its text by a range's box, as the visible check judges it. A closed shadow\n// root is out of page code's reach, so a sign inside one, which a Patchright locator could count,\n// is not counted. Class hints left uncounted after the budget are null.\nconst waitSignsInPage = (first, second) => {\n const [roots, spec] = second === undefined ? [[document], first] : [first, second];\n const started = performance.now();\n const scopes = new Set(roots);\n for (const scope of scopes) {\n if (scope.shadowRoot) scopes.add(scope.shadowRoot);\n for (const node of scope.querySelectorAll(\"*\")) if (node.shadowRoot) scopes.add(node.shadowRoot);\n }\n const boxed = (box) => box.width > 0 && box.height > 0;\n const textShows = (text) => {\n const range = text.ownerDocument.createRange();\n range.selectNode(text);\n return boxed(range.getBoundingClientRect());\n };\n const shows = (element) => {\n const rendered = typeof element.checkVisibility !== \"function\" ||\n element.checkVisibility({ visibilityProperty: true, contentVisibilityAuto: true });\n // Without a box: display: contents shows when a child element or text does; hidden or skipped\n // content does not.\n if (!rendered)\n return !element.checkVisibility() && getComputedStyle(element).display === \"contents\" &&\n [...element.childNodes].some((child) =>\n child.nodeType === Node.ELEMENT_NODE ? shows(child) : child.nodeType === Node.TEXT_NODE && textShows(child));\n return boxed(element.getBoundingClientRect());\n };\n const count = (selector, budgetMs) => {\n const seen = new Set();\n let shown = 0;\n for (const scope of scopes)\n for (const element of scope.querySelectorAll(selector)) {\n if (seen.has(element)) continue;\n seen.add(element);\n if (shows(element)) shown += 1;\n if (performance.now() - started > budgetMs) return null;\n }\n return shown;\n };\n // Countdown ticks, read when spec.countdown: an element whose own text is short and holds a\n // number is kept between looks. The same text with its numbers lower, read as a clock (0:10 to\n // 0:09), is a tick. The baseline look reads every element, however long that takes, and marks\n // what shows as the wait's own, such as a hold timer from before the action, which never ticks\n // for it and is not measured again while its text keeps its words. A later look reads no\n // further once past the budget.\n const ticks = () => {\n const timers = (globalThis[Symbol.for(\"pomerado.waitCountdowns\")] ??= new WeakMap());\n const begun = performance.now();\n const seen = new Set();\n let ticked = 0;\n for (const scope of scopes) {\n const walker = document.createTreeWalker(scope, NodeFilter.SHOW_TEXT);\n for (let text = walker.nextNode(); text !== null; text = walker.nextNode()) {\n if (!spec.baseline && performance.now() - begun > spec.budgetMs) return ticked;\n const element = text.parentElement;\n if (element === null || seen.has(element) || !/\\d/.test(text.data)) continue;\n seen.add(element);\n let own = \"\";\n for (const child of element.childNodes) if (child.nodeType === Node.TEXT_NODE) own += child.data;\n own = own.trim();\n if (own.length > 80) continue;\n const shape = own.replace(/\\d+/g, \"#\");\n const last = timers.get(element);\n const same = last?.shape === shape;\n if ((!spec.baseline && same && last.wait === spec.key) || !shows(element)) continue;\n const numbers = own.match(/\\d+/g).map(Number);\n if (!spec.baseline && same) {\n const at = numbers.findIndex((value, index) => value !== last.numbers[index]);\n if (at >= 0 && numbers[at] < last.numbers[at]) ticked += 1;\n }\n timers.set(element, { shape, numbers, wait: spec.baseline ? spec.key : undefined });\n }\n }\n return ticked;\n };\n const counted = { signs: count(spec.signs, Infinity), classes: count(spec.classes, spec.budgetMs) };\n if (spec.countdown) counted.ticks = ticks();\n return counted;\n};\nconst waitSignsSpec = { signs: waitLoadingSigns, classes: waitLoadingClasses, budgetMs: waitClassesBudgetMs };\n// A request the wait's action started, while it ran or in the second after, is the answer on its\n// way: it counts as progress and keeps the page busy until it ends, up to\n// lateFillCap. Any other request counts as progress for up to 10 s, and keeps the page busy for up\n// to 4 s (or the no-progress window when shorter): a long-poll or a stream stays open with nothing\n// to come, and starts on its own.\nconst waitCausedMs = 1000;\nconst waitInflightMs = 10000;\nconst waitBusyRequestMs = 4000;\n// The site's registrable domain, when the code gave none: the last two labels of the page's host,\n// or three under a country's shared second level (example.co.uk, never co.uk). Pass the context's\n// siteDomain, which the host computed with the public suffix list, to be exact.\nconst waitSiteDomain = (host) => {\n const labels = host.split(\".\");\n if (labels.length <= 2 || /^\\d+$/.test(labels.at(-1))) return host;\n const shared = labels.at(-1).length === 2 &&\n /^(?:ac|co|com|edu|gen|go|gob|gov|gv|in|ind|info|int|lg|ltd|me|mil|ne|net|nhs|nic|nom|or|org|plc|sch|web)$/.test(labels.at(-2));\n return labels.slice(shared ? -3 : -2).join(\".\");\n};\n// What makes two requests the same one again: method, path, query and body, with every number\n// (counters, timestamps, cache busters) read as the same.\nconst waitRequestKey = (request) => {\n const url = new URL(request.url());\n const body = String(request.postData() ?? \"\").slice(0, 4096).replace(/\\d+/g, \"#\");\n let hash = 2166136261;\n for (let i = 0; i < body.length; i += 1) hash = Math.imul(hash ^ body.charCodeAt(i), 16777619);\n return request.method() + \" \" + url.origin + url.pathname + url.search.replace(/\\d+/g, \"#\") + \" \" + (hash >>> 0).toString(36);\n};\nconst waitProgress = (options = {}) => {\n const noProgressMs = options.noProgressMs ?? waitLimits.answer;\n const key = \"pomerado.waitProgress.\" + Date.now() + \".\" + Math.random();\n waitClosedLosses = 0;\n let closedAtSample = 0;\n let started = Date.now();\n // Requests that start before this are the action's: from the baseline look, taken just before\n // the action, to a second after it returned. A wait without an action causes none.\n let causedUntil = -Infinity;\n let acted = false;\n let lastProgress = started;\n let signs = {};\n const mark = (kind, at = Date.now()) => {\n const sign = (signs[kind] ??= { first: at - started, last: at - started });\n sign.last = at - started;\n if (at > lastProgress) lastProgress = at;\n };\n const sameSite = (url) => {\n try {\n const host = new URL(url).hostname;\n const domain = options.siteDomain ?? waitSiteDomain(new URL(page.url()).hostname);\n return domain !== \"\" && (host === domain || host.endsWith(\".\" + domain));\n } catch {\n return false;\n }\n };\n // The site's requests in flight, by request: when each started and what makes it the same again.\n const pending = new Map();\n const starts = new Map();\n const polls = new Set();\n let ignoredRepeats = 0;\n const onRequest = (request) => {\n if (![\"document\", \"xhr\", \"fetch\"].includes(request.resourceType()) || !sameSite(request.url())) return;\n const key = waitRequestKey(request);\n const now = Date.now();\n // A poll repeats the same request at a steady interval: from its third start, once two\n // intervals of at least 50 ms agree within half, it is ignored with every copy in flight.\n // Requests to one path that differ, such as an API's different queries, never are.\n const times = [...(starts.get(key) ?? []), now].slice(-3);\n starts.set(key, times);\n if (!polls.has(key) && times.length === 3) {\n const [first, second] = [times[1] - times[0], times[2] - times[1]];\n if (Math.min(first, second) >= 50 && Math.abs(first - second) <= Math.max(first, second) / 2) {\n polls.add(key);\n for (const [other, entry] of pending) if (entry.key === key) pending.delete(other);\n }\n }\n if (polls.has(key)) {\n ignoredRepeats += 1;\n return;\n }\n pending.set(request, { at: now, key, caused: now <= causedUntil });\n mark(\"site request\");\n };\n // When the action's last request ended: the page then gets unchangedMs to render its answer.\n let causedEnded = -Infinity;\n const onDone = (request) => {\n const entry = pending.get(request);\n if (entry === undefined) return;\n pending.delete(request);\n if (entry.caused) causedEnded = Date.now();\n mark(\"site request\");\n };\n page.on(\"request\", onRequest);\n page.on(\"requestfinished\", onDone);\n page.on(\"requestfailed\", onDone);\n let url = page.url();\n // Generic signs, each kind with its count before the action (or, for class hints, at the first\n // look), its count at the last look and when that last changed. A sign counts while it shows\n // more than before, until its count has held for the no-progress window. A sign that stays is\n // part of the page. (waitForRows also judges the signs beside its rows: see listSigns.)\n const generic = {\n signs: { holdMs: noProgressMs, before: undefined, count: 0, changedAt: started, shows: false },\n classes: { holdMs: noProgressMs, before: undefined, count: 0, changedAt: started, shows: false, firstLook: true },\n };\n let loadingShows = false;\n let region = { count: 0, targets: 0 };\n // One look at the page's signs. The baseline look, taken before the action, notes them without\n // counting anything as progress.\n // Quiet time runs to the latest look that could see progress: the first look after the start\n // only installs the region's observer and notes the signs.\n let samples = 0;\n let sampledAt = started;\n const sample = async (changes = [], baseline = false) => {\n const now = Date.now();\n samples += 1;\n sampledAt = now;\n // A look that lost a read to a closed target saw no progress by it. One that lost none ends\n // the run of such losses.\n if (waitClosedLosses > closedAtSample) changes = changes.filter((kind) => kind !== \"page replaced\");\n else waitClosedLosses = 0;\n closedAtSample = waitClosedLosses;\n const note = (kind) => {\n if (!baseline) mark(kind, now);\n };\n for (const kind of changes) note(kind);\n if (page.url() !== url) {\n url = page.url();\n note(\"URL change\");\n }\n for (const { at, caused } of pending.values())\n if (now - at < (caused ? waitLimits.lateFillCap : waitInflightMs)) {\n note(\"site request\");\n break;\n }\n try {\n loadingShows = options.loading !== undefined && (await options.loading.filter({ visible: true }).count()) > 0;\n if (loadingShows) note(\"loading sign\");\n // A generic sign counts when it comes or goes, and while it is new: see generic above. Both\n // kinds are counted in one page call; class hints left uncounted are no news at this look.\n // After an action, waitForOutcome's call also reads countdowns.\n const spec = options.whileSending && acted ? { ...waitSignsSpec, key, countdown: true, baseline } : waitSignsSpec;\n const counted = await (options.region === undefined\n ? page.evaluate(waitSignsInPage, spec)\n : options.region.evaluateAll(waitSignsInPage, spec));\n if (counted.ticks > 0) note(\"countdown\");\n for (const [name, sign] of Object.entries(generic)) {\n // A count left undone is no news: the last count stands, so a sign showing keeps its\n // hold, and a baseline or first look notes nothing.\n const fresh = counted[name];\n if (fresh === null && (baseline || (sign.firstLook && sign.before === undefined))) continue;\n const count = fresh ?? sign.count;\n if (baseline || (sign.firstLook && sign.before === undefined)) {\n sign.before = count;\n sign.changedAt = now;\n } else {\n if (count !== sign.count) {\n sign.changedAt = now;\n note(\"loading sign\");\n }\n sign.shows = count > (sign.before ?? 0) && now - sign.changedAt < sign.holdMs;\n if (sign.shows) note(\"loading sign\");\n }\n sign.count = count;\n }\n if (options.region !== undefined) {\n const seen = await options.region.evaluateAll((elements, key) => {\n const state = (globalThis[Symbol.for(key)] ??= { count: 0, targets: new Set() });\n state.observer ??= new MutationObserver((records) => {\n state.count += records.length;\n });\n for (const element of elements)\n if (!state.targets.has(element)) {\n state.targets.add(element);\n state.observer.observe(element, {\n subtree: true,\n childList: true,\n characterData: true,\n attributes: true,\n attributeFilter: [\"class\", \"hidden\", \"aria-busy\", \"aria-hidden\", \"src\", \"value\", \"disabled\"],\n });\n }\n return { count: state.count, targets: state.targets.size };\n }, key);\n // The first look only installs the observer; a region that appears later is progress.\n if (seen.count !== region.count || (seen.targets !== region.targets && region.targets !== 0))\n note(\"region changes\");\n region = seen;\n }\n } catch (error) {\n const closedBefore = waitClosedLosses;\n if (!waitContextLost(error)) throw error;\n if (waitClosedLosses === closedBefore) note(\"page replaced\");\n }\n };\n return {\n // Before the action: what already shows is the page from before it.\n baseline: () => {\n acted = true;\n causedUntil = Infinity;\n // waitForOutcome counts a sign the action brought for as long as it shows: the page is\n // still sending.\n if (options.whileSending) for (const sign of Object.values(generic)) sign.holdMs = Infinity;\n return sample([], true);\n },\n // The budgets start once the action returns; requests it started stay in flight.\n begin: () => {\n started = Date.now();\n causedUntil = acted ? started + waitCausedMs : -Infinity;\n lastProgress = started;\n signs = {};\n samples = 0;\n },\n // Without a baseline, a sign already showing at the first look is the page still loading.\n sample: (changes) => sample(changes),\n quietMs: () => (samples < 2 ? 0 : sampledAt - lastProgress),\n // A loading sign showing or a site request in flight, at the last look. waitForRows judges the\n // generic signs itself, beside its rows (pageSigns false).\n busy: (pageSigns = true) => {\n const now = Date.now();\n const busyRequestMs = Math.min(noProgressMs, waitBusyRequestMs);\n return loadingShows || (pageSigns && (generic.signs.shows || generic.classes.shows)) ||\n now - causedEnded < (options.unchangedMs ?? waitLimits.unchanged) ||\n [...pending.values()].some(({ at, caused }) => now - at < (caused ? waitLimits.lateFillCap : busyRequestMs));\n },\n // A request the action started still in flight.\n causedInflight: () => {\n const now = Date.now();\n return [...pending.values()].some(({ at, caused }) => caused && now - at < waitLimits.lateFillCap);\n },\n diagnostics: () => ({\n signs: Object.fromEntries(Object.entries(signs).map(([kind, sign]) => [kind, { ...sign }])),\n quietSinceMs: lastProgress - started,\n inflight: pending.size,\n ignoredRepeats,\n }),\n describe: () => {\n const entries = Object.entries(signs);\n const seen = entries.length === 0\n ? \"no progress seen\"\n : \"progress seen: \" +\n entries\n .map(([kind, { first, last }]) =>\n kind + \" \" + (last > first ? waitSeconds(first) + \"–\" + waitSeconds(last) : \"at \" + waitSeconds(first)))\n .join(\", \") +\n \"; last progress at \" + waitSeconds(lastProgress - started);\n return seen + (ignoredRepeats > 0 ? \"; ignored \" + ignoredRepeats + \" repeating requests\" : \"\");\n },\n stop: async (inPage = true) => {\n page.off(\"request\", onRequest);\n page.off(\"requestfinished\", onDone);\n page.off(\"requestfailed\", onDone);\n if (inPage && options.region !== undefined) {\n const cleanup = options.region\n .evaluateAll((elements, key) => {\n globalThis[Symbol.for(key)]?.observer?.disconnect();\n delete globalThis[Symbol.for(key)];\n }, key)\n .catch(() => undefined);\n let timer;\n await Promise.race([cleanup, new Promise((resolve) => { timer = setTimeout(resolve, 250); })]);\n clearTimeout(timer);\n }\n },\n };\n};\nconst waitRecord = (record) => {\n waitRecords.push(record);\n return record;\n};\n`;\n/**\n * `waitForOutcome`, unchanged in what it decides, now with a progress budget: it fails as\n * `outcome_unknown` once the page shows no outcome and no progress for `noProgressMs`.\n */\nconst outcomeCode = String.raw `\nconst outcomeWaitSeen = (observations) =>\n Object.entries(observations)\n .map(([name, observation]) => {\n const { kind, count, visible, changed, matched, invalid, seen } = observation;\n if (kind === undefined || kind === \"gone\")\n return name + (kind === \"gone\" ? \" (gone) \" : \" \") + visible + \" visible of \" + count +\n (changed === 0 && visible > 0 ? \", unchanged\" : \"\");\n if (kind === \"invalid\") return name + \" \" + invalid + \" invalid fields\";\n if (kind === \"url\") return name + (matched ? \" URL matched\" : \" URL not matched\");\n if (kind === \"check\") return name + (matched ? \" check true\" : \" check not true\");\n if (kind === \"announced\") return name + (matched ? \" announced\" : \" no matching announcement of \" + seen + \" seen\");\n return name + (matched ? \" \" + kind + \" matched\" : \" no matching \" + kind + \" of \" + seen + \" seen\");\n })\n .join(\", \");\nconst outcomeWaitFailure = (reason, message, observations, extra) =>\n Object.assign(new Error(reason + message), {\n name: \"OutcomeWaitFailure\",\n reason,\n observations,\n ...extra,\n });\n// What each visible element showed before the action, kept in the page by a key of this wait's\n// own; a page the action replaced has none, so everything on it is new.\nconst outcomeWaitNote = (locator, key) =>\n locator.filter({ visible: true }).evaluateAll((elements, key) => {\n const noted = (globalThis[Symbol.for(key)] ??= new WeakMap());\n for (const element of elements) noted.set(element, element.innerText);\n }, key);\nconst outcomeWaitChanged = (locator, key) =>\n locator.filter({ visible: true }).evaluateAll((elements, key) => {\n const noted = globalThis[Symbol.for(key)];\n return elements.filter((element) => noted?.get(element) !== element.innerText).length;\n }, key);\n// Reads the outcomes highest priority last, so a look that sees one also sees a higher one drawn\n// in the same render. The observations keep the listed order.\nconst outcomeWaitObserve = async (outcomes, key, state, events) => {\n const candidates = Array.isArray(outcomes) ? outcomes\n : Object.entries(outcomes).map(([name, locator]) => ({ name, kind: \"locator\", locator }));\n const observations = {};\n for (const candidate of [...candidates].reverse())\n observations[candidate.name] = await outcomeWaitRead(candidate, state, key, events);\n return Object.fromEntries(candidates.map(({ name }) => [name, observations[name]]));\n};\n// How long a look the page holds up may still finish once a response or popup outcome arrived, and\n// once the deadline passed.\nconst outcomeWaitGraceMs = 1000;\nconst outcomeWaitLateMs = 500;\n// What a pending hold leaves of the call, whose end the runtime declares as __pomeradoCallEnds, for\n// the code after the wait, such as confirmCommit's reads.\nconst outcomeWaitCallRoomMs = 5000;\nconst waitForOutcomeResult = async (outcomes, options = {}) => {\n const names = Object.keys(outcomes ?? {});\n if (names.length === 0) throw new TypeError(\"waitForOutcome needs at least one outcome\");\n const candidates = names.map((name) => outcomeWaitCandidate(name, outcomes[name]));\n const pendingNames = new Set(options.pending === undefined ? [] : [options.pending].flat());\n for (const name of pendingNames) {\n const kind = candidates.find((candidate) => candidate.name === name)?.kind;\n if (kind === undefined) throw new TypeError('waitForOutcome pending \"' + name + '\" names none of its outcomes');\n if ([\"response\", \"dialog\", \"popup\"].includes(kind))\n throw new TypeError('waitForOutcome pending \"' + name + '\" names a ' + kind + \" outcome; pending takes outcomes the page shows\");\n }\n const timeout = options.timeout ?? waitLimits.answerCap;\n const noProgressMs = options.noProgressMs ?? waitLimits.answer;\n const progress = waitProgress({ ...options, noProgressMs, whileSending: true });\n const events = outcomeWaitEvents(candidates);\n const state = {\n goneSeen: new Set(),\n goneSince: new Map(),\n invalidFields: new Map(),\n invalidBefore: new Map(),\n checked: new Map(),\n announcedText: new Map(),\n announceKey: candidates.some((candidate) => candidate.kind === \"announced\")\n ? \"pomerado.outcomeAnnounce.\" + Date.now() + \".\" + Math.random() : undefined,\n urlBefore: undefined,\n actedAt: -Infinity,\n };\n let looks = 0;\n const finish = (fields, summary) =>\n waitRecord({\n wait: \"waitForOutcome\",\n ...fields,\n elapsedMs: Date.now() - begun,\n looks,\n progress: progress.describe(),\n summary: \"waitForOutcome: \" + summary + \"; \" + progress.describe(),\n });\n let begun = Date.now();\n let key;\n // How long the cleanup may take: 250 ms, and nothing past the wait's hard stop.\n let cleanupMs = () => 250;\n try {\n if (options.action !== undefined) {\n key = \"pomerado.outcomeWait.\" + Date.now() + \".\" + Math.random();\n for (const candidate of candidates) {\n if (candidate.kind === \"locator\") await outcomeWaitNote(candidate.locator, key);\n if (candidate.kind === \"gone\" && (await candidate.locator.filter({ visible: true }).count()) > 0)\n state.goneSeen.add(candidate.name);\n if (candidate.kind === \"invalid\")\n state.invalidBefore.set(candidate.name, outcomeWaitInvalidKey(await candidate.locator.evaluateAll(outcomeWaitInvalidInPage)));\n }\n state.urlBefore = page.url();\n if (state.announceKey !== undefined) await page.evaluate(outcomeWaitAnnounceInPage, { key: state.announceKey, seed: false });\n await progress.baseline();\n state.actedAt = Date.now();\n // A click whose handler opens a native dialog does not return until the dialog is handled,\n // and the wait's dialog listener keeps Playwright from dismissing it: with a dialog outcome,\n // the wait goes on once the action returns or a dialog opens.\n if (candidates.some((candidate) => candidate.kind === \"dialog\")) {\n const acting = Promise.resolve().then(() => options.action());\n acting.catch(() => undefined);\n const first = await Promise.race([acting.then(() => \"acted\"), events.dialogSignal.then(() => \"dialog\")]);\n if (first === \"acted\") await acting;\n } else await options.action();\n }\n progress.begin();\n begun = Date.now();\n // deadline, a Date.now() time such as the call's own, bounds the wait wherever the action left it.\n let until = Math.min(begun + timeout, options.deadline ?? Infinity);\n // Past the deadline, every page call shares outcomeWaitLateMs of grace and then ends: the wait\n // never outlasts hardStop, however long the page holds it.\n let hardStop = until + outcomeWaitLateMs;\n let pendingSince;\n const beforeStop = () => Math.max(0, hardStop - Date.now());\n cleanupMs = () => Math.min(250, beforeStop());\n const unchangedMs = options.unchangedMs ?? waitLimits.unchanged;\n const unchangedFrom = begun + unchangedMs;\n // A page or frame the action is replacing or removing can drop a look midway; the next look\n // reads the page again.\n // The page cannot always be read: a native dialog stops its scripts, and while a navigation\n // is pending Playwright cannot evaluate in it. A look the page holds up ends at the deadline\n // (with outcomeWaitLateMs of grace, so a look begun just before it finishes), at once for a dialog,\n // and outcomeWaitGraceMs after a response or popup outcome arrived, which then decides on the\n // outcomes the page announced as events.\n const unblocked = (reading) => {\n reading.catch(() => undefined);\n const bounded = waitBounded(reading, beforeStop());\n if (!candidates.some((candidate) => [\"response\", \"dialog\", \"popup\"].includes(candidate.kind))) return bounded;\n return Promise.race([\n bounded,\n events.dialogSignal.then(() => undefined),\n events.hitSignal.then(() => waitBounded(reading, Math.min(outcomeWaitGraceMs, beforeStop()))),\n ]);\n };\n const look = () =>\n unblocked(outcomeWaitObserve(candidates, key, state, events).catch((error) => {\n if (waitContextLost(error)) return undefined;\n throw error;\n }));\n const result = (candidate, observations, evidence) => {\n const handles = events.hit(candidate.name)?.handles ?? {};\n // A native dialog stops the page, so the last look it allowed can predate an event outcome\n // that matched since, such as a save's response just before the dialog. Once a dialog opened,\n // each event outcome reads as it stands now, and those that matched besides the winner, the\n // dialog's own outcome included, are on the result and in the summary too.\n const evented = [\"response\", \"dialog\", \"popup\"];\n const dialogOpened = events.dialogOpen();\n const also = !dialogOpened ? []\n : candidates.filter((each) => each !== candidate && evented.includes(each.kind) && events.hit(each.name) !== undefined);\n const observed = !dialogOpened ? observations\n : Object.fromEntries(candidates.flatMap((each) =>\n evented.includes(each.kind) ? [[each.name, outcomeWaitEventRead(each, events)]]\n : observations[each.name] === undefined ? [] : [[each.name, observations[each.name]]]));\n const pending = pendingNames.has(candidate.name);\n const answer = {\n outcome: candidate.name,\n kind: candidate.kind,\n ...(pending ? { pending: true } : {}),\n afterMs: Date.now() - begun,\n looks,\n evidence,\n observations: observed,\n };\n for (const [name, value] of Object.entries(handles)) outcomeWaitHidden(answer, name, value);\n for (const each of also)\n for (const [name, value] of Object.entries(events.hit(each.name).handles))\n if (answer[name] === undefined) outcomeWaitHidden(answer, name, value);\n // A dialog that opened while the wait listened stays open whichever outcome won, and the\n // summary says so.\n if (answer.dialog === undefined) outcomeWaitHidden(answer, \"dialog\", events.dialog());\n finish(\n { outcome: candidate.name },\n '\"' + candidate.name + '\"' + (candidate.kind === \"locator\" ? \"\" : \" (\" + candidate.kind + \")\") + \" showed after \" +\n (pending ? pendingSince - begun + \" ms and was still pending after \" : \"\") +\n answer.afterMs + \" ms (\" + looks + (looks === 1 ? \" look)\" : \" looks)\") +\n also.map((each) => '; \"' + each.name + '\" (' + each.kind + \") also matched\").join(\"\") +\n (answer.dialog === undefined ? \"\" : \"; a native \" + answer.dialog.type() + \" dialog is left open on the result's dialog\"),\n );\n return answer;\n };\n // The first look that shows an outcome decides: no second look confirms it. An answer from\n // before the action is kept out of that look by the stale rule below, not by a second look.\n let last;\n let signature;\n let quietBefore = false;\n while (true) {\n // A request the action started that was in flight as the look began counts as in flight for\n // that look's matches, even when it ends while the look runs.\n const inflightAtStart = progress.causedInflight();\n const observations = await look();\n events.rethrow();\n looks += 1;\n last = observations ?? last;\n // A match from before the action stays stale while a request the action started is in flight,\n // but only until the deadline less the unchanged window, so a match the wait returned before\n // such requests held it back still returns in time. One clock read serves this and the\n // deadline below, so the hold never outlasts the deadline even with no unchanged window.\n const now = Date.now();\n const stale = now < unchangedFrom ||\n (now < until - unchangedMs && (inflightAtStart || progress.causedInflight()));\n // With the page unreadable, a native dialog open included, only the outcomes the page\n // announced as events decide, in the listed order: a dialog outcome wins unless a response\n // or popup outcome listed before it already matched, and that one wins with the dialog held.\n const blocked = events.dialogOpen() || (observations === undefined && events.anyHit());\n // While a navigation the action set off is on its way, the elements shown are the old\n // document's, about to be replaced: a locator or invalid fields count only on the new one.\n const replacing = key !== undefined && events.navigating(state.actedAt);\n const shows = (candidate, staleNow = stale) =>\n blocked ? [\"response\", \"dialog\", \"popup\"].includes(candidate.kind) && events.hit(candidate.name) !== undefined\n : !(replacing && (candidate.kind === \"locator\" || candidate.kind === \"invalid\")) &&\n outcomeWaitShows(candidate, observations?.[candidate.name], state, staleNow, now);\n // An in-between answer the code named in pending never decides while it shows: it holds the\n // wait for a final one, up to waitLimits.pending from the first look that shows it, never past\n // the deadline nor later than outcomeWaitCallRoomMs before the call's own end. One still\n // showing when the hold ends is the answer. One that showed before the action, unchanged, is\n // no answer to it and never holds the wait.\n const shown = candidates.find((candidate) => !pendingNames.has(candidate.name) && shows(candidate));\n const held = blocked ? undefined : candidates.find((candidate) => pendingNames.has(candidate.name) && shows(candidate, true));\n if (held !== undefined && pendingSince === undefined) {\n pendingSince = now;\n const callEnds = typeof __pomeradoCallEnds === \"number\" ? __pomeradoCallEnds - outcomeWaitCallRoomMs : Infinity;\n until = Math.max(until, Math.min(now + waitLimits.pending, options.deadline ?? Infinity, callEnds));\n hardStop = until + outcomeWaitLateMs;\n }\n if (shown !== undefined) {\n const observation = observations?.[shown.name];\n if (shown.kind === \"locator\" && observation.count > 1) {\n const failure = outcomeWaitFailure(\"outcome_ambiguous\", \": \" + outcomeWaitSeen(observations), observations, {\n outcome: shown.name,\n });\n finish({ reason: \"outcome_ambiguous\", outcome: shown.name }, failure.message);\n throw failure;\n }\n const evidence = await waitBounded(\n outcomeWaitEvidence(shown, observation, state, events, now),\n Math.max(250, until - Date.now()),\n {},\n );\n return result(shown, observations ?? last ?? {}, evidence);\n }\n if (events.unnamedDialog() !== undefined) {\n const opened = events.unnamedDialog();\n const failure = outcomeWaitFailure(\n \"outcome_unknown\",\n \" after \" + (now - begun) + \" ms: a native \" + opened.type() + \" dialog opened that no outcome names\",\n last ?? {},\n {},\n );\n outcomeWaitHidden(failure, \"dialog\", opened);\n finish({ reason: \"outcome_unknown\" }, failure.message);\n throw failure;\n }\n // Only a look that decides nothing samples the page's progress: the decision never uses it.\n const current = JSON.stringify(observations ?? null);\n await unblocked(progress.sample(\n observations === undefined ? [\"page replaced\"]\n : signature !== undefined && current !== signature ? [\"outcome matches changing\"] : [],\n ));\n // An outcome the page announced as an event during the sample decides at the next look.\n if (events.dialogOpen() || events.anyHit()) continue;\n signature = current;\n if (now >= until && held !== undefined) {\n const evidence = await waitBounded(\n outcomeWaitEvidence(held, observations[held.name], state, events, now),\n Math.max(250, until - Date.now()),\n {},\n );\n return result(held, observations, evidence);\n }\n if (now >= until) {\n const seen = last ?? (beforeStop() > 0 ? await look().catch(() => undefined) : undefined) ?? {};\n const failure = outcomeWaitFailure(\n \"outcome_timeout\",\n \" after \" + Math.round(Math.max(0, until - begun)) + \" ms: \" +\n (Object.keys(seen).length === 0 ? \"the page could not be read\" : outcomeWaitSeen(seen)) + \"; \" + progress.describe(),\n seen,\n { progress: progress.diagnostics() },\n );\n finish({ reason: \"outcome_timeout\" }, failure.message);\n throw failure;\n }\n // Nothing shows, not even an answer from before the action, and the page went quiet.\n // A quiet page fails only when the next look agrees, since the page may have answered\n // between this look's outcomes and its progress sample.\n const anyShown = candidates.some((candidate) => outcomeWaitShowsAny(candidate, observations?.[candidate.name]));\n const quiet = !anyShown && held === undefined && progress.quietMs() >= noProgressMs;\n if (quiet && !quietBefore) quietBefore = true;\n else if (quiet) {\n const seen = last ?? {};\n const failure = outcomeWaitFailure(\n \"outcome_unknown\",\n \" after \" + (Date.now() - begun) + \" ms, \" + Math.round(noProgressMs) + \" ms without progress, no outcome showing: \" +\n outcomeWaitSeen(seen) + \"; \" + progress.describe(),\n seen,\n { progress: progress.diagnostics() },\n );\n finish({ reason: \"outcome_unknown\" }, failure.message);\n throw failure;\n } else quietBefore = false;\n await waitSleep(100);\n }\n } catch (error) {\n // A dialog that opened while the wait listened stays open: the failure carries it too.\n if (error !== null && typeof error === \"object\" && error.dialog === undefined) outcomeWaitHidden(error, \"dialog\", events.dialog());\n throw error;\n } finally {\n events.stop();\n // With a native dialog open the page cannot run the cleanup; what it leaves is inert.\n const inPage = !events.dialogOpen();\n // A page held up by a pending navigation gets a moment; what it keeps is inert.\n for (const each of [key, state.announceKey])\n if (each !== undefined && inPage)\n await waitBounded(\n page.evaluate((key) => {\n globalThis[Symbol.for(key)]?.observer?.disconnect?.();\n delete globalThis[Symbol.for(key)];\n }, each),\n cleanupMs(),\n ).catch(() => undefined);\n await progress.stop(inPage && cleanupMs() > 0);\n }\n};\nconst waitForOutcome = async (outcomes, options = {}) => (await waitForOutcomeResult(outcomes, options)).outcome;\n`;\n/**\n * `waitForRows`, `waitForValues` and `waitForChange`: wait for the values a tool returns to be\n * filled in and to read the same on two looks.\n */\nconst valueCode = String.raw `\n// Runs in the page: reads each element's value, or says it is absent or still loading. A value is\n// still loading when it is empty, reads as a loading word or only dots, matches the author's\n// placeholder, or sits in an aria-busy, skeleton or shimmer element (up to its row).\nconst waitReadInPage = (elements, spec) => {\n const loadingWords = /^(?:loading|updating|calculating|fetching|searching|please wait)\\b/i;\n const visible = (element) =>\n typeof element.checkVisibility === \"function\" ? element.checkVisibility()\n : element.getClientRects().length > 0;\n const busy = (element, stop) => {\n for (let node = element, depth = 0; node instanceof Element && depth < 8; node = node.parentElement, depth += 1) {\n if (node.getAttribute(\"aria-busy\") === \"true\") return true;\n if (/skeleton|shimmer/i.test(node.getAttribute(\"class\") ?? \"\")) return true;\n if (node === stop) break;\n }\n return false;\n };\n const read = (element, field, stop, identity) => {\n if (!(element instanceof Element)) return { state: \"absent\" };\n const raw = field.attribute ? element.getAttribute(field.attribute) : visible(element) ? element.innerText : \"\";\n const value = String(raw ?? \"\").trim();\n const placeholder = field.placeholder ? new RegExp(field.placeholder.source, field.placeholder.flags) : undefined;\n if (value === \"\" || loadingWords.test(value) || /^[.…\\s]+$/.test(value) || placeholder?.test(value))\n return { state: \"loading\" };\n if (!identity && busy(element, stop)) return { state: \"loading\" };\n return { state: \"filled\", value };\n };\n // How many loading signs show beside a list's rows: in the rows' container or the element around\n // it, never inside a row. A decoration lives in its card, while a list still loading shows its\n // spinner, skeleton or busy state beside the rows. A class hint that holds rows is their layout,\n // not a sign, and a sign kept in layout but invisible (visibility or opacity) does not show.\n const shown = (element) =>\n typeof element.checkVisibility === \"function\"\n ? element.checkVisibility({ visibilityProperty: true, opacityProperty: true })\n : element.getClientRects().length > 0;\n const listSigns = (rows, selectors) => {\n if (rows.length === 0) return 0;\n let common = rows[0].parentElement;\n while (common !== null && !rows.every((row) => common.contains(row))) common = common.parentElement;\n if (common === null) return 0;\n const outer = common.parentElement;\n const root = outer === null || outer === document.body || outer === document.documentElement ? common : outer;\n let count = 0;\n for (const element of [root, ...root.querySelectorAll(selectors.all)])\n if (\n element.matches(selectors.all) &&\n shown(element) &&\n !rows.some((row) => row.contains(element)) &&\n (element.matches(selectors.signs) || !rows.some((row) => element.contains(row)))\n )\n count += 1;\n return count;\n };\n if (spec.mode === \"rows\")\n return { signs: listSigns(elements, spec.signs), rows: elements.map((row) => {\n // A row's field is its first visible match, such as the price a responsive card shows\n // beside a hidden copy. Read text whose matches are all hidden is hidden, not loading: the\n // selector names the wrong copy, or the site shows it only on another layout.\n const at = (field) => {\n if (!field.selector) return row;\n const matches = [...row.querySelectorAll(field.selector)];\n return matches.find(visible) ?? (field.attribute || matches.length === 0 ? matches[0] : \"hidden\");\n };\n const take = (field, identity) => {\n const element = at(field);\n return element === \"hidden\" ? { state: \"hidden\" } : read(element, field, row, identity);\n };\n const fields = {};\n for (const [name, field] of Object.entries(spec.fields)) fields[name] = take(field, false);\n return { key: take(spec.key, true), fields };\n }) };\n const field = spec.field;\n const candidates = field.attribute ? elements : elements.filter(visible);\n if (candidates.length === 0) return { state: \"absent\" };\n if (field.all) {\n const values = candidates.map((element) => read(element, field, undefined, false));\n return values.some((value) => value.state !== \"filled\") ? { state: \"loading\" }\n : { state: \"filled\", value: values.map((value) => value.value) };\n }\n if (candidates.length > 1) return { state: \"ambiguous\", count: candidates.length };\n return read(candidates[0], field, undefined, false);\n};\n// A field as the page code reads it: a CSS selector inside the row (or the row itself), or for\n// waitForValues a Playwright locator, with an attribute to read instead of the text.\nconst waitFieldSpec = (field, where) => {\n const spec = typeof field === \"string\" ? { selector: field }\n : field !== null && typeof field === \"object\" && typeof field.evaluateAll === \"function\" ? { locator: field }\n : field !== null && typeof field === \"object\" ? field\n : undefined;\n if (spec === undefined) throw new TypeError(where + \" needs a selector, a locator or { selector | locator, attribute }\");\n const placeholder = spec.placeholder instanceof RegExp\n ? { source: spec.placeholder.source, flags: spec.placeholder.flags.replace(\"g\", \"\") }\n : undefined;\n return {\n ...(spec.selector === undefined ? {} : { selector: spec.selector }),\n ...(spec.locator === undefined ? {} : { locator: spec.locator }),\n ...(spec.attribute === undefined ? {} : { attribute: spec.attribute }),\n ...(spec.all === true ? { all: true } : {}),\n ...(spec.optional === true ? { optional: true } : {}),\n ...(placeholder === undefined ? {} : { placeholder }),\n };\n};\nconst valueWaitFailure = (reason, message, details) =>\n Object.assign(new Error(reason + message), { name: \"ValueWaitFailure\", reason, ...details });\nconst valueWaitRows = (list) =>\n list.length === 0 ? \"\" : (list.length === 1 ? \" in row \" : \" in rows \") + list.slice(0, 10).join(\", \") + (list.length > 10 ? \" and \" + (list.length - 10) + \" more\" : \"\");\n// Runs the shared loop for a value wait: look, note progress, return once ready on two agreeing\n// looks, fail once quiet or past the cap. evaluate() returns { ready, snapshot, filled, problems,\n// result, settleMs }.\nconst valueWaitLoop = async (wait, options, evaluate, timeoutDefault) => {\n const timeout = options.timeout ?? timeoutDefault;\n const noProgressMs = options.noProgressMs ?? waitLimits.answer;\n const progress = waitProgress({ ...options, noProgressMs });\n let looks = 0;\n let begun = Date.now();\n const finish = (fields, summary) =>\n waitRecord({\n wait,\n ...fields,\n elapsedMs: Date.now() - begun,\n looks,\n progress: progress.describe(),\n summary: wait + \": \" + summary + \"; \" + progress.describe(),\n });\n try {\n await options.prepare?.();\n if (options.action !== undefined) {\n await progress.baseline();\n await options.action();\n }\n progress.begin();\n begun = Date.now();\n const until = begun + timeout;\n let candidate;\n let candidateAt = begun;\n let filled = -1;\n let quietBefore = false;\n while (true) {\n let state;\n try {\n state = await evaluate(progress);\n } catch (error) {\n if (!waitContextLost(error)) throw error;\n state = undefined;\n }\n looks += 1;\n const changes = [];\n if (state === undefined) changes.push(\"page replaced\");\n else if (state.signs) changes.push(\"loading sign\");\n else if (candidate !== undefined && state.snapshot !== candidate) {\n changes.push(state.filled > filled ? \"values filling\" : \"values changing\");\n }\n await progress.sample(changes);\n const now = Date.now();\n if (state !== undefined) {\n if (state.snapshot !== candidate) {\n candidate = state.snapshot;\n candidateAt = now;\n }\n filled = state.filled;\n // Readiness that depends on progress is judged after this look's sample.\n state.ready = typeof state.ready === \"function\" ? state.ready() : state.ready;\n if (state.ready && now - candidateAt >= state.settleMs) {\n finish({ outcome: \"ready\" }, state.summary(now - begun, looks));\n return state.result;\n }\n }\n if (now >= until) {\n const problems = state?.problems ?? \"the page was being replaced\";\n const failure = valueWaitFailure(\n \"values_timeout\",\n \" after \" + Math.round(timeout) + \" ms: \" + problems + \"; \" + progress.describe(),\n { progress: progress.diagnostics() },\n );\n finish({ reason: \"values_timeout\" }, failure.message);\n throw failure;\n }\n // A quiet page fails only when the next look agrees, as in waitForOutcome.\n const quiet = progress.quietMs() >= noProgressMs && !state?.ready;\n if (quiet && !quietBefore) quietBefore = true;\n else if (quiet) {\n const reason = state?.reason ?? \"values_loading\";\n const failure = valueWaitFailure(\n reason,\n \" after \" + (now - begun) + \" ms, \" + Math.round(noProgressMs) + \" ms without progress: \" +\n (state?.problems ?? \"nothing read\") + \"; \" + progress.describe(),\n { progress: progress.diagnostics() },\n );\n finish({ reason }, failure.message);\n throw failure;\n } else quietBefore = false;\n await waitSleep(100);\n }\n } finally {\n await progress.stop();\n }\n};\nconst waitForRows = async (rows, fields, options = {}) => {\n const count = options.count;\n if (!Number.isInteger(count) || count < 1) throw new TypeError(\"waitForRows needs count, the number of rows you return\");\n if (options.key === undefined) throw new TypeError(\"waitForRows needs key, the field that identifies a row\");\n const key = waitFieldSpec(options.key, \"waitForRows key\");\n const spec = {\n mode: \"rows\",\n key,\n fields: Object.fromEntries(Object.entries(fields).map(([name, field]) => [name, waitFieldSpec(field, \"waitForRows field \" + name)])),\n };\n const settle = options.stableMs ?? waitLimits.settle;\n const fewSettle = Math.max(settle, options.unchangedMs ?? waitLimits.unchanged);\n spec.signs = { all: waitLoadingSigns + \", \" + waitLoadingClasses, signs: waitLoadingSigns };\n const noProgressMs = options.noProgressMs ?? waitLimits.answer;\n // The signs beside the rows. Those there before the action, in the same number, are the page's\n // own. One that came after it, or that shows without an action, counts while it shows, until it\n // and the rows have held unchanged for noProgressMs with no request the action started still in\n // flight: then it is decoration too, so a sign that never leaves costs one window, never the cap.\n let signsBefore = 0;\n let signsCount;\n let signsChangedAt = 0;\n let rowsSeen;\n let rowsChangedAt = 0;\n const prepare = async () => {\n await options.prepare?.();\n if (options.action !== undefined) signsBefore = (await rows.evaluateAll(waitReadInPage, spec)).signs;\n };\n return valueWaitLoop(\"waitForRows\", { ...options, prepare }, async (progress) => {\n const { rows: read, signs: listSigns } = await rows.evaluateAll(waitReadInPage, spec);\n const identified = read.filter((row) => row.key.state === \"filled\");\n const hiddenKeys = read.flatMap((row, index) => (row.key.state === \"hidden\" ? [index + 1] : []));\n const taken = identified.slice(0, count);\n const loading = {};\n const hidden = {};\n const missing = {};\n let filledCount = 0;\n taken.forEach((row, index) => {\n for (const [name, value] of Object.entries(row.fields)) {\n if (value.state === \"filled\") filledCount += 1;\n else if (value.state === \"loading\") (loading[name] ??= []).push(index + 1);\n else if (spec.fields[name].optional) continue;\n else if (value.state === \"hidden\") (hidden[name] ??= []).push(index + 1);\n else (missing[name] ??= []).push(index + 1);\n }\n });\n const problems = [\n ...Object.entries(loading).map(([name, list]) => name + \" still loading\" + valueWaitRows(list)),\n ...Object.entries(hidden).map(([name, list]) => name + \" hidden\" + valueWaitRows(list)),\n ...Object.entries(missing).map(([name, list]) => name + \" missing\" + valueWaitRows(list)),\n ];\n const complete = problems.length === 0;\n const few = taken.length < count;\n if (hiddenKeys.length > 0) problems.push(\"key hidden\" + valueWaitRows(hiddenKeys));\n const now = Date.now();\n if (listSigns !== signsCount) {\n signsCount = listSigns;\n signsChangedAt = now;\n }\n const rowsNow = JSON.stringify(taken);\n if (rowsNow !== rowsSeen) {\n rowsSeen = rowsNow;\n rowsChangedAt = now;\n }\n const listLoading = listSigns > signsBefore &&\n (now - Math.max(signsChangedAt, rowsChangedAt) < noProgressMs || progress.causedInflight());\n return {\n // No identified row is never an answer: an empty list is waitForOutcome's to decide. Fewer\n // rows than asked are an answer only once nothing shows the list is still loading.\n ready: () => complete && taken.length > 0 && (!few || (!listLoading && !progress.busy(false))),\n signs: listLoading,\n settleMs: few ? fewSettle : settle,\n filled: taken.length * 1000 + filledCount,\n // The rows are read before the signs beside them, so a loader leaving in between restarts\n // the settle, and the next look sees the rows it left for.\n snapshot: JSON.stringify([listSigns, taken]),\n // A needed field the page still lacks once it stopped changing is a page the code does not\n // match, not one still loading.\n reason: Object.keys(missing).length > 0 && Object.keys(loading).length === 0 && Object.keys(hidden).length === 0\n ? \"page_mismatch\" : \"values_loading\",\n problems:\n identified.length + \" identified rows of \" + read.length + \", needed \" + count +\n (problems.length === 0 ? \"\" : \"; \" + problems.join(\"; \")),\n summary: (elapsed, looks) =>\n taken.length + \" of \" + count + \" rows filled and holding after \" + elapsed + \" ms (\" + looks + \" looks)\" +\n (few ? \", fewer rows than asked and the count held\" : \"\"),\n result: {\n rows: taken.map((row) => ({\n key: row.key.value,\n ...Object.fromEntries(Object.entries(row.fields).map(([name, value]) => [name, value.state === \"filled\" ? value.value : null])),\n })),\n more: identified.length > count,\n },\n };\n }, waitLimits.lateFillCap);\n};\n// Reads each named field once: its value, or that it is absent, ambiguous or still loading.\nconst valueWaitRead = async (specs) => {\n const read = {};\n for (const [name, spec] of Object.entries(specs))\n read[name] = await spec.locator.evaluateAll(waitReadInPage, { mode: \"field\", field: { ...spec, locator: undefined } });\n return read;\n};\nconst valueWaitState = (specs, read) => {\n const problems = [];\n let filled = 0;\n let absent = false;\n for (const [name, value] of Object.entries(read)) {\n if (value.state === \"filled\") filled += 1;\n else if (value.state === \"loading\") problems.push(name + \" still loading\");\n else if (value.state === \"ambiguous\") problems.push(name + \" matches \" + value.count + \" visible elements\");\n else if (!specs[name].optional) {\n absent = true;\n problems.push(name + \" missing\");\n }\n }\n const values = Object.fromEntries(Object.entries(read).map(([name, value]) => [name, value.state === \"filled\" ? value.value : null]));\n return { problems, filled, absent, values, complete: problems.length === 0 };\n};\nconst valueWaitSpecs = (fields, where) => {\n const specs = Object.fromEntries(Object.entries(fields).map(([name, field]) => [name, waitFieldSpec(field, where + \" field \" + name)]));\n for (const [name, spec] of Object.entries(specs))\n if (spec.locator === undefined) throw new TypeError(where + \" field \" + name + \" needs a Playwright locator\");\n if (Object.keys(specs).length === 0) throw new TypeError(where + \" needs at least one field\");\n return specs;\n};\nconst waitForValues = async (fields, options = {}) => {\n const specs = valueWaitSpecs(fields, \"waitForValues\");\n const settle = options.stableMs ?? waitLimits.settle;\n return valueWaitLoop(\"waitForValues\", options, async () => {\n const state = valueWaitState(specs, await valueWaitRead(specs));\n return {\n ready: state.complete,\n settleMs: settle,\n filled: state.filled,\n snapshot: JSON.stringify(state.values),\n reason: state.absent && state.problems.every((problem) => problem.endsWith(\" missing\")) ? \"page_mismatch\" : \"values_loading\",\n problems: state.problems.join(\"; \"),\n summary: (elapsed, looks) => Object.keys(specs).length + \" values filled and holding after \" + elapsed + \" ms (\" + looks + \" looks)\",\n result: { values: state.values },\n };\n }, waitLimits.lateFillCap);\n};\nconst waitForChange = async (fields, options = {}) => {\n const specs = valueWaitSpecs(fields, \"waitForChange\");\n if (options.before === undefined && options.action === undefined)\n throw new TypeError(\"waitForChange needs before (the values from before the choice) or action (the choice itself)\");\n let before = options.before;\n if (before !== undefined && (before === null || typeof before !== \"object\" || Array.isArray(before) ||\n Object.keys(before).sort().join() !== Object.keys(specs).sort().join()))\n throw new TypeError(\"waitForChange's before must be the values object an earlier wait returned, with the same field names\");\n const settle = options.stableMs ?? waitLimits.settle;\n const unchangedMs = options.unchangedMs ?? waitLimits.unchanged;\n const noProgressMs = options.noProgressMs ?? waitLimits.answer;\n return valueWaitLoop(\"waitForChange\", {\n ...options,\n prepare: async () => {\n if (before === undefined) before = valueWaitState(specs, await valueWaitRead(specs)).values;\n },\n }, async (progress) => {\n const state = valueWaitState(specs, await valueWaitRead(specs));\n const changed = JSON.stringify(state.values) !== JSON.stringify(before);\n // The same values count once nothing has shown progress for unchangedMs: a loading sign or\n // request that came after the choice must first go.\n return {\n ready: () => state.complete && (changed || progress.quietMs() >= Math.min(unchangedMs, noProgressMs)),\n settleMs: changed ? settle : 0,\n filled: state.filled,\n snapshot: JSON.stringify(state.values),\n reason: state.absent && state.problems.every((problem) => problem.endsWith(\" missing\")) ? \"change_unknown\" : \"values_loading\",\n problems: state.problems.length > 0 ? state.problems.join(\"; \") : changed ? \"values changed but not yet holding\" : \"values unchanged\",\n summary: (elapsed, looks) =>\n (changed ? \"values changed\" : \"values confirmed unchanged after \" + unchangedMs + \" ms without progress\") +\n \", after \" + elapsed + \" ms (\" + looks + \" looks)\",\n result: { values: state.values, changed },\n };\n }, waitLimits.answerCap);\n};\n`;\n/**\n * Page code for a Kernel call body, where `page` is in scope: paste it once at the top of the code\n * string, then wait with your verified Playwright locators. It declares the waits below, which share\n * one set of limits (`waitLimits`, from `timeoutDefaults`) and one progress budget, and\n * `waitReport()`.\n *\n * Every wait returns as soon as its condition holds: a ready page costs `waitForOutcome` one look,\n * and the value waits two looks `settle` (0.5 s) apart. While it waits it watches the page's\n * progress: the site's own loading sign passed as `loading`, for as long as it shows; a generic\n * sign (a busy region, an indeterminate progress bar, a skeleton, shimmer, spinner or loader class,\n * within `region` when named) only while it is new, so a decoration holds a wait for at most one\n * no-progress window, and one there before the action not at all (`waitForOutcome` counts one\n * its action brought for as long as it shows, and a countdown ticking that was not there before\n * the action, such as a review step that submits on its own at zero); DOM changes\n * inside the `region` you name; one of the site's own document or API requests in flight (beacons,\n * polls and long-open requests aside; pass the context's `siteDomain` to say which hosts are the\n * site's); the URL changing; and the wait's own reads filling or changing. It keeps waiting while progress\n * continues, up to `timeout`, and fails once nothing has progressed for `noProgressMs` (default\n * `answer`, 8 s). A failure is an `Error` with a `reason`, and a message that names the reason, what\n * each outcome or field showed (counts and states, never page text), which progress signs it saw\n * and when progress stopped. `waitReport()` returns one record per wait this call ran, each with a\n * `summary` sentence: return it from a probe to see how each wait ended.\n *\n * `waitForOutcome(outcomes, { action, pending, loading, region, siteDomain, noProgressMs, timeout,\n * unchangedMs }?)` waits for whichever of the page's possible answers appears, after a step whose\n * answer can vary, such as a search, a filter, a date pick or a submit, and returns its key.\n * `outcomes` names one locator per answer, highest priority first, such as `{ refused, failed,\n * unavailable, empty, results }`: when several show at once, the first listed wins, so list a\n * refusal, the site's error or a greyed-out choice before an empty state, and an empty state before\n * results. Each locator names one element, such as the results list rather than its rows. It only\n * observes: about every 100 ms it counts each locator's matches and its visible ones, and never\n * clicks, types or navigates itself. It answers at the first look that shows an outcome.\n * `timeout` (default `answerCap`, 30 s) is the hard cap, reached only while the page keeps\n * progressing. `action` is the step itself, such as `() => apply.click()`, which it runs exactly\n * once, after noting what each outcome showed: a match that was visible before it, with the same\n * text, counts only once it has stayed so for `unchangedMs` (default 2000) and no request the\n * action started is still in flight, or was as the look began. Such a request holds it back for\n * at most `lateFillCap` (15 s), and never past `timeout` less `unchangedMs`, so the match still\n * counts before the timeout.\n * `timeout`, `noProgressMs` and `unchangedMs` start once the action returns; `deadline`, a\n * `Date.now()` time such as the call's own, ends the wait by then however long the action took.\n * `pending` names the outcomes, one key or a list, that are the site's in-between answers to the\n * action, such as a save it is still processing, each one the page shows (never a response, dialog\n * or popup), and counting only once new or changed since the action. One never decides while it\n * shows: from the first look that shows one, the wait holds for a final outcome for `pending` (60 s) past it, or past\n * `timeout` when that ends later, never past `deadline` nor later than 5 s before the call's own\n * end. A final outcome wins at once. One still showing when the hold ends is the answer, with\n * `pending: true` on the result. Its\n * `OutcomeWaitFailure` has `observations` (`OutcomeObservation` by key) and one of these reasons:\n *\n * - `outcome_ambiguous`, when the winning outcome's locator matches more than one element; its\n * `outcome` is that key. Scope the locator, for example with `.filter({ visible: true })`.\n * - `outcome_unknown`, when no outcome shows and the page made no progress for `noProgressMs`: a\n * challenge, the site's error or a layout the code does not handle, never slowness.\n * - `outcome_timeout`, when the page was still progressing at `timeout`.\n *\n * An outcome may also be an object naming one declared kind, raced beside the locators in the same\n * listed order, so a site that answers in a way the code did not expect still ends the wait:\n *\n * - `{ gone: locator, stableMs? }`: the element, visible before the action (or at a look), has\n * had no visible match for `stableMs` (default 300), such as a form or a modal closing. A form\n * redrawn in place within that time is not gone.\n * - `{ invalid: locator }`: a control inside it is marked invalid (`aria-invalid=\"true\"`, the\n * `is-invalid` class, or the browser's own check after a submit). Fields flagged before the\n * action, and unchanged, follow the same `unchangedMs` rule as a locator.\n * - `{ url }`: the page's URL matches a string (the whole URL, its path, or path and query), a\n * RegExp or a function of the `URL`. After an `action` it counts only once the page navigated,\n * by a document load or a route change, so an edit page whose URL already matched waits.\n * - `{ response }`: a response arrived, from before the action, that a function of the Playwright\n * `Response` accepts, or that matches `{ method, url, status, navigation }` (`status` a number,\n * `[low, high]` or a function). It races the page's answers, so a request the site batches,\n * caches or renames never hangs the wait: name one only for a write's commit request.\n * - `{ dialog: true | type | [types] }`: a native dialog opened, even one the action's own click\n * raised. Page scripts stop while it is open, so it decides at once, in the listed order: a\n * response or popup outcome listed before it that already matched still wins, else the dialog\n * does. Once a dialog opened, every other response, dialog or popup outcome that matched is on\n * the result too, such as `result.response`, and the summary says it also matched: prefer\n * checking a response before reading a dialog as a refusal. The wait never accepts or dismisses\n * it: a dialog that opened while it listened is on the result's or failure's `dialog`, whichever\n * won, and the result's summary names it. Until it is handled, reads of the page or of a\n * response's body wait, so prefer handing a dialog on `result.dialog` over before any other\n * read. A dialog of a type no outcome names fails as `outcome_unknown` only when no response or\n * popup outcome has already matched; otherwise that outcome wins with the dialog still open on\n * `result.dialog`. An action still waiting to click when a dialog opens clicks once the dialog\n * is handled, so handle it before ending the call.\n * - `{ popup: true | (page) => boolean }`: the page opened a new tab or window.\n * - `{ announced: string | RegExp }`: a live region (`aria-live`, or the role `alert`, `status`,\n * `log` or `alertdialog`) announced matching text after the action, as a screen reader hears\n * it. A toast that comes and goes between two looks still counts.\n * - `{ check: async () => value }`: a condition of your own, true once it returns a truthy value.\n * It has no stale rule: one already true before the action wins at the first look.\n *\n * `waitForOutcomeResult(outcomes, options?)` is the same wait returning `OutcomeResult`: the\n * winning `outcome` and its `kind`, `afterMs`, `looks`, the `observations`, and `evidence` of what\n * showed it (a locator's visible text, the invalid fields' labels and messages, the URL reached,\n * the response's method, URL and status, the dialog's type and message). The winning Playwright\n * `response`, `dialog` or popup `page` is on the result too, kept off its JSON. Every listener\n * the losing outcomes used is removed before it returns or throws.\n *\n * `waitForRows(rows, fields, { count, key, ...options })` waits until the first `count` identified\n * rows have every field filled and read the same on two looks `stableMs` apart (default `settle`,\n * 0.5 s), and returns `{ rows: [{ key, ...fields }], more }`. `rows` is a locator for every row;\n * `key` and each field are a CSS selector inside the row, or `{ selector, attribute, optional,\n * placeholder }` (no selector reads the row itself), read from its first visible match; a needed\n * text field whose matches are all hidden is reported `hidden`. A row without a key is a\n * placeholder slot and is skipped. When fewer identified rows than `count` exist, it returns them\n * once their count and values held for `unchangedMs`, no loading sign beside the rows still counts,\n * no request the action started is in flight, and no other site request started under 4 s ago is;\n * no identified row at all\n * is never an answer, so decide an empty list with `waitForOutcome` first. Options also take\n * `action` (run once first, such as a \"load more\" click), `loading`, `region`, `siteDomain`,\n * `noProgressMs` and `timeout` (default `lateFillCap`, 15 s).\n *\n * `waitForValues(fields, options?)` waits until each named field (a Playwright locator, or\n * `{ locator, attribute, all, optional, placeholder }`) is filled in and the values read the same\n * on two looks, and returns `{ values }`. `all` reads every visible match as a list.\n *\n * `waitForChange(fields, { before, action, ...options })` waits, after a choice, for the values\n * that depend on it: it returns `{ values, changed }` once they differ from `before` (or from what\n * they were before `action` ran) and hold, or once they stayed the same for `unchangedMs` with no\n * progress sign showing, so a loading sign or request the choice started must first go.\n *\n * `waitForReady(control, { overlays, expand, dismiss, pending, until, editable, stableMs,\n * dismissLimit, watch, deadline, ...options })` waits before an action until the control's one visible\n * match is attached, visible, enabled (and not read-only when `editable`), not busy (no\n * `aria-busy` around it, no spinner inside it), in the same place on two looks, and what a click\n * at its centre would hit is the control itself, not an overlay. It also waits while an `overlays`\n * locator shows, while `pending` (a function run in the page, such as\n * `() => window.jQuery?.active ?? 0`) returns a truthy count, and until `until()` is true. Once\n * anything held it back, ready must hold for `stableMs` (default `settle`), so a spinner that\n * flickers off between two requests does not count as gone. `expand` names the toggle of the\n * control's section: it clicks it once while the control is hidden and the toggle says the\n * section is collapsed (`aria-expanded` false, or the summary of a closed `details`), so it never\n * closes an open one. `dismiss`\n * names the close or skip controls of panels that open on their own, such as a tour, a what's-new\n * dialog or a cookie banner: it clicks one that shows, up to `dismissLimit` (5) times, and once\n * ready keeps a Playwright locator handler on each, so one that opens later is closed before the\n * next action, until `result.release()` or `dismissLimit` uses (`watch: false` skips it). It\n * returns `ReadyResult`, and fails as a `ReadyWaitFailure` with `blockers` and a message naming\n * what held it back last: `not_ready` once nothing progressed for `noProgressMs`, `ready_timeout`\n * at `timeout` (default `answerCap`), `ready_ambiguous` when more than one visible element\n * matches.\n *\n * A value is still loading, never absent, while it is empty, reads as a loading word or only dots,\n * matches the field's `placeholder` pattern, or sits in an `aria-busy`, skeleton or shimmer\n * element. An `optional` field may be absent and is then `null`; a needed one may not. A value\n * still loading when progress stops fails with `values_loading`, whether optional or not; a needed\n * one missing then, when only missing ones held the wait back, with `page_mismatch`;\n * `change_unknown` when waitForChange's fields are missing; `values_timeout` at the cap. Each is a\n * `ValueWaitFailure`.\n */\nexport const waitCode = `${progressCode}${outcomeKindsCode}${outcomeCode}${valueCode}${readyWaitCode}`;\n/**\n * `waitForOutcome` alone, for code written against the first release of it: it declares only the\n * names that release declared (`waitForOutcome`, `outcomeWaitFailure`, `outcomeWaitNote`,\n * `outcomeWaitChanged` and `outcomeWaitObserve`), keeping every other helper inside, so code that\n * pastes it beside helpers of its own still parses. New code pastes `waitCode` instead; never both.\n */\nexport const outcomeOnlyWaitCode = `\nconst { outcomeWaitFailure, outcomeWaitNote, outcomeWaitChanged, outcomeWaitObserve, waitForOutcome } = (() => {\n${progressCode}${outcomeKindsCode}${outcomeCode}\nreturn { outcomeWaitFailure, outcomeWaitNote, outcomeWaitChanged, outcomeWaitObserve, waitForOutcome };\n})();\n`;\n/**\n * `confirmCommit(outcome, page)`, pasted after `waitCode` in a write's commit call, just before the\n * click's wait. It declares that one name, its helpers inside, so code that pastes `waitCode`\n * beside a `confirmCommit` of its own still parses. It uses `page`, and `waitCode`'s `waitLimits`,\n * `waitBounded`, `waitSleep`, `outcomeWaitClean` and `outcomeWaitInvalidInPage`. Pasting it notes\n * the page's address, how many messages show each text, and its flagged fields as they stand.\n * After, as many messages with a text as showed it then are stale, whatever element or page shows\n * them, so a page that draws its messages again, or a redirect to a page with the same banner,\n * adds no error, while one more message with an old text is new.\n *\n * It judges the commit from the `{ response }` answer of the click's `waitForOutcomeResult` and\n * the page, and returns `CommitConfirmation`, plain data a call can return. It never marks a write\n * done or not done without proof: whatever the response and the page leave open is `unclear`.\n *\n * - A 4xx response, or one below 200, is `not_done`; a 5xx is `unclear`, since a server can fail\n * after it saved; a 201 with a Location is `done` at once. A 3xx whose Location is the page that\n * posted (same path), or whose query names an error or failure, is `unclear` unless the page\n * shows an error.\n * - A 2xx body that reads as JSON is `not_done` for a success field (`success`, `succeeded`,\n * `isSuccess`, any case) that is false, `\"false\"`, 0 or `\"no\"` or holds an error word, `ok:\n * false`, an error field holding an error (not empty, and not a word for none such as \"No\n * error\"), a status of 400 or more, or an error word in a status or message. An error field is\n * any named for errors up to two levels down, and `error`, `errors` or `userErrors` up to four;\n * true counts only under `error`, `errors` or `hasError(s)`, and a setting such as\n * `notifyOnError` is never one. It is `unclear` for a success field holding anything but true,\n * `\"true\"`, 1, `\"yes\"`, `\"ok\"` or `\"success\"`, or a status or message that refuses a value\n * (\"required\", \"unable\", \"could not\") or says declined, rejected or denied, words a write may\n * itself have meant. A string holding JSON, as in `{ d: \"...\" }`, is read too. A body that is\n * neither JSON nor HTML, or can't be read within 1 s, is `unclear`; a 3xx's or an empty one is no\n * body.\n * - The page then gets the settle window (`settle`, 0.5 s). A field newly marked invalid, or a\n * message whose text is new with words of an error or a refusal, is `not_done`, whatever the\n * body's message said. A message is an alert, an assertive live region or anything styled as an\n * error, with letters, outside links, buttons and labels, and not one only a screen reader hears.\n * A new message styled as an error with no such words, one that mixes them with a success, one\n * that says declined, rejected or denied, an alert that says neither error nor success, or a\n * field still marked invalid as before, is `unclear`.\n * - Otherwise the commit is `done`: `queued` for a 202, or a body whose status says queued, pending\n * or processing, with that word as `status_label`, else `completed`. An outcome with no response\n * is `not_done` when the page shows a new error, else `unclear`, except a `pending` answer still\n * showing when its wait ended: that is `done` and `pending`, with its text as `status_label`,\n * unless the page shows a new message other than an alert. A native dialog that opened\n * during the wait and says the write failed is `not_done`, unless the response is a 5xx or\n * proves a record (a 201 with a Location): that is `unclear`, naming both. While one stays open\n * the page can't be read, which is `unclear`.\n *\n * It never clicks, and it reads the body for at most 1 s and the page for at most about 2 s.\n */\nexport const confirmCommitCode = String.raw `\nconst confirmCommit = await (async () => {\n // Words that say a write failed; \"no errors\" says none. Words that refuse a value prove nothing\n // on their own, nor do words a write may itself have meant, as declining or rejecting something.\n const errorWords = /\\b(?:errors?|fail(?:s|ed|ure)?|invalid|forbidden|unauthori[sz]ed)\\b/i;\n const noErrors = /\\b(?:no|without|zero|0)\\s+errors?\\b/i;\n const refusalWords = /\\b(?:required|must|cannot|can't|could not|couldn't|unable|not valid|please (?:enter|select|choose|provide|fill|complete|correct|try again))\\b/i;\n const openWords = /\\b(?:declined|rejected|denied)\\b/i;\n const successWords = /\\b(?:success(?:ful|fully)?|saved|created|updated|submitted|completed|confirmed|thank you)\\b/i;\n const queuedWords = /\\b(?:queued|enqueued|pending|processing|in progress)\\b/i;\n const words = (value) => String(value).replace(/[_-]+/g, \" \");\n const saysError = (value) => typeof value === \"string\" && errorWords.test(words(value)) && !noErrors.test(words(value));\n const saysRefusal = (value) => typeof value === \"string\" && refusalWords.test(words(value));\n const clip = (value) => outcomeWaitClean(typeof value === \"string\" ? value : JSON.stringify(value), 160);\n const list = (texts) => texts.slice(0, 3).map((text) => '\"' + clip(text) + '\"').join(\", \");\n // A success field's value: true, false, or anything else, which leaves it unclear.\n const truth = (value) => {\n const text = typeof value === \"string\" ? value.trim().toLowerCase() : value;\n if (text === true || text === 1 || [\"true\", \"1\", \"yes\", \"ok\", \"success\"].includes(text)) return true;\n if (text === false || text === 0 || [\"false\", \"0\", \"no\"].includes(text) || saysError(value)) return false;\n return undefined;\n };\n // Whether an error field holds an error: not empty, zero, false or a word for none, at any depth.\n const filled = (value, depth = 0) => {\n if (value === null || value === undefined || value === false || value === 0) return false;\n if (typeof value === \"string\")\n return !/^\\s*(?:0+|none|null|false|ok|success|n\\/a|no errors?(?: found)?)?\\s*\\.?\\s*$/i.test(value);\n if (typeof value !== \"object\" || depth > 3) return true;\n return (Array.isArray(value) ? value : Object.values(value)).some((each) => filled(each, depth + 1));\n };\n // Whether a field is an error field: up to two levels down, any named for errors, as in\n // { data: { save: { errors } } }; deeper, only error, errors and userErrors. A setting for what\n // to do on an error, such as notifyOnError, never is.\n const errorField = (name, depth) =>\n !/onerrors?$/.test(name) &&\n (depth <= 2 ? /errors?$|^error(?:message|msg|text|code)s?$/.test(name) : [\"error\", \"errors\", \"usererrors\"].includes(name));\n // Whether an error field holds an error; true does only under error, errors or hasError(s).\n const holdsError = (name, field) =>\n field === true ? [\"error\", \"errors\", \"haserror\", \"haserrors\"].includes(name) : filled(field);\n // What a JSON body says: the first sign the write failed, the first that leaves it unclear, and\n // the site's word for queued work. Error fields count up to four levels down (see errorField),\n // as in { data: { records: { save: { userErrors } } } }; success and ok fields up to two;\n // status and message words up to one. A string that holds JSON, as some frameworks wrap a body\n // in { d: \"...\" }, is read as one more level. It looks at 2,000 values at most.\n const judgeBody = (body) => {\n const found = {};\n let budget = 2000;\n const visit = (value, depth) => {\n if (depth > 4 || value === null || typeof value !== \"object\" || (budget -= 1) < 0) return;\n if (Array.isArray(value)) {\n for (const each of value.slice(0, 50)) visit(each, depth + 1);\n return;\n }\n for (const [key, field] of Object.entries(value)) {\n const name = key.toLowerCase().replace(/[_-]/g, \"\");\n const said = key + \" is \" + clip(field);\n if (depth <= 2 && /^(?:is)?succe(?:ss|ssful|eded)$/.test(name)) {\n const holds = truth(field);\n if (holds === false) found.failed ??= said;\n else if (holds === undefined) found.unclear ??= said + \", not true\";\n } else if (depth <= 2 && name === \"ok\" && field === false) found.failed ??= said;\n else if (errorField(name, depth)) {\n if (holdsError(name, field)) found.failed ??= said;\n } else if (depth <= 1 && (name === \"status\" || name === \"statuscode\") && typeof field === \"number\" && field >= 400)\n found.failed ??= said;\n else if (depth <= 1 && /^(?:status|state|result|outcome|message|msg|statusmessage|detail)$/.test(name) && typeof field === \"string\") {\n if (saysError(field)) found.failed ??= said;\n else if (saysRefusal(field) || openWords.test(field)) found.unclear ??= said;\n else if ((name === \"status\" || name === \"state\") && queuedWords.test(words(field)))\n found.queued ??= outcomeWaitClean(field, 100);\n }\n if (typeof field === \"string\" && depth <= 1 && /^\\s*[[{]/.test(field)) {\n try {\n visit(JSON.parse(field), depth + 1);\n } catch {}\n } else visit(field, depth + 1);\n }\n };\n visit(body, 0);\n return found;\n };\n // The body: JSON, HTML, none (empty, or a redirect's, which can't be read), or unclear when it\n // is something else or can't be read within 1 s.\n const readBody = async (response, status) => {\n const text = await waitBounded(Promise.resolve().then(() => response.text()).catch(() => null), 1000);\n if (text === undefined) return { unclear: \"its body could not be read within 1 s\" };\n if (text === null) return status >= 300 ? {} : { unclear: \"its body could not be read\" };\n if (text.trim() === \"\") return {};\n try {\n return { json: JSON.parse(text) };\n } catch {}\n const type = String(response.headers()[\"content-type\"] ?? \"\").toLowerCase();\n if (type.includes(\"html\") || /^\\s*(?:<!doctype html|<html[\\s>])/i.test(text)) return { html: true };\n return { unclear: \"its body is neither JSON nor HTML\" + (type === \"\" ? \"\" : \" (\" + clip(type) + \")\") };\n };\n // Elements that may hold the site's message: alerts, assertive live regions, and anything styled\n // as an error.\n const messages =\n '[role=\"alert\"], [role=\"alertdialog\"], [aria-live=\"assertive\"], [class*=\"error\" i], [class*=\"danger\" i], [class*=\"invalid\" i]';\n // Runs in the page: each visible message with letters, outside links, buttons and labels and\n // wider than a pixel, its text (500 characters at most), what its styling says (its own or up\n // to two elements around it), and whether it is an alert.\n const messagesInPage = (elements) => {\n const shows = (element) =>\n typeof element.checkVisibility === \"function\"\n ? element.checkVisibility({ visibilityProperty: true, opacityProperty: true })\n : element.getClientRects().length > 0;\n const styling = (element) => {\n const parts = [];\n for (let node = element, depth = 0; node instanceof Element && depth < 3; node = node.parentElement, depth += 1)\n for (const name of [\"class\", \"data-type\", \"data-status\", \"data-variant\", \"data-severity\"]) parts.push(node.getAttribute(name) ?? \"\");\n return parts.join(\" \");\n };\n return elements.flatMap((element) => {\n if (element.closest('a, button, label, summary, input, select, textarea, option, [role=\"button\"], [role=\"link\"]') || !shows(element))\n return [];\n const box = element.getBoundingClientRect();\n if (box.width <= 1 || box.height <= 1) return [];\n const text = String(element.innerText ?? \"\").replace(/\\s+/g, \" \").trim().slice(0, 500);\n if (!/\\p{L}/u.test(text)) return [];\n const style = styling(element);\n return [{\n text,\n errorStyle: /error|danger|invalid|fail/i.test(style),\n successStyle: /success/i.test(style),\n alert: element.matches('[role=\"alert\"], [role=\"alertdialog\"], [aria-live=\"assertive\"]'),\n }];\n });\n };\n const neutralAlert = \" (an alert that says neither error nor success)\";\n const fieldKey = (field) => field.field + \"\\u0000\" + field.message;\n const fieldText = (field) => field.field + (field.message === \"\" ? \" is marked invalid\" : \": \" + field.message);\n // Notes the page as it stands now, before the click: its address, how many messages show each\n // text, and its flagged fields. After, as many messages with a text as showed it then are stale,\n // whatever element or page shows them, as a page that draws its messages again or a redirect to\n // a page with the same banner; one more with that text is new.\n const read = (promise) => waitBounded(promise.catch(() => undefined), 1000);\n const postedFrom = page.url();\n const shownBefore = await read(page.locator(messages).evaluateAll(messagesInPage));\n const staleCounts = new Map();\n for (const message of shownBefore ?? []) {\n const text = message.text.toLowerCase();\n staleCounts.set(text, (staleCounts.get(text) ?? 0) + 1);\n }\n const flaggedBefore = await read(page.locator(\"body\").evaluateAll(outcomeWaitInvalidInPage));\n const staleFields = new Set((flaggedBefore ?? []).map(fieldKey));\n // One look at the page: the new errors it shows, and what it shows that leaves the write open.\n const look = async (page) => {\n const fields = await page.locator(\"body\").evaluateAll(outcomeWaitInvalidInPage);\n const shown = await page.locator(messages).evaluateAll(messagesInPage);\n const errors = fields.filter((field) => !staleFields.has(fieldKey(field))).map(fieldText);\n const open = fields.filter((field) => staleFields.has(fieldKey(field))).map((field) => fieldText(field) + \", as before the click\");\n const counted = new Map();\n for (const message of shown) {\n const text = message.text.toLowerCase();\n counted.set(text, (counted.get(text) ?? 0) + 1);\n if (counted.get(text) <= (staleCounts.get(text) ?? 0)) continue;\n const refuses = saysError(message.text) || saysRefusal(message.text);\n const succeeds = message.successStyle || successWords.test(message.text);\n if (refuses && !succeeds) errors.push(message.text);\n else if (refuses) open.push(message.text + \" (a success beside a refusal)\");\n else if (openWords.test(message.text)) open.push(message.text);\n else if (message.errorStyle && !message.successStyle) open.push(message.text + \" (styled as an error, with no words of one)\");\n else if (message.alert && !succeeds) open.push(message.text + neutralAlert);\n }\n return { errors: [...new Set(errors)], open: [...new Set(open)] };\n };\n // Looks for the settle window, so an error the page draws just after the response counts, and\n // returns at the first look that shows one. Undefined when no look could read the page.\n const watch = async (page) => {\n const begun = Date.now();\n const capMs = 2000;\n let seen;\n while (true) {\n const each = await waitBounded(look(page).catch(() => undefined), Math.max(0, begun + capMs - Date.now()));\n if (each !== undefined) {\n seen = each;\n if (each.errors.length > 0) return each;\n }\n const elapsed = Date.now() - begun;\n if ((seen !== undefined && elapsed >= waitLimits.settle) || elapsed >= capMs) return seen;\n await waitSleep(100);\n }\n };\n // A redirect gives no body, so one back to the page that posted, or to an address whose query\n // names an error or failure, may carry a refusal the page check can't see: why, or undefined.\n const redirectedBack = (response) => {\n const location = String(response.headers()[\"location\"] ?? \"\").trim();\n if (location === \"\") return undefined;\n try {\n const to = new URL(location, response.url());\n const from = new URL(postedFrom);\n let query = to.search + to.hash;\n try {\n query = decodeURIComponent(query);\n } catch {}\n if (/error|fail/i.test(query)) return \"it redirected to \" + clip(location) + \", whose query names an error\";\n if (to.origin === from.origin && to.pathname === from.pathname)\n return \"it redirected back to the page that posted, \" + clip(to.pathname);\n } catch {}\n return undefined;\n };\n return async (outcome, page) => {\n const done = (reason, queued, label) => ({\n state: \"done\",\n status: queued ? \"queued\" : \"completed\",\n ...(label === undefined ? {} : { status_label: label }),\n reason,\n });\n const notDone = (reason) => ({ state: \"not_done\", status: \"failed\", reason });\n const unclear = (reason) => ({ state: \"unclear\", status: \"unconfirmed\", reason });\n // A native dialog that opened during the wait and says the write failed is the page's answer,\n // unless the response is a server error or proves a record (below). While one stays open the\n // page can't be read, and the look below finds it unclear.\n const dialog = outcome?.dialog;\n const dialogFailed =\n dialog !== undefined && dialog !== null && saysError(dialog.message())\n ? \"a native \" + dialog.type() + ' dialog said \"' + clip(dialog.message()) + '\"'\n : undefined;\n const response = outcome?.response;\n if (response === undefined || response === null) {\n if (dialogFailed !== undefined) return notDone(dialogFailed);\n const seen = await watch(page);\n const answered = outcome?.outcome === undefined ? \"\" : '; \"' + outcome.outcome + '\" answered the wait';\n if (seen !== undefined && seen.errors.length > 0)\n return notDone(\"no commit response\" + answered + \"; the page shows \" + list(seen.errors));\n // A pending answer still showing when its wait ended is the site's own word that it took the\n // write and is still working on it, unless the page shows more than an alert beside it.\n if (outcome?.pending === true && seen !== undefined && seen.open.every((text) => text.endsWith(neutralAlert))) {\n const text = outcome.evidence?.text;\n return {\n state: \"done\",\n status: \"pending\",\n ...(typeof text === \"string\" && text !== \"\" ? { status_label: outcomeWaitClean(text, 100) } : {}),\n reason: '\"' + outcome.outcome + '\" was still pending when the wait ended, with no error on the page',\n };\n }\n return unclear(\"no commit response to confirm\" + answered);\n }\n const status = response.status();\n const where = response.request().method() + \" \" + new URL(response.url()).pathname + \" answered \" + status;\n // A server can fail after it saved, so a 5xx never proves the write did not go through.\n if (status >= 500)\n return unclear(where + \", a server error, which can come after a save\" + (dialogFailed === undefined ? \"\" : \"; \" + dialogFailed));\n const location = String(response.headers()[\"location\"] ?? \"\").trim();\n // A 201 with a Location names the record the commit created, so a dialog's words alone can't\n // make it not done.\n const created = status === 201 && location !== \"\" ? where + \" with Location \" + clip(location) : undefined;\n if (created !== undefined && dialogFailed !== undefined) return unclear(created + \", which proves a record, but \" + dialogFailed);\n if (dialogFailed !== undefined) return notDone(dialogFailed);\n if (status < 200 || status >= 400) return notDone(where);\n if (created !== undefined) return done(created, false);\n const body = await readBody(response, status);\n const found = body.json === undefined ? {} : judgeBody(body.json);\n if (found.failed !== undefined) return notDone(where + \"; its body's \" + found.failed);\n const seen = await watch(page);\n if (seen !== undefined && seen.errors.length > 0) return notDone(where + \"; the page shows \" + list(seen.errors));\n const back = status >= 300 ? redirectedBack(response) : undefined;\n if (back !== undefined) return unclear(where + \"; \" + back);\n if (body.unclear !== undefined) return unclear(where + \"; \" + body.unclear);\n if (found.unclear !== undefined) return unclear(where + \"; its body's \" + found.unclear);\n if (seen === undefined) return unclear(where + \"; the page could not be read after it\");\n if (seen.open.length > 0) return unclear(where + \"; the page shows \" + list(seen.open));\n return done(\n where + (body.json === undefined ? \"\" : \"; its body shows no error\") + \"; the page shows no error\",\n status === 202 || found.queued !== undefined,\n found.queued,\n );\n };\n})();\n`;\n"
|
|
93
93
|
},
|
|
94
94
|
{
|
|
95
95
|
"path": "runtime/list-page.js",
|
|
@@ -137,7 +137,7 @@
|
|
|
137
137
|
},
|
|
138
138
|
{
|
|
139
139
|
"path": "runtime/browser-action-timeout.js",
|
|
140
|
-
"text": "/** A completed provider call whose native browser action timed out, not a lost execution. */\nexport class BrowserActionTimeout extends Error {\n _tag = \"BrowserActionTimeout\";\n dispatch;\n constructor(failure) {\n super(failure.message, { cause: failure });\n this.name = \"BrowserActionTimeout\";\n this.dispatch = failure.dispatch;\n }\n}\n/**\n * Only Kernel's failed response establishes a settled timeout: a native action's, or one of the\n * runtime's page waits that ended without its answer: no outcome, values still loading
|
|
140
|
+
"text": "/** A completed provider call whose native browser action timed out, not a lost execution. */\nexport class BrowserActionTimeout extends Error {\n _tag = \"BrowserActionTimeout\";\n dispatch;\n constructor(failure) {\n super(failure.message, { cause: failure });\n this.name = \"BrowserActionTimeout\";\n this.dispatch = failure.dispatch;\n }\n}\n/**\n * Only Kernel's failed response establishes a settled timeout: a native action's, or one of the\n * runtime's page waits that ended without its answer: no outcome, values still loading or a needed\n * one missing, or a control not ready to act on, within its cap or once the page stopped progressing.\n */\nexport const nativeActionTimeout = (answer) => answer.success === false &&\n typeof answer.error === \"string\" &&\n (/^(?:TimeoutError:\\s*)?(?:locator|page|frame)\\.[A-Za-z]+: Timeout \\d+ms exceeded\\b/u.test(answer.error) ||\n /^(?:(?:OutcomeWait|ValueWait|ReadyWait)Failure:\\s*)?(?:outcome_(?:timeout|unknown)|values_(?:loading|timeout)|page_mismatch|change_unknown|not_ready|ready_timeout) after \\d+ ms\\b/u.test(answer.error))\n ? answer.error\n : undefined;\n"
|
|
141
141
|
},
|
|
142
142
|
{
|
|
143
143
|
"path": "runtime/dialogs.js",
|
|
@@ -866,8 +866,9 @@ Prefer the wait helpers' own settling over loops of your own that poll until val
|
|
|
866
866
|
the same on two looks.
|
|
867
867
|
`waitForChange(fields, { before, action, loading })` returns `{ values, changed }` after a choice:
|
|
868
868
|
changed, or the same with no progress sign for `unchangedMs`. They throw a `ValueWaitFailure`:
|
|
869
|
-
`values_loading` when a value is still loading as progress stops, `
|
|
870
|
-
|
|
869
|
+
`values_loading` when a value is still loading as progress stops, `page_mismatch` when a needed
|
|
870
|
+
field is missing then, `change_unknown` when the fields are missing, `values_timeout` at the
|
|
871
|
+
cap. A host may retry a read once after
|
|
871
872
|
`outcome_timeout`, `outcome_unknown`, `values_loading`, `values_timeout` or `change_unknown`,
|
|
872
873
|
so let them throw. `waitReport()` returns a one-line summary of how each wait in the call ended.
|
|
873
874
|
A field is a Playwright locator, or `{ locator, attribute, optional, all }`, where `all` reads
|
|
@@ -90,9 +90,10 @@ the source files, never captures.
|
|
|
90
90
|
**Identify the site and login prerequisites before dependent work.**
|
|
91
91
|
|
|
92
92
|
Judge completion against the user's requested end state. An intermediate website state is
|
|
93
|
-
neither proof of completion nor, by itself, a reason to abandon the task.
|
|
94
|
-
|
|
95
|
-
|
|
93
|
+
neither proof of completion nor, by itself, a reason to abandon the task. When the site answers
|
|
94
|
+
with an in-between state, wait for its final answer; one still showing after that wait is
|
|
95
|
+
pending, not completed. Continue through the remaining authorized steps when their prerequisites
|
|
96
|
+
are satisfied. Verify that the resulting state matches the request before reporting success.
|
|
96
97
|
|
|
97
98
|
Return `InvalidInput` when authoritative evidence establishes that the supplied request cannot
|
|
98
99
|
be fulfilled as specified. Explain the conflicting input, unavailable option, or unmet constraint.
|
|
@@ -328,8 +328,11 @@ too. Run each step with `execute` purpose `act`, target `liveBrowser`.
|
|
|
328
328
|
only what a change since the checks would make wrong, such as the total and items they
|
|
329
329
|
read, and when one moved it returns before clicking and the script throws
|
|
330
330
|
`OperationFailure` naming the change, such as `total_changed`; otherwise it clicks once
|
|
331
|
-
and waits for the confirmation. That guard is expected.
|
|
332
|
-
|
|
331
|
+
and waits for the confirmation. That guard is expected. Name the in-between state the site
|
|
332
|
+
can show after the click, beside its final answers, in that wait's `pending`: it holds up to
|
|
333
|
+
60 s from when that state shows, and `confirmCommit` reports one still showing then as
|
|
334
|
+
`pending`. An entered mark counts as possibly sent even when its call stopped before the
|
|
335
|
+
click, so a check that can refuse placed there
|
|
333
336
|
reports a possible change and sends a write that never happened to maintenance. If the call
|
|
334
337
|
returns an unexpected page or fails while waiting for an assumed review, read back before another submission: the task may already be
|
|
335
338
|
complete. The host cannot see a commit sent as a GET link or over a websocket, so
|
|
@@ -44,6 +44,8 @@ export interface OutcomeKindObservation {
|
|
|
44
44
|
export interface OutcomeResult {
|
|
45
45
|
readonly outcome: string;
|
|
46
46
|
readonly kind: OutcomeKind;
|
|
47
|
+
/** The outcome is one `pending` named, still showing when the wait's hold ended. */
|
|
48
|
+
readonly pending?: true;
|
|
47
49
|
readonly afterMs: number;
|
|
48
50
|
readonly looks: number;
|
|
49
51
|
readonly evidence: OutcomeEvidence;
|
|
@@ -36,11 +36,13 @@ export interface WaitRecord {
|
|
|
36
36
|
* `confirmCommit`'s answer (`confirmCommitCode`): whether the write's final commit went through
|
|
37
37
|
* (`done`), did not (`not_done`) or can't be told from the response and the page (`unclear`); its
|
|
38
38
|
* status in the core notation, `queued` with the site's own word in `status_label` when the site
|
|
39
|
-
* took the work to finish later
|
|
39
|
+
* took the work to finish later, or `pending` with the site's text in `status_label` when the
|
|
40
|
+
* in-between answer its wait named still showed as the wait ended; and a sentence saying what
|
|
41
|
+
* decided it.
|
|
40
42
|
*/
|
|
41
43
|
export interface CommitConfirmation {
|
|
42
44
|
readonly state: "done" | "not_done" | "unclear";
|
|
43
|
-
readonly status: "completed" | "queued" | "failed" | "unconfirmed";
|
|
45
|
+
readonly status: "completed" | "queued" | "pending" | "failed" | "unconfirmed";
|
|
44
46
|
readonly status_label?: string;
|
|
45
47
|
readonly reason: string;
|
|
46
48
|
}
|
|
@@ -67,7 +69,7 @@ export interface CommitConfirmation {
|
|
|
67
69
|
* and when progress stopped. `waitReport()` returns one record per wait this call ran, each with a
|
|
68
70
|
* `summary` sentence: return it from a probe to see how each wait ended.
|
|
69
71
|
*
|
|
70
|
-
* `waitForOutcome(outcomes, { action, loading, region, siteDomain, noProgressMs, timeout,
|
|
72
|
+
* `waitForOutcome(outcomes, { action, pending, loading, region, siteDomain, noProgressMs, timeout,
|
|
71
73
|
* unchangedMs }?)` waits for whichever of the page's possible answers appears, after a step whose
|
|
72
74
|
* answer can vary, such as a search, a filter, a date pick or a submit, and returns its key.
|
|
73
75
|
* `outcomes` names one locator per answer, highest priority first, such as `{ refused, failed,
|
|
@@ -84,7 +86,14 @@ export interface CommitConfirmation {
|
|
|
84
86
|
* at most `lateFillCap` (15 s), and never past `timeout` less `unchangedMs`, so the match still
|
|
85
87
|
* counts before the timeout.
|
|
86
88
|
* `timeout`, `noProgressMs` and `unchangedMs` start once the action returns; `deadline`, a
|
|
87
|
-
* `Date.now()` time such as the call's own, ends the wait by then however long the action took.
|
|
89
|
+
* `Date.now()` time such as the call's own, ends the wait by then however long the action took.
|
|
90
|
+
* `pending` names the outcomes, one key or a list, that are the site's in-between answers to the
|
|
91
|
+
* action, such as a save it is still processing, each one the page shows (never a response, dialog
|
|
92
|
+
* or popup), and counting only once new or changed since the action. One never decides while it
|
|
93
|
+
* shows: from the first look that shows one, the wait holds for a final outcome for `pending` (60 s) past it, or past
|
|
94
|
+
* `timeout` when that ends later, never past `deadline` nor later than 5 s before the call's own
|
|
95
|
+
* end. A final outcome wins at once. One still showing when the hold ends is the answer, with
|
|
96
|
+
* `pending: true` on the result. Its
|
|
88
97
|
* `OutcomeWaitFailure` has `observations` (`OutcomeObservation` by key) and one of these reasons:
|
|
89
98
|
*
|
|
90
99
|
* - `outcome_ambiguous`, when the winning outcome's locator matches more than one element; its
|
|
@@ -183,7 +192,8 @@ export interface CommitConfirmation {
|
|
|
183
192
|
* A value is still loading, never absent, while it is empty, reads as a loading word or only dots,
|
|
184
193
|
* matches the field's `placeholder` pattern, or sits in an `aria-busy`, skeleton or shimmer
|
|
185
194
|
* element. An `optional` field may be absent and is then `null`; a needed one may not. A value
|
|
186
|
-
* still loading when progress stops fails with `values_loading`, whether optional or not;
|
|
195
|
+
* still loading when progress stops fails with `values_loading`, whether optional or not; a needed
|
|
196
|
+
* one missing then, when only missing ones held the wait back, with `page_mismatch`;
|
|
187
197
|
* `change_unknown` when waitForChange's fields are missing; `values_timeout` at the cap. Each is a
|
|
188
198
|
* `ValueWaitFailure`.
|
|
189
199
|
*/
|
|
@@ -234,7 +244,9 @@ export declare const outcomeOnlyWaitCode: string;
|
|
|
234
244
|
* field still marked invalid as before, is `unclear`.
|
|
235
245
|
* - Otherwise the commit is `done`: `queued` for a 202, or a body whose status says queued, pending
|
|
236
246
|
* or processing, with that word as `status_label`, else `completed`. An outcome with no response
|
|
237
|
-
* is `not_done` when the page shows a new error, else `unclear
|
|
247
|
+
* is `not_done` when the page shows a new error, else `unclear`, except a `pending` answer still
|
|
248
|
+
* showing when its wait ended: that is `done` and `pending`, with its text as `status_label`,
|
|
249
|
+
* unless the page shows a new message other than an alert. A native dialog that opened
|
|
238
250
|
* during the wait and says the write failed is `not_done`, unless the response is a 5xx or
|
|
239
251
|
* proves a record (a 201 with a Location): that is `unclear`, naming both. While one stays open
|
|
240
252
|
* the page can't be read, which is `unclear`.
|
|
@@ -42,6 +42,7 @@ const waitLimits = Object.freeze(${JSON.stringify({
|
|
|
42
42
|
settle: timeoutDefaults.settle,
|
|
43
43
|
unchanged: timeoutDefaults.unchanged,
|
|
44
44
|
lateFillCap: timeoutDefaults.lateFillCap,
|
|
45
|
+
pending: timeoutDefaults.pending,
|
|
45
46
|
})});
|
|
46
47
|
const waitRecords = [];
|
|
47
48
|
// Every wait this call ran, oldest first, each with a sentence saying how it ended.
|
|
@@ -490,10 +491,20 @@ const outcomeWaitObserve = async (outcomes, key, state, events) => {
|
|
|
490
491
|
// once the deadline passed.
|
|
491
492
|
const outcomeWaitGraceMs = 1000;
|
|
492
493
|
const outcomeWaitLateMs = 500;
|
|
494
|
+
// What a pending hold leaves of the call, whose end the runtime declares as __pomeradoCallEnds, for
|
|
495
|
+
// the code after the wait, such as confirmCommit's reads.
|
|
496
|
+
const outcomeWaitCallRoomMs = 5000;
|
|
493
497
|
const waitForOutcomeResult = async (outcomes, options = {}) => {
|
|
494
498
|
const names = Object.keys(outcomes ?? {});
|
|
495
499
|
if (names.length === 0) throw new TypeError("waitForOutcome needs at least one outcome");
|
|
496
500
|
const candidates = names.map((name) => outcomeWaitCandidate(name, outcomes[name]));
|
|
501
|
+
const pendingNames = new Set(options.pending === undefined ? [] : [options.pending].flat());
|
|
502
|
+
for (const name of pendingNames) {
|
|
503
|
+
const kind = candidates.find((candidate) => candidate.name === name)?.kind;
|
|
504
|
+
if (kind === undefined) throw new TypeError('waitForOutcome pending "' + name + '" names none of its outcomes');
|
|
505
|
+
if (["response", "dialog", "popup"].includes(kind))
|
|
506
|
+
throw new TypeError('waitForOutcome pending "' + name + '" names a ' + kind + " outcome; pending takes outcomes the page shows");
|
|
507
|
+
}
|
|
497
508
|
const timeout = options.timeout ?? waitLimits.answerCap;
|
|
498
509
|
const noProgressMs = options.noProgressMs ?? waitLimits.answer;
|
|
499
510
|
const progress = waitProgress({ ...options, noProgressMs, whileSending: true });
|
|
@@ -551,10 +562,11 @@ const waitForOutcomeResult = async (outcomes, options = {}) => {
|
|
|
551
562
|
progress.begin();
|
|
552
563
|
begun = Date.now();
|
|
553
564
|
// deadline, a Date.now() time such as the call's own, bounds the wait wherever the action left it.
|
|
554
|
-
|
|
565
|
+
let until = Math.min(begun + timeout, options.deadline ?? Infinity);
|
|
555
566
|
// Past the deadline, every page call shares outcomeWaitLateMs of grace and then ends: the wait
|
|
556
567
|
// never outlasts hardStop, however long the page holds it.
|
|
557
|
-
|
|
568
|
+
let hardStop = until + outcomeWaitLateMs;
|
|
569
|
+
let pendingSince;
|
|
558
570
|
const beforeStop = () => Math.max(0, hardStop - Date.now());
|
|
559
571
|
cleanupMs = () => Math.min(250, beforeStop());
|
|
560
572
|
const unchangedMs = options.unchangedMs ?? waitLimits.unchanged;
|
|
@@ -595,9 +607,11 @@ const waitForOutcomeResult = async (outcomes, options = {}) => {
|
|
|
595
607
|
: Object.fromEntries(candidates.flatMap((each) =>
|
|
596
608
|
evented.includes(each.kind) ? [[each.name, outcomeWaitEventRead(each, events)]]
|
|
597
609
|
: observations[each.name] === undefined ? [] : [[each.name, observations[each.name]]]));
|
|
610
|
+
const pending = pendingNames.has(candidate.name);
|
|
598
611
|
const answer = {
|
|
599
612
|
outcome: candidate.name,
|
|
600
613
|
kind: candidate.kind,
|
|
614
|
+
...(pending ? { pending: true } : {}),
|
|
601
615
|
afterMs: Date.now() - begun,
|
|
602
616
|
looks,
|
|
603
617
|
evidence,
|
|
@@ -613,6 +627,7 @@ const waitForOutcomeResult = async (outcomes, options = {}) => {
|
|
|
613
627
|
finish(
|
|
614
628
|
{ outcome: candidate.name },
|
|
615
629
|
'"' + candidate.name + '"' + (candidate.kind === "locator" ? "" : " (" + candidate.kind + ")") + " showed after " +
|
|
630
|
+
(pending ? pendingSince - begun + " ms and was still pending after " : "") +
|
|
616
631
|
answer.afterMs + " ms (" + looks + (looks === 1 ? " look)" : " looks)") +
|
|
617
632
|
also.map((each) => '; "' + each.name + '" (' + each.kind + ") also matched").join("") +
|
|
618
633
|
(answer.dialog === undefined ? "" : "; a native " + answer.dialog.type() + " dialog is left open on the result's dialog"),
|
|
@@ -646,10 +661,23 @@ const waitForOutcomeResult = async (outcomes, options = {}) => {
|
|
|
646
661
|
// While a navigation the action set off is on its way, the elements shown are the old
|
|
647
662
|
// document's, about to be replaced: a locator or invalid fields count only on the new one.
|
|
648
663
|
const replacing = key !== undefined && events.navigating(state.actedAt);
|
|
649
|
-
const
|
|
664
|
+
const shows = (candidate, staleNow = stale) =>
|
|
650
665
|
blocked ? ["response", "dialog", "popup"].includes(candidate.kind) && events.hit(candidate.name) !== undefined
|
|
651
666
|
: !(replacing && (candidate.kind === "locator" || candidate.kind === "invalid")) &&
|
|
652
|
-
outcomeWaitShows(candidate, observations?.[candidate.name], state,
|
|
667
|
+
outcomeWaitShows(candidate, observations?.[candidate.name], state, staleNow, now);
|
|
668
|
+
// An in-between answer the code named in pending never decides while it shows: it holds the
|
|
669
|
+
// wait for a final one, up to waitLimits.pending from the first look that shows it, never past
|
|
670
|
+
// the deadline nor later than outcomeWaitCallRoomMs before the call's own end. One still
|
|
671
|
+
// showing when the hold ends is the answer. One that showed before the action, unchanged, is
|
|
672
|
+
// no answer to it and never holds the wait.
|
|
673
|
+
const shown = candidates.find((candidate) => !pendingNames.has(candidate.name) && shows(candidate));
|
|
674
|
+
const held = blocked ? undefined : candidates.find((candidate) => pendingNames.has(candidate.name) && shows(candidate, true));
|
|
675
|
+
if (held !== undefined && pendingSince === undefined) {
|
|
676
|
+
pendingSince = now;
|
|
677
|
+
const callEnds = typeof __pomeradoCallEnds === "number" ? __pomeradoCallEnds - outcomeWaitCallRoomMs : Infinity;
|
|
678
|
+
until = Math.max(until, Math.min(now + waitLimits.pending, options.deadline ?? Infinity, callEnds));
|
|
679
|
+
hardStop = until + outcomeWaitLateMs;
|
|
680
|
+
}
|
|
653
681
|
if (shown !== undefined) {
|
|
654
682
|
const observation = observations?.[shown.name];
|
|
655
683
|
if (shown.kind === "locator" && observation.count > 1) {
|
|
@@ -687,6 +715,14 @@ const waitForOutcomeResult = async (outcomes, options = {}) => {
|
|
|
687
715
|
// An outcome the page announced as an event during the sample decides at the next look.
|
|
688
716
|
if (events.dialogOpen() || events.anyHit()) continue;
|
|
689
717
|
signature = current;
|
|
718
|
+
if (now >= until && held !== undefined) {
|
|
719
|
+
const evidence = await waitBounded(
|
|
720
|
+
outcomeWaitEvidence(held, observations[held.name], state, events, now),
|
|
721
|
+
Math.max(250, until - Date.now()),
|
|
722
|
+
{},
|
|
723
|
+
);
|
|
724
|
+
return result(held, observations, evidence);
|
|
725
|
+
}
|
|
690
726
|
if (now >= until) {
|
|
691
727
|
const seen = last ?? (beforeStop() > 0 ? await look().catch(() => undefined) : undefined) ?? {};
|
|
692
728
|
const failure = outcomeWaitFailure(
|
|
@@ -703,7 +739,7 @@ const waitForOutcomeResult = async (outcomes, options = {}) => {
|
|
|
703
739
|
// A quiet page fails only when the next look agrees, since the page may have answered
|
|
704
740
|
// between this look's outcomes and its progress sample.
|
|
705
741
|
const anyShown = candidates.some((candidate) => outcomeWaitShowsAny(candidate, observations?.[candidate.name]));
|
|
706
|
-
const quiet = !anyShown && progress.quietMs() >= noProgressMs;
|
|
742
|
+
const quiet = !anyShown && held === undefined && progress.quietMs() >= noProgressMs;
|
|
707
743
|
if (quiet && !quietBefore) quietBefore = true;
|
|
708
744
|
else if (quiet) {
|
|
709
745
|
const seen = last ?? {};
|
|
@@ -1018,7 +1054,10 @@ const waitForRows = async (rows, fields, options = {}) => {
|
|
|
1018
1054
|
// The rows are read before the signs beside them, so a loader leaving in between restarts
|
|
1019
1055
|
// the settle, and the next look sees the rows it left for.
|
|
1020
1056
|
snapshot: JSON.stringify([listSigns, taken]),
|
|
1021
|
-
|
|
1057
|
+
// A needed field the page still lacks once it stopped changing is a page the code does not
|
|
1058
|
+
// match, not one still loading.
|
|
1059
|
+
reason: Object.keys(missing).length > 0 && Object.keys(loading).length === 0 && Object.keys(hidden).length === 0
|
|
1060
|
+
? "page_mismatch" : "values_loading",
|
|
1022
1061
|
problems:
|
|
1023
1062
|
identified.length + " identified rows of " + read.length + ", needed " + count +
|
|
1024
1063
|
(problems.length === 0 ? "" : "; " + problems.join("; ")),
|
|
@@ -1075,7 +1114,7 @@ const waitForValues = async (fields, options = {}) => {
|
|
|
1075
1114
|
settleMs: settle,
|
|
1076
1115
|
filled: state.filled,
|
|
1077
1116
|
snapshot: JSON.stringify(state.values),
|
|
1078
|
-
reason: "values_loading",
|
|
1117
|
+
reason: state.absent && state.problems.every((problem) => problem.endsWith(" missing")) ? "page_mismatch" : "values_loading",
|
|
1079
1118
|
problems: state.problems.join("; "),
|
|
1080
1119
|
summary: (elapsed, looks) => Object.keys(specs).length + " values filled and holding after " + elapsed + " ms (" + looks + " looks)",
|
|
1081
1120
|
result: { values: state.values },
|
|
@@ -1141,7 +1180,7 @@ const waitForChange = async (fields, options = {}) => {
|
|
|
1141
1180
|
* and when progress stopped. `waitReport()` returns one record per wait this call ran, each with a
|
|
1142
1181
|
* `summary` sentence: return it from a probe to see how each wait ended.
|
|
1143
1182
|
*
|
|
1144
|
-
* `waitForOutcome(outcomes, { action, loading, region, siteDomain, noProgressMs, timeout,
|
|
1183
|
+
* `waitForOutcome(outcomes, { action, pending, loading, region, siteDomain, noProgressMs, timeout,
|
|
1145
1184
|
* unchangedMs }?)` waits for whichever of the page's possible answers appears, after a step whose
|
|
1146
1185
|
* answer can vary, such as a search, a filter, a date pick or a submit, and returns its key.
|
|
1147
1186
|
* `outcomes` names one locator per answer, highest priority first, such as `{ refused, failed,
|
|
@@ -1158,7 +1197,14 @@ const waitForChange = async (fields, options = {}) => {
|
|
|
1158
1197
|
* at most `lateFillCap` (15 s), and never past `timeout` less `unchangedMs`, so the match still
|
|
1159
1198
|
* counts before the timeout.
|
|
1160
1199
|
* `timeout`, `noProgressMs` and `unchangedMs` start once the action returns; `deadline`, a
|
|
1161
|
-
* `Date.now()` time such as the call's own, ends the wait by then however long the action took.
|
|
1200
|
+
* `Date.now()` time such as the call's own, ends the wait by then however long the action took.
|
|
1201
|
+
* `pending` names the outcomes, one key or a list, that are the site's in-between answers to the
|
|
1202
|
+
* action, such as a save it is still processing, each one the page shows (never a response, dialog
|
|
1203
|
+
* or popup), and counting only once new or changed since the action. One never decides while it
|
|
1204
|
+
* shows: from the first look that shows one, the wait holds for a final outcome for `pending` (60 s) past it, or past
|
|
1205
|
+
* `timeout` when that ends later, never past `deadline` nor later than 5 s before the call's own
|
|
1206
|
+
* end. A final outcome wins at once. One still showing when the hold ends is the answer, with
|
|
1207
|
+
* `pending: true` on the result. Its
|
|
1162
1208
|
* `OutcomeWaitFailure` has `observations` (`OutcomeObservation` by key) and one of these reasons:
|
|
1163
1209
|
*
|
|
1164
1210
|
* - `outcome_ambiguous`, when the winning outcome's locator matches more than one element; its
|
|
@@ -1257,7 +1303,8 @@ const waitForChange = async (fields, options = {}) => {
|
|
|
1257
1303
|
* A value is still loading, never absent, while it is empty, reads as a loading word or only dots,
|
|
1258
1304
|
* matches the field's `placeholder` pattern, or sits in an `aria-busy`, skeleton or shimmer
|
|
1259
1305
|
* element. An `optional` field may be absent and is then `null`; a needed one may not. A value
|
|
1260
|
-
* still loading when progress stops fails with `values_loading`, whether optional or not;
|
|
1306
|
+
* still loading when progress stops fails with `values_loading`, whether optional or not; a needed
|
|
1307
|
+
* one missing then, when only missing ones held the wait back, with `page_mismatch`;
|
|
1261
1308
|
* `change_unknown` when waitForChange's fields are missing; `values_timeout` at the cap. Each is a
|
|
1262
1309
|
* `ValueWaitFailure`.
|
|
1263
1310
|
*/
|
|
@@ -1313,7 +1360,9 @@ return { outcomeWaitFailure, outcomeWaitNote, outcomeWaitChanged, outcomeWaitObs
|
|
|
1313
1360
|
* field still marked invalid as before, is `unclear`.
|
|
1314
1361
|
* - Otherwise the commit is `done`: `queued` for a 202, or a body whose status says queued, pending
|
|
1315
1362
|
* or processing, with that word as `status_label`, else `completed`. An outcome with no response
|
|
1316
|
-
* is `not_done` when the page shows a new error, else `unclear
|
|
1363
|
+
* is `not_done` when the page shows a new error, else `unclear`, except a `pending` answer still
|
|
1364
|
+
* showing when its wait ended: that is `done` and `pending`, with its text as `status_label`,
|
|
1365
|
+
* unless the page shows a new message other than an alert. A native dialog that opened
|
|
1317
1366
|
* during the wait and says the write failed is `not_done`, unless the response is a 5xx or
|
|
1318
1367
|
* proves a record (a 201 with a Location): that is `unclear`, naming both. While one stays open
|
|
1319
1368
|
* the page can't be read, which is `unclear`.
|
|
@@ -1449,6 +1498,7 @@ const confirmCommit = await (async () => {
|
|
|
1449
1498
|
}];
|
|
1450
1499
|
});
|
|
1451
1500
|
};
|
|
1501
|
+
const neutralAlert = " (an alert that says neither error nor success)";
|
|
1452
1502
|
const fieldKey = (field) => field.field + "\u0000" + field.message;
|
|
1453
1503
|
const fieldText = (field) => field.field + (field.message === "" ? " is marked invalid" : ": " + field.message);
|
|
1454
1504
|
// Notes the page as it stands now, before the click: its address, how many messages show each
|
|
@@ -1482,7 +1532,7 @@ const confirmCommit = await (async () => {
|
|
|
1482
1532
|
else if (refuses) open.push(message.text + " (a success beside a refusal)");
|
|
1483
1533
|
else if (openWords.test(message.text)) open.push(message.text);
|
|
1484
1534
|
else if (message.errorStyle && !message.successStyle) open.push(message.text + " (styled as an error, with no words of one)");
|
|
1485
|
-
else if (message.alert && !succeeds) open.push(message.text +
|
|
1535
|
+
else if (message.alert && !succeeds) open.push(message.text + neutralAlert);
|
|
1486
1536
|
}
|
|
1487
1537
|
return { errors: [...new Set(errors)], open: [...new Set(open)] };
|
|
1488
1538
|
};
|
|
@@ -1545,6 +1595,17 @@ const confirmCommit = await (async () => {
|
|
|
1545
1595
|
const answered = outcome?.outcome === undefined ? "" : '; "' + outcome.outcome + '" answered the wait';
|
|
1546
1596
|
if (seen !== undefined && seen.errors.length > 0)
|
|
1547
1597
|
return notDone("no commit response" + answered + "; the page shows " + list(seen.errors));
|
|
1598
|
+
// A pending answer still showing when its wait ended is the site's own word that it took the
|
|
1599
|
+
// write and is still working on it, unless the page shows more than an alert beside it.
|
|
1600
|
+
if (outcome?.pending === true && seen !== undefined && seen.open.every((text) => text.endsWith(neutralAlert))) {
|
|
1601
|
+
const text = outcome.evidence?.text;
|
|
1602
|
+
return {
|
|
1603
|
+
state: "done",
|
|
1604
|
+
status: "pending",
|
|
1605
|
+
...(typeof text === "string" && text !== "" ? { status_label: outcomeWaitClean(text, 100) } : {}),
|
|
1606
|
+
reason: '"' + outcome.outcome + '" was still pending when the wait ended, with no error on the page',
|
|
1607
|
+
};
|
|
1608
|
+
}
|
|
1548
1609
|
return unclear("no commit response to confirm" + answered);
|
|
1549
1610
|
}
|
|
1550
1611
|
const status = response.status();
|
|
@@ -8,8 +8,8 @@ export declare class BrowserActionTimeout extends Error {
|
|
|
8
8
|
}
|
|
9
9
|
/**
|
|
10
10
|
* Only Kernel's failed response establishes a settled timeout: a native action's, or one of the
|
|
11
|
-
* runtime's page waits that ended without its answer: no outcome, values still loading
|
|
12
|
-
* not ready to act on, within its cap or once the page stopped progressing.
|
|
11
|
+
* runtime's page waits that ended without its answer: no outcome, values still loading or a needed
|
|
12
|
+
* one missing, or a control not ready to act on, within its cap or once the page stopped progressing.
|
|
13
13
|
*/
|
|
14
14
|
export declare const nativeActionTimeout: (answer: {
|
|
15
15
|
readonly success: boolean;
|
|
@@ -10,12 +10,12 @@ export class BrowserActionTimeout extends Error {
|
|
|
10
10
|
}
|
|
11
11
|
/**
|
|
12
12
|
* Only Kernel's failed response establishes a settled timeout: a native action's, or one of the
|
|
13
|
-
* runtime's page waits that ended without its answer: no outcome, values still loading
|
|
14
|
-
* not ready to act on, within its cap or once the page stopped progressing.
|
|
13
|
+
* runtime's page waits that ended without its answer: no outcome, values still loading or a needed
|
|
14
|
+
* one missing, or a control not ready to act on, within its cap or once the page stopped progressing.
|
|
15
15
|
*/
|
|
16
16
|
export const nativeActionTimeout = (answer) => answer.success === false &&
|
|
17
17
|
typeof answer.error === "string" &&
|
|
18
18
|
(/^(?:TimeoutError:\s*)?(?:locator|page|frame)\.[A-Za-z]+: Timeout \d+ms exceeded\b/u.test(answer.error) ||
|
|
19
|
-
/^(?:(?:OutcomeWait|ValueWait|ReadyWait)Failure:\s*)?(?:outcome_(?:timeout|unknown)|values_(?:loading|timeout)|change_unknown|not_ready|ready_timeout) after \d+ ms\b/u.test(answer.error))
|
|
19
|
+
/^(?:(?:OutcomeWait|ValueWait|ReadyWait)Failure:\s*)?(?:outcome_(?:timeout|unknown)|values_(?:loading|timeout)|page_mismatch|change_unknown|not_ready|ready_timeout) after \d+ ms\b/u.test(answer.error))
|
|
20
20
|
? answer.error
|
|
21
21
|
: undefined;
|
|
@@ -10,6 +10,8 @@ import { Effect } from "effect";
|
|
|
10
10
|
* - `settle`: the gap between the two looks that must agree on the values a tool returns.
|
|
11
11
|
* - `unchanged`: how long an answer or value from before an action must hold to count as unchanged.
|
|
12
12
|
* - `lateFillCap`: the cap on waiting for values the site fills in after its answer.
|
|
13
|
+
* - `pending`: how long an answer wait holds, from the first look that shows an in-between answer
|
|
14
|
+
* the code named (`pending`), for the site's final answer.
|
|
13
15
|
* - `http`: an HTTP request that names no `timeoutMs` of its own, to its whole body.
|
|
14
16
|
* - `httpRead`: a read's request that names none, such as each of `batchRead`'s and
|
|
15
17
|
* `batchFetch`'s. A site answers a read within a few seconds, and one that holds a read longer
|
|
@@ -26,6 +28,7 @@ export declare const timeoutDefaults: {
|
|
|
26
28
|
readonly settle: 500;
|
|
27
29
|
readonly unchanged: 2000;
|
|
28
30
|
readonly lateFillCap: 15000;
|
|
31
|
+
readonly pending: 60000;
|
|
29
32
|
readonly http: 60000;
|
|
30
33
|
readonly httpRead: 8000;
|
|
31
34
|
};
|
|
@@ -10,6 +10,8 @@ import { Effect } from "effect";
|
|
|
10
10
|
* - `settle`: the gap between the two looks that must agree on the values a tool returns.
|
|
11
11
|
* - `unchanged`: how long an answer or value from before an action must hold to count as unchanged.
|
|
12
12
|
* - `lateFillCap`: the cap on waiting for values the site fills in after its answer.
|
|
13
|
+
* - `pending`: how long an answer wait holds, from the first look that shows an in-between answer
|
|
14
|
+
* the code named (`pending`), for the site's final answer.
|
|
13
15
|
* - `http`: an HTTP request that names no `timeoutMs` of its own, to its whole body.
|
|
14
16
|
* - `httpRead`: a read's request that names none, such as each of `batchRead`'s and
|
|
15
17
|
* `batchFetch`'s. A site answers a read within a few seconds, and one that holds a read longer
|
|
@@ -26,6 +28,7 @@ export const timeoutDefaults = {
|
|
|
26
28
|
settle: 500,
|
|
27
29
|
unchanged: 2_000,
|
|
28
30
|
lateFillCap: 15_000,
|
|
31
|
+
pending: 60_000,
|
|
29
32
|
http: 60_000,
|
|
30
33
|
httpRead: 8_000,
|
|
31
34
|
};
|
|
@@ -480,8 +480,11 @@ const clickNavigationWait = String.raw `(until) => {
|
|
|
480
480
|
* reads it (`__pomeradoEffect`).
|
|
481
481
|
*/
|
|
482
482
|
export const withRunEffect = (code, effect) => `const __pomeradoEffect = ${JSON.stringify(effect)};${code}`;
|
|
483
|
-
/**
|
|
484
|
-
|
|
483
|
+
/**
|
|
484
|
+
* A call's code inside `clickNavigationWait`, which ends a second before its `timeout_sec`, with
|
|
485
|
+
* that end declared as `__pomeradoCallEnds`, where a pending `waitForOutcome` ends its hold.
|
|
486
|
+
*/
|
|
487
|
+
const withClickNavigationWait = (code, timeoutSec = 60) => `const __pomeradoCallEnds = Date.now() + ${timeoutSec * 1000 - 1000}; const __pomeradoClickNavigation = (${clickNavigationWait})(__pomeradoCallEnds); try {${code}
|
|
485
488
|
} finally { __pomeradoClickNavigation(); }`;
|
|
486
489
|
/**
|
|
487
490
|
* One run of a script's function against a Kernel client: Kernel's own, or the saved-DOM stand-in.
|