"use strict";
/**
 * Copyright 2017 Google Inc. All rights reserved.
 * Modifications copyright (c) Microsoft Corporation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.prepareBrowserContextOptions = exports.BrowserContext = void 0;
const page_1 = require("./page");
const network = require("./network");
const util = require("util");
const fs = require("fs");
const channelOwner_1 = require("./channelOwner");
const clientHelper_1 = require("./clientHelper");
const browser_1 = require("./browser");
const events_1 = require("./events");
const timeoutSettings_1 = require("../utils/timeoutSettings");
const waiter_1 = require("./waiter");
const utils_1 = require("../utils/utils");
const errors_1 = require("../utils/errors");
const jsHandle_1 = require("./jsHandle");
const fsWriteFileAsync = util.promisify(fs.writeFile.bind(fs));
const fsReadFileAsync = util.promisify(fs.readFile.bind(fs));
class BrowserContext extends channelOwner_1.ChannelOwner {
    constructor(parent, type, guid, initializer, browserName) {
        super(parent, type, guid, initializer);
        this._pages = new Set();
        this._routes = [];
        this._browser = null;
        this._bindings = new Map();
        this._timeoutSettings = new timeoutSettings_1.TimeoutSettings();
        this._options = {};
        if (parent instanceof browser_1.Browser)
            this._browser = parent;
        this._browserName = browserName;
        this._channel.on('bindingCall', ({ binding }) => this._onBinding(page_1.BindingCall.from(binding)));
        this._channel.on('close', () => this._onClose());
        this._channel.on('page', ({ page }) => this._onPage(page_1.Page.from(page)));
        this._channel.on('route', ({ route, request }) => this._onRoute(network.Route.from(route), network.Request.from(request)));
        this._closedPromise = new Promise(f => this.once(events_1.Events.BrowserContext.Close, f));
    }
    static from(context) {
        return context._object;
    }
    static fromNullable(context) {
        return context ? BrowserContext.from(context) : null;
    }
    _onPage(page) {
        this._pages.add(page);
        this.emit(events_1.Events.BrowserContext.Page, page);
    }
    _onRoute(route, request) {
        for (const { url, handler } of this._routes) {
            if (clientHelper_1.urlMatches(request.url(), url)) {
                handler(route, request);
                return;
            }
        }
        route.continue();
    }
    async _onBinding(bindingCall) {
        const func = this._bindings.get(bindingCall._initializer.name);
        if (!func)
            return;
        bindingCall.call(func);
    }
    setDefaultNavigationTimeout(timeout) {
        this._timeoutSettings.setDefaultNavigationTimeout(timeout);
        this._channel.setDefaultNavigationTimeoutNoReply({ timeout });
    }
    setDefaultTimeout(timeout) {
        this._timeoutSettings.setDefaultTimeout(timeout);
        this._channel.setDefaultTimeoutNoReply({ timeout });
    }
    browser() {
        return this._browser;
    }
    pages() {
        return [...this._pages];
    }
    async newPage() {
        return this._wrapApiCall('browserContext.newPage', async () => {
            if (this._ownerPage)
                throw new Error('Please use browser.newContext()');
            return page_1.Page.from((await this._channel.newPage()).page);
        });
    }
    async cookies(urls) {
        if (!urls)
            urls = [];
        if (urls && typeof urls === 'string')
            urls = [urls];
        return this._wrapApiCall('browserContext.cookies', async () => {
            return (await this._channel.cookies({ urls: urls })).cookies;
        });
    }
    async addCookies(cookies) {
        return this._wrapApiCall('browserContext.addCookies', async () => {
            await this._channel.addCookies({ cookies });
        });
    }
    async clearCookies() {
        return this._wrapApiCall('browserContext.clearCookies', async () => {
            await this._channel.clearCookies();
        });
    }
    async grantPermissions(permissions, options) {
        return this._wrapApiCall('browserContext.grantPermissions', async () => {
            await this._channel.grantPermissions({ permissions, ...options });
        });
    }
    async clearPermissions() {
        return this._wrapApiCall('browserContext.clearPermissions', async () => {
            await this._channel.clearPermissions();
        });
    }
    async setGeolocation(geolocation) {
        return this._wrapApiCall('browserContext.setGeolocation', async () => {
            await this._channel.setGeolocation({ geolocation: geolocation || undefined });
        });
    }
    async setExtraHTTPHeaders(headers) {
        return this._wrapApiCall('browserContext.setExtraHTTPHeaders', async () => {
            network.validateHeaders(headers);
            await this._channel.setExtraHTTPHeaders({ headers: utils_1.headersObjectToArray(headers) });
        });
    }
    async setOffline(offline) {
        return this._wrapApiCall('browserContext.setOffline', async () => {
            await this._channel.setOffline({ offline });
        });
    }
    async setHTTPCredentials(httpCredentials) {
        if (!utils_1.isUnderTest())
            clientHelper_1.deprecate(`context.setHTTPCredentials`, `warning: method |context.setHTTPCredentials()| is deprecated. Instead of changing credentials, create another browser context with new credentials.`);
        return this._wrapApiCall('browserContext.setHTTPCredentials', async () => {
            await this._channel.setHTTPCredentials({ httpCredentials: httpCredentials || undefined });
        });
    }
    async addInitScript(script, arg) {
        return this._wrapApiCall('browserContext.addInitScript', async () => {
            const source = await clientHelper_1.evaluationScript(script, arg);
            await this._channel.addInitScript({ source });
        });
    }
    async exposeBinding(name, playwrightBinding, options = {}) {
        return this._wrapApiCall('browserContext.exposeBinding', async () => {
            await this._channel.exposeBinding({ name, needsHandle: options.handle });
            this._bindings.set(name, playwrightBinding);
        });
    }
    async exposeFunction(name, playwrightFunction) {
        return this._wrapApiCall('browserContext.exposeFunction', async () => {
            await this._channel.exposeBinding({ name });
            const binding = (source, ...args) => playwrightFunction(...args);
            this._bindings.set(name, binding);
        });
    }
    async route(url, handler) {
        return this._wrapApiCall('browserContext.route', async () => {
            this._routes.push({ url, handler });
            if (this._routes.length === 1)
                await this._channel.setNetworkInterceptionEnabled({ enabled: true });
        });
    }
    async unroute(url, handler) {
        return this._wrapApiCall('browserContext.unroute', async () => {
            this._routes = this._routes.filter(route => route.url !== url || (handler && route.handler !== handler));
            if (this._routes.length === 0)
                await this._channel.setNetworkInterceptionEnabled({ enabled: false });
        });
    }
    async waitForEvent(event, optionsOrPredicate = {}) {
        const timeout = this._timeoutSettings.timeout(typeof optionsOrPredicate === 'function' ? {} : optionsOrPredicate);
        const predicate = typeof optionsOrPredicate === 'function' ? optionsOrPredicate : optionsOrPredicate.predicate;
        const waiter = new waiter_1.Waiter();
        waiter.rejectOnTimeout(timeout, `Timeout while waiting for event "${event}"`);
        if (event !== events_1.Events.BrowserContext.Close)
            waiter.rejectOnEvent(this, events_1.Events.BrowserContext.Close, new Error('Context closed'));
        const result = await waiter.waitForEvent(this, event, predicate);
        waiter.dispose();
        return result;
    }
    async storageState(options = {}) {
        return await this._wrapApiCall('browserContext.storageState', async () => {
            const state = await this._channel.storageState();
            if (options.path) {
                await utils_1.mkdirIfNeeded(options.path);
                await fsWriteFileAsync(options.path, JSON.stringify(state), 'utf8');
            }
            return state;
        });
    }
    async _onClose() {
        if (this._browser)
            this._browser._contexts.delete(this);
        this.emit(events_1.Events.BrowserContext.Close);
    }
    async close() {
        try {
            await this._wrapApiCall('browserContext.close', async () => {
                await this._channel.close();
                await this._closedPromise;
            });
        }
        catch (e) {
            if (errors_1.isSafeCloseError(e))
                return;
            throw e;
        }
    }
    async _extendInjectedScript(source, arg) {
        await this._channel.extendInjectedScript({ source, arg: jsHandle_1.serializeArgument(arg) });
    }
}
exports.BrowserContext = BrowserContext;
async function prepareBrowserContextOptions(options) {
    if (options.videoSize && !options.videosPath)
        throw new Error(`"videoSize" option requires "videosPath" to be specified`);
    if (options.extraHTTPHeaders)
        network.validateHeaders(options.extraHTTPHeaders);
    const contextOptions = {
        ...options,
        viewport: options.viewport === null ? undefined : options.viewport,
        noDefaultViewport: options.viewport === null,
        extraHTTPHeaders: options.extraHTTPHeaders ? utils_1.headersObjectToArray(options.extraHTTPHeaders) : undefined,
        storageState: typeof options.storageState === 'string' ? JSON.parse(await fsReadFileAsync(options.storageState, 'utf8')) : options.storageState,
    };
    if (!contextOptions.recordVideo && options.videosPath) {
        contextOptions.recordVideo = {
            dir: options.videosPath,
            size: options.videoSize
        };
    }
    return contextOptions;
}
exports.prepareBrowserContextOptions = prepareBrowserContextOptions;
//# sourceMappingURL=browserContext.js.map