native-bridge.js

52.2 KB · raw

12/*! Capacitor: https://capacitorjs.com/ - MIT License */3/* Generated File. Do not edit. */45var nativeBridge = (function (exports) {6    'use strict';78    var ExceptionCode;9    (function (ExceptionCode) {10        /**11         * API is not implemented.12         *13         * This usually means the API can't be used because it is not implemented for14         * the current platform.15         */16        ExceptionCode["Unimplemented"] = "UNIMPLEMENTED";17        /**18         * API is not available.19         *20         * This means the API can't be used right now because:21         *   - it is currently missing a prerequisite, such as network connectivity22         *   - it requires a particular platform or browser version23         */24        ExceptionCode["Unavailable"] = "UNAVAILABLE";25    })(ExceptionCode || (ExceptionCode = {}));26    class CapacitorException extends Error {27        constructor(message, code, data) {28            super(message);29            this.message = message;30            this.code = code;31            this.data = data;32        }33    }3435    // For removing exports for iOS/Android, keep let for reassignment36    // eslint-disable-next-line37    let dummy = {};38    const readFileAsBase64 = (file) => new Promise((resolve, reject) => {39        const reader = new FileReader();40        reader.onloadend = () => {41            const data = reader.result;42            resolve(btoa(data));43        };44        reader.onerror = reject;45        reader.readAsBinaryString(file);46    });47    const convertFormData = async (formData) => {48        const newFormData = [];49        for (const pair of formData.entries()) {50            const [key, value] = pair;51            if (value instanceof File) {52                const base64File = await readFileAsBase64(value);53                newFormData.push({54                    key,55                    value: base64File,56                    type: 'base64File',57                    contentType: value.type,58                    fileName: value.name,59                });60            }61            else {62                newFormData.push({ key, value, type: 'string' });63            }64        }65        return newFormData;66    };67    const convertBody = async (body, contentType) => {68        if (body instanceof ReadableStream || body instanceof Uint8Array) {69            let encodedData;70            if (body instanceof ReadableStream) {71                const reader = body.getReader();72                const chunks = [];73                while (true) {74                    const { done, value } = await reader.read();75                    if (done)76                        break;77                    chunks.push(value);78                }79                const concatenated = new Uint8Array(chunks.reduce((acc, chunk) => acc + chunk.length, 0));80                let position = 0;81                for (const chunk of chunks) {82                    concatenated.set(chunk, position);83                    position += chunk.length;84                }85                encodedData = concatenated;86            }87            else {88                encodedData = body;89            }90            let data = new TextDecoder().decode(encodedData);91            let type;92            if (contentType === 'application/json') {93                try {94                    data = JSON.parse(data);95                }96                catch (ignored) {97                    // ignore98                }99                type = 'json';100            }101            else if (contentType === 'multipart/form-data') {102                type = 'formData';103            }104            else if (contentType === null || contentType === void 0 ? void 0 : contentType.startsWith('image')) {105                type = 'image';106            }107            else if (contentType === 'application/octet-stream') {108                type = 'binary';109            }110            else {111                type = 'text';112            }113            return {114                data,115                type,116                headers: { 'Content-Type': contentType || 'application/octet-stream' },117            };118        }119        else if (body instanceof URLSearchParams) {120            return {121                data: body.toString(),122                type: 'text',123            };124        }125        else if (body instanceof FormData) {126            return {127                data: await convertFormData(body),128                type: 'formData',129            };130        }131        else if (body instanceof File) {132            const fileData = await readFileAsBase64(body);133            return {134                data: fileData,135                type: 'file',136                headers: { 'Content-Type': body.type },137            };138        }139        return { data: body, type: 'json' };140    };141    const CAPACITOR_HTTP_INTERCEPTOR = '/_capacitor_http_interceptor_';142    const CAPACITOR_HTTP_INTERCEPTOR_URL_PARAM = 'u';143    // TODO: export as Cap function144    const isRelativeOrProxyUrl = (url) => !url || !(url.startsWith('http:') || url.startsWith('https:')) || url.indexOf(CAPACITOR_HTTP_INTERCEPTOR) > -1;145    // TODO: export as Cap function146    const createProxyUrl = (url, win) => {147        var _a, _b;148        if (isRelativeOrProxyUrl(url))149            return url;150        const bridgeUrl = new URL((_b = (_a = win.Capacitor) === null || _a === void 0 ? void 0 : _a.getServerUrl()) !== null && _b !== void 0 ? _b : '');151        bridgeUrl.pathname = CAPACITOR_HTTP_INTERCEPTOR;152        bridgeUrl.searchParams.append(CAPACITOR_HTTP_INTERCEPTOR_URL_PARAM, url);153        return bridgeUrl.toString();154    };155    const initBridge = (w) => {156        const getPlatformId = (win) => {157            var _a, _b;158            if (win === null || win === void 0 ? void 0 : win.androidBridge) {159                return 'android';160            }161            else if ((_b = (_a = win === null || win === void 0 ? void 0 : win.webkit) === null || _a === void 0 ? void 0 : _a.messageHandlers) === null || _b === void 0 ? void 0 : _b.bridge) {162                return 'ios';163            }164            else {165                return 'web';166            }167        };168        const convertFileSrcServerUrl = (webviewServerUrl, filePath) => {169            if (typeof filePath === 'string') {170                if (filePath.startsWith('/')) {171                    return webviewServerUrl + '/_capacitor_file_' + filePath;172                }173                else if (filePath.startsWith('file://')) {174                    return webviewServerUrl + filePath.replace('file://', '/_capacitor_file_');175                }176                else if (filePath.startsWith('content://')) {177                    return webviewServerUrl + filePath.replace('content:/', '/_capacitor_content_');178                }179            }180            return filePath;181        };182        const initEvents = (win, cap) => {183            cap.addListener = (pluginName, eventName, callback) => {184                const callbackId = cap.nativeCallback(pluginName, 'addListener', {185                    eventName: eventName,186                }, callback);187                return {188                    remove: async () => {189                        var _a;190                        (_a = win === null || win === void 0 ? void 0 : win.console) === null || _a === void 0 ? void 0 : _a.debug('Removing listener', pluginName, eventName);191                        cap.removeListener(pluginName, callbackId, eventName, callback);192                    },193                };194            };195            cap.removeListener = (pluginName, callbackId, eventName, callback) => {196                cap.nativeCallback(pluginName, 'removeListener', {197                    callbackId: callbackId,198                    eventName: eventName,199                }, callback);200            };201            cap.createEvent = (eventName, eventData) => {202                const doc = win.document;203                if (doc) {204                    const ev = doc.createEvent('Events');205                    ev.initEvent(eventName, false, false);206                    if (eventData && typeof eventData === 'object') {207                        for (const i in eventData) {208                            // eslint-disable-next-line no-prototype-builtins209                            if (eventData.hasOwnProperty(i)) {210                                ev[i] = eventData[i];211                            }212                        }213                    }214                    return ev;215                }216                return null;217            };218            cap.triggerEvent = (eventName, target, eventData) => {219                const doc = win.document;220                const cordova = win.cordova;221                eventData = eventData || {};222                const ev = cap.createEvent(eventName, eventData);223                if (ev) {224                    if (target === 'document') {225                        if (cordova === null || cordova === void 0 ? void 0 : cordova.fireDocumentEvent) {226                            cordova.fireDocumentEvent(eventName, eventData);227                            return true;228                        }229                        else if (doc === null || doc === void 0 ? void 0 : doc.dispatchEvent) {230                            return doc.dispatchEvent(ev);231                        }232                    }233                    else if (target === 'window' && win.dispatchEvent) {234                        return win.dispatchEvent(ev);235                    }236                    else if (doc === null || doc === void 0 ? void 0 : doc.querySelector) {237                        const targetEl = doc.querySelector(target);238                        if (targetEl) {239                            return targetEl.dispatchEvent(ev);240                        }241                    }242                }243                return false;244            };245            win.Capacitor = cap;246        };247        const initLegacyHandlers = (win, cap) => {248            // define cordova if it's not there already249            win.cordova = win.cordova || {};250            const doc = win.document;251            const nav = win.navigator;252            if (nav) {253                nav.app = nav.app || {};254                nav.app.exitApp = () => {255                    var _a;256                    if (!((_a = cap.Plugins) === null || _a === void 0 ? void 0 : _a.App)) {257                        win.console.warn('App plugin not installed');258                    }259                    else {260                        cap.nativeCallback('App', 'exitApp', {});261                    }262                };263            }264            if (doc) {265                const docAddEventListener = doc.addEventListener;266                doc.addEventListener = (...args) => {267                    var _a;268                    const eventName = args[0];269                    const handler = args[1];270                    if (eventName === 'deviceready' && handler) {271                        Promise.resolve().then(handler);272                    }273                    else if (eventName === 'backbutton' && cap.Plugins.App) {274                        // Add a dummy listener so Capacitor doesn't do the default275                        // back button action276                        if (!((_a = cap.Plugins) === null || _a === void 0 ? void 0 : _a.App)) {277                            win.console.warn('App plugin not installed');278                        }279                        else {280                            cap.Plugins.App.addListener('backButton', () => {281                                // ignore282                            });283                        }284                    }285                    return docAddEventListener.apply(doc, args);286                };287            }288            win.Capacitor = cap;289        };290        const initVendor = (win, cap) => {291            const Ionic = (win.Ionic = win.Ionic || {});292            const IonicWebView = (Ionic.WebView = Ionic.WebView || {});293            const Plugins = cap.Plugins;294            IonicWebView.getServerBasePath = (callback) => {295                var _a;296                (_a = Plugins === null || Plugins === void 0 ? void 0 : Plugins.WebView) === null || _a === void 0 ? void 0 : _a.getServerBasePath().then((result) => {297                    callback(result.path);298                });299            };300            IonicWebView.setServerAssetPath = (path) => {301                var _a;302                (_a = Plugins === null || Plugins === void 0 ? void 0 : Plugins.WebView) === null || _a === void 0 ? void 0 : _a.setServerAssetPath({ path });303            };304            IonicWebView.setServerBasePath = (path) => {305                var _a;306                (_a = Plugins === null || Plugins === void 0 ? void 0 : Plugins.WebView) === null || _a === void 0 ? void 0 : _a.setServerBasePath({ path });307            };308            IonicWebView.persistServerBasePath = () => {309                var _a;310                (_a = Plugins === null || Plugins === void 0 ? void 0 : Plugins.WebView) === null || _a === void 0 ? void 0 : _a.persistServerBasePath();311            };312            IonicWebView.convertFileSrc = (url) => cap.convertFileSrc(url);313            win.Capacitor = cap;314            win.Ionic.WebView = IonicWebView;315        };316        const initLogger = (win, cap) => {317            const BRIDGED_CONSOLE_METHODS = ['debug', 'error', 'info', 'log', 'trace', 'warn'];318            const createLogFromNative = (c) => (result) => {319                if (isFullConsole(c)) {320                    const success = result.success === true;321                    const tagStyles = success322                        ? 'font-style: italic; font-weight: lighter; color: gray'323                        : 'font-style: italic; font-weight: lighter; color: red';324                    c.groupCollapsed('%cresult %c' + result.pluginId + '.' + result.methodName + ' (#' + result.callbackId + ')', tagStyles, 'font-style: italic; font-weight: bold; color: #444');325                    if (result.success === false) {326                        c.error(result.error);327                    }328                    else {329                        c.dir(JSON.stringify(result.data));330                    }331                    c.groupEnd();332                }333                else {334                    if (result.success === false) {335                        c.error('LOG FROM NATIVE', result.error);336                    }337                    else {338                        c.log('LOG FROM NATIVE', result.data);339                    }340                }341            };342            const createLogToNative = (c) => (call) => {343                if (isFullConsole(c)) {344                    c.groupCollapsed('%cnative %c' + call.pluginId + '.' + call.methodName + ' (#' + call.callbackId + ')', 'font-weight: lighter; color: gray', 'font-weight: bold; color: #000');345                    c.dir(call);346                    c.groupEnd();347                }348                else {349                    c.log('LOG TO NATIVE: ', call);350                }351            };352            const isFullConsole = (c) => {353                if (!c) {354                    return false;355                }356                return typeof c.groupCollapsed === 'function' || typeof c.groupEnd === 'function' || typeof c.dir === 'function';357            };358            const serializeConsoleMessage = (msg) => {359                try {360                    if (typeof msg === 'object') {361                        msg = JSON.stringify(msg);362                    }363                    return String(msg);364                }365                catch (e) {366                    return '';367                }368            };369            const platform = getPlatformId(win);370            if (platform == 'android' && typeof win.CapacitorSystemBarsAndroidInterface !== 'undefined') {371                // add DOM ready listener for System Bars372                document.addEventListener('DOMContentLoaded', function () {373                    win.CapacitorSystemBarsAndroidInterface.onDOMReady();374                });375            }376            if (platform == 'android' || platform == 'ios') {377                // patch document.cookie on Android/iOS378                win.CapacitorCookiesDescriptor =379                    Object.getOwnPropertyDescriptor(Document.prototype, 'cookie') ||380                        Object.getOwnPropertyDescriptor(HTMLDocument.prototype, 'cookie');381                let doPatchCookies = false;382                // check if capacitor cookies is disabled before patching383                if (platform === 'ios') {384                    // Use prompt to synchronously get capacitor cookies config.385                    // https://stackoverflow.com/questions/29249132/wkwebview-complex-communication-between-javascript-native-code/49474323#49474323386                    const payload = {387                        type: 'CapacitorCookies.isEnabled',388                    };389                    const isCookiesEnabled = prompt(JSON.stringify(payload));390                    if (isCookiesEnabled === 'true') {391                        doPatchCookies = true;392                    }393                }394                else if (typeof win.CapacitorCookiesAndroidInterface !== 'undefined') {395                    const isCookiesEnabled = win.CapacitorCookiesAndroidInterface.isEnabled();396                    if (isCookiesEnabled === true) {397                        doPatchCookies = true;398                    }399                }400                if (doPatchCookies) {401                    Object.defineProperty(document, 'cookie', {402                        get: function () {403                            var _a, _b, _c;404                            if (platform === 'ios') {405                                // Use prompt to synchronously get cookies.406                                // https://stackoverflow.com/questions/29249132/wkwebview-complex-communication-between-javascript-native-code/49474323#49474323407                                const payload = {408                                    type: 'CapacitorCookies.get',409                                };410                                const res = prompt(JSON.stringify(payload));411                                return res;412                            }413                            else if (typeof win.CapacitorCookiesAndroidInterface !== 'undefined') {414                                // return original document.cookie since Android does not support filtering of `httpOnly` cookies415                                return (_c = (_b = (_a = win.CapacitorCookiesDescriptor) === null || _a === void 0 ? void 0 : _a.get) === null || _b === void 0 ? void 0 : _b.call(document)) !== null && _c !== void 0 ? _c : '';416                            }417                        },418                        set: function (val) {419                            const cookiePairs = val.split(';');420                            const domainSection = val.toLowerCase().split('domain=')[1];421                            const domain = cookiePairs.length > 1 && domainSection != null && domainSection.length > 0422                                ? domainSection.split(';')[0].trim()423                                : '';424                            if (platform === 'ios') {425                                // Use prompt to synchronously set cookies.426                                // https://stackoverflow.com/questions/29249132/wkwebview-complex-communication-between-javascript-native-code/49474323#49474323427                                const payload = {428                                    type: 'CapacitorCookies.set',429                                    action: val,430                                    domain,431                                };432                                prompt(JSON.stringify(payload));433                            }434                            else if (typeof win.CapacitorCookiesAndroidInterface !== 'undefined') {435                                win.CapacitorCookiesAndroidInterface.setCookie(domain, val);436                            }437                        },438                    });439                }440                // patch fetch / XHR on Android/iOS441                // store original fetch & XHR functions442                win.CapacitorWebFetch = window.fetch;443                win.CapacitorWebXMLHttpRequest = {444                    abort: window.XMLHttpRequest.prototype.abort,445                    constructor: window.XMLHttpRequest.prototype.constructor,446                    fullObject: window.XMLHttpRequest,447                    getAllResponseHeaders: window.XMLHttpRequest.prototype.getAllResponseHeaders,448                    getResponseHeader: window.XMLHttpRequest.prototype.getResponseHeader,449                    open: window.XMLHttpRequest.prototype.open,450                    prototype: window.XMLHttpRequest.prototype,451                    send: window.XMLHttpRequest.prototype.send,452                    setRequestHeader: window.XMLHttpRequest.prototype.setRequestHeader,453                };454                let doPatchHttp = false;455                // check if capacitor http is disabled before patching456                if (platform === 'ios') {457                    // Use prompt to synchronously get capacitor http config.458                    // https://stackoverflow.com/questions/29249132/wkwebview-complex-communication-between-javascript-native-code/49474323#49474323459                    const payload = {460                        type: 'CapacitorHttp',461                    };462                    const isHttpEnabled = prompt(JSON.stringify(payload));463                    if (isHttpEnabled === 'true') {464                        doPatchHttp = true;465                    }466                }467                else if (typeof win.CapacitorHttpAndroidInterface !== 'undefined') {468                    const isHttpEnabled = win.CapacitorHttpAndroidInterface.isEnabled();469                    if (isHttpEnabled === true) {470                        doPatchHttp = true;471                    }472                }473                if (doPatchHttp) {474                    // fetch patch475                    window.fetch = async (resource, options) => {476                        const headers = new Headers(options === null || options === void 0 ? void 0 : options.headers);477                        const contentType = headers.get('Content-Type') || headers.get('content-type');478                        if ((options === null || options === void 0 ? void 0 : options.body) instanceof FormData &&479                            (contentType === null || contentType === void 0 ? void 0 : contentType.includes('multipart/form-data')) &&480                            !contentType.includes('boundary')) {481                            headers.delete('Content-Type');482                            headers.delete('content-type');483                            options.headers = headers;484                        }485                        const request = new Request(resource, options);486                        if (request.url.startsWith(`${cap.getServerUrl()}/`)) {487                            return win.CapacitorWebFetch(resource, options);488                        }489                        const { method } = request;490                        if (method.toLocaleUpperCase() === 'GET' ||491                            method.toLocaleUpperCase() === 'HEAD' ||492                            method.toLocaleUpperCase() === 'OPTIONS' ||493                            method.toLocaleUpperCase() === 'TRACE') {494                            // a workaround for following android webview issue:495                            // https://issues.chromium.org/issues/40450316496                            // Sets the user-agent header to a custom value so that its not stripped497                            // on its way to the native layer498                            if (platform === 'android' && (options === null || options === void 0 ? void 0 : options.headers)) {499                                const userAgent = headers.get('User-Agent') || headers.get('user-agent');500                                if (userAgent !== null) {501                                    headers.set('x-cap-user-agent', userAgent);502                                    options.headers = headers;503                                }504                            }505                            if (typeof resource === 'string') {506                                return await win.CapacitorWebFetch(createProxyUrl(resource, win), options);507                            }508                            else if (resource instanceof URL) {509                                const modifiedURL = new URL(createProxyUrl(resource.toString(), win));510                                return await win.CapacitorWebFetch(modifiedURL, options);511                            }512                            else if (resource instanceof Request) {513                                const modifiedRequest = new Request(createProxyUrl(resource.url, win), resource);514                                return await win.CapacitorWebFetch(modifiedRequest, options);515                            }516                        }517                        const tag = `CapacitorHttp fetch ${Date.now()} ${resource}`;518                        console.time(tag);519                        try {520                            const { body } = request;521                            const optionHeaders = Object.fromEntries(request.headers.entries());522                            const { data: requestData, type, headers: requestHeaders, } = await convertBody((options === null || options === void 0 ? void 0 : options.body) || body || undefined, optionHeaders['Content-Type'] || optionHeaders['content-type']);523                            const nativeHeaders = Object.assign(Object.assign({}, requestHeaders), optionHeaders);524                            if (platform === 'android') {525                                if (headers.has('User-Agent')) {526                                    nativeHeaders['User-Agent'] = headers.get('User-Agent');527                                }528                                if (headers.has('user-agent')) {529                                    nativeHeaders['user-agent'] = headers.get('user-agent');530                                }531                            }532                            const nativeResponse = await cap.nativePromise('CapacitorHttp', 'request', {533                                url: request.url,534                                method: method,535                                data: requestData,536                                dataType: type,537                                headers: nativeHeaders,538                            });539                            const contentType = nativeResponse.headers['Content-Type'] || nativeResponse.headers['content-type'];540                            let data = (contentType === null || contentType === void 0 ? void 0 : contentType.startsWith('application/json'))541                                ? JSON.stringify(nativeResponse.data)542                                : nativeResponse.data;543                            // use null data for 204 No Content HTTP response544                            if (nativeResponse.status === 204) {545                                data = null;546                            }547                            // intercept & parse response before returning548                            const response = new Response(data, {549                                headers: nativeResponse.headers,550                                status: nativeResponse.status,551                            });552                            /*553                             * copy url to response, `cordova-plugin-ionic` uses this url from the response554                             * we need `Object.defineProperty` because url is an inherited getter on the Response555                             * see: https://stackoverflow.com/a/57382543556                             * */557                            Object.defineProperty(response, 'url', {558                                value: nativeResponse.url,559                            });560                            console.timeEnd(tag);561                            return response;562                        }563                        catch (error) {564                            console.timeEnd(tag);565                            return Promise.reject(error);566                        }567                    };568                    window.XMLHttpRequest = function () {569                        const xhr = new win.CapacitorWebXMLHttpRequest.constructor();570                        Object.defineProperties(xhr, {571                            _headers: {572                                value: {},573                                writable: true,574                            },575                            _method: {576                                value: xhr.method,577                                writable: true,578                            },579                        });580                        const prototype = win.CapacitorWebXMLHttpRequest.prototype;581                        const isProgressEventAvailable = () => typeof ProgressEvent !== 'undefined' && ProgressEvent.prototype instanceof Event;582                        // XHR patch abort583                        prototype.abort = function () {584                            if (isRelativeOrProxyUrl(this._url)) {585                                return win.CapacitorWebXMLHttpRequest.abort.call(this);586                            }587                            this.readyState = 0;588                            setTimeout(() => {589                                this.dispatchEvent(new Event('abort'));590                                this.dispatchEvent(new Event('loadend'));591                            });592                        };593                        // XHR patch open594                        prototype.open = function (method, url) {595                            this._method = method.toLocaleUpperCase();596                            this._url = url;597                            if (!this._method ||598                                this._method === 'GET' ||599                                this._method === 'HEAD' ||600                                this._method === 'OPTIONS' ||601                                this._method === 'TRACE') {602                                if (isRelativeOrProxyUrl(url)) {603                                    return win.CapacitorWebXMLHttpRequest.open.call(this, method, url);604                                }605                                this._url = createProxyUrl(this._url, win);606                                return win.CapacitorWebXMLHttpRequest.open.call(this, method, this._url);607                            }608                            Object.defineProperties(this, {609                                readyState: {610                                    get: function () {611                                        var _a;612                                        return (_a = this._readyState) !== null && _a !== void 0 ? _a : 0;613                                    },614                                    set: function (val) {615                                        this._readyState = val;616                                        setTimeout(() => {617                                            this.dispatchEvent(new Event('readystatechange'));618                                        });619                                    },620                                },621                            });622                            setTimeout(() => {623                                this.dispatchEvent(new Event('loadstart'));624                            });625                            this.readyState = 1;626                        };627                        // XHR patch set request header628                        prototype.setRequestHeader = function (header, value) {629                            // a workaround for the following android web view issue:630                            // https://issues.chromium.org/issues/40450316631                            // Sets the user-agent header to a custom value so that its not stripped632                            // on its way to the native layer633                            if (platform === 'android' && (header === 'User-Agent' || header === 'user-agent')) {634                                header = 'x-cap-user-agent';635                            }636                            if (isRelativeOrProxyUrl(this._url)) {637                                return win.CapacitorWebXMLHttpRequest.setRequestHeader.call(this, header, value);638                            }639                            this._headers[header] = value;640                        };641                        // XHR patch send642                        prototype.send = function (body) {643                            if (isRelativeOrProxyUrl(this._url)) {644                                return win.CapacitorWebXMLHttpRequest.send.call(this, body);645                            }646                            const tag = `CapacitorHttp XMLHttpRequest ${Date.now()} ${this._url}`;647                            console.time(tag);648                            try {649                                this.readyState = 2;650                                Object.defineProperties(this, {651                                    response: {652                                        value: '',653                                        writable: true,654                                    },655                                    responseText: {656                                        value: '',657                                        writable: true,658                                    },659                                    responseURL: {660                                        value: '',661                                        writable: true,662                                    },663                                    status: {664                                        value: 0,665                                        writable: true,666                                    },667                                });668                                convertBody(body).then(({ data, type, headers }) => {669                                    let otherHeaders = this._headers != null && Object.keys(this._headers).length > 0 ? this._headers : undefined;670                                    if (body instanceof FormData) {671                                        if (!this._headers['Content-Type'] && !this._headers['content-type']) {672                                            otherHeaders = Object.assign(Object.assign({}, otherHeaders), { 'Content-Type': `multipart/form-data; boundary=----WebKitFormBoundary${Math.random().toString(36).substring(2, 15)}` });673                                        }674                                    }675                                    // intercept request & pass to the bridge676                                    cap677                                        .nativePromise('CapacitorHttp', 'request', {678                                        url: this._url,679                                        method: this._method,680                                        data: data !== null ? data : undefined,681                                        headers: Object.assign(Object.assign({}, headers), otherHeaders),682                                        dataType: type,683                                    })684                                        .then((nativeResponse) => {685                                        var _a;686                                        // intercept & parse response before returning687                                        if (this.readyState == 2) {688                                            //TODO: Add progress event emission on native side689                                            if (isProgressEventAvailable()) {690                                                this.dispatchEvent(new ProgressEvent('progress', {691                                                    lengthComputable: true,692                                                    loaded: nativeResponse.data.length,693                                                    total: nativeResponse.data.length,694                                                }));695                                            }696                                            this._headers = nativeResponse.headers;697                                            this.status = nativeResponse.status;698                                            if (this.responseType === '' || this.responseType === 'text') {699                                                this.response =700                                                    typeof nativeResponse.data !== 'string'701                                                        ? JSON.stringify(nativeResponse.data)702                                                        : nativeResponse.data;703                                            }704                                            else {705                                                this.response = nativeResponse.data;706                                            }707                                            this.responseText = ((_a = (nativeResponse.headers['Content-Type'] || nativeResponse.headers['content-type'])) === null || _a === void 0 ? void 0 : _a.startsWith('application/json'))708                                                ? JSON.stringify(nativeResponse.data)709                                                : nativeResponse.data;710                                            this.responseURL = nativeResponse.url;711                                            this.readyState = 4;712                                            setTimeout(() => {713                                                this.dispatchEvent(new Event('load'));714                                                this.dispatchEvent(new Event('loadend'));715                                            });716                                        }717                                        console.timeEnd(tag);718                                    })719                                        .catch((error) => {720                                        this.status = error.status;721                                        this._headers = error.headers;722                                        this.response = error.data;723                                        this.responseText = JSON.stringify(error.data);724                                        this.responseURL = error.url;725                                        this.readyState = 4;726                                        if (isProgressEventAvailable()) {727                                            this.dispatchEvent(new ProgressEvent('progress', {728                                                lengthComputable: false,729                                                loaded: 0,730                                                total: 0,731                                            }));732                                        }733                                        setTimeout(() => {734                                            this.dispatchEvent(new Event('error'));735                                            this.dispatchEvent(new Event('loadend'));736                                        });737                                        console.timeEnd(tag);738                                    });739                                });740                            }741                            catch (error) {742                                this.status = 500;743                                this._headers = {};744                                this.response = error;745                                this.responseText = error.toString();746                                this.responseURL = this._url;747                                this.readyState = 4;748                                if (isProgressEventAvailable()) {749                                    this.dispatchEvent(new ProgressEvent('progress', {750                                        lengthComputable: false,751                                        loaded: 0,752                                        total: 0,753                                    }));754                                }755                                setTimeout(() => {756                                    this.dispatchEvent(new Event('error'));757                                    this.dispatchEvent(new Event('loadend'));758                                });759                                console.timeEnd(tag);760                            }761                        };762                        // XHR patch getAllResponseHeaders763                        prototype.getAllResponseHeaders = function () {764                            if (isRelativeOrProxyUrl(this._url)) {765                                return win.CapacitorWebXMLHttpRequest.getAllResponseHeaders.call(this);766                            }767                            let returnString = '';768                            for (const key in this._headers) {769                                if (key != 'Set-Cookie') {770                                    returnString += key + ': ' + this._headers[key] + '\r\n';771                                }772                            }773                            return returnString;774                        };775                        // XHR patch getResponseHeader776                        prototype.getResponseHeader = function (name) {777                            if (isRelativeOrProxyUrl(this._url)) {778                                return win.CapacitorWebXMLHttpRequest.getResponseHeader.call(this, name);779                            }780                            return this._headers[name];781                        };782                        Object.setPrototypeOf(xhr, prototype);783                        return xhr;784                    };785                    Object.assign(window.XMLHttpRequest, win.CapacitorWebXMLHttpRequest.fullObject);786                }787            }788            // patch window.console on iOS and store original console fns789            const isIos = getPlatformId(win) === 'ios';790            if (win.console && isIos) {791                Object.defineProperties(win.console, BRIDGED_CONSOLE_METHODS.reduce((props, method) => {792                    const consoleMethod = win.console[method].bind(win.console);793                    props[method] = {794                        value: (...args) => {795                            const msgs = [...args];796                            cap.toNative('Console', 'log', {797                                level: method,798                                message: msgs.map(serializeConsoleMessage).join(' '),799                            });800                            return consoleMethod(...args);801                        },802                    };803                    return props;804                }, {}));805            }806            cap.logJs = (msg, level) => {807                switch (level) {808                    case 'error':809                        win.console.error(msg);810                        break;811                    case 'warn':812                        win.console.warn(msg);813                        break;814                    case 'info':815                        win.console.info(msg);816                        break;817                    default:818                        win.console.log(msg);819                }820            };821            cap.logToNative = createLogToNative(win.console);822            cap.logFromNative = createLogFromNative(win.console);823            cap.handleError = (err) => win.console.error(err);824            win.Capacitor = cap;825        };826        function initNativeBridge(win) {827            const cap = win.Capacitor || {};828            // keep a collection of callbacks for native response data829            const callbacks = new Map();830            const webviewServerUrl = typeof win.WEBVIEW_SERVER_URL === 'string' ? win.WEBVIEW_SERVER_URL : '';831            cap.getServerUrl = () => webviewServerUrl;832            cap.convertFileSrc = (filePath) => convertFileSrcServerUrl(webviewServerUrl, filePath);833            // Counter of callback ids, randomized to avoid834            // any issues during reloads if a call comes back with835            // an existing callback id from an old session836            let callbackIdCount = Math.floor(Math.random() * 134217728);837            let postToNative = null;838            const isNativePlatform = () => true;839            const getPlatform = () => getPlatformId(win);840            cap.getPlatform = getPlatform;841            cap.isPluginAvailable = (name) => Object.prototype.hasOwnProperty.call(cap.Plugins, name);842            cap.isNativePlatform = isNativePlatform;843            // create the postToNative() fn if needed844            if (getPlatformId(win) === 'android') {845                // android platform846                postToNative = (data) => {847                    var _a;848                    try {849                        win.androidBridge.postMessage(JSON.stringify(data));850                    }851                    catch (e) {852                        (_a = win === null || win === void 0 ? void 0 : win.console) === null || _a === void 0 ? void 0 : _a.error(e);853                    }854                };855            }856            else if (getPlatformId(win) === 'ios') {857                // ios platform858                postToNative = (data) => {859                    var _a;860                    try {861                        data.type = data.type ? data.type : 'message';862                        win.webkit.messageHandlers.bridge.postMessage(data);863                    }864                    catch (e) {865                        (_a = win === null || win === void 0 ? void 0 : win.console) === null || _a === void 0 ? void 0 : _a.error(e);866                    }867                };868            }869            cap.handleWindowError = (msg, url, lineNo, columnNo, err) => {870                const str = msg.toLowerCase();871                if (str.indexOf('script error') > -1) ;872                else {873                    const errObj = {874                        type: 'js.error',875                        error: {876                            message: msg,877                            url: url,878                            line: lineNo,879                            col: columnNo,880                            errorObject: JSON.stringify(err),881                        },882                    };883                    if (err !== null) {884                        cap.handleError(err);885                    }886                    postToNative(errObj);887                }888                return false;889            };890            if (cap.DEBUG) {891                window.onerror = cap.handleWindowError;892            }893            initLogger(win, cap);894            /**895             * Send a plugin method call to the native layer896             */897            cap.toNative = (pluginName, methodName, options, storedCallback) => {898                var _a, _b;899                try {900                    if (typeof postToNative === 'function') {901                        let callbackId = '-1';902                        if (storedCallback &&903                            (typeof storedCallback.callback === 'function' || typeof storedCallback.resolve === 'function')) {904                            // store the call for later lookup905                            callbackId = String(++callbackIdCount);906                            callbacks.set(callbackId, storedCallback);907                        }908                        const callData = {909                            callbackId: callbackId,910                            pluginId: pluginName,911                            methodName: methodName,912                            options: options || {},913                        };914                        if (cap.isLoggingEnabled && pluginName !== 'Console') {915                            cap.logToNative(callData);916                        }917                        // post the call data to native918                        postToNative(callData);919                        return callbackId;920                    }921                    else {922                        (_a = win === null || win === void 0 ? void 0 : win.console) === null || _a === void 0 ? void 0 : _a.warn(`implementation unavailable for: ${pluginName}`);923                    }924                }925                catch (e) {926                    (_b = win === null || win === void 0 ? void 0 : win.console) === null || _b === void 0 ? void 0 : _b.error(e);927                }928                return null;929            };930            if (win === null || win === void 0 ? void 0 : win.androidBridge) {931                win.androidBridge.onmessage = function (event) {932                    returnResult(JSON.parse(event.data));933                };934            }935            /**936             * Process a response from the native layer.937             */938            cap.fromNative = (result) => {939                returnResult(result);940            };941            const returnResult = (result) => {942                var _a, _b;943                if (cap.isLoggingEnabled && result.pluginId !== 'Console') {944                    cap.logFromNative(result);945                }946                // get the stored call, if it exists947                try {948                    const storedCall = callbacks.get(result.callbackId);949                    if (storedCall) {950                        // looks like we've got a stored call951                        if (result.error) {952                            // ensure stacktraces by copying error properties to an Error953                            result.error = Object.keys(result.error).reduce((err, key) => {954                                // use any type to avoid importing util and compiling most of .ts files955                                err[key] = result.error[key];956                                return err;957                            }, new cap.Exception(''));958                        }959                        if (typeof storedCall.callback === 'function') {960                            // callback961                            if (result.success) {962                                storedCall.callback(result.data);963                            }964                            else {965                                storedCall.callback(null, result.error);966                            }967                        }968                        else if (typeof storedCall.resolve === 'function') {969                            // promise970                            if (result.success) {971                                storedCall.resolve(result.data);972                            }973                            else {974                                storedCall.reject(result.error);975                            }976                            // no need to keep this stored callback977                            // around for a one time resolve promise978                            callbacks.delete(result.callbackId);979                        }980                    }981                    else if (!result.success && result.error) {982                        // no stored callback, but if there was an error let's log it983                        (_a = win === null || win === void 0 ? void 0 : win.console) === null || _a === void 0 ? void 0 : _a.warn(result.error);984                    }985                    if (result.save === false) {986                        callbacks.delete(result.callbackId);987                    }988                }989                catch (e) {990                    (_b = win === null || win === void 0 ? void 0 : win.console) === null || _b === void 0 ? void 0 : _b.error(e);991                }992                // always delete to prevent memory leaks993                // overkill but we're not sure what apps will do with this data994                delete result.data;995                delete result.error;996            };997            cap.nativeCallback = (pluginName, methodName, options, callback) => {998                if (typeof options === 'function') {999                    console.warn(`Using a callback as the 'options' parameter of 'nativeCallback()' is deprecated.`);1000                    callback = options;1001                    options = null;1002                }1003                return cap.toNative(pluginName, methodName, options, { callback });1004            };1005            cap.nativePromise = (pluginName, methodName, options) => {1006                return new Promise((resolve, reject) => {1007                    cap.toNative(pluginName, methodName, options, {1008                        resolve: resolve,1009                        reject: reject,1010                    });1011                });1012            };1013            // eslint-disable-next-line @typescript-eslint/no-unused-vars1014            cap.withPlugin = (_pluginId, _fn) => dummy;1015            cap.Exception = CapacitorException;1016            initEvents(win, cap);1017            initLegacyHandlers(win, cap);1018            initVendor(win, cap);1019            win.Capacitor = cap;1020        }1021        initNativeBridge(w);1022    };1023    initBridge(typeof globalThis !== 'undefined'1024        ? globalThis1025        : typeof self !== 'undefined'1026            ? self1027            : typeof window !== 'undefined'1028                ? window1029                : typeof global !== 'undefined'1030                    ? global1031                    : {});10321033    dummy = initBridge;10341035    Object.defineProperty(exports, '__esModule', { value: true });10361037    return exports;10381039})({});