Brunobkr/llama.cpp_AlgMor24_github
ΩFFFΣLLIa • llama.cpp • AlgMor24 ██████╗ ███████╗███████╗███████╗██╗ ██╗ ██╗ █████╗ ██╔═══██╗██╔════╝██╔════╝██╔════╝██║ ██║ ██║██╔══██╗ ██║ ██║█████╗ █████╗ █████╗ ██║ ██║ ██║███████║ ██║ ██║██╔══╝ ██╔══╝ ██╔══╝ ██║ ██║ ██║██╔══██║ ╚██████╔╝██║ ██║ ███████╗███████╗███████╗██║██║ ██║ ╚═════╝ ╚═╝ ╚═╝ ╚══════╝╚══════╝╚══════╝╚═╝╚═╝ ╚═╝ High-Performance LLM / VLM Inference & Autonomous Agentic Ecosystem… See the full description on the dataset page: https://huggingface.co/datasets/Brunobkr/llama.cpp_AlgMor24_github.
03.1k
1"use strict";2var __create = Object.create;3var __defProp = Object.defineProperty;4var __getOwnPropDesc = Object.getOwnPropertyDescriptor;5var __getOwnPropNames = Object.getOwnPropertyNames;6var __getProtoOf = Object.getPrototypeOf;7var __hasOwnProp = Object.prototype.hasOwnProperty;8var __export = (target, all) => {9 for (var name in all)10 __defProp(target, name, { get: all[name], enumerable: true });11};12var __copyProps = (to, from, except, desc) => {13 if (from && typeof from === "object" || typeof from === "function") {14 for (let key of __getOwnPropNames(from))15 if (!__hasOwnProp.call(to, key) && key !== except)16 __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });17 }18 return to;19};20var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(21 // If the importer is in node compatibility mode or this is not an ESM22 // file that has been converted to a CommonJS file using a Babel-23 // compatible transform (i.e. "__esModule" has not been set), then set24 // "default" to the CommonJS "module.exports" for node compatibility.25 isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,26 mod27));28var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);29var page_exports = {};30__export(page_exports, {31 InitScript: () => InitScript,32 Page: () => Page,33 PageBinding: () => PageBinding,34 Worker: () => Worker35});36module.exports = __toCommonJS(page_exports);37var accessibility = __toESM(require("./accessibility"));38var import_browserContext = require("./browserContext");39var import_console = require("./console");40var import_errors = require("./errors");41var import_fileChooser = require("./fileChooser");42var frames = __toESM(require("./frames"));43var import_helper = require("./helper");44var input = __toESM(require("./input"));45var import_instrumentation = require("./instrumentation");46var js = __toESM(require("./javascript"));47var import_screenshotter = require("./screenshotter");48var import_utils = require("../utils");49var import_utils2 = require("../utils");50var import_comparators = require("./utils/comparators");51var import_debugLogger = require("./utils/debugLogger");52var import_selectorParser = require("../utils/isomorphic/selectorParser");53var import_manualPromise = require("../utils/isomorphic/manualPromise");54var import_utilityScriptSerializers = require("../utils/isomorphic/utilityScriptSerializers");55var import_callLog = require("./callLog");56var rawBindingsControllerSource = __toESM(require("../generated/bindingsControllerSource"));57class Page extends import_instrumentation.SdkObject {58 constructor(delegate, browserContext) {59 super(browserContext, "page");60 this._closedState = "open";61 this._closedPromise = new import_manualPromise.ManualPromise();62 this._initializedPromise = new import_manualPromise.ManualPromise();63 this._consoleMessages = [];64 this._pageErrors = [];65 this._crashed = false;66 this.openScope = new import_utils.LongStandingScope();67 this._emulatedMedia = {};68 this._fileChooserInterceptedBy = /* @__PURE__ */ new Set();69 this._pageBindings = /* @__PURE__ */ new Map();70 this.initScripts = [];71 this._workers = /* @__PURE__ */ new Map();72 this.requestInterceptors = [];73 this.video = null;74 this._locatorHandlers = /* @__PURE__ */ new Map();75 this._lastLocatorHandlerUid = 0;76 this._locatorHandlerRunningCounter = 0;77 this._networkRequests = [];78 // Aiming at 25 fps by default - each frame is 40ms, but we give some slack with 35ms.79 // When throttling for tracing, 200ms between frames, except for 10 frames around the action.80 this._frameThrottler = new FrameThrottler(10, 35, 200);81 this.lastSnapshotFrameIds = [];82 this.attribution.page = this;83 this.delegate = delegate;84 this.browserContext = browserContext;85 this.accessibility = new accessibility.Accessibility(delegate.getAccessibilityTree.bind(delegate));86 this.keyboard = new input.Keyboard(delegate.rawKeyboard, this);87 this.mouse = new input.Mouse(delegate.rawMouse, this);88 this.touchscreen = new input.Touchscreen(delegate.rawTouchscreen, this);89 this.screenshotter = new import_screenshotter.Screenshotter(this);90 this.frameManager = new frames.FrameManager(this);91 if (delegate.pdf)92 this.pdf = delegate.pdf.bind(delegate);93 this.coverage = delegate.coverage ? delegate.coverage() : null;94 this.isStorageStatePage = browserContext.isCreatingStorageStatePage();95 }96 static {97 this.Events = {98 Close: "close",99 Crash: "crash",100 Download: "download",101 EmulatedSizeChanged: "emulatedsizechanged",102 FileChooser: "filechooser",103 FrameAttached: "frameattached",104 FrameDetached: "framedetached",105 InternalFrameNavigatedToNewDocument: "internalframenavigatedtonewdocument",106 LocatorHandlerTriggered: "locatorhandlertriggered",107 ScreencastFrame: "screencastframe",108 Video: "video",109 WebSocket: "websocket",110 Worker: "worker"111 };112 }113 async reportAsNew(opener, error) {114 if (opener) {115 const openerPageOrError = await opener.waitForInitializedOrError();116 if (openerPageOrError instanceof Page && !openerPageOrError.isClosed())117 this._opener = openerPageOrError;118 }119 this._markInitialized(error);120 }121 _markInitialized(error = void 0) {122 if (error) {123 if (this.browserContext.isClosingOrClosed())124 return;125 this.frameManager.createDummyMainFrameIfNeeded();126 }127 this._initialized = error || this;128 this.emitOnContext(import_browserContext.BrowserContext.Events.Page, this);129 for (const pageError of this._pageErrors)130 this.emitOnContext(import_browserContext.BrowserContext.Events.PageError, pageError, this);131 for (const message of this._consoleMessages)132 this.emitOnContext(import_browserContext.BrowserContext.Events.Console, message);133 if (this.isClosed())134 this.emit(Page.Events.Close);135 else136 this.instrumentation.onPageOpen(this);137 this._initializedPromise.resolve(this._initialized);138 }139 initializedOrUndefined() {140 return this._initialized ? this : void 0;141 }142 waitForInitializedOrError() {143 return this._initializedPromise;144 }145 emitOnContext(event, ...args) {146 if (this.isStorageStatePage)147 return;148 this.browserContext.emit(event, ...args);149 }150 async resetForReuse(progress) {151 await this.mainFrame().gotoImpl(progress, "about:blank", {});152 this._emulatedSize = void 0;153 this._emulatedMedia = {};154 this._extraHTTPHeaders = void 0;155 await Promise.all([156 this.delegate.updateEmulatedViewportSize(),157 this.delegate.updateEmulateMedia(),158 this.delegate.updateExtraHTTPHeaders()159 ]);160 await this.delegate.resetForReuse(progress);161 }162 _didClose() {163 this.frameManager.dispose();164 this._frameThrottler.dispose();165 (0, import_utils.assert)(this._closedState !== "closed", "Page closed twice");166 this._closedState = "closed";167 this.emit(Page.Events.Close);168 this._closedPromise.resolve();169 this.instrumentation.onPageClose(this);170 this.openScope.close(new import_errors.TargetClosedError());171 }172 _didCrash() {173 this.frameManager.dispose();174 this._frameThrottler.dispose();175 this.emit(Page.Events.Crash);176 this._crashed = true;177 this.instrumentation.onPageClose(this);178 this.openScope.close(new Error("Page crashed"));179 }180 async _onFileChooserOpened(handle) {181 let multiple;182 try {183 multiple = await handle.evaluate((element) => !!element.multiple);184 } catch (e) {185 return;186 }187 if (!this.listenerCount(Page.Events.FileChooser)) {188 handle.dispose();189 return;190 }191 const fileChooser = new import_fileChooser.FileChooser(this, handle, multiple);192 this.emit(Page.Events.FileChooser, fileChooser);193 }194 opener() {195 return this._opener;196 }197 mainFrame() {198 return this.frameManager.mainFrame();199 }200 frames() {201 return this.frameManager.frames();202 }203 async exposeBinding(progress, name, needsHandle, playwrightBinding) {204 if (this._pageBindings.has(name))205 throw new Error(`Function "${name}" has been already registered`);206 if (this.browserContext._pageBindings.has(name))207 throw new Error(`Function "${name}" has been already registered in the browser context`);208 await progress.race(this.browserContext.exposePlaywrightBindingIfNeeded());209 const binding = new PageBinding(name, playwrightBinding, needsHandle);210 this._pageBindings.set(name, binding);211 try {212 await progress.race(this.delegate.addInitScript(binding.initScript));213 await progress.race(this.safeNonStallingEvaluateInAllFrames(binding.initScript.source, "main"));214 return binding;215 } catch (error) {216 this._pageBindings.delete(name);217 throw error;218 }219 }220 async removeExposedBindings(bindings) {221 bindings = bindings.filter((binding) => this._pageBindings.get(binding.name) === binding);222 for (const binding of bindings)223 this._pageBindings.delete(binding.name);224 await this.delegate.removeInitScripts(bindings.map((binding) => binding.initScript));225 const cleanup = bindings.map((binding) => `{ ${binding.cleanupScript} };226`).join("");227 await this.safeNonStallingEvaluateInAllFrames(cleanup, "main");228 }229 async setExtraHTTPHeaders(progress, headers) {230 const oldHeaders = this._extraHTTPHeaders;231 try {232 this._extraHTTPHeaders = headers;233 await progress.race(this.delegate.updateExtraHTTPHeaders());234 } catch (error) {235 this._extraHTTPHeaders = oldHeaders;236 this.delegate.updateExtraHTTPHeaders().catch(() => {237 });238 throw error;239 }240 }241 extraHTTPHeaders() {242 return this._extraHTTPHeaders;243 }244 addNetworkRequest(request) {245 this._networkRequests.push(request);246 ensureArrayLimit(this._networkRequests, 100);247 }248 networkRequests() {249 return this._networkRequests;250 }251 async onBindingCalled(payload, context) {252 if (this._closedState === "closed")253 return;254 await PageBinding.dispatch(this, payload, context);255 }256 addConsoleMessage(type, args, location, text) {257 const message = new import_console.ConsoleMessage(this, type, text, args, location);258 const intercepted = this.frameManager.interceptConsoleMessage(message);259 if (intercepted) {260 args.forEach((arg) => arg.dispose());261 return;262 }263 this._consoleMessages.push(message);264 ensureArrayLimit(this._consoleMessages, 200);265 if (this._initialized)266 this.emitOnContext(import_browserContext.BrowserContext.Events.Console, message);267 }268 consoleMessages() {269 return this._consoleMessages;270 }271 addPageError(pageError) {272 this._pageErrors.push(pageError);273 ensureArrayLimit(this._pageErrors, 200);274 if (this._initialized)275 this.emitOnContext(import_browserContext.BrowserContext.Events.PageError, pageError, this);276 }277 pageErrors() {278 return this._pageErrors;279 }280 async reload(progress, options) {281 return this.mainFrame().raceNavigationAction(progress, async () => {282 const [response] = await Promise.all([283 // Reload must be a new document, and should not be confused with a stray pushState.284 this.mainFrame()._waitForNavigation(progress, true, options),285 progress.race(this.delegate.reload())286 ]);287 return response;288 });289 }290 async goBack(progress, options) {291 return this.mainFrame().raceNavigationAction(progress, async () => {292 let error;293 const waitPromise = this.mainFrame()._waitForNavigation(progress, false, options).catch((e) => {294 error = e;295 return null;296 });297 const result = await progress.race(this.delegate.goBack());298 if (!result) {299 waitPromise.catch(() => {300 });301 return null;302 }303 const response = await waitPromise;304 if (error)305 throw error;306 return response;307 });308 }309 async goForward(progress, options) {310 return this.mainFrame().raceNavigationAction(progress, async () => {311 let error;312 const waitPromise = this.mainFrame()._waitForNavigation(progress, false, options).catch((e) => {313 error = e;314 return null;315 });316 const result = await progress.race(this.delegate.goForward());317 if (!result) {318 waitPromise.catch(() => {319 });320 return null;321 }322 const response = await waitPromise;323 if (error)324 throw error;325 return response;326 });327 }328 requestGC() {329 return this.delegate.requestGC();330 }331 registerLocatorHandler(selector, noWaitAfter) {332 const uid = ++this._lastLocatorHandlerUid;333 this._locatorHandlers.set(uid, { selector, noWaitAfter });334 return uid;335 }336 resolveLocatorHandler(uid, remove) {337 const handler = this._locatorHandlers.get(uid);338 if (remove)339 this._locatorHandlers.delete(uid);340 if (handler) {341 handler.resolved?.resolve();342 handler.resolved = void 0;343 }344 }345 unregisterLocatorHandler(uid) {346 this._locatorHandlers.delete(uid);347 }348 async performActionPreChecks(progress) {349 await this._performWaitForNavigationCheck(progress);350 await this._performLocatorHandlersCheckpoint(progress);351 await this._performWaitForNavigationCheck(progress);352 }353 async _performWaitForNavigationCheck(progress) {354 const mainFrame = this.frameManager.mainFrame();355 if (!mainFrame || !mainFrame.pendingDocument())356 return;357 const url = mainFrame.pendingDocument()?.request?.url();358 const toUrl = url ? `" ${(0, import_utils.trimStringWithEllipsis)(url, 200)}"` : "";359 progress.log(` waiting for${toUrl} navigation to finish...`);360 await import_helper.helper.waitForEvent(progress, mainFrame, frames.Frame.Events.InternalNavigation, (e) => {361 if (!e.isPublic)362 return false;363 if (!e.error)364 progress.log(` navigated to "${(0, import_utils.trimStringWithEllipsis)(mainFrame.url(), 200)}"`);365 return true;366 }).promise;367 }368 async _performLocatorHandlersCheckpoint(progress) {369 if (this._locatorHandlerRunningCounter)370 return;371 for (const [uid, handler] of this._locatorHandlers) {372 if (!handler.resolved) {373 if (await this.mainFrame().isVisibleInternal(progress, handler.selector, { strict: true })) {374 handler.resolved = new import_manualPromise.ManualPromise();375 this.emit(Page.Events.LocatorHandlerTriggered, uid);376 }377 }378 if (handler.resolved) {379 ++this._locatorHandlerRunningCounter;380 progress.log(` found ${(0, import_utils2.asLocator)(this.browserContext._browser.sdkLanguage(), handler.selector)}, intercepting action to run the handler`);381 const promise = handler.resolved.then(async () => {382 if (!handler.noWaitAfter) {383 progress.log(` locator handler has finished, waiting for ${(0, import_utils2.asLocator)(this.browserContext._browser.sdkLanguage(), handler.selector)} to be hidden`);384 await this.mainFrame().waitForSelector(progress, handler.selector, false, { state: "hidden" });385 } else {386 progress.log(` locator handler has finished`);387 }388 });389 await progress.race(this.openScope.race(promise)).finally(() => --this._locatorHandlerRunningCounter);390 progress.log(` interception handler has finished, continuing`);391 }392 }393 }394 async emulateMedia(progress, options) {395 const oldEmulatedMedia = { ...this._emulatedMedia };396 if (options.media !== void 0)397 this._emulatedMedia.media = options.media;398 if (options.colorScheme !== void 0)399 this._emulatedMedia.colorScheme = options.colorScheme;400 if (options.reducedMotion !== void 0)401 this._emulatedMedia.reducedMotion = options.reducedMotion;402 if (options.forcedColors !== void 0)403 this._emulatedMedia.forcedColors = options.forcedColors;404 if (options.contrast !== void 0)405 this._emulatedMedia.contrast = options.contrast;406 try {407 await progress.race(this.delegate.updateEmulateMedia());408 } catch (error) {409 this._emulatedMedia = oldEmulatedMedia;410 this.delegate.updateEmulateMedia().catch(() => {411 });412 throw error;413 }414 }415 emulatedMedia() {416 const contextOptions = this.browserContext._options;417 return {418 media: this._emulatedMedia.media || "no-override",419 colorScheme: this._emulatedMedia.colorScheme !== void 0 ? this._emulatedMedia.colorScheme : contextOptions.colorScheme ?? "light",420 reducedMotion: this._emulatedMedia.reducedMotion !== void 0 ? this._emulatedMedia.reducedMotion : contextOptions.reducedMotion ?? "no-preference",421 forcedColors: this._emulatedMedia.forcedColors !== void 0 ? this._emulatedMedia.forcedColors : contextOptions.forcedColors ?? "none",422 contrast: this._emulatedMedia.contrast !== void 0 ? this._emulatedMedia.contrast : contextOptions.contrast ?? "no-preference"423 };424 }425 async setViewportSize(progress, viewportSize) {426 const oldEmulatedSize = this._emulatedSize;427 try {428 this._setEmulatedSize({ viewport: { ...viewportSize }, screen: { ...viewportSize } });429 await progress.race(this.delegate.updateEmulatedViewportSize());430 } catch (error) {431 this._emulatedSize = oldEmulatedSize;432 this.delegate.updateEmulatedViewportSize().catch(() => {433 });434 throw error;435 }436 }437 setEmulatedSizeFromWindowOpen(emulatedSize) {438 this._setEmulatedSize(emulatedSize);439 }440 _setEmulatedSize(emulatedSize) {441 this._emulatedSize = emulatedSize;442 this.emit(Page.Events.EmulatedSizeChanged);443 }444 emulatedSize() {445 if (this._emulatedSize)446 return this._emulatedSize;447 const contextOptions = this.browserContext._options;448 return contextOptions.viewport ? { viewport: contextOptions.viewport, screen: contextOptions.screen || contextOptions.viewport } : void 0;449 }450 async bringToFront() {451 await this.delegate.bringToFront();452 }453 async addInitScript(progress, source) {454 const initScript = new InitScript(source);455 this.initScripts.push(initScript);456 try {457 await progress.race(this.delegate.addInitScript(initScript));458 } catch (error) {459 this.removeInitScripts([initScript]).catch(() => {460 });461 throw error;462 }463 return initScript;464 }465 async removeInitScripts(initScripts) {466 const set = new Set(initScripts);467 this.initScripts = this.initScripts.filter((script) => !set.has(script));468 await this.delegate.removeInitScripts(initScripts);469 }470 needsRequestInterception() {471 return this.requestInterceptors.length > 0 || this.browserContext.requestInterceptors.length > 0;472 }473 async addRequestInterceptor(progress, handler, prepend) {474 if (prepend)475 this.requestInterceptors.unshift(handler);476 else477 this.requestInterceptors.push(handler);478 await this.delegate.updateRequestInterception();479 }480 async removeRequestInterceptor(handler) {481 const index = this.requestInterceptors.indexOf(handler);482 if (index === -1)483 return;484 this.requestInterceptors.splice(index, 1);485 await this.browserContext.notifyRoutesInFlightAboutRemovedHandler(handler);486 await this.delegate.updateRequestInterception();487 }488 async expectScreenshot(progress, options) {489 const locator = options.locator;490 const rafrafScreenshot = locator ? async (timeout) => {491 return await locator.frame.rafrafTimeoutScreenshotElementWithProgress(progress, locator.selector, timeout, options || {});492 } : async (timeout) => {493 await this.performActionPreChecks(progress);494 await this.mainFrame().rafrafTimeout(progress, timeout);495 return await this.screenshotter.screenshotPage(progress, options || {});496 };497 const comparator = (0, import_comparators.getComparator)("image/png");498 if (!options.expected && options.isNot)499 return { errorMessage: '"not" matcher requires expected result' };500 try {501 const format = (0, import_screenshotter.validateScreenshotOptions)(options || {});502 if (format !== "png")503 throw new Error("Only PNG screenshots are supported");504 } catch (error) {505 return { errorMessage: error.message };506 }507 let intermediateResult;508 const areEqualScreenshots = (actual, expected, previous) => {509 const comparatorResult = actual && expected ? comparator(actual, expected, options) : void 0;510 if (comparatorResult !== void 0 && !!comparatorResult === !!options.isNot)511 return true;512 if (comparatorResult)513 intermediateResult = { errorMessage: comparatorResult.errorMessage, diff: comparatorResult.diff, actual, previous };514 return false;515 };516 try {517 let actual;518 let previous;519 const pollIntervals = [0, 100, 250, 500];520 progress.log(`${(0, import_utils.renderTitleForCall)(progress.metadata)}${options.timeout ? ` with timeout ${options.timeout}ms` : ""}`);521 if (options.expected)522 progress.log(` verifying given screenshot expectation`);523 else524 progress.log(` generating new stable screenshot expectation`);525 let isFirstIteration = true;526 while (true) {527 if (this.isClosed())528 throw new Error("The page has closed");529 const screenshotTimeout = pollIntervals.shift() ?? 1e3;530 if (screenshotTimeout)531 progress.log(`waiting ${screenshotTimeout}ms before taking screenshot`);532 previous = actual;533 actual = await rafrafScreenshot(screenshotTimeout).catch((e) => {534 if (this.mainFrame().isNonRetriableError(e))535 throw e;536 progress.log(`failed to take screenshot - ` + e.message);537 return void 0;538 });539 if (!actual)540 continue;541 const expectation = options.expected && isFirstIteration ? options.expected : previous;542 if (areEqualScreenshots(actual, expectation, previous))543 break;544 if (intermediateResult)545 progress.log(intermediateResult.errorMessage);546 isFirstIteration = false;547 }548 if (!isFirstIteration)549 progress.log(`captured a stable screenshot`);550 if (!options.expected)551 return { actual };552 if (isFirstIteration) {553 progress.log(`screenshot matched expectation`);554 return {};555 }556 if (areEqualScreenshots(actual, options.expected, void 0)) {557 progress.log(`screenshot matched expectation`);558 return {};559 }560 throw new Error(intermediateResult.errorMessage);561 } catch (e) {562 if (js.isJavaScriptErrorInEvaluate(e) || (0, import_selectorParser.isInvalidSelectorError)(e))563 throw e;564 let errorMessage = e.message;565 if (e instanceof import_errors.TimeoutError && intermediateResult?.previous)566 errorMessage = `Failed to take two consecutive stable screenshots.`;567 return {568 log: (0, import_callLog.compressCallLog)(e.message ? [...progress.metadata.log, e.message] : progress.metadata.log),569 ...intermediateResult,570 errorMessage,571 timedOut: e instanceof import_errors.TimeoutError572 };573 }574 }575 async screenshot(progress, options) {576 return await this.screenshotter.screenshotPage(progress, options);577 }578 async close(options = {}) {579 if (this._closedState === "closed")580 return;581 if (options.reason)582 this.closeReason = options.reason;583 const runBeforeUnload = !!options.runBeforeUnload;584 if (this._closedState !== "closing") {585 this._closedState = "closing";586 await this.delegate.closePage(runBeforeUnload).catch((e) => import_debugLogger.debugLogger.log("error", e));587 }588 if (!runBeforeUnload)589 await this._closedPromise;590 }591 isClosed() {592 return this._closedState === "closed";593 }594 hasCrashed() {595 return this._crashed;596 }597 isClosedOrClosingOrCrashed() {598 return this._closedState !== "open" || this._crashed;599 }600 addWorker(workerId, worker) {601 this._workers.set(workerId, worker);602 this.emit(Page.Events.Worker, worker);603 }604 removeWorker(workerId) {605 const worker = this._workers.get(workerId);606 if (!worker)607 return;608 worker.didClose();609 this._workers.delete(workerId);610 }611 clearWorkers() {612 for (const [workerId, worker] of this._workers) {613 worker.didClose();614 this._workers.delete(workerId);615 }616 }617 async setFileChooserInterceptedBy(enabled, by) {618 const wasIntercepted = this.fileChooserIntercepted();619 if (enabled)620 this._fileChooserInterceptedBy.add(by);621 else622 this._fileChooserInterceptedBy.delete(by);623 if (wasIntercepted !== this.fileChooserIntercepted())624 await this.delegate.updateFileChooserInterception();625 }626 fileChooserIntercepted() {627 return this._fileChooserInterceptedBy.size > 0;628 }629 frameNavigatedToNewDocument(frame) {630 this.emit(Page.Events.InternalFrameNavigatedToNewDocument, frame);631 const origin = frame.origin();632 if (origin)633 this.browserContext.addVisitedOrigin(origin);634 }635 allInitScripts() {636 const bindings = [...this.browserContext._pageBindings.values(), ...this._pageBindings.values()].map((binding) => binding.initScript);637 if (this.browserContext.bindingsInitScript)638 bindings.unshift(this.browserContext.bindingsInitScript);639 return [...bindings, ...this.browserContext.initScripts, ...this.initScripts];640 }641 getBinding(name) {642 return this._pageBindings.get(name) || this.browserContext._pageBindings.get(name);643 }644 setScreencastOptions(options) {645 this.delegate.setScreencastOptions(options).catch((e) => import_debugLogger.debugLogger.log("error", e));646 this._frameThrottler.setThrottlingEnabled(!!options);647 }648 throttleScreencastFrameAck(ack) {649 this._frameThrottler.ack(ack);650 }651 temporarilyDisableTracingScreencastThrottling() {652 this._frameThrottler.recharge();653 }654 async safeNonStallingEvaluateInAllFrames(expression, world, options = {}) {655 await Promise.all(this.frames().map(async (frame) => {656 try {657 await frame.nonStallingEvaluateInExistingContext(expression, world);658 } catch (e) {659 if (options.throwOnJSErrors && js.isJavaScriptErrorInEvaluate(e))660 throw e;661 }662 }));663 }664 async hideHighlight() {665 await Promise.all(this.frames().map((frame) => frame.hideHighlight().catch(() => {666 })));667 }668 async snapshotForAI(progress) {669 this.lastSnapshotFrameIds = [];670 const snapshot = await snapshotFrameForAI(progress, this.mainFrame(), 0, this.lastSnapshotFrameIds);671 return snapshot.join("\n");672 }673}674class Worker extends import_instrumentation.SdkObject {675 constructor(parent, url) {676 super(parent, "worker");677 this.existingExecutionContext = null;678 this.openScope = new import_utils.LongStandingScope();679 this.url = url;680 this._executionContextCallback = () => {681 };682 this._executionContextPromise = new Promise((x) => this._executionContextCallback = x);683 }684 static {685 this.Events = {686 Close: "close"687 };688 }689 createExecutionContext(delegate) {690 this.existingExecutionContext = new js.ExecutionContext(this, delegate, "worker");691 this._executionContextCallback(this.existingExecutionContext);692 return this.existingExecutionContext;693 }694 didClose() {695 if (this.existingExecutionContext)696 this.existingExecutionContext.contextDestroyed("Worker was closed");697 this.emit(Worker.Events.Close, this);698 this.openScope.close(new Error("Worker closed"));699 }700 async evaluateExpression(expression, isFunction, arg) {701 return js.evaluateExpression(await this._executionContextPromise, expression, { returnByValue: true, isFunction }, arg);702 }703 async evaluateExpressionHandle(expression, isFunction, arg) {704 return js.evaluateExpression(await this._executionContextPromise, expression, { returnByValue: false, isFunction }, arg);705 }706}707class PageBinding {708 static {709 this.kController = "__playwright__binding__controller__";710 }711 static {712 this.kBindingName = "__playwright__binding__";713 }714 static createInitScript() {715 return new InitScript(`716 (() => {717 const module = {};718 ${rawBindingsControllerSource.source}719 const property = '${PageBinding.kController}';720 if (!globalThis[property])721 globalThis[property] = new (module.exports.BindingsController())(globalThis, '${PageBinding.kBindingName}');722 })();723 `);724 }725 constructor(name, playwrightFunction, needsHandle) {726 this.name = name;727 this.playwrightFunction = playwrightFunction;728 this.initScript = new InitScript(`globalThis['${PageBinding.kController}'].addBinding(${JSON.stringify(name)}, ${needsHandle})`);729 this.needsHandle = needsHandle;730 this.cleanupScript = `globalThis['${PageBinding.kController}'].removeBinding(${JSON.stringify(name)})`;731 }732 static async dispatch(page, payload, context) {733 const { name, seq, serializedArgs } = JSON.parse(payload);734 try {735 (0, import_utils.assert)(context.world);736 const binding = page.getBinding(name);737 if (!binding)738 throw new Error(`Function "${name}" is not exposed`);739 let result;740 if (binding.needsHandle) {741 const handle = await context.evaluateExpressionHandle(`arg => globalThis['${PageBinding.kController}'].takeBindingHandle(arg)`, { isFunction: true }, { name, seq }).catch((e) => null);742 result = await binding.playwrightFunction({ frame: context.frame, page, context: page.browserContext }, handle);743 } else {744 if (!Array.isArray(serializedArgs))745 throw new Error(`serializedArgs is not an array. This can happen when Array.prototype.toJSON is defined incorrectly`);746 const args = serializedArgs.map((a) => (0, import_utilityScriptSerializers.parseEvaluationResultValue)(a));747 result = await binding.playwrightFunction({ frame: context.frame, page, context: page.browserContext }, ...args);748 }749 context.evaluateExpressionHandle(`arg => globalThis['${PageBinding.kController}'].deliverBindingResult(arg)`, { isFunction: true }, { name, seq, result }).catch((e) => import_debugLogger.debugLogger.log("error", e));750 } catch (error) {751 context.evaluateExpressionHandle(`arg => globalThis['${PageBinding.kController}'].deliverBindingResult(arg)`, { isFunction: true }, { name, seq, error }).catch((e) => import_debugLogger.debugLogger.log("error", e));752 }753 }754}755class InitScript {756 constructor(source) {757 this.source = `(() => {758 ${source}759 })();`;760 }761}762class FrameThrottler {763 constructor(nonThrottledFrames, defaultInterval, throttlingInterval) {764 this._acks = [];765 this._throttlingEnabled = false;766 this._nonThrottledFrames = nonThrottledFrames;767 this._budget = nonThrottledFrames;768 this._defaultInterval = defaultInterval;769 this._throttlingInterval = throttlingInterval;770 this._tick();771 }772 dispose() {773 if (this._timeoutId) {774 clearTimeout(this._timeoutId);775 this._timeoutId = void 0;776 }777 }778 setThrottlingEnabled(enabled) {779 this._throttlingEnabled = enabled;780 }781 recharge() {782 for (const ack of this._acks)783 ack();784 this._acks = [];785 this._budget = this._nonThrottledFrames;786 if (this._timeoutId) {787 clearTimeout(this._timeoutId);788 this._tick();789 }790 }791 ack(ack) {792 if (!this._timeoutId) {793 ack();794 return;795 }796 this._acks.push(ack);797 }798 _tick() {799 const ack = this._acks.shift();800 if (ack) {801 --this._budget;802 ack();803 }804 if (this._throttlingEnabled && this._budget <= 0) {805 this._timeoutId = setTimeout(() => this._tick(), this._throttlingInterval);806 } else {807 this._timeoutId = setTimeout(() => this._tick(), this._defaultInterval);808 }809 }810}811async function snapshotFrameForAI(progress, frame, frameOrdinal, frameIds) {812 const snapshot = await frame.retryWithProgressAndTimeouts(progress, [1e3, 2e3, 4e3, 8e3], async (continuePolling) => {813 try {814 const context = await progress.race(frame._utilityContext());815 const injectedScript = await progress.race(context.injectedScript());816 const snapshotOrRetry = await progress.race(injectedScript.evaluate((injected, refPrefix) => {817 const node = injected.document.body;818 if (!node)819 return true;820 return injected.ariaSnapshot(node, { mode: "ai", refPrefix });821 }, frameOrdinal ? "f" + frameOrdinal : ""));822 if (snapshotOrRetry === true)823 return continuePolling;824 return snapshotOrRetry;825 } catch (e) {826 if (frame.isNonRetriableError(e))827 throw e;828 return continuePolling;829 }830 });831 const lines = snapshot.split("\n");832 const result = [];833 for (const line of lines) {834 const match = line.match(/^(\s*)- iframe (?:\[active\] )?\[ref=([^\]]*)\]/);835 if (!match) {836 result.push(line);837 continue;838 }839 const leadingSpace = match[1];840 const ref = match[2];841 const frameSelector = `aria-ref=${ref} >> internal:control=enter-frame`;842 const frameBodySelector = `${frameSelector} >> body`;843 const child = await progress.race(frame.selectors.resolveFrameForSelector(frameBodySelector, { strict: true }));844 if (!child) {845 result.push(line);846 continue;847 }848 const frameOrdinal2 = frameIds.length + 1;849 frameIds.push(child.frame._id);850 try {851 const childSnapshot = await snapshotFrameForAI(progress, child.frame, frameOrdinal2, frameIds);852 result.push(line + ":", ...childSnapshot.map((l) => leadingSpace + " " + l));853 } catch {854 result.push(line);855 }856 }857 return result;858}859function ensureArrayLimit(array, limit) {860 if (array.length > limit)861 return array.splice(0, limit / 10);862 return [];863}864// Annotate the CommonJS export names for ESM import in node:8650 && (module.exports = {866 InitScript,867 Page,868 PageBinding,869 Worker870});871 