"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TEST_CONFIG_URL_PARAM_KEY = void 0;
exports.isNode = isNode;
exports.b64DecodeUnicodeInNode = b64DecodeUnicodeInNode;
exports.b64EncodeUnicodeInNode = b64EncodeUnicodeInNode;
exports.b64DecodeUnicodeNodeOrBrowser = b64DecodeUnicodeNodeOrBrowser;
exports.encodeTestConfigAsParamsForParsedUrlProtocol = encodeTestConfigAsParamsForParsedUrlProtocol;
exports.decodeTestConfigAsParamsForParsedUrlProtocol = decodeTestConfigAsParamsForParsedUrlProtocol;
const querystring_1 = __importDefault(require("querystring"));
const mablscriptFind_1 = require("@mablhq/test-model/mablscriptFind");
const MAX_PARSED_URL_PROTOCOL_PARAMS_LENGTH = 2000;
exports.TEST_CONFIG_URL_PARAM_KEY = 'scriptConfig';
function isNode() {
    return !!process?.versions?.node;
}
function b64DecodeUnicodeInNode(encoded) {
    return Buffer.from(encoded, 'base64').toString();
}
function b64EncodeUnicodeInNode(text) {
    return Buffer.from(text).toString('base64');
}
function b64DecodeUnicodeNodeOrBrowser(encoded) {
    if (isNode()) {
        return b64DecodeUnicodeInNode(encoded);
    }
    return (0, mablscriptFind_1.b64DecodeUnicode)(encoded);
}
function encodeTestConfigAsParamsForParsedUrlProtocol(testConfig, b64Encode, enforceSize = true) {
    const encoded = querystring_1.default.stringify({
        ...testConfig,
        [exports.TEST_CONFIG_URL_PARAM_KEY]: b64Encode(JSON.stringify(testConfig)),
    });
    if (encoded.length > MAX_PARSED_URL_PROTOCOL_PARAMS_LENGTH && enforceSize) {
        throw new Error('Test parameters exceed size limit. Please use the mabl Desktop App to create or edit tests.');
    }
    return encoded;
}
function decodeTestConfigAsParamsForParsedUrlProtocol(encoded, b64Decode, useV2) {
    const params = querystring_1.default.parse(encoded);
    if (useV2 && params[exports.TEST_CONFIG_URL_PARAM_KEY]) {
        return JSON.parse(b64Decode(params[exports.TEST_CONFIG_URL_PARAM_KEY]));
    }
    delete params[exports.TEST_CONFIG_URL_PARAM_KEY];
    return params;
}
