"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SelectNetworkResources = void 0;
const url_1 = __importDefault(require("url"));
const index_js_1 = require("../model/index.js");
const util = __importStar(require("../util/index.js"));
class SelectNetworkResources extends index_js_1.Pipe {
    constructor() {
        super(...arguments);
        this.resourceType = '*';
        this.statusCode = '2xx';
        this.method = '*';
        this.hostnameRegexp = '.*';
        this.pathnameRegexp = '.*';
        this.requestBodyFormat = 'none';
        this.responseBodyFormat = 'none';
    }
    async apply(inputSet, _ctx) {
        const results = [];
        for (const el of inputSet) {
            const resources = await this.collectNetworkResults(el);
            for (const res of resources) {
                results.push(el.clone(res));
            }
        }
        return results;
    }
    async collectNetworkResults(el) {
        const resourceType = this.resourceType;
        const statusCode = this.statusCode;
        const method = this.method;
        const hostnameRegexp = this.hostnameRegexp;
        const pathnameRegexp = this.pathnameRegexp;
        const requestBodyFormat = this.requestBodyFormat;
        const responseBodyFormat = this.responseBodyFormat;
        const resources = el.remote.page.networkManager.getCollectedResources();
        const results = [];
        for (const rs of resources) {
            const { requestId, request, response } = rs;
            if (rs.status !== 'loadingFinished' || !response) {
                continue;
            }
            if (resourceType !== '*' && rs.type !== resourceType) {
                continue;
            }
            if (method !== '*' && request.method !== method) {
                continue;
            }
            if (!this.matchStatusCode(statusCode, response.status)) {
                continue;
            }
            const url = url_1.default.parse(request.url);
            if (!new RegExp(`^${hostnameRegexp}$`).test(url.hostname || '')) {
                continue;
            }
            if (!new RegExp(`^${pathnameRegexp}$`).test(url.pathname || '')) {
                continue;
            }
            const requestBody = await this.readRequestBody(rs, requestBodyFormat);
            const responseBody = await this.readResponseBody(rs, responseBodyFormat);
            results.push({
                requestId,
                request: {
                    url: request.url,
                    method: request.method,
                    headers: request.headers,
                    body: requestBody,
                },
                response: {
                    url: response.url,
                    status: response.status,
                    statusText: response.statusText,
                    headers: response.headers,
                    body: responseBody,
                },
            });
        }
        return results;
    }
    async readRequestBody(rs, requestBodyFormat) {
        const { postData } = rs.request;
        if (!postData) {
            return null;
        }
        const buffer = Buffer.from(postData, 'utf-8');
        return await util.parseBodyData(buffer, requestBodyFormat);
    }
    async readResponseBody(rs, responseBodyFormat) {
        try {
            const buffer = await this.$page.networkManager.getResponseBody(rs.requestId);
            return util.parseBodyData(buffer, responseBodyFormat);
        }
        catch (err) {
            return null;
        }
    }
    matchStatusCode(pattern, status) {
        switch (pattern) {
            case '*':
                return true;
            case '2xx':
                return status >= 200 && status < 300;
            case '3xx':
                return status >= 300 && status < 400;
            case '4xx':
                return status >= 400 && status < 500;
            case '5xx':
                return status >= 500;
            default:
                return Number(pattern) === status;
        }
    }
}
SelectNetworkResources.$type = 'Browser.selectNetworkResources';
SelectNetworkResources.$help = `
Returns information about network requests and responses that match specified filters.

### Use For

- extracting data from ongoing network requests
`;
__decorate([
    index_js_1.params.Enum({
        enum: [
            '*',
            'XHR',
            'Fetch',
            'Document',
            'Stylesheet',
            'Image',
            'Media',
            'Font',
            'Script',
            'TextTrack',
            'EventSource',
            'WebSocket',
            'Manifest',
            'SignedExchange',
            'Other',
        ],
        help: 'Filter by resource type (XHR and Fetch are most commonly used).',
    }),
    __metadata("design:type", String)
], SelectNetworkResources.prototype, "resourceType", void 0);
__decorate([
    index_js_1.params.Enum({
        enum: ['*', '2xx', '3xx', '4xx', '5xx', '200', '201', '203', '204', '205', '206', '300', '301', '302'],
        help: 'Filter by response status code.',
    }),
    __metadata("design:type", String)
], SelectNetworkResources.prototype, "statusCode", void 0);
__decorate([
    index_js_1.params.Enum({
        enum: ['*', 'GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
        help: 'Filter by request method.',
    }),
    __metadata("design:type", String)
], SelectNetworkResources.prototype, "method", void 0);
__decorate([
    index_js_1.params.String({
        help: 'Flob filter by hostname (* matches hostnames).',
    }),
    __metadata("design:type", String)
], SelectNetworkResources.prototype, "hostnameRegexp", void 0);
__decorate([
    index_js_1.params.String({
        help: 'Flob filter by request pathname (/** matches all pathnames).',
    }),
    __metadata("design:type", String)
], SelectNetworkResources.prototype, "pathnameRegexp", void 0);
__decorate([
    index_js_1.params.Enum({
        enum: ['none', 'json', 'urlencoded', 'text', 'base64'],
        help: `
If specified, the result will include parsed request body
(consider omitting if accessing request body is not required).
`,
    }),
    __metadata("design:type", String)
], SelectNetworkResources.prototype, "requestBodyFormat", void 0);
__decorate([
    index_js_1.params.Enum({
        enum: ['none', 'json', 'urlencoded', 'text', 'base64'],
        help: `
If specified, the result will include parsed response body
(consider omitting if accessing response body is not required).
`,
    }),
    __metadata("design:type", String)
], SelectNetworkResources.prototype, "responseBodyFormat", void 0);
exports.SelectNetworkResources = SelectNetworkResources;
//# sourceMappingURL=Browser.selectNetworkResources.js.map