function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import json from "../../package.json";
import { LogComplianceProcessor } from "../foundation/service/log/processor";
import { SPM_MAP } from "./spm-map";
export var Logger = /*#__PURE__*/function () {
  function Logger(config, debug) {
    _classCallCheck(this, Logger);
    _defineProperty(this, "logs", void 0);
    _defineProperty(this, "config", void 0);
    _defineProperty(this, "debug", void 0);
    _defineProperty(this, "componentStartTime", void 0);
    _defineProperty(this, "isLoaded", void 0);
    _defineProperty(this, "trackId", void 0);
    this.logs = [];
    this.config = config;
    this.debug = debug;
    this.componentStartTime = 0;
    this.isLoaded = false;
  }
  _createClass(Logger, [{
    key: "setMedta",
    value: function setMedta(mdata) {
      var _window,
        _this = this;
      this.config.mdata = Object.assign(this.config.mdata, mdata);
      if ((_window = window) !== null && _window !== void 0 && _window.iTracker) {
        var _window2;
        (_window2 = window) === null || _window2 === void 0 || (_window2 = _window2.iTracker) === null || _window2 === void 0 || _window2.set({
          mdata: this.config.mdata
        });
        setTimeout(function () {
          _this.reportLogs();
        }, 80);
      } else {
        this.initTracker();
      }
    }
  }, {
    key: "logError",
    value: function logError(error, extra) {
      var _this2 = this;
      var enableExtractCompliance = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
      var newExtra = enableExtractCompliance ? LogComplianceProcessor.extractComplianceParams(error.title, extra !== null && extra !== void 0 ? extra : {}, function (error, ext) {
        _this2.logError(error, ext, false);
      }) : extra !== null && extra !== void 0 ? extra : {};
      var now = Date.now();
      var fsDuration = now - this.componentStartTime;
      var newError = _objectSpread({}, error);
      var oldTitle = error === null || error === void 0 ? void 0 : error.title;
      if (SPM_MAP[oldTitle]) {
        newError.title = SPM_MAP[oldTitle];
      }
      newExtra.eventSource = 'sdk';
      newExtra.eventAlias = extra !== null && extra !== void 0 && extra.eventAlias ? extra === null || extra === void 0 ? void 0 : extra.eventAlias : oldTitle;
      this.logs.push({
        type: 'error',
        logPayload: newError,
        extra: _objectSpread(_objectSpread({}, newExtra), {}, {
          fsDuration: fsDuration,
          timeStamp: now
        })
      });
      if (this.debug) {
        console.log('[web-sdk] Log error', newError, newExtra);
      }
      this.send();
      return this;
    }
  }, {
    key: "logInfo",
    value: function logInfo(info, extra) {
      var _this3 = this;
      var newExtra = LogComplianceProcessor.extractComplianceParams(info.title, extra !== null && extra !== void 0 ? extra : {}, function (error, ext) {
        _this3.logError(error, ext, false);
      });
      var now = Date.now();
      var fsDuration = now - this.componentStartTime;
      var newInfo = _objectSpread({}, info);
      var oldTitle = info === null || info === void 0 ? void 0 : info.title;
      if (SPM_MAP[oldTitle]) {
        newInfo.title = SPM_MAP[oldTitle];
      }
      newExtra.eventSource = 'sdk';
      newExtra.eventAlias = extra !== null && extra !== void 0 && extra.eventAlias ? extra === null || extra === void 0 ? void 0 : extra.eventAlias : oldTitle;
      this.logs.push({
        type: 'info',
        logPayload: newInfo,
        extra: _objectSpread(_objectSpread({}, newExtra), {}, {
          fsDuration: fsDuration,
          timeStamp: now
        })
      });
      if (this.debug) {
        console.log('[web-sdk] Log info', newInfo, newExtra);
      }
      this.send();
      return this;
    }
  }, {
    key: "reportRPC",
    value: function reportRPC(rpcData, extra) {
      var _this4 = this;
      var newExtra = LogComplianceProcessor.extractComplianceParams(rpcData.title, extra !== null && extra !== void 0 ? extra : {}, function (error, ext) {
        _this4.logError(error, ext, false);
      });
      var now = Date.now();
      var fsDuration = now - this.componentStartTime;
      var newRpcData = _objectSpread({}, rpcData);
      var oldTitle = rpcData === null || rpcData === void 0 ? void 0 : rpcData.title;
      if (SPM_MAP[oldTitle]) {
        newRpcData.title = SPM_MAP[oldTitle];
      }
      newExtra.eventSource = 'sdk';
      newExtra.eventAlias = extra !== null && extra !== void 0 && extra.eventAlias ? extra === null || extra === void 0 ? void 0 : extra.eventAlias : oldTitle;
      this.logs.push({
        type: 'rpc',
        logPayload: newRpcData,
        extra: _objectSpread(_objectSpread({}, newExtra), {}, {
          fsDuration: fsDuration,
          timeStamp: now
        })
      });
      if (this.debug) {
        console.log('[web-sdk] Log rpc', newRpcData, newExtra);
      }
      this.send();
      return this;
    }
  }, {
    key: "reportLogs",
    value: function reportLogs() {
      var _window3;
      if (!((_window3 = window) !== null && _window3 !== void 0 && _window3.iTracker)) {
        return;
      }
      var _window$iTracker = window.iTracker,
        logError = _window$iTracker.logError,
        logInfo = _window$iTracker.logInfo,
        reportRPC = _window$iTracker.reportRPC;
      var logs = this.logs;
      while (logs.length > 0) {
        try {
          var log = logs.pop();
          if (log.type === 'error') {
            var _log$logPayload;
            logError(log.logPayload, _objectSpread({
              trackId: this.trackId,
              title: (_log$logPayload = log.logPayload) === null || _log$logPayload === void 0 ? void 0 : _log$logPayload.title
            }, log === null || log === void 0 ? void 0 : log.extra));
          } else if (log.type === 'info') {
            var _log$logPayload2;
            logInfo(log.logPayload, _objectSpread({
              trackId: this.trackId,
              title: (_log$logPayload2 = log.logPayload) === null || _log$logPayload2 === void 0 ? void 0 : _log$logPayload2.title
            }, log === null || log === void 0 ? void 0 : log.extra));
          } else if (log.type === 'rpc') {
            var _log$logPayload3;
            reportRPC(log.logPayload, _objectSpread({
              trackId: this.trackId,
              title: (_log$logPayload3 = log.logPayload) === null || _log$logPayload3 === void 0 ? void 0 : _log$logPayload3.title
            }, log === null || log === void 0 ? void 0 : log.extra));
          }
        } catch (error) {
          console.error('Error occurred while calling iTracker method:', error);
        }
      }
    }
  }, {
    key: "loadScript",
    value: function loadScript(url, callback) {
      var _this5 = this;
      /*
       * 如果宿主环境存在AMD加载器，通过直接创建script标签的方式加载会造成宿主环境报错：
       * Message: Mismatched anonymous define() module
       * 原因是直接通过script标签加载的模块如果没有定义模块名，会被AMD加载器认为是匿名模块，
       * 而宿主环境中已经存在匿名模块，导致报错。
       *
       * TODO: 所有通过window.iTracker调用的方法都需要判断
       *  是否是AMD环境，如果是，需要通过require加载获取iTracker实例
       * */
      if (typeof window.define === 'function' && window.define.amd && typeof window.require === 'function') {
        var moduleId = 'antom_iTracker';
        try {
          var _specified, _ref;
          // 避免重复 config
          if (!((_specified = (_ref = window.require).specified) !== null && _specified !== void 0 && _specified.call(_ref, moduleId))) {
            // @ts-expect-error amd
            window.require.config({
              paths: _defineProperty({}, moduleId, url.replace(/\.js$/, ''))
            });
          }

          // @ts-expect-error amd
          window.require([moduleId], callback, function (err) {
            console.error('AMD load failed, falling back to script tag', err);
            _this5.fallbackLoadScript(url, callback);
          });
          return;
        } catch (e) {
          console.warn('require not available, using script tag', e);
        }
      }
      this.fallbackLoadScript(url, callback);
    }
  }, {
    key: "fallbackLoadScript",
    value: function fallbackLoadScript(url, callback) {
      var script = document.createElement('script');
      script.type = 'text/javascript';
      script.src = url;
      script.onload = callback;
      script.onerror = function () {
        console.error("unable to load Antom script: ".concat(url));
      };
      // CDN 方式接入 sdk，执行时机可能在 body 创建之前
      if (document.body) {
        document.body.appendChild(script);
      } else if (document.head) {
        document.head.appendChild(script);
      }
    }
  }, {
    key: "initTracker",
    value: function initTracker() {
      var _this6 = this;
      if (this.isLoaded) return;
      this.isLoaded = true;
      try {
        if (typeof localStorage !== 'undefined') {
          this.loadScript(this.config.scriptUrl, function () {
            var _window4;
            (_window4 = window) === null || _window4 === void 0 || _window4.iTracker.initiTracker(_this6.config);
            setTimeout(function () {
              _this6.reportLogs();
            }, 80);
          });
        }
      } catch (error) {
        console.error('Failed to initialize iTracker:', error);
      }
    }
  }, {
    key: "send",
    value: function send() {
      var _window5;
      if ((_window5 = window) !== null && _window5 !== void 0 && _window5.iTracker) {
        this.reportLogs();
      } else {
        this.initTracker();
      }
    }
  }, {
    key: "setComponentStartTime",
    value: function setComponentStartTime(val) {
      this.componentStartTime = val;
    }
  }, {
    key: "setTrackId",
    value: function setTrackId(trackId) {
      this.trackId = trackId;
    }
  }, {
    key: "getComponentStartTime",
    value: function getComponentStartTime() {
      return this.componentStartTime;
    }
  }], [{
    key: "setInstance",
    value: function setInstance(instance) {
      return this.instance = instance;
    }
  }, {
    key: "getInstance",
    value: function getInstance() {
      return this.instance;
    }
  }]);
  return Logger;
}();
_defineProperty(Logger, "instance", void 0);
export var LogConfig = {
  scriptUrl: 'https://gw-intl.alipayobjects.com/render/p/yuyan_npm/@alipay_intl-tracker/1.6.0/dist/common.min.js',
  spmConfig: {},
  batchCount: 1,
  appId: 'antom_sdk',
  server: 'https://imdap-sea.alipay.com/loggw/dwcookieLogGet.do',
  bizType: 'antom_sdk',
  productId: 'ANTOM_SDK',
  version: 'iteration/20231021',
  mdata: {
    firstLogTime: Date.now(),
    sdkVersion: json === null || json === void 0 ? void 0 : json.version
  }
};