var that = this;
function __skpm_run (key, context) {
  that.context = context;

var exports =
/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ 		}
/******/ 	};
/******/
/******/ 	// define __esModule on exports
/******/ 	__webpack_require__.r = function(exports) {
/******/ 		if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 			Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 		}
/******/ 		Object.defineProperty(exports, '__esModule', { value: true });
/******/ 	};
/******/
/******/ 	// create a fake namespace object
/******/ 	// mode & 1: value is a module id, require it
/******/ 	// mode & 2: merge all properties of value into the ns
/******/ 	// mode & 4: return value when already ns object
/******/ 	// mode & 8|1: behave like require
/******/ 	__webpack_require__.t = function(value, mode) {
/******/ 		if(mode & 1) value = __webpack_require__(value);
/******/ 		if(mode & 8) return value;
/******/ 		if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ 		var ns = Object.create(null);
/******/ 		__webpack_require__.r(ns);
/******/ 		Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ 		if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ 		return ns;
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = "./src/styleLink/styleLink.js");
/******/ })
/************************************************************************/
/******/ ({

/***/ "./node_modules/@skpm/timers/immediate.js":
/*!************************************************!*\
  !*** ./node_modules/@skpm/timers/immediate.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* globals coscript, sketch */
var timeout = __webpack_require__(/*! ./timeout */ "./node_modules/@skpm/timers/timeout.js")

function setImmediate(func, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10) {
  return timeout.setTimeout(func, 0, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10)
}

function clearImmediate(id) {
  return timeout.clearTimeout(id)
}

module.exports = {
  setImmediate: setImmediate,
  clearImmediate: clearImmediate
}


/***/ }),

/***/ "./node_modules/@skpm/timers/interval.js":
/*!***********************************************!*\
  !*** ./node_modules/@skpm/timers/interval.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* globals coscript, sketch */
var fiberAvailable = __webpack_require__(/*! ./test-if-fiber */ "./node_modules/@skpm/timers/test-if-fiber.js")

var setInterval
var clearInterval

var fibers = []

if (fiberAvailable()) {
  setInterval = function (func, delay, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10) {
    // fibers takes care of keeping coscript around
    var id = fibers.length
    fibers.push(coscript.scheduleWithRepeatingInterval_jsFunction(
      (delay || 0) / 1000,
      function () {
        func(param1, param2, param3, param4, param5, param6, param7, param8, param9, param10)
      }
    ))
    return id
  }

  clearInterval = function (id) {
    var interval = fibers[id]
    if (interval) {
      interval.cancel() // fibers takes care of keeping coscript around
      fibers[id] = undefined // garbage collect the fiber
    }
  }
} else {
  setInterval = function (func, delay, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10) {
    coscript.shouldKeepAround = true
    var id = fibers.length
    fibers.push(true)
    function trigger () {
      coscript.scheduleWithInterval_jsFunction(
        (delay || 0) / 1000,
        function () {
          if (fibers[id]) { // if not cleared
            func(param1, param2, param3, param4, param5, param6, param7, param8, param9, param10)
            trigger()
          }
        }
      )
    }
    trigger()
    return id
  }

  clearInterval = function (id) {
    fibers[id] = false
    if (fibers.every(function (_id) { return !_id })) { // if everything is cleared
      coscript.shouldKeepAround = false
    }
  }
}

module.exports = {
  setInterval: setInterval,
  clearInterval: clearInterval
}


/***/ }),

/***/ "./node_modules/@skpm/timers/test-if-fiber.js":
/*!****************************************************!*\
  !*** ./node_modules/@skpm/timers/test-if-fiber.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = function () {
  return typeof coscript !== 'undefined' && coscript.createFiber
}


/***/ }),

/***/ "./node_modules/@skpm/timers/timeout.js":
/*!**********************************************!*\
  !*** ./node_modules/@skpm/timers/timeout.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* globals coscript, sketch */
var fiberAvailable = __webpack_require__(/*! ./test-if-fiber */ "./node_modules/@skpm/timers/test-if-fiber.js")

var setTimeout
var clearTimeout

var fibers = []

if (fiberAvailable()) {
  var fibers = []

  setTimeout = function (func, delay, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10) {
    // fibers takes care of keeping coscript around
    var id = fibers.length
    fibers.push(coscript.scheduleWithInterval_jsFunction(
      (delay || 0) / 1000,
      function () {
        func(param1, param2, param3, param4, param5, param6, param7, param8, param9, param10)
      }
    ))
    return id
  }

  clearTimeout = function (id) {
    var timeout = fibers[id]
    if (timeout) {
      timeout.cancel() // fibers takes care of keeping coscript around
      fibers[id] = undefined // garbage collect the fiber
    }
  }
} else {
  setTimeout = function (func, delay, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10) {
    coscript.shouldKeepAround = true
    var id = fibers.length
    fibers.push(true)
    coscript.scheduleWithInterval_jsFunction(
      (delay || 0) / 1000,
      function () {
        if (fibers[id]) { // if not cleared
          func(param1, param2, param3, param4, param5, param6, param7, param8, param9, param10)
        }
        clearTimeout(id)
        if (fibers.every(function (_id) { return !_id })) { // if everything is cleared
          coscript.shouldKeepAround = false
        }
      }
    )
    return id
  }

  clearTimeout = function (id) {
    fibers[id] = false
  }
}

module.exports = {
  setTimeout: setTimeout,
  clearTimeout: clearTimeout
}


/***/ }),

/***/ "./node_modules/cocoascript-class/lib/index.js":
/*!*****************************************************!*\
  !*** ./node_modules/cocoascript-class/lib/index.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SuperCall = undefined;
exports.default = ObjCClass;

var _runtime = __webpack_require__(/*! ./runtime.js */ "./node_modules/cocoascript-class/lib/runtime.js");

exports.SuperCall = _runtime.SuperCall;

// super when returnType is id and args are void
// id objc_msgSendSuper(struct objc_super *super, SEL op, void)

const SuperInit = (0, _runtime.SuperCall)(NSStringFromSelector("init"), [], { type: "@" });

// Returns a real ObjC class. No need to use new.
function ObjCClass(defn) {
  const superclass = defn.superclass || NSObject;
  const className = (defn.className || defn.classname || "ObjCClass") + NSUUID.UUID().UUIDString();
  const reserved = new Set(['className', 'classname', 'superclass']);
  var cls = MOClassDescription.allocateDescriptionForClassWithName_superclass_(className, superclass);
  // Add each handler to the class description
  const ivars = [];
  for (var key in defn) {
    const v = defn[key];
    if (typeof v == 'function' && key !== 'init') {
      var selector = NSSelectorFromString(key);
      cls.addInstanceMethodWithSelector_function_(selector, v);
    } else if (!reserved.has(key)) {
      ivars.push(key);
      cls.addInstanceVariableWithName_typeEncoding(key, "@");
    }
  }

  cls.addInstanceMethodWithSelector_function_(NSSelectorFromString('init'), function () {
    const self = SuperInit.call(this);
    ivars.map(name => {
      Object.defineProperty(self, name, {
        get() {
          return getIvar(self, name);
        },
        set(v) {
          (0, _runtime.object_setInstanceVariable)(self, name, v);
        }
      });
      self[name] = defn[name];
    });
    // If there is a passsed-in init funciton, call it now.
    if (typeof defn.init == 'function') defn.init.call(this);
    return self;
  });

  return cls.registerClass();
};

function getIvar(obj, name) {
  const retPtr = MOPointer.new();
  (0, _runtime.object_getInstanceVariable)(obj, name, retPtr);
  return retPtr.value().retain().autorelease();
}

/***/ }),

/***/ "./node_modules/cocoascript-class/lib/runtime.js":
/*!*******************************************************!*\
  !*** ./node_modules/cocoascript-class/lib/runtime.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SuperCall = SuperCall;
exports.CFunc = CFunc;
const objc_super_typeEncoding = '{objc_super="receiver"@"super_class"#}';

// You can store this to call your function. this must be bound to the current instance.
function SuperCall(selector, argTypes, returnType) {
  const func = CFunc("objc_msgSendSuper", [{ type: '^' + objc_super_typeEncoding }, { type: ":" }, ...argTypes], returnType);
  return function (...args) {
    const struct = make_objc_super(this, this.superclass());
    const structPtr = MOPointer.alloc().initWithValue_(struct);
    return func(structPtr, selector, ...args);
  };
}

// Recursively create a MOStruct
function makeStruct(def) {
  if (typeof def !== 'object' || Object.keys(def).length == 0) {
    return def;
  }
  const name = Object.keys(def)[0];
  const values = def[name];

  const structure = MOStruct.structureWithName_memberNames_runtime(name, Object.keys(values), Mocha.sharedRuntime());

  Object.keys(values).map(member => {
    structure[member] = makeStruct(values[member]);
  });

  return structure;
}

function make_objc_super(self, cls) {
  return makeStruct({
    objc_super: {
      receiver: self,
      super_class: cls
    }
  });
}

// Due to particularities of the JS bridge, we can't call into MOBridgeSupport objects directly
// But, we can ask key value coding to do the dirty work for us ;)
function setKeys(o, d) {
  const funcDict = NSMutableDictionary.dictionary();
  funcDict.o = o;
  Object.keys(d).map(k => funcDict.setValue_forKeyPath(d[k], "o." + k));
}

// Use any C function, not just ones with BridgeSupport
function CFunc(name, args, retVal) {
  function makeArgument(a) {
    if (!a) return null;
    const arg = MOBridgeSupportArgument.alloc().init();
    setKeys(arg, {
      type64: a.type
    });
    return arg;
  }
  const func = MOBridgeSupportFunction.alloc().init();
  setKeys(func, {
    name: name,
    arguments: args.map(makeArgument),
    returnValue: makeArgument(retVal)
  });
  return func;
}

/*
@encode(char*) = "*"
@encode(id) = "@"
@encode(Class) = "#"
@encode(void*) = "^v"
@encode(CGRect) = "{CGRect={CGPoint=dd}{CGSize=dd}}"
@encode(SEL) = ":"
*/

function addStructToBridgeSupport(key, structDef) {
  // OK, so this is probably the nastiest hack in this file.
  // We go modify MOBridgeSupportController behind its back and use kvc to add our own definition
  // There isn't another API for this though. So the only other way would be to make a real bridgesupport file.
  const symbols = MOBridgeSupportController.sharedController().valueForKey('symbols');
  if (!symbols) throw Error("Something has changed within bridge support so we can't add our definitions");
  // If someone already added this definition, don't re-register it.
  if (symbols[key] !== null) return;
  const def = MOBridgeSupportStruct.alloc().init();
  setKeys(def, {
    name: key,
    type: structDef.type
  });
  symbols[key] = def;
};

// This assumes the ivar is an object type. Return value is pretty useless.
const object_getInstanceVariable = exports.object_getInstanceVariable = CFunc("object_getInstanceVariable", [{ type: "@" }, { type: '*' }, { type: "^@" }], { type: "^{objc_ivar=}" });
// Again, ivar is of object type
const object_setInstanceVariable = exports.object_setInstanceVariable = CFunc("object_setInstanceVariable", [{ type: "@" }, { type: '*' }, { type: "@" }], { type: "^{objc_ivar=}" });

// We need Mocha to understand what an objc_super is so we can use it as a function argument
addStructToBridgeSupport('objc_super', { type: objc_super_typeEncoding });

/***/ }),

/***/ "./node_modules/mocha-js-delegate/index.js":
/*!*************************************************!*\
  !*** ./node_modules/mocha-js-delegate/index.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/* globals MOClassDescription, NSObject, NSSelectorFromString, NSClassFromString, MOPropertyDescription */

module.exports = function MochaDelegate(definition, superclass) {
  var uniqueClassName =
    'MochaJSDelegate_DynamicClass_' + NSUUID.UUID().UUIDString()

  var delegateClassDesc = MOClassDescription.allocateDescriptionForClassWithName_superclass_(
    uniqueClassName,
    superclass || NSObject
  )

  // Storage
  var handlers = {}
  var ivars = {}

  // Define an instance method
  function setHandlerForSelector(selectorString, func) {
    var handlerHasBeenSet = selectorString in handlers
    var selector = NSSelectorFromString(selectorString)

    handlers[selectorString] = func

    /*
      For some reason, Mocha acts weird about arguments: https://github.com/logancollins/Mocha/issues/28
      We have to basically create a dynamic handler with a likewise dynamic number of predefined arguments.
    */
    if (!handlerHasBeenSet) {
      var args = []
      var regex = /:/g
      while (regex.exec(selectorString)) {
        args.push('arg' + args.length)
      }

      // eslint-disable-next-line no-eval
      var dynamicFunction = eval(
        '(function (' +
          args.join(', ') +
          ') { return handlers[selectorString].apply(this, arguments); })'
      )

      delegateClassDesc.addInstanceMethodWithSelector_function(
        selector,
        dynamicFunction
      )
    }
  }

  // define a property
  function setIvar(key, value) {
    var ivarHasBeenSet = key in handlers

    ivars[key] = value

    if (!ivarHasBeenSet) {
      delegateClassDesc.addInstanceVariableWithName_typeEncoding(key, '@')
      var description = MOPropertyDescription.new()
      description.name = key
      description.typeEncoding = '@'
      description.weak = true
      description.ivarName = key
      delegateClassDesc.addProperty(description)
    }
  }

  this.getClass = function() {
    return NSClassFromString(uniqueClassName)
  }

  this.getClassInstance = function(instanceVariables) {
    var instance = NSClassFromString(uniqueClassName).new()
    Object.keys(ivars).forEach(function(key) {
      instance[key] = ivars[key]
    })
    Object.keys(instanceVariables || {}).forEach(function(key) {
      instance[key] = instanceVariables[key]
    })
    return instance
  }
  // alias
  this.new = this.getClassInstance

  // Convenience
  if (typeof definition === 'object') {
    Object.keys(definition).forEach(
      function(key) {
        if (typeof definition[key] === 'function') {
          setHandlerForSelector(key, definition[key])
        } else {
          setIvar(key, definition[key])
        }
      }
    )
  }

  delegateClassDesc.registerClass()
}


/***/ }),

/***/ "./node_modules/process/browser.js":
/*!*****************************************!*\
  !*** ./node_modules/process/browser.js ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(setTimeout, clearTimeout) {// shim for using process in browser
var process = module.exports = {};

// cached from whatever global is present so that test runners that stub it
// don't break things.  But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals.  It's inside a
// function because try/catches deoptimize in certain engines.

var cachedSetTimeout;
var cachedClearTimeout;

function defaultSetTimout() {
    throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
    throw new Error('clearTimeout has not been defined');
}
(function () {
    try {
        if (typeof setTimeout === 'function') {
            cachedSetTimeout = setTimeout;
        } else {
            cachedSetTimeout = defaultSetTimout;
        }
    } catch (e) {
        cachedSetTimeout = defaultSetTimout;
    }
    try {
        if (typeof clearTimeout === 'function') {
            cachedClearTimeout = clearTimeout;
        } else {
            cachedClearTimeout = defaultClearTimeout;
        }
    } catch (e) {
        cachedClearTimeout = defaultClearTimeout;
    }
} ())
function runTimeout(fun) {
    if (cachedSetTimeout === setTimeout) {
        //normal enviroments in sane situations
        return setTimeout(fun, 0);
    }
    // if setTimeout wasn't available but was latter defined
    if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
        cachedSetTimeout = setTimeout;
        return setTimeout(fun, 0);
    }
    try {
        // when when somebody has screwed with setTimeout but no I.E. maddness
        return cachedSetTimeout(fun, 0);
    } catch(e){
        try {
            // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
            return cachedSetTimeout.call(null, fun, 0);
        } catch(e){
            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
            return cachedSetTimeout.call(this, fun, 0);
        }
    }


}
function runClearTimeout(marker) {
    if (cachedClearTimeout === clearTimeout) {
        //normal enviroments in sane situations
        return clearTimeout(marker);
    }
    // if clearTimeout wasn't available but was latter defined
    if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
        cachedClearTimeout = clearTimeout;
        return clearTimeout(marker);
    }
    try {
        // when when somebody has screwed with setTimeout but no I.E. maddness
        return cachedClearTimeout(marker);
    } catch (e){
        try {
            // When we are in I.E. but the script has been evaled so I.E. doesn't  trust the global object when called normally
            return cachedClearTimeout.call(null, marker);
        } catch (e){
            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
            // Some versions of I.E. have different rules for clearTimeout vs setTimeout
            return cachedClearTimeout.call(this, marker);
        }
    }



}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;

function cleanUpNextTick() {
    if (!draining || !currentQueue) {
        return;
    }
    draining = false;
    if (currentQueue.length) {
        queue = currentQueue.concat(queue);
    } else {
        queueIndex = -1;
    }
    if (queue.length) {
        drainQueue();
    }
}

function drainQueue() {
    if (draining) {
        return;
    }
    var timeout = runTimeout(cleanUpNextTick);
    draining = true;

    var len = queue.length;
    while(len) {
        currentQueue = queue;
        queue = [];
        while (++queueIndex < len) {
            if (currentQueue) {
                currentQueue[queueIndex].run();
            }
        }
        queueIndex = -1;
        len = queue.length;
    }
    currentQueue = null;
    draining = false;
    runClearTimeout(timeout);
}

process.nextTick = function (fun) {
    var args = new Array(arguments.length - 1);
    if (arguments.length > 1) {
        for (var i = 1; i < arguments.length; i++) {
            args[i - 1] = arguments[i];
        }
    }
    queue.push(new Item(fun, args));
    if (queue.length === 1 && !draining) {
        runTimeout(drainQueue);
    }
};

// v8 likes predictible objects
function Item(fun, array) {
    this.fun = fun;
    this.array = array;
}
Item.prototype.run = function () {
    this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};

function noop() {}

process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;

process.listeners = function (name) { return [] }

process.binding = function (name) {
    throw new Error('process.binding is not supported');
};

process.cwd = function () { return '/' };
process.chdir = function (dir) {
    throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./node_modules/@skpm/timers/timeout.js */ "./node_modules/@skpm/timers/timeout.js")["setTimeout"], __webpack_require__(/*! ./node_modules/@skpm/timers/timeout.js */ "./node_modules/@skpm/timers/timeout.js")["clearTimeout"]))

/***/ }),

/***/ "./node_modules/promise-polyfill/lib/index.js":
/*!****************************************************!*\
  !*** ./node_modules/promise-polyfill/lib/index.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(setTimeout, setImmediate) {

/**
 * @this {Promise}
 */
function finallyConstructor(callback) {
  var constructor = this.constructor;
  return this.then(
    function(value) {
      // @ts-ignore
      return constructor.resolve(callback()).then(function() {
        return value;
      });
    },
    function(reason) {
      // @ts-ignore
      return constructor.resolve(callback()).then(function() {
        // @ts-ignore
        return constructor.reject(reason);
      });
    }
  );
}

// Store setTimeout reference so promise-polyfill will be unaffected by
// other code modifying setTimeout (like sinon.useFakeTimers())
var setTimeoutFunc = setTimeout;

function isArray(x) {
  return Boolean(x && typeof x.length !== 'undefined');
}

function noop() {}

// Polyfill for Function.prototype.bind
function bind(fn, thisArg) {
  return function() {
    fn.apply(thisArg, arguments);
  };
}

/**
 * @constructor
 * @param {Function} fn
 */
function Promise(fn) {
  if (!(this instanceof Promise))
    throw new TypeError('Promises must be constructed via new');
  if (typeof fn !== 'function') throw new TypeError('not a function');
  /** @type {!number} */
  this._state = 0;
  /** @type {!boolean} */
  this._handled = false;
  /** @type {Promise|undefined} */
  this._value = undefined;
  /** @type {!Array<!Function>} */
  this._deferreds = [];

  doResolve(fn, this);
}

function handle(self, deferred) {
  while (self._state === 3) {
    self = self._value;
  }
  if (self._state === 0) {
    self._deferreds.push(deferred);
    return;
  }
  self._handled = true;
  Promise._immediateFn(function() {
    var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
    if (cb === null) {
      (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
      return;
    }
    var ret;
    try {
      ret = cb(self._value);
    } catch (e) {
      reject(deferred.promise, e);
      return;
    }
    resolve(deferred.promise, ret);
  });
}

function resolve(self, newValue) {
  try {
    // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
    if (newValue === self)
      throw new TypeError('A promise cannot be resolved with itself.');
    if (
      newValue &&
      (typeof newValue === 'object' || typeof newValue === 'function')
    ) {
      var then = newValue.then;
      if (newValue instanceof Promise) {
        self._state = 3;
        self._value = newValue;
        finale(self);
        return;
      } else if (typeof then === 'function') {
        doResolve(bind(then, newValue), self);
        return;
      }
    }
    self._state = 1;
    self._value = newValue;
    finale(self);
  } catch (e) {
    reject(self, e);
  }
}

function reject(self, newValue) {
  self._state = 2;
  self._value = newValue;
  finale(self);
}

function finale(self) {
  if (self._state === 2 && self._deferreds.length === 0) {
    Promise._immediateFn(function() {
      if (!self._handled) {
        Promise._unhandledRejectionFn(self._value);
      }
    });
  }

  for (var i = 0, len = self._deferreds.length; i < len; i++) {
    handle(self, self._deferreds[i]);
  }
  self._deferreds = null;
}

/**
 * @constructor
 */
function Handler(onFulfilled, onRejected, promise) {
  this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  this.promise = promise;
}

/**
 * Take a potentially misbehaving resolver function and make sure
 * onFulfilled and onRejected are only called once.
 *
 * Makes no guarantees about asynchrony.
 */
function doResolve(fn, self) {
  var done = false;
  try {
    fn(
      function(value) {
        if (done) return;
        done = true;
        resolve(self, value);
      },
      function(reason) {
        if (done) return;
        done = true;
        reject(self, reason);
      }
    );
  } catch (ex) {
    if (done) return;
    done = true;
    reject(self, ex);
  }
}

Promise.prototype['catch'] = function(onRejected) {
  return this.then(null, onRejected);
};

Promise.prototype.then = function(onFulfilled, onRejected) {
  // @ts-ignore
  var prom = new this.constructor(noop);

  handle(this, new Handler(onFulfilled, onRejected, prom));
  return prom;
};

Promise.prototype['finally'] = finallyConstructor;

Promise.all = function(arr) {
  return new Promise(function(resolve, reject) {
    if (!isArray(arr)) {
      return reject(new TypeError('Promise.all accepts an array'));
    }

    var args = Array.prototype.slice.call(arr);
    if (args.length === 0) return resolve([]);
    var remaining = args.length;

    function res(i, val) {
      try {
        if (val && (typeof val === 'object' || typeof val === 'function')) {
          var then = val.then;
          if (typeof then === 'function') {
            then.call(
              val,
              function(val) {
                res(i, val);
              },
              reject
            );
            return;
          }
        }
        args[i] = val;
        if (--remaining === 0) {
          resolve(args);
        }
      } catch (ex) {
        reject(ex);
      }
    }

    for (var i = 0; i < args.length; i++) {
      res(i, args[i]);
    }
  });
};

Promise.resolve = function(value) {
  if (value && typeof value === 'object' && value.constructor === Promise) {
    return value;
  }

  return new Promise(function(resolve) {
    resolve(value);
  });
};

Promise.reject = function(value) {
  return new Promise(function(resolve, reject) {
    reject(value);
  });
};

Promise.race = function(arr) {
  return new Promise(function(resolve, reject) {
    if (!isArray(arr)) {
      return reject(new TypeError('Promise.race accepts an array'));
    }

    for (var i = 0, len = arr.length; i < len; i++) {
      Promise.resolve(arr[i]).then(resolve, reject);
    }
  });
};

// Use polyfill for setImmediate for performance gains
Promise._immediateFn =
  // @ts-ignore
  (typeof setImmediate === 'function' &&
    function(fn) {
      // @ts-ignore
      setImmediate(fn);
    }) ||
  function(fn) {
    setTimeoutFunc(fn, 0);
  };

Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
  if (typeof console !== 'undefined' && console) {
    console.warn('Possible Unhandled Promise Rejection:', err); // eslint-disable-line no-console
  }
};

module.exports = Promise;

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./node_modules/@skpm/timers/timeout.js */ "./node_modules/@skpm/timers/timeout.js")["setTimeout"], __webpack_require__(/*! ./node_modules/@skpm/timers/immediate.js */ "./node_modules/@skpm/timers/immediate.js")["setImmediate"]))

/***/ }),

/***/ "./node_modules/setimmediate/setImmediate.js":
/*!***************************************************!*\
  !*** ./node_modules/setimmediate/setImmediate.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(global, setTimeout, process) {(function (global, undefined) {
    "use strict";

    if (global.setImmediate) {
        return;
    }

    var nextHandle = 1; // Spec says greater than zero
    var tasksByHandle = {};
    var currentlyRunningATask = false;
    var doc = global.document;
    var registerImmediate;

    function setImmediate(callback) {
      // Callback can either be a function or a string
      if (typeof callback !== "function") {
        callback = new Function("" + callback);
      }
      // Copy function arguments
      var args = new Array(arguments.length - 1);
      for (var i = 0; i < args.length; i++) {
          args[i] = arguments[i + 1];
      }
      // Store and register the task
      var task = { callback: callback, args: args };
      tasksByHandle[nextHandle] = task;
      registerImmediate(nextHandle);
      return nextHandle++;
    }

    function clearImmediate(handle) {
        delete tasksByHandle[handle];
    }

    function run(task) {
        var callback = task.callback;
        var args = task.args;
        switch (args.length) {
        case 0:
            callback();
            break;
        case 1:
            callback(args[0]);
            break;
        case 2:
            callback(args[0], args[1]);
            break;
        case 3:
            callback(args[0], args[1], args[2]);
            break;
        default:
            callback.apply(undefined, args);
            break;
        }
    }

    function runIfPresent(handle) {
        // From the spec: "Wait until any invocations of this algorithm started before this one have completed."
        // So if we're currently running a task, we'll need to delay this invocation.
        if (currentlyRunningATask) {
            // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a
            // "too much recursion" error.
            setTimeout(runIfPresent, 0, handle);
        } else {
            var task = tasksByHandle[handle];
            if (task) {
                currentlyRunningATask = true;
                try {
                    run(task);
                } finally {
                    clearImmediate(handle);
                    currentlyRunningATask = false;
                }
            }
        }
    }

    function installNextTickImplementation() {
        registerImmediate = function(handle) {
            process.nextTick(function () { runIfPresent(handle); });
        };
    }

    function canUsePostMessage() {
        // The test against `importScripts` prevents this implementation from being installed inside a web worker,
        // where `global.postMessage` means something completely different and can't be used for this purpose.
        if (global.postMessage && !global.importScripts) {
            var postMessageIsAsynchronous = true;
            var oldOnMessage = global.onmessage;
            global.onmessage = function() {
                postMessageIsAsynchronous = false;
            };
            global.postMessage("", "*");
            global.onmessage = oldOnMessage;
            return postMessageIsAsynchronous;
        }
    }

    function installPostMessageImplementation() {
        // Installs an event handler on `global` for the `message` event: see
        // * https://developer.mozilla.org/en/DOM/window.postMessage
        // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages

        var messagePrefix = "setImmediate$" + Math.random() + "$";
        var onGlobalMessage = function(event) {
            if (event.source === global &&
                typeof event.data === "string" &&
                event.data.indexOf(messagePrefix) === 0) {
                runIfPresent(+event.data.slice(messagePrefix.length));
            }
        };

        if (global.addEventListener) {
            global.addEventListener("message", onGlobalMessage, false);
        } else {
            global.attachEvent("onmessage", onGlobalMessage);
        }

        registerImmediate = function(handle) {
            global.postMessage(messagePrefix + handle, "*");
        };
    }

    function installMessageChannelImplementation() {
        var channel = new MessageChannel();
        channel.port1.onmessage = function(event) {
            var handle = event.data;
            runIfPresent(handle);
        };

        registerImmediate = function(handle) {
            channel.port2.postMessage(handle);
        };
    }

    function installReadyStateChangeImplementation() {
        var html = doc.documentElement;
        registerImmediate = function(handle) {
            // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
            // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
            var script = doc.createElement("script");
            script.onreadystatechange = function () {
                runIfPresent(handle);
                script.onreadystatechange = null;
                html.removeChild(script);
                script = null;
            };
            html.appendChild(script);
        };
    }

    function installSetTimeoutImplementation() {
        registerImmediate = function(handle) {
            setTimeout(runIfPresent, 0, handle);
        };
    }

    // If supported, we should attach to the prototype of global, since that is where setTimeout et al. live.
    var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global);
    attachTo = attachTo && attachTo.setTimeout ? attachTo : global;

    // Don't get fooled by e.g. browserify environments.
    if ({}.toString.call(global.process) === "[object process]") {
        // For Node.js before 0.9
        installNextTickImplementation();

    } else if (canUsePostMessage()) {
        // For non-IE10 modern browsers
        installPostMessageImplementation();

    } else if (global.MessageChannel) {
        // For web workers, where supported
        installMessageChannelImplementation();

    } else if (doc && "onreadystatechange" in doc.createElement("script")) {
        // For IE 6–8
        installReadyStateChangeImplementation();

    } else {
        // For older browsers
        installSetTimeoutImplementation();
    }

    attachTo.setImmediate = setImmediate;
    attachTo.clearImmediate = clearImmediate;
}(typeof self === "undefined" ? typeof global === "undefined" ? this : global : self));

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "./node_modules/webpack/buildin/global.js"), __webpack_require__(/*! ./node_modules/@skpm/timers/timeout.js */ "./node_modules/@skpm/timers/timeout.js")["setTimeout"], __webpack_require__(/*! ./../process/browser.js */ "./node_modules/process/browser.js")))

/***/ }),

/***/ "./node_modules/sketch-module-web-view/lib/browser-api.js":
/*!****************************************************************!*\
  !*** ./node_modules/sketch-module-web-view/lib/browser-api.js ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

function parseHexColor(color) {
  // Check the string for incorrect formatting.
  if (!color || color[0] !== '#') {
    if (
      color &&
      typeof color.isKindOfClass === 'function' &&
      color.isKindOfClass(NSColor)
    ) {
      return color
    }
    throw new Error(
      'Incorrect color formating. It should be an hex color: #RRGGBBAA'
    )
  }

  // append FF if alpha channel is not specified.
  var source = color.substr(1)
  if (source.length === 3) {
    source += 'F'
  } else if (source.length === 6) {
    source += 'FF'
  }
  // Convert the string from #FFF format to #FFFFFF format.
  var hex
  if (source.length === 4) {
    for (var i = 0; i < 4; i += 1) {
      hex += source[i]
      hex += source[i]
    }
  } else if (source.length === 8) {
    hex = source
  } else {
    return NSColor.whiteColor()
  }

  var r = parseInt(hex.slice(0, 2), 16) / 255
  var g = parseInt(hex.slice(2, 4), 16) / 255
  var b = parseInt(hex.slice(4, 6), 16) / 255
  var a = parseInt(hex.slice(6, 8), 16) / 255

  return NSColor.colorWithSRGBRed_green_blue_alpha(r, g, b, a)
}

module.exports = function(browserWindow, panel, webview) {
  // keep reference to the subviews
  browserWindow._panel = panel
  browserWindow._webview = webview
  browserWindow._destroyed = false

  browserWindow.destroy = function() {
    return panel.close()
  }

  browserWindow.close = function() {
    if (panel.delegate().utils && panel.delegate().utils.parentWindow) {
      var shouldClose = true
      browserWindow.emit('close', {
        get defaultPrevented() {
          return !shouldClose
        },
        preventDefault: function() {
          shouldClose = false
        },
      })
      if (shouldClose) {
        panel.delegate().utils.parentWindow.endSheet(panel)
      }
      return
    }

    if (!browserWindow.isClosable()) {
      return
    }

    panel.performClose(null)
  }

  function focus(focused) {
    if (!browserWindow.isVisible()) {
      return
    }
    if (focused) {
      NSApplication.sharedApplication().activateIgnoringOtherApps(true)
      panel.makeKeyAndOrderFront(null)
    } else {
      panel.orderBack(null)
      NSApp.mainWindow().makeKeyAndOrderFront(null)
    }
  }

  browserWindow.focus = focus.bind(this, true)
  browserWindow.blur = focus.bind(this, false)

  browserWindow.isFocused = function() {
    return panel.isKeyWindow()
  }

  browserWindow.isDestroyed = function() {
    return browserWindow._destroyed
  }

  browserWindow.show = function() {
    // This method is supposed to put focus on window, however if the app does not
    // have focus then "makeKeyAndOrderFront" will only show the window.
    NSApp.activateIgnoringOtherApps(true)

    if (panel.delegate().utils && panel.delegate().utils.parentWindow) {
      return panel.delegate().utils.parentWindow.beginSheet_completionHandler(
        panel,
        __mocha__.createBlock_function('v16@?0q8', function() {
          browserWindow.emit('closed')
        })
      )
    }

    return panel.makeKeyAndOrderFront(null)
  }

  browserWindow.showInactive = function() {
    return panel.orderFrontRegardless()
  }

  browserWindow.hide = function() {
    return panel.orderOut(null)
  }

  browserWindow.isVisible = function() {
    return panel.isVisible()
  }

  browserWindow.isModal = function() {
    return false
  }

  browserWindow.maximize = function() {
    if (!browserWindow.isMaximized()) {
      panel.zoom(null)
    }
  }
  browserWindow.unmaximize = function() {
    if (browserWindow.isMaximized()) {
      panel.zoom(null)
    }
  }

  browserWindow.isMaximized = function() {
    if ((panel.styleMask() & NSResizableWindowMask) !== 0) {
      return panel.isZoomed()
    }
    var rectScreen = NSScreen.mainScreen().visibleFrame()
    var rectWindow = panel.frame()
    return (
      rectScreen.origin.x == rectWindow.origin.x &&
      rectScreen.origin.y == rectWindow.origin.y &&
      rectScreen.size.width == rectWindow.size.width &&
      rectScreen.size.height == rectWindow.size.height
    )
  }

  browserWindow.minimize = function() {
    return panel.miniaturize(null)
  }

  browserWindow.restore = function() {
    return panel.deminiaturize(null)
  }

  browserWindow.isMinimized = function() {
    return panel.isMiniaturized()
  }

  browserWindow.setFullScreen = function(fullscreen) {
    if (fullscreen !== browserWindow.isFullscreen()) {
      panel.toggleFullScreen(null)
    }
  }

  browserWindow.isFullscreen = function() {
    return panel.styleMask() & NSFullScreenWindowMask
  }

  browserWindow.setAspectRatio = function(aspectRatio /* , extraSize */) {
    // Reset the behaviour to default if aspect_ratio is set to 0 or less.
    if (aspectRatio > 0.0) {
      panel.setAspectRatio(NSMakeSize(aspectRatio, 1.0))
    } else {
      panel.setResizeIncrements(NSMakeSize(1.0, 1.0))
    }
  }

  browserWindow.setBounds = function(bounds, animate) {
    if (!bounds) {
      return
    }

    // Do nothing if in fullscreen mode.
    if (browserWindow.isFullscreen()) {
      return
    }

    const newBounds = Object.assign(browserWindow.getBounds(), bounds)

    // TODO: Check size constraints since setFrame does not check it.
    // var size = bounds.size
    // size.SetToMax(GetMinimumSize());
    // gfx::Size max_size = GetMaximumSize();
    // if (!max_size.IsEmpty())
    //   size.SetToMin(max_size);

    var cocoaBounds = NSMakeRect(
      newBounds.x,
      0,
      newBounds.width,
      newBounds.height
    )
    // Flip Y coordinates based on the primary screen
    var screen = NSScreen.screens().firstObject()
    cocoaBounds.origin.y = NSHeight(screen.frame()) - newBounds.y

    panel.setFrame_display_animate(cocoaBounds, true, animate)
  }

  browserWindow.getBounds = function() {
    const cocoaBounds = panel.frame()
    var mainScreenRect = NSScreen.screens()
      .firstObject()
      .frame()
    return {
      x: cocoaBounds.origin.x,
      y: Math.round(NSHeight(mainScreenRect) - cocoaBounds.origin.y),
      width: cocoaBounds.size.width,
      height: cocoaBounds.size.height,
    }
  }

  browserWindow.setContentBounds = function(bounds, animate) {
    // TODO:
    browserWindow.setBounds(bounds, animate)
  }

  browserWindow.getContentBounds = function() {
    // TODO:
    return browserWindow.getBounds()
  }

  browserWindow.setSize = function(width, height, animate) {
    // TODO: handle resizing around center
    return browserWindow.setBounds({ width: width, height: height }, animate)
  }

  browserWindow.getSize = function() {
    var bounds = browserWindow.getBounds()
    return [bounds.width, bounds.height]
  }

  browserWindow.setContentSize = function(width, height, animate) {
    // TODO: handle resizing around center
    return browserWindow.setContentBounds(
      { width: width, height: height },
      animate
    )
  }

  browserWindow.getContentSize = function() {
    var bounds = browserWindow.getContentBounds()
    return [bounds.width, bounds.height]
  }

  browserWindow.setMinimumSize = function(width, height) {
    const minSize = CGSizeMake(width, height)
    panel.setContentMinSize(minSize)
  }

  browserWindow.getMinimumSize = function() {
    const size = panel.contentMinSize()
    return [size.width, size.height]
  }

  browserWindow.setMaximumSize = function(width, height) {
    const maxSize = CGSizeMake(width, height)
    panel.setContentMaxSize(maxSize)
  }

  browserWindow.getMaximumSize = function() {
    const size = panel.contentMaxSize()
    return [size.width, size.height]
  }

  browserWindow.setResizable = function(resizable) {
    return browserWindow._setStyleMask(resizable, NSResizableWindowMask)
  }

  browserWindow.isResizable = function() {
    return panel.styleMask() & NSResizableWindowMask
  }

  browserWindow.setMovable = function(movable) {
    return panel.setMovable(movable)
  }
  browserWindow.isMovable = function() {
    return panel.isMovable()
  }

  browserWindow.setMinimizable = function(minimizable) {
    return browserWindow._setStyleMask(minimizable, NSMiniaturizableWindowMask)
  }

  browserWindow.isMinimizable = function() {
    return panel.styleMask() & NSMiniaturizableWindowMask
  }

  browserWindow.setMaximizable = function(maximizable) {
    if (panel.standardWindowButton(NSWindowZoomButton)) {
      panel.standardWindowButton(NSWindowZoomButton).setEnabled(maximizable)
    }
  }

  browserWindow.isMaximizable = function() {
    return (
      panel.standardWindowButton(NSWindowZoomButton) &&
      panel.standardWindowButton(NSWindowZoomButton).isEnabled()
    )
  }

  browserWindow.setFullScreenable = function(fullscreenable) {
    browserWindow._setCollectionBehavior(
      fullscreenable,
      NSWindowCollectionBehaviorFullScreenPrimary
    )
    // On EL Capitan this flag is required to hide fullscreen button.
    browserWindow._setCollectionBehavior(
      !fullscreenable,
      NSWindowCollectionBehaviorFullScreenAuxiliary
    )
  }

  browserWindow.isFullScreenable = function() {
    var collectionBehavior = panel.collectionBehavior()
    return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary
  }

  browserWindow.setClosable = function(closable) {
    browserWindow._setStyleMask(closable, NSClosableWindowMask)
  }

  browserWindow.isClosable = function() {
    return panel.styleMask() & NSClosableWindowMask
  }

  browserWindow.setAlwaysOnTop = function(top, level, relativeLevel) {
    var windowLevel = NSNormalWindowLevel
    var maxWindowLevel = CGWindowLevelForKey(kCGMaximumWindowLevelKey)
    var minWindowLevel = CGWindowLevelForKey(kCGMinimumWindowLevelKey)

    if (top) {
      if (level === 'normal') {
        windowLevel = NSNormalWindowLevel
      } else if (level === 'torn-off-menu') {
        windowLevel = NSTornOffMenuWindowLevel
      } else if (level === 'modal-panel') {
        windowLevel = NSModalPanelWindowLevel
      } else if (level === 'main-menu') {
        windowLevel = NSMainMenuWindowLevel
      } else if (level === 'status') {
        windowLevel = NSStatusWindowLevel
      } else if (level === 'pop-up-menu') {
        windowLevel = NSPopUpMenuWindowLevel
      } else if (level === 'screen-saver') {
        windowLevel = NSScreenSaverWindowLevel
      } else if (level === 'dock') {
        // Deprecated by macOS, but kept for backwards compatibility
        windowLevel = NSDockWindowLevel
      } else {
        windowLevel = NSFloatingWindowLevel
      }
    }

    var newLevel = windowLevel + (relativeLevel || 0)
    if (newLevel >= minWindowLevel && newLevel <= maxWindowLevel) {
      panel.setLevel(newLevel)
    } else {
      throw new Error(
        'relativeLevel must be between ' +
          minWindowLevel +
          ' and ' +
          maxWindowLevel
      )
    }
  }

  browserWindow.isAlwaysOnTop = function() {
    return panel.level() !== NSNormalWindowLevel
  }

  browserWindow.moveTop = function() {
    return panel.orderFrontRegardless()
  }

  browserWindow.center = function() {
    panel.center()
  }

  browserWindow.setPosition = function(x, y, animate) {
    return browserWindow.setBounds({ x: x, y: y }, animate)
  }

  browserWindow.getPosition = function() {
    var bounds = browserWindow.getBounds()
    return [bounds.x, bounds.y]
  }

  browserWindow.setTitle = function(title) {
    panel.setTitle(title)
  }

  browserWindow.getTitle = function() {
    return String(panel.title())
  }

  var attentionRequestId = 0
  browserWindow.flashFrame = function(flash) {
    if (flash) {
      attentionRequestId = NSApp.requestUserAttention(NSInformationalRequest)
    } else {
      NSApp.cancelUserAttentionRequest(attentionRequestId)
      attentionRequestId = 0
    }
  }

  browserWindow.getNativeWindowHandle = function() {
    return panel
  }

  browserWindow.getNativeWebViewHandle = function() {
    return webview
  }

  browserWindow.loadURL = function(url) {
    // When frameLocation is a file, prefix it with the Sketch Resources path
    if (/^(?!https?|file).*\.html?$/.test(url)) {
      if (typeof __command !== 'undefined' && __command.pluginBundle()) {
        url =
          'file://' +
          __command
            .pluginBundle()
            .urlForResourceNamed(url)
            .path()
      }
    }

    if (/^file:\/\/.*\.html?$/.test(url)) {
      // ensure URLs containing spaces are properly handled
      url = NSString.alloc().initWithString(url)
      url = url.stringByAddingPercentEncodingWithAllowedCharacters(
        NSCharacterSet.URLQueryAllowedCharacterSet()
      )
      webview.loadFileURL_allowingReadAccessToURL(
        NSURL.URLWithString(url),
        NSURL.URLWithString('file:///')
      )
      return
    }

    const properURL = NSURL.URLWithString(url)
    const urlRequest = NSURLRequest.requestWithURL(properURL)

    webview.loadRequest(urlRequest)
  }

  browserWindow.reload = function() {
    webview.reload()
  }

  browserWindow.setHasShadow = function(hasShadow) {
    return panel.setHasShadow(hasShadow)
  }

  browserWindow.hasShadow = function() {
    return panel.hasShadow()
  }

  browserWindow.setOpacity = function(opacity) {
    return panel.setAlphaValue(opacity)
  }

  browserWindow.getOpacity = function() {
    return panel.alphaValue()
  }

  browserWindow.setVisibleOnAllWorkspaces = function(visible) {
    return browserWindow._setCollectionBehavior(
      visible,
      NSWindowCollectionBehaviorCanJoinAllSpaces
    )
  }

  browserWindow.isVisibleOnAllWorkspaces = function() {
    var collectionBehavior = panel.collectionBehavior()
    return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces
  }

  browserWindow.setIgnoreMouseEvents = function(ignore) {
    return panel.setIgnoresMouseEvents(ignore)
  }

  browserWindow.setContentProtection = function(enable) {
    panel.setSharingType(enable ? NSWindowSharingNone : NSWindowSharingReadOnly)
  }

  browserWindow.setAutoHideCursor = function(autoHide) {
    panel.setDisableAutoHideCursor(autoHide)
  }

  browserWindow.setVibrancy = function(type) {
    var effectView = browserWindow._vibrantView

    if (!type) {
      if (effectView == null) {
        return
      }

      effectView.removeFromSuperview()
      panel.setVibrantView(null)
      return
    }

    if (effectView == null) {
      var contentView = panel.contentView()
      effectView = NSVisualEffectView.alloc().initWithFrame(
        contentView.bounds()
      )
      browserWindow._vibrantView = effectView

      effectView.setAutoresizingMask(NSViewWidthSizable | NSViewHeightSizable)
      effectView.setBlendingMode(NSVisualEffectBlendingModeBehindWindow)
      effectView.setState(NSVisualEffectStateActive)
      effectView.setFrame(contentView.bounds())
      contentView.addSubview_positioned_relativeTo(
        effectView,
        NSWindowBelow,
        null
      )
    }

    var vibrancyType = NSVisualEffectMaterialLight

    if (type === 'appearance-based') {
      vibrancyType = NSVisualEffectMaterialAppearanceBased
    } else if (type === 'light') {
      vibrancyType = NSVisualEffectMaterialLight
    } else if (type === 'dark') {
      vibrancyType = NSVisualEffectMaterialDark
    } else if (type === 'titlebar') {
      vibrancyType = NSVisualEffectMaterialTitlebar
    } else if (type === 'selection') {
      vibrancyType = NSVisualEffectMaterialSelection
    } else if (type === 'menu') {
      vibrancyType = NSVisualEffectMaterialMenu
    } else if (type === 'popover') {
      vibrancyType = NSVisualEffectMaterialPopover
    } else if (type === 'sidebar') {
      vibrancyType = NSVisualEffectMaterialSidebar
    } else if (type === 'medium-light') {
      vibrancyType = NSVisualEffectMaterialMediumLight
    } else if (type === 'ultra-dark') {
      vibrancyType = NSVisualEffectMaterialUltraDark
    }

    effectView.setMaterial(vibrancyType)
  }

  browserWindow._setBackgroundColor = function(colorName) {
    var color = parseHexColor(colorName)
    webview.setValue_forKey(false, 'drawsBackground')
    panel.backgroundColor = color
  }

  browserWindow._invalidate = function() {
    panel.flushWindow()
    panel.contentView().setNeedsDisplay(true)
  }

  browserWindow._setStyleMask = function(on, flag) {
    var wasMaximizable = browserWindow.isMaximizable()
    if (on) {
      panel.setStyleMask(panel.styleMask() | flag)
    } else {
      panel.setStyleMask(panel.styleMask() & ~flag)
    }
    // Change style mask will make the zoom button revert to default, probably
    // a bug of Cocoa or macOS.
    browserWindow.setMaximizable(wasMaximizable)
  }

  browserWindow._setCollectionBehavior = function(on, flag) {
    var wasMaximizable = browserWindow.isMaximizable()
    if (on) {
      panel.setCollectionBehavior(panel.collectionBehavior() | flag)
    } else {
      panel.setCollectionBehavior(panel.collectionBehavior() & ~flag)
    }
    // Change collectionBehavior will make the zoom button revert to default,
    // probably a bug of Cocoa or macOS.
    browserWindow.setMaximizable(wasMaximizable)
  }

  browserWindow._showWindowButton = function(button) {
    var view = panel.standardWindowButton(button)
    view.superview().addSubview_positioned_relative(view, NSWindowAbove, null)
  }
}


/***/ }),

/***/ "./node_modules/sketch-module-web-view/lib/constants.js":
/*!**************************************************************!*\
  !*** ./node_modules/sketch-module-web-view/lib/constants.js ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = {
  JS_BRIDGE: '__skpm_sketchBridge',
  JS_BRIDGE_RESULT_SUCCESS: '__skpm_sketchBridge_success',
  JS_BRIDGE_RESULT_ERROR: '__skpm_sketchBridge_error',
  START_MOVING_WINDOW: '__skpm_startMovingWindow',
  EXECUTE_JAVASCRIPT: '__skpm_executeJS',
  EXECUTE_JAVASCRIPT_SUCCESS: '__skpm_executeJS_success_',
  EXECUTE_JAVASCRIPT_ERROR: '__skpm_executeJS_error_',
}


/***/ }),

/***/ "./node_modules/sketch-module-web-view/lib/dispatch-first-click.js":
/*!*************************************************************************!*\
  !*** ./node_modules/sketch-module-web-view/lib/dispatch-first-click.js ***!
  \*************************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

var tagsToFocus =
  '["text", "textarea", "date", "datetime-local", "email", "number", "month", "password", "search", "tel", "time", "url", "week" ]'

module.exports = function(webView, event) {
  var point = webView.convertPoint_fromView(event.locationInWindow(), null)
  return (
    'var el = document.elementFromPoint(' + // get the DOM element that match the event
    point.x +
    ', ' +
    point.y +
    '); ' +
    'if (el && el.tagName === "SELECT") {' + // select needs special handling
    '  var event = document.createEvent("MouseEvents");' +
    '  event.initMouseEvent("mousedown", true, true, window);' +
    '  el.dispatchEvent(event);' +
    '} else if (el && ' + // some tags need to be focused instead of clicked
    tagsToFocus +
    '.indexOf(el.type) >= 0 && ' +
    'el.focus' +
    ') {' +
    'el.focus();' + // so focus them
    '} else if (el) {' +
    'el.dispatchEvent(new Event("click", {bubbles: true}))' + // click the others
    '}'
  )
}


/***/ }),

/***/ "./node_modules/sketch-module-web-view/lib/execute-javascript.js":
/*!***********************************************************************!*\
  !*** ./node_modules/sketch-module-web-view/lib/execute-javascript.js ***!
  \***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(Promise) {var CONSTANTS = __webpack_require__(/*! ./constants */ "./node_modules/sketch-module-web-view/lib/constants.js")

module.exports = function(webview, browserWindow) {
  function executeJavaScript(script, userGesture, callback) {
    if (typeof userGesture === 'function') {
      callback = userGesture
      userGesture = false
    }
    var fiber = coscript.createFiber()

    // if the webview is not ready yet, defer the execution until it is
    if (
      webview.navigationDelegate().state &&
      webview.navigationDelegate().state.wasReady == 0
    ) {
      return new Promise(function(resolve, reject) {
        browserWindow.once('ready-to-show', function() {
          executeJavaScript(script, userGesture, callback)
            .then(resolve)
            .catch(reject)
          fiber.cleanup()
        })
      })
    }

    return new Promise(function(resolve, reject) {
      var requestId = Math.random()

      browserWindow.webContents.on(
        CONSTANTS.EXECUTE_JAVASCRIPT_SUCCESS + requestId,
        function(res) {
          try {
            if (callback) {
              callback(null, res)
            }
            resolve(res)
          } catch (err) {
            reject(err)
          }
          fiber.cleanup()
        }
      )
      browserWindow.webContents.on(
        CONSTANTS.EXECUTE_JAVASCRIPT_ERROR + requestId,
        function(err) {
          try {
            if (callback) {
              callback(err)
              resolve()
            } else {
              reject(err)
            }
          } catch (err2) {
            reject(err2)
          }
          fiber.cleanup()
        }
      )

      webview.evaluateJavaScript_completionHandler(
        module.exports.wrapScript(script, requestId),
        null
      )
    })
  }

  return executeJavaScript
}

module.exports.wrapScript = function(script, requestId) {
  return (
    'window.' +
    CONSTANTS.EXECUTE_JAVASCRIPT +
    '(' +
    requestId +
    ', ' +
    JSON.stringify(script) +
    ')'
  )
}

module.exports.injectScript = function(webView) {
  var source =
    'window.' +
    CONSTANTS.EXECUTE_JAVASCRIPT +
    ' = function(id, script) {' +
    '  try {' +
    '    var res = eval(script);' +
    '    if (res && typeof res.then === "function" && typeof res.catch === "function") {' +
    '      res.then(function (res2) {' +
    '        window.postMessage("' +
    CONSTANTS.EXECUTE_JAVASCRIPT_SUCCESS +
    '" + id, res2);' +
    '      })' +
    '      .catch(function (err) {' +
    '        window.postMessage("' +
    CONSTANTS.EXECUTE_JAVASCRIPT_ERROR +
    '" + id, err);' +
    '      })' +
    '    } else {' +
    '      window.postMessage("' +
    CONSTANTS.EXECUTE_JAVASCRIPT_SUCCESS +
    '" + id, res);' +
    '    }' +
    '  } catch (err) {' +
    '    window.postMessage("' +
    CONSTANTS.EXECUTE_JAVASCRIPT_ERROR +
    '" + id, err);' +
    '  }' +
    '}'
  var script = WKUserScript.alloc().initWithSource_injectionTime_forMainFrameOnly(
    source,
    0,
    true
  )
  webView
    .configuration()
    .userContentController()
    .addUserScript(script)
}

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./node_modules/promise-polyfill/lib/index.js */ "./node_modules/promise-polyfill/lib/index.js")))

/***/ }),

/***/ "./node_modules/sketch-module-web-view/lib/fitSubview.js":
/*!***************************************************************!*\
  !*** ./node_modules/sketch-module-web-view/lib/fitSubview.js ***!
  \***************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

function addEdgeConstraint(edge, subview, view, constant) {
  view.addConstraint(
    NSLayoutConstraint.constraintWithItem_attribute_relatedBy_toItem_attribute_multiplier_constant(
      subview,
      edge,
      NSLayoutRelationEqual,
      view,
      edge,
      1,
      constant
    )
  )
}
module.exports = function fitSubviewToView(subview, view, constants) {
  constants = constants || []
  subview.setTranslatesAutoresizingMaskIntoConstraints(false)

  addEdgeConstraint(NSLayoutAttributeLeft, subview, view, constants[0] || 0)
  addEdgeConstraint(NSLayoutAttributeTop, subview, view, constants[1] || 0)
  addEdgeConstraint(NSLayoutAttributeRight, subview, view, constants[2] || 0)
  addEdgeConstraint(NSLayoutAttributeBottom, subview, view, constants[3] || 0)
}


/***/ }),

/***/ "./node_modules/sketch-module-web-view/lib/index.js":
/*!**********************************************************!*\
  !*** ./node_modules/sketch-module-web-view/lib/index.js ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* let's try to match the API from Electron's Browser window
(https://github.com/electron/electron/blob/master/docs/api/browser-window.md) */
var EventEmitter = __webpack_require__(/*! events */ "events")
var buildBrowserAPI = __webpack_require__(/*! ./browser-api */ "./node_modules/sketch-module-web-view/lib/browser-api.js")
var buildWebAPI = __webpack_require__(/*! ./webview-api */ "./node_modules/sketch-module-web-view/lib/webview-api.js")
var fitSubviewToView = __webpack_require__(/*! ./fitSubview */ "./node_modules/sketch-module-web-view/lib/fitSubview.js")
var dispatchFirstClick = __webpack_require__(/*! ./dispatch-first-click */ "./node_modules/sketch-module-web-view/lib/dispatch-first-click.js")
var injectClientMessaging = __webpack_require__(/*! ./inject-client-messaging */ "./node_modules/sketch-module-web-view/lib/inject-client-messaging.js")
var movableArea = __webpack_require__(/*! ./movable-area */ "./node_modules/sketch-module-web-view/lib/movable-area.js")
var executeJavaScript = __webpack_require__(/*! ./execute-javascript */ "./node_modules/sketch-module-web-view/lib/execute-javascript.js")
var setDelegates = __webpack_require__(/*! ./set-delegates */ "./node_modules/sketch-module-web-view/lib/set-delegates.js")

function BrowserWindow(options) {
  options = options || {}

  var identifier = options.identifier || NSUUID.UUID().UUIDString()
  var threadDictionary = NSThread.mainThread().threadDictionary()

  var existingBrowserWindow = BrowserWindow.fromId(identifier)

  // if we already have a window opened, reuse it
  if (existingBrowserWindow) {
    return existingBrowserWindow
  }

  var browserWindow = new EventEmitter()
  browserWindow.id = identifier

  if (options.modal && !options.parent) {
    throw new Error('A modal needs to have a parent.')
  }

  // Long-running script
  var fiber = coscript.createFiber()

  // Window size
  var width = options.width || 800
  var height = options.height || 600
  var mainScreenRect = NSScreen.screens()
    .firstObject()
    .frame()
  var cocoaBounds = NSMakeRect(
    typeof options.x !== 'undefined'
      ? options.x
      : Math.round((NSWidth(mainScreenRect) - width) / 2),
    typeof options.y !== 'undefined'
      ? NSHeight(mainScreenRect) - options.y
      : Math.round((NSHeight(mainScreenRect) - height) / 2),
    width,
    height
  )

  if (options.titleBarStyle && options.titleBarStyle !== 'default') {
    options.frame = false
  }

  var useStandardWindow = options.windowType !== 'textured'
  var styleMask = NSTitledWindowMask

  // this is commented out because the toolbar doesn't appear otherwise :thinking-face:
  // if (!useStandardWindow || options.frame === false) {
  //   styleMask = NSFullSizeContentViewWindowMask
  // }
  if (options.minimizable !== false) {
    styleMask |= NSMiniaturizableWindowMask
  }
  if (options.closable !== false) {
    styleMask |= NSClosableWindowMask
  }
  if (options.resizable !== false) {
    styleMask |= NSResizableWindowMask
  }
  if (!useStandardWindow || options.transparent || options.frame === false) {
    styleMask |= NSTexturedBackgroundWindowMask
  }

  var panel = NSPanel.alloc().initWithContentRect_styleMask_backing_defer(
    cocoaBounds,
    styleMask,
    NSBackingStoreBuffered,
    true
  )

  var wkwebviewConfig = WKWebViewConfiguration.alloc().init()
  var webView = WKWebView.alloc().initWithFrame_configuration(
    CGRectMake(0, 0, options.width || 800, options.height || 600),
    wkwebviewConfig
  )
  injectClientMessaging(webView)
  webView.setAutoresizingMask(NSViewWidthSizable | NSViewHeightSizable)

  buildBrowserAPI(browserWindow, panel, webView)
  buildWebAPI(browserWindow, panel, webView)
  setDelegates(browserWindow, panel, webView, options)

  if (options.windowType === 'desktop') {
    panel.setLevel(kCGDesktopWindowLevel - 1)
    // panel.setCanBecomeKeyWindow(false)
    panel.setCollectionBehavior(
      NSWindowCollectionBehaviorCanJoinAllSpaces |
        NSWindowCollectionBehaviorStationary |
        NSWindowCollectionBehaviorIgnoresCycle
    )
  }

  if (
    typeof options.minWidth !== 'undefined' ||
    typeof options.minHeight !== 'undefined'
  ) {
    browserWindow.setMinimumSize(options.minWidth || 0, options.minHeight || 0)
  }

  if (
    typeof options.maxWidth !== 'undefined' ||
    typeof options.maxHeight !== 'undefined'
  ) {
    browserWindow.setMaximumSize(
      options.maxWidth || 10000,
      options.maxHeight || 10000
    )
  }

  // if (options.focusable === false) {
  //   panel.setCanBecomeKeyWindow(false)
  // }

  if (options.transparent || options.frame === false) {
    panel.titlebarAppearsTransparent = true
    panel.titleVisibility = NSWindowTitleHidden
    panel.setOpaque(0)
    panel.isMovableByWindowBackground = true
    var toolbar2 = NSToolbar.alloc().initWithIdentifier(
      'titlebarStylingToolbar'
    )
    toolbar2.setShowsBaselineSeparator(false)
    panel.setToolbar(toolbar2)
  }

  if (options.titleBarStyle === 'hiddenInset') {
    var toolbar = NSToolbar.alloc().initWithIdentifier('titlebarStylingToolbar')
    toolbar.setShowsBaselineSeparator(false)
    panel.setToolbar(toolbar)
  }

  if (options.frame === false || !options.useContentSize) {
    browserWindow.setSize(width, height)
  }

  if (options.center) {
    browserWindow.center()
  }

  if (options.alwaysOnTop) {
    browserWindow.setAlwaysOnTop(true)
  }

  if (options.fullscreen) {
    browserWindow.setFullScreen(true)
  }
  browserWindow.setFullScreenable(!!options.fullscreenable)

  let title = options.title
  if (options.frame === false) {
    title = undefined
  } else if (
    typeof title === 'undefined' &&
    typeof __command !== 'undefined' &&
    __command.pluginBundle()
  ) {
    title = __command.pluginBundle().name()
  }

  if (title) {
    browserWindow.setTitle(title)
  }

  var backgroundColor = options.backgroundColor
  if (options.transparent) {
    backgroundColor = NSColor.clearColor()
  }
  if (!backgroundColor && options.frame === false && options.vibrancy) {
    backgroundColor = NSColor.clearColor()
  }

  browserWindow._setBackgroundColor(
    backgroundColor || NSColor.windowBackgroundColor()
  )

  if (options.hasShadow === false) {
    browserWindow.setHasShadow(false)
  }

  if (typeof options.opacity !== 'undefined') {
    browserWindow.setOpacity(options.opacity)
  }

  options.webPreferences = options.webPreferences || {}

  webView
    .configuration()
    .preferences()
    .setValue_forKey(
      options.webPreferences.devTools !== false,
      'developerExtrasEnabled'
    )
  webView
    .configuration()
    .preferences()
    .setValue_forKey(
      options.webPreferences.javascript !== false,
      'javaScriptEnabled'
    )
  webView
    .configuration()
    .preferences()
    .setValue_forKey(!!options.webPreferences.plugins, 'plugInsEnabled')
  webView
    .configuration()
    .preferences()
    .setValue_forKey(
      options.webPreferences.minimumFontSize || 0,
      'minimumFontSize'
    )

  if (options.webPreferences.zoomFactor) {
    webView.setMagnification(options.webPreferences.zoomFactor)
  }

  var contentView = panel.contentView()

  if (options.frame !== false) {
    webView.setFrame(contentView.bounds())
    contentView.addSubview(webView)
  } else {
    // In OSX 10.10, adding subviews to the root view for the NSView hierarchy
    // produces warnings. To eliminate the warnings, we resize the contentView
    // to fill the window, and add subviews to that.
    // http://crbug.com/380412
    contentView.setAutoresizingMask(NSViewWidthSizable | NSViewHeightSizable)
    fitSubviewToView(contentView, contentView.superview())

    webView.setFrame(contentView.bounds())
    contentView.addSubview(webView)

    // The fullscreen button should always be hidden for frameless window.
    if (panel.standardWindowButton(NSWindowFullScreenButton)) {
      panel.standardWindowButton(NSWindowFullScreenButton).setHidden(true)
    }

    if (!options.titleBarStyle || options.titleBarStyle === 'default') {
      // Hide the window buttons.
      panel.standardWindowButton(NSWindowZoomButton).setHidden(true)
      panel.standardWindowButton(NSWindowMiniaturizeButton).setHidden(true)
      panel.standardWindowButton(NSWindowCloseButton).setHidden(true)

      // Some third-party macOS utilities check the zoom button's enabled state to
      // determine whether to show custom UI on hover, so we disable it here to
      // prevent them from doing so in a frameless app window.
      panel.standardWindowButton(NSWindowZoomButton).setEnabled(false)
    }
  }

  if (options.vibrancy) {
    browserWindow.setVibrancy(options.vibrancy)
  }

  // Set maximizable state last to ensure zoom button does not get reset
  // by calls to other APIs.
  browserWindow.setMaximizable(options.maximizable !== false)

  panel.setHidesOnDeactivate(options.hidesOnDeactivate !== false)

  if (options.remembersWindowFrame) {
    panel.setFrameAutosaveName(identifier)
    panel.setFrameUsingName_force(panel.frameAutosaveName(), false)
  }

  if (options.acceptsFirstMouse) {
    browserWindow.on('focus', function(event) {
      if (event.type() === NSEventTypeLeftMouseDown) {
        browserWindow.webContents
          .executeJavaScript(dispatchFirstClick(webView, event))
          .catch(() => {})
      }
    })
  }

  executeJavaScript.injectScript(webView)
  movableArea.injectScript(webView)
  movableArea.setupHandler(browserWindow)

  if (options.show !== false) {
    browserWindow.show()
  }

  browserWindow.on('closed', function() {
    browserWindow._destroyed = true
    threadDictionary.removeObjectForKey(identifier)
    var observer = threadDictionary[identifier + '.themeObserver']
    if (observer) {
      NSApplication.sharedApplication().removeObserver_forKeyPath(
        observer,
        'effectiveAppearance'
      )
      threadDictionary.removeObjectForKey(identifier + '.themeObserver')
    }
    fiber.cleanup()
  })

  threadDictionary[identifier] = panel

  fiber.onCleanup(function() {
    if (!browserWindow._destroyed) {
      browserWindow.destroy()
    }
  })

  return browserWindow
}

BrowserWindow.fromId = function(identifier) {
  var threadDictionary = NSThread.mainThread().threadDictionary()

  if (threadDictionary[identifier]) {
    return BrowserWindow.fromPanel(threadDictionary[identifier], identifier)
  }

  return undefined
}

BrowserWindow.fromPanel = function(panel, identifier) {
  var browserWindow = new EventEmitter()
  browserWindow.id = identifier

  if (!panel || !panel.contentView) {
    throw new Error('needs to pass an NSPanel')
  }

  var webView = null
  var subviews = panel.contentView().subviews()
  for (var i = 0; i < subviews.length; i += 1) {
    if (
      !webView &&
      !subviews[i].isKindOfClass(WKInspectorWKWebView) &&
      subviews[i].isKindOfClass(WKWebView)
    ) {
      webView = subviews[i]
    }
  }

  if (!webView) {
    throw new Error('The panel needs to have a webview')
  }

  buildBrowserAPI(browserWindow, panel, webView)
  buildWebAPI(browserWindow, panel, webView)

  return browserWindow
}

module.exports = BrowserWindow


/***/ }),

/***/ "./node_modules/sketch-module-web-view/lib/inject-client-messaging.js":
/*!****************************************************************************!*\
  !*** ./node_modules/sketch-module-web-view/lib/inject-client-messaging.js ***!
  \****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var CONSTANTS = __webpack_require__(/*! ./constants */ "./node_modules/sketch-module-web-view/lib/constants.js")

module.exports = function(webView) {
  var source =
    'window.originalPostMessage = window.postMessage;' +
    'window.postMessage = function(actionName) {' +
    '  if (!actionName) {' +
    "    throw new Error('missing action name')" +
    '  }' +
    '  var id = String(Math.random()).replace(".", "");' +
    '    var args = [].slice.call(arguments);' +
    '    args.unshift(id);' +
    '  return new Promise(function (resolve, reject) {' +
    '    window["' +
    CONSTANTS.JS_BRIDGE_RESULT_SUCCESS +
    '" + id] = resolve;' +
    '    window["' +
    CONSTANTS.JS_BRIDGE_RESULT_ERROR +
    '" + id] = reject;' +
    '    window.webkit.messageHandlers.' +
    CONSTANTS.JS_BRIDGE +
    '.postMessage(JSON.stringify(args));' +
    '  });' +
    '}'
  var script = WKUserScript.alloc().initWithSource_injectionTime_forMainFrameOnly(
    source,
    0,
    true
  )
  webView
    .configuration()
    .userContentController()
    .addUserScript(script)
}


/***/ }),

/***/ "./node_modules/sketch-module-web-view/lib/movable-area.js":
/*!*****************************************************************!*\
  !*** ./node_modules/sketch-module-web-view/lib/movable-area.js ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(clearInterval, setInterval) {var CONSTANTS = __webpack_require__(/*! ./constants */ "./node_modules/sketch-module-web-view/lib/constants.js")

module.exports.injectScript = function(webView) {
  var source =
    '(function () {' +
    "document.addEventListener('mousedown', onMouseDown);" +
    '' +
    'function shouldDrag(target) {' +
    '  if (!target || (target.dataset || {}).appRegion === "no-drag") { return false }' +
    '  if ((target.dataset || {}).appRegion === "drag") { return true }' +
    '  return shouldDrag(target.parentElement)' +
    '};' +
    '' +
    'function onMouseDown(e) {' +
    '  if (e.button !== 0 || !shouldDrag(e.target)) { return }' +
    '  window.postMessage("' +
    CONSTANTS.START_MOVING_WINDOW +
    '");' +
    '};' +
    '})()'
  var script = WKUserScript.alloc().initWithSource_injectionTime_forMainFrameOnly(
    source,
    0,
    true
  )
  webView
    .configuration()
    .userContentController()
    .addUserScript(script)
}

module.exports.setupHandler = function(browserWindow) {
  var initialMouseLocation = null
  var initialWindowPosition = null
  var interval = null

  function moveWindow() {
    // if the user released the button, stop moving the window
    if (!initialWindowPosition || NSEvent.pressedMouseButtons() !== 1) {
      clearInterval(interval)
      initialMouseLocation = null
      initialWindowPosition = null
      return
    }

    var mouse = NSEvent.mouseLocation()
    browserWindow.setPosition(
      initialWindowPosition.x + (mouse.x - initialMouseLocation.x),
      initialWindowPosition.y + (initialMouseLocation.y - mouse.y), // y is inverted
      false
    )
  }

  browserWindow.webContents.on(CONSTANTS.START_MOVING_WINDOW, function() {
    initialMouseLocation = NSEvent.mouseLocation()
    var position = browserWindow.getPosition()
    initialWindowPosition = {
      x: position[0],
      y: position[1],
    }

    interval = setInterval(moveWindow, 1000 / 60) // 60 fps
  })
}

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./node_modules/@skpm/timers/interval.js */ "./node_modules/@skpm/timers/interval.js")["clearInterval"], __webpack_require__(/*! ./node_modules/@skpm/timers/interval.js */ "./node_modules/@skpm/timers/interval.js")["setInterval"]))

/***/ }),

/***/ "./node_modules/sketch-module-web-view/lib/parseWebArguments.js":
/*!**********************************************************************!*\
  !*** ./node_modules/sketch-module-web-view/lib/parseWebArguments.js ***!
  \**********************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = function(webArguments) {
  var args = null
  try {
    args = JSON.parse(webArguments)
  } catch (e) {
    // malformed arguments
  }

  if (
    !args ||
    !args.constructor ||
    args.constructor !== Array ||
    args.length == 0
  ) {
    return null
  }

  return args
}


/***/ }),

/***/ "./node_modules/sketch-module-web-view/lib/set-delegates.js":
/*!******************************************************************!*\
  !*** ./node_modules/sketch-module-web-view/lib/set-delegates.js ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(process, Promise) {var ObjCClass = __webpack_require__(/*! mocha-js-delegate */ "./node_modules/mocha-js-delegate/index.js")
var parseWebArguments = __webpack_require__(/*! ./parseWebArguments */ "./node_modules/sketch-module-web-view/lib/parseWebArguments.js")
var CONSTANTS = __webpack_require__(/*! ./constants */ "./node_modules/sketch-module-web-view/lib/constants.js")

// We create one ObjC class for ourselves here
var WindowDelegateClass
var NavigationDelegateClass
var WebScriptHandlerClass
var ThemeObserverClass

// TODO: events
// - 'page-favicon-updated'
// - 'new-window'
// - 'did-navigate-in-page'
// - 'will-prevent-unload'
// - 'crashed'
// - 'unresponsive'
// - 'responsive'
// - 'destroyed'
// - 'before-input-event'
// - 'certificate-error'
// - 'found-in-page'
// - 'media-started-playing'
// - 'media-paused'
// - 'did-change-theme-color'
// - 'update-target-url'
// - 'cursor-changed'
// - 'context-menu'
// - 'select-bluetooth-device'
// - 'paint'
// - 'console-message'

module.exports = function(browserWindow, panel, webview, options) {
  if (!ThemeObserverClass) {
    ThemeObserverClass = new ObjCClass({
      utils: null,

      'observeValueForKeyPath:ofObject:change:context:': function(keyPath,object,change) {
        const newAppearance = change[NSKeyValueChangeNewKey]
        const isDark = String(newAppearance.bestMatchFromAppearancesWithNames(['NSAppearanceNameAqua', 'NSAppearanceNameDarkAqua'])) === 'NSAppearanceNameDarkAqua'

        this.utils.executeJavaScript(
          "document.body.classList.remove('__skpm-" +
            (isDark ? 'light' : 'dark') +
            "'); document.body.classList.add('__skpm-" +
            (isDark ? 'dark' : 'light') +
            "')"
        )
      },
    })
  }

  if (!WindowDelegateClass) {
    WindowDelegateClass = new ObjCClass({
      utils: null,
      panel: null,

      'windowDidResize:': function() {
        this.utils.emit('resize')
      },

      'windowDidMiniaturize:': function() {
        this.utils.emit('minimize')
      },

      'windowDidDeminiaturize:': function() {
        this.utils.emit('restore')
      },

      'windowDidEnterFullScreen:': function() {
        this.utils.emit('enter-full-screen')
      },

      'windowDidExitFullScreen:': function() {
        this.utils.emit('leave-full-screen')
      },

      'windowDidMove:': function() {
        this.utils.emit('move')
        this.utils.emit('moved')
      },

      'windowShouldClose:': function() {
        var shouldClose = 1
        this.utils.emit('close', {
          get defaultPrevented() {
            return !shouldClose
          },
          preventDefault: function() {
            shouldClose = 0
          },
        })
        return shouldClose
      },

      'windowWillClose:': function() {
        this.utils.emit('closed')
      },

      'windowDidBecomeKey:': function() {
        this.utils.emit('focus', this.panel.currentEvent())
      },

      'windowDidResignKey:': function() {
        this.utils.emit('blur')
      },
    })
  }

  if (!NavigationDelegateClass) {
    NavigationDelegateClass = new ObjCClass({
      state: {
        wasReady: 0,
      },
      utils: null,

      // // Called when the web view begins to receive web content.
      'webView:didCommitNavigation:': function(webView) {
        this.utils.emit('will-navigate', {}, String(String(webView.URL())))
      },

      // // Called when web content begins to load in a web view.
      'webView:didStartProvisionalNavigation:': function() {
        this.utils.emit('did-start-navigation')
        this.utils.emit('did-start-loading')
      },

      // Called when a web view receives a server redirect.
      'webView:didReceiveServerRedirectForProvisionalNavigation:': function() {
        this.utils.emit('did-get-redirect-request')
      },

      // // Called when the web view needs to respond to an authentication challenge.
      // 'webView:didReceiveAuthenticationChallenge:completionHandler:': function(
      //   webView,
      //   challenge,
      //   completionHandler
      // ) {
      //   function callback(username, password) {
      //     completionHandler(
      //       0,
      //       NSURLCredential.credentialWithUser_password_persistence(
      //         username,
      //         password,
      //         1
      //       )
      //     )
      //   }
      //   var protectionSpace = challenge.protectionSpace()
      //   this.utils.emit(
      //     'login',
      //     {},
      //     {
      //       method: String(protectionSpace.authenticationMethod()),
      //       url: 'not implemented', // TODO:
      //       referrer: 'not implemented', // TODO:
      //     },
      //     {
      //       isProxy: !!protectionSpace.isProxy(),
      //       scheme: String(protectionSpace.protocol()),
      //       host: String(protectionSpace.host()),
      //       port: Number(protectionSpace.port()),
      //       realm: String(protectionSpace.realm()),
      //     },
      //     callback
      //   )
      // },

      // Called when an error occurs during navigation.
      // 'webView:didFailNavigation:withError:': function(
      //   webView,
      //   navigation,
      //   error
      // ) {},

      // Called when an error occurs while the web view is loading content.
      'webView:didFailProvisionalNavigation:withError:': function(
        webView,
        navigation,
        error
      ) {
        this.utils.emit('did-fail-load', error)
      },

      // Called when the navigation is complete.
      'webView:didFinishNavigation:': function() {
        if (this.state.wasReady == 0) {
          this.state.wasReady = 1
          this.utils.emitBrowserEvent('ready-to-show')
        }
        this.utils.emit('did-navigate')
        this.utils.emit('did-frame-navigate')
        this.utils.emit('did-stop-loading')
        this.utils.emit('did-finish-load')
        this.utils.emit('did-frame-finish-load')
      },

      // Called when the web view’s web content process is terminated.
      'webViewWebContentProcessDidTerminate:': function() {
        this.utils.emit('dom-ready')
      },

      // Decides whether to allow or cancel a navigation.
      // webView:decidePolicyForNavigationAction:decisionHandler:

      // Decides whether to allow or cancel a navigation after its response is known.
      // webView:decidePolicyForNavigationResponse:decisionHandler:
    })
  }

  if (!WebScriptHandlerClass) {
    WebScriptHandlerClass = new ObjCClass({
      utils: null,
      'userContentController:didReceiveScriptMessage:': function(_, message) {
        var args = this.utils.parseWebArguments(String(message.body()))
        if (!args) {
          return
        }
        if (!args[0] || typeof args[0] !== 'string') {
          return
        }
        args[0] = String(args[0])

        this.utils.emit.apply(this, args)
      },
    })
  }

  var themeObserver = ThemeObserverClass.new({
    utils: {
      executeJavaScript(script) {
        webview.evaluateJavaScript_completionHandler(script, null)
      },
    },
  })

  var script = WKUserScript.alloc().initWithSource_injectionTime_forMainFrameOnly(
    "document.addEventListener('DOMContentLoaded', function() { document.body.classList.add('__skpm-" +
      (typeof MSTheme !== 'undefined' && MSTheme.sharedTheme().isDark()
        ? 'dark'
        : 'light') +
      "') }, false)",
    0,
    true
  )
  webview
    .configuration()
    .userContentController()
    .addUserScript(script)

  NSApplication.sharedApplication().addObserver_forKeyPath_options_context(
    themeObserver,
    'effectiveAppearance',
    NSKeyValueObservingOptionNew,
    null
  )

  var threadDictionary = NSThread.mainThread().threadDictionary()
  threadDictionary[browserWindow.id + '.themeObserver'] = themeObserver

  var navigationDelegate = NavigationDelegateClass.new({
    utils: {
      setTitle: browserWindow.setTitle.bind(browserWindow),
      emitBrowserEvent() {
        try {
          browserWindow.emit.apply(browserWindow, arguments)
        } catch (err) {
          if (
            typeof process !== 'undefined' &&
            process.listenerCount &&
            process.listenerCount('uncaughtException')
          ) {
            process.emit('uncaughtException', err, 'uncaughtException')
          } else {
            console.error(err)
            throw err
          }
        }
      },
      emit() {
        try {
          browserWindow.webContents.emit.apply(
            browserWindow.webContents,
            arguments
          )
        } catch (err) {
          if (
            typeof process !== 'undefined' &&
            process.listenerCount &&
            process.listenerCount('uncaughtException')
          ) {
            process.emit('uncaughtException', err, 'uncaughtException')
          } else {
            console.error(err)
            throw err
          }
        }
      },
    },
    state: {
      wasReady: 0,
    },
  })

  webview.setNavigationDelegate(navigationDelegate)

  var webScriptHandler = WebScriptHandlerClass.new({
    utils: {
      emit(id, type) {
        if (!type) {
          webview.evaluateJavaScript_completionHandler(
            CONSTANTS.JS_BRIDGE_RESULT_SUCCESS + id + '()',
            null
          )
          return
        }

        var args = []
        for (var i = 2; i < arguments.length; i += 1) args.push(arguments[i])

        var listeners = browserWindow.webContents.listeners(type)

        Promise.all(
          listeners.map(function(l) {
            return Promise.resolve().then(function() {
              return l.apply(l, args)
            })
          })
        )
          .then(function(res) {
            webview.evaluateJavaScript_completionHandler(
              CONSTANTS.JS_BRIDGE_RESULT_SUCCESS +
                id +
                '(' +
                JSON.stringify(res) +
                ')',
              null
            )
          })
          .catch(function(err) {
            webview.evaluateJavaScript_completionHandler(
              CONSTANTS.JS_BRIDGE_RESULT_ERROR +
                id +
                '(' +
                JSON.stringify(err) +
                ')',
              null
            )
          })
      },
      parseWebArguments: parseWebArguments,
    },
  })

  webview
    .configuration()
    .userContentController()
    .addScriptMessageHandler_name(webScriptHandler, CONSTANTS.JS_BRIDGE)

  var utils = {
    emit() {
      try {
        browserWindow.emit.apply(browserWindow, arguments)
      } catch (err) {
        if (
          typeof process !== 'undefined' &&
          process.listenerCount &&
          process.listenerCount('uncaughtException')
        ) {
          process.emit('uncaughtException', err, 'uncaughtException')
        } else {
          console.error(err)
          throw err
        }
      }
    },
  }
  if (options.modal) {
    // find the window of the document
    var msdocument
    if (options.parent.type === 'Document') {
      msdocument = options.parent.sketchObject
    } else {
      msdocument = options.parent
    }
    if (msdocument && String(msdocument.class()) === 'MSDocumentData') {
      // we only have an MSDocumentData instead of a MSDocument
      // let's try to get back to the MSDocument
      msdocument = msdocument.delegate()
    }
    utils.parentWindow = msdocument.windowForSheet()
  }

  var windowDelegate = WindowDelegateClass.new({
    utils: utils,
    panel: panel,
  })

  panel.setDelegate(windowDelegate)
}

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../process/browser.js */ "./node_modules/process/browser.js"), __webpack_require__(/*! ./node_modules/promise-polyfill/lib/index.js */ "./node_modules/promise-polyfill/lib/index.js")))

/***/ }),

/***/ "./node_modules/sketch-module-web-view/lib/webview-api.js":
/*!****************************************************************!*\
  !*** ./node_modules/sketch-module-web-view/lib/webview-api.js ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var EventEmitter = __webpack_require__(/*! events */ "events")
var executeJavaScript = __webpack_require__(/*! ./execute-javascript */ "./node_modules/sketch-module-web-view/lib/execute-javascript.js")

// let's try to match https://github.com/electron/electron/blob/master/docs/api/web-contents.md
module.exports = function buildAPI(browserWindow, panel, webview) {
  var webContents = new EventEmitter()

  webContents.loadURL = browserWindow.loadURL

  webContents.loadFile = function(/* filePath */) {
    // TODO:
    console.warn(
      'Not implemented yet, please open a PR on https://github.com/skpm/sketch-module-web-view :)'
    )
  }

  webContents.downloadURL = function(/* filePath */) {
    // TODO:
    console.warn(
      'Not implemented yet, please open a PR on https://github.com/skpm/sketch-module-web-view :)'
    )
  }

  webContents.getURL = function() {
    return String(webview.URL())
  }

  webContents.getTitle = function() {
    return String(webview.title())
  }

  webContents.isDestroyed = function() {
    // TODO:
    console.warn(
      'Not implemented yet, please open a PR on https://github.com/skpm/sketch-module-web-view :)'
    )
  }

  webContents.focus = browserWindow.focus
  webContents.isFocused = browserWindow.isFocused

  webContents.isLoading = function() {
    return !!webview.loading()
  }

  webContents.isLoadingMainFrame = function() {
    // TODO:
    return !!webview.loading()
  }

  webContents.isWaitingForResponse = function() {
    return !webview.loading()
  }

  webContents.stop = function() {
    webview.stopLoading()
  }
  webContents.reload = function() {
    webview.reload()
  }
  webContents.reloadIgnoringCache = function() {
    webview.reloadFromOrigin()
  }
  webContents.canGoBack = function() {
    return !!webview.canGoBack()
  }
  webContents.canGoForward = function() {
    return !!webview.canGoForward()
  }
  webContents.canGoToOffset = function(offset) {
    return !!webview.backForwardList().itemAtIndex(offset)
  }
  webContents.clearHistory = function() {
    // TODO:
    console.warn(
      'Not implemented yet, please open a PR on https://github.com/skpm/sketch-module-web-view :)'
    )
  }
  webContents.goBack = function() {
    webview.goBack()
  }
  webContents.goForward = function() {
    webview.goForward()
  }
  webContents.goToIndex = function(index) {
    var backForwardList = webview.backForwardList()
    var backList = backForwardList.backList()
    var backListLength = backList.count()
    if (backListLength > index) {
      webview.loadRequest(NSURLRequest.requestWithURL(backList[index]))
      return
    }
    var forwardList = backForwardList.forwardList()
    if (forwardList.count() > index - backListLength) {
      webview.loadRequest(
        NSURLRequest.requestWithURL(forwardList[index - backListLength])
      )
      return
    }
    throw new Error('Cannot go to index ' + index)
  }
  webContents.goToOffset = function(offset) {
    if (!webContents.canGoToOffset(offset)) {
      throw new Error('Cannot go to offset ' + offset)
    }
    webview.loadRequest(
      NSURLRequest.requestWithURL(webview.backForwardList().itemAtIndex(offset))
    )
  }
  webContents.isCrashed = function() {
    // TODO:
    console.warn(
      'Not implemented yet, please open a PR on https://github.com/skpm/sketch-module-web-view :)'
    )
  }
  webContents.setUserAgent = function(/* userAgent */) {
    // TODO:
    console.warn(
      'Not implemented yet, please open a PR on https://github.com/skpm/sketch-module-web-view :)'
    )
  }
  webContents.getUserAgent = function() {
    const userAgent = webview.customUserAgent()
    return userAgent ? String(userAgent) : undefined
  }
  webContents.insertCSS = function(css) {
    var source =
      "var style = document.createElement('style'); style.innerHTML = " +
      css.replace(/"/, '\\"') +
      '; document.head.appendChild(style);'
    var script = WKUserScript.alloc().initWithSource_injectionTime_forMainFrameOnly(
      source,
      0,
      true
    )
    webview
      .configuration()
      .userContentController()
      .addUserScript(script)
  }
  webContents.insertJS = function(source) {
    var script = WKUserScript.alloc().initWithSource_injectionTime_forMainFrameOnly(
      source,
      0,
      true
    )
    webview
      .configuration()
      .userContentController()
      .addUserScript(script)
  }
  webContents.executeJavaScript = executeJavaScript(webview, browserWindow)
  webContents.setIgnoreMenuShortcuts = function() {
    // TODO:??
    console.warn(
      'Not implemented yet, please open a PR on https://github.com/skpm/sketch-module-web-view :)'
    )
  }
  webContents.setAudioMuted = function(/* muted */) {
    // TODO:??
    console.warn(
      'Not implemented yet, please open a PR on https://github.com/skpm/sketch-module-web-view :)'
    )
  }
  webContents.isAudioMuted = function() {
    // TODO:??
    console.warn(
      'Not implemented yet, please open a PR on https://github.com/skpm/sketch-module-web-view :)'
    )
  }
  webContents.setZoomFactor = function(factor) {
    webview.setMagnification_centeredAtPoint(factor, CGPointMake(0, 0))
  }
  webContents.getZoomFactor = function(callback) {
    callback(Number(webview.magnification()))
  }
  webContents.setZoomLevel = function(level) {
    // eslint-disable-next-line no-restricted-properties
    webContents.setZoomFactor(Math.pow(1.2, level))
  }
  webContents.getZoomLevel = function(callback) {
    // eslint-disable-next-line no-restricted-properties
    callback(Math.log(Number(webview.magnification())) / Math.log(1.2))
  }
  webContents.setVisualZoomLevelLimits = function(/* minimumLevel, maximumLevel */) {
    // TODO:??
    console.warn(
      'Not implemented yet, please open a PR on https://github.com/skpm/sketch-module-web-view :)'
    )
  }
  webContents.setLayoutZoomLevelLimits = function(/* minimumLevel, maximumLevel */) {
    // TODO:??
    console.warn(
      'Not implemented yet, please open a PR on https://github.com/skpm/sketch-module-web-view :)'
    )
  }

  // TODO:
  // webContents.undo = function() {
  //   webview.undoManager().undo()
  // }
  // webContents.redo = function() {
  //   webview.undoManager().redo()
  // }
  // webContents.cut = webview.cut
  // webContents.copy = webview.copy
  // webContents.paste = webview.paste
  // webContents.pasteAndMatchStyle = webview.pasteAsRichText
  // webContents.delete = webview.delete
  // webContents.replace = webview.replaceSelectionWithText

  webContents.send = function() {
    const script =
      'window.postMessage({' +
      'isSketchMessage: true,' +
      "origin: '" +
      String(__command.identifier()) +
      "'," +
      'args: ' +
      JSON.stringify([].slice.call(arguments)) +
      '}, "*")'
    webview.evaluateJavaScript_completionHandler(script, null)
  }

  webContents.getNativeWebview = function() {
    return webview
  }

  browserWindow.webContents = webContents
}


/***/ }),

/***/ "./node_modules/sketch-module-web-view/remote.js":
/*!*******************************************************!*\
  !*** ./node_modules/sketch-module-web-view/remote.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* globals NSThread */
var threadDictionary = NSThread.mainThread().threadDictionary()

module.exports.getWebview = function(identifier) {
  return __webpack_require__(/*! ./lib */ "./node_modules/sketch-module-web-view/lib/index.js").fromId(identifier) // eslint-disable-line
}

module.exports.isWebviewPresent = function isWebviewPresent(identifier) {
  return !!threadDictionary[identifier]
}

module.exports.sendToWebview = function sendToWebview(identifier, evalString) {
  if (!module.exports.isWebviewPresent(identifier)) {
    return
  }

  var panel = threadDictionary[identifier]
  var webview = null
  var subviews = panel.contentView().subviews()
  for (var i = 0; i < subviews.length; i += 1) {
    if (
      !webview &&
      !subviews[i].isKindOfClass(WKInspectorWKWebView) &&
      subviews[i].isKindOfClass(WKWebView)
    ) {
      webview = subviews[i]
    }
  }

  if (!webview || !webview.evaluateJavaScript_completionHandler) {
    throw new Error('Webview ' + identifier + ' not found')
  }

  webview.evaluateJavaScript_completionHandler(evalString, null)
}


/***/ }),

/***/ "./node_modules/sketch-polyfill-fetch/lib/index.js":
/*!*********************************************************!*\
  !*** ./node_modules/sketch-polyfill-fetch/lib/index.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(Promise) {/* globals NSJSONSerialization NSJSONWritingPrettyPrinted NSDictionary NSHTTPURLResponse NSString NSASCIIStringEncoding NSUTF8StringEncoding coscript NSURL NSMutableURLRequest NSMutableData NSURLConnection */
var Buffer;
try {
  Buffer = __webpack_require__(/*! buffer */ "buffer").Buffer;
} catch (err) {}

function response(httpResponse, data) {
  var keys = [];
  var all = [];
  var headers = {};
  var header;

  for (var i = 0; i < httpResponse.allHeaderFields().allKeys().length; i++) {
    var key = httpResponse
      .allHeaderFields()
      .allKeys()
      [i].toLowerCase();
    var value = String(httpResponse.allHeaderFields()[key]);
    keys.push(key);
    all.push([key, value]);
    header = headers[key];
    headers[key] = header ? header + "," + value : value;
  }

  return {
    ok: ((httpResponse.statusCode() / 200) | 0) == 1, // 200-399
    status: Number(httpResponse.statusCode()),
    statusText: String(
      NSHTTPURLResponse.localizedStringForStatusCode(httpResponse.statusCode())
    ),
    useFinalURL: true,
    url: String(httpResponse.URL().absoluteString()),
    clone: response.bind(this, httpResponse, data),
    text: function() {
      return new Promise(function(resolve, reject) {
        const str = String(
          NSString.alloc().initWithData_encoding(data, NSASCIIStringEncoding)
        );
        if (str) {
          resolve(str);
        } else {
          reject(new Error("Couldn't parse body"));
        }
      });
    },
    json: function() {
      return new Promise(function(resolve, reject) {
        var str = String(
          NSString.alloc().initWithData_encoding(data, NSUTF8StringEncoding)
        );
        if (str) {
          // parse errors are turned into exceptions, which cause promise to be rejected
          var obj = JSON.parse(str);
          resolve(obj);
        } else {
          reject(
            new Error(
              "Could not parse JSON because it is not valid UTF-8 data."
            )
          );
        }
      });
    },
    blob: function() {
      return Promise.resolve(data);
    },
    arrayBuffer: function() {
      return Promise.resolve(Buffer.from(data));
    },
    headers: {
      keys: function() {
        return keys;
      },
      entries: function() {
        return all;
      },
      get: function(n) {
        return headers[n.toLowerCase()];
      },
      has: function(n) {
        return n.toLowerCase() in headers;
      }
    }
  };
}

// We create one ObjC class for ourselves here
var DelegateClass;

function fetch(urlString, options) {
  if (
    typeof urlString === "object" &&
    (!urlString.isKindOfClass || !urlString.isKindOfClass(NSString))
  ) {
    options = urlString;
    urlString = options.url;
  }
  options = options || {};
  if (!urlString) {
    return Promise.reject("Missing URL");
  }
  var fiber;
  try {
    fiber = coscript.createFiber();
  } catch (err) {
    coscript.shouldKeepAround = true;
  }
  return new Promise(function(resolve, reject) {
    var url = NSURL.alloc().initWithString(urlString);
    var request = NSMutableURLRequest.requestWithURL(url);
    request.setHTTPMethod(options.method || "GET");

    Object.keys(options.headers || {}).forEach(function(i) {
      request.setValue_forHTTPHeaderField(options.headers[i], i);
    });

    if (options.body) {
      var data;
      if (typeof options.body === "string") {
        var str = NSString.alloc().initWithString(options.body);
        data = str.dataUsingEncoding(NSUTF8StringEncoding);
      } else if (Buffer && Buffer.isBuffer(options.body)) {
        data = options.body.toNSData();
      } else if (
        options.body.isKindOfClass &&
        options.body.isKindOfClass(NSData) == 1
      ) {
        data = options.body;
      } else if (options.body._isFormData) {
        var boundary = options.body._boundary;
        data = options.body._data;
        data.appendData(
          NSString.alloc()
            .initWithString("--" + boundary + "--\r\n")
            .dataUsingEncoding(NSUTF8StringEncoding)
        );
        request.setValue_forHTTPHeaderField(
          "multipart/form-data; boundary=" + boundary,
          "Content-Type"
        );
      } else {
        var error;
        data = NSJSONSerialization.dataWithJSONObject_options_error(
          options.body,
          NSJSONWritingPrettyPrinted,
          error
        );
        if (error != null) {
          return reject(error);
        }
        request.setValue_forHTTPHeaderField(
          "" + data.length(),
          "Content-Length"
        );
      }
      request.setHTTPBody(data);
    }

    if (options.cache) {
      switch (options.cache) {
        case "reload":
        case "no-cache":
        case "no-store": {
          request.setCachePolicy(1); // NSURLRequestReloadIgnoringLocalCacheData
        }
        case "force-cache": {
          request.setCachePolicy(2); // NSURLRequestReturnCacheDataElseLoad
        }
        case "only-if-cached": {
          request.setCachePolicy(3); // NSURLRequestReturnCacheDataElseLoad
        }
      }
    }

    if (!options.credentials) {
      request.setHTTPShouldHandleCookies(false);
    }

    var finished = false;

    var connection = NSURLSession.sharedSession().dataTaskWithRequest_completionHandler(
      request,
      __mocha__.createBlock_function(
        'v32@?0@"NSData"8@"NSURLResponse"16@"NSError"24',
        function(data, res, error) {
          if (fiber) {
            fiber.cleanup();
          } else {
            coscript.shouldKeepAround = false;
          }
          if (error) {
            finished = true;
            return reject(error);
          }
          return resolve(response(res, data));
        }
      )
    );

    connection.resume();

    if (fiber) {
      fiber.onCleanup(function() {
        if (!finished) {
          connection.cancel();
        }
      });
    }
  });
}

module.exports = fetch;

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./node_modules/promise-polyfill/lib/index.js */ "./node_modules/promise-polyfill/lib/index.js")))

/***/ }),

/***/ "./node_modules/timers-browserify/main.js":
/*!************************************************!*\
  !*** ./node_modules/timers-browserify/main.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(global, setTimeout, clearTimeout, setInterval, clearInterval) {var scope = (typeof global !== "undefined" && global) ||
            (typeof self !== "undefined" && self) ||
            window;
var apply = Function.prototype.apply;

// DOM APIs, for completeness

exports.setTimeout = function() {
  return new Timeout(apply.call(setTimeout, scope, arguments), clearTimeout);
};
exports.setInterval = function() {
  return new Timeout(apply.call(setInterval, scope, arguments), clearInterval);
};
exports.clearTimeout =
exports.clearInterval = function(timeout) {
  if (timeout) {
    timeout.close();
  }
};

function Timeout(id, clearFn) {
  this._id = id;
  this._clearFn = clearFn;
}
Timeout.prototype.unref = Timeout.prototype.ref = function() {};
Timeout.prototype.close = function() {
  this._clearFn.call(scope, this._id);
};

// Does not start the time, just sets up the members needed.
exports.enroll = function(item, msecs) {
  clearTimeout(item._idleTimeoutId);
  item._idleTimeout = msecs;
};

exports.unenroll = function(item) {
  clearTimeout(item._idleTimeoutId);
  item._idleTimeout = -1;
};

exports._unrefActive = exports.active = function(item) {
  clearTimeout(item._idleTimeoutId);

  var msecs = item._idleTimeout;
  if (msecs >= 0) {
    item._idleTimeoutId = setTimeout(function onTimeout() {
      if (item._onTimeout)
        item._onTimeout();
    }, msecs);
  }
};

// setimmediate attaches itself to the global object
__webpack_require__(/*! setimmediate */ "./node_modules/setimmediate/setImmediate.js");
// On some exotic environments, it's not clear which object `setimmediate` was
// able to install onto.  Search each possibility in the same order as the
// `setimmediate` library.
exports.setImmediate = (typeof self !== "undefined" && self.setImmediate) ||
                       (typeof global !== "undefined" && global.setImmediate) ||
                       (this && this.setImmediate);
exports.clearImmediate = (typeof self !== "undefined" && self.clearImmediate) ||
                         (typeof global !== "undefined" && global.clearImmediate) ||
                         (this && this.clearImmediate);

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "./node_modules/webpack/buildin/global.js"), __webpack_require__(/*! ./node_modules/@skpm/timers/timeout.js */ "./node_modules/@skpm/timers/timeout.js")["setTimeout"], __webpack_require__(/*! ./node_modules/@skpm/timers/timeout.js */ "./node_modules/@skpm/timers/timeout.js")["clearTimeout"], __webpack_require__(/*! ./node_modules/@skpm/timers/interval.js */ "./node_modules/@skpm/timers/interval.js")["setInterval"], __webpack_require__(/*! ./node_modules/@skpm/timers/interval.js */ "./node_modules/@skpm/timers/interval.js")["clearInterval"]))

/***/ }),

/***/ "./node_modules/webpack/buildin/global.js":
/*!***********************************!*\
  !*** (webpack)/buildin/global.js ***!
  \***********************************/
/*! no static exports found */
/***/ (function(module, exports) {

var g;

// This works in non-strict mode
g = (function() {
	return this;
})();

try {
	// This works if eval is allowed (see CSP)
	g = g || new Function("return this")();
} catch (e) {
	// This works if the window reference is available
	if (typeof window === "object") g = window;
}

// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}

module.exports = g;


/***/ }),

/***/ "./src/globalConfig.js":
/*!*****************************!*\
  !*** ./src/globalConfig.js ***!
  \*****************************/
/*! exports provided: timeStamp, enableAdaptive, enableWebInspector, gc_sidebar_base_url, gc_sidebar_domain, gc_uxfm_domain, gc_uxfm_ip, gc_sidebar_server_ip, gc_sidebar_path_name, gc_adaptive_base_host, gc_adaptive_domain */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "timeStamp", function() { return timeStamp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "enableAdaptive", function() { return enableAdaptive; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "enableWebInspector", function() { return enableWebInspector; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "gc_sidebar_base_url", function() { return gc_sidebar_base_url; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "gc_sidebar_domain", function() { return gc_sidebar_domain; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "gc_uxfm_domain", function() { return gc_uxfm_domain; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "gc_uxfm_ip", function() { return gc_uxfm_ip; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "gc_sidebar_server_ip", function() { return gc_sidebar_server_ip; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "gc_sidebar_path_name", function() { return gc_sidebar_path_name; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "gc_adaptive_base_host", function() { return gc_adaptive_base_host; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "gc_adaptive_domain", function() { return gc_adaptive_domain; });
/* harmony import */ var sketch_settings__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! sketch/settings */ "sketch/settings");
/* harmony import */ var sketch_settings__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(sketch_settings__WEBPACK_IMPORTED_MODULE_0__);
/*
 * 所有的url连接配置都在这里, 连本地和特定电脑的自己看下本地部署情况,去函数里面调整, 生产环境暂时没有配置, 后续补充
 */
 // import logUtil from './ux/src/utils/logUtil';

var timeStamp = sketch_settings__WEBPACK_IMPORTED_MODULE_0___default.a.settingForKey('timeStamp'); // 环境标签

var ENV_LOCAL = 'local'; // 本地环境

var ENV_SOMEONE = 'someone'; // 某台机器环境

var ENV_DEV = 'dev'; // 开发环境

var ENV_DEV_NO_PORTAL = 'dev_no_portal'; // 开发环境, 无代理

var ENV_BETA = 'beta'; // 测试环境

var ENV_PROD = 'prod'; // 正式环境
//= ================这里面不是url,配置OC打开的webview能否开启"检查元素"的功能=========================

var enableWebInspector = true; // 默认在测试环境和正式环境下关闭, 其他情况打开

switch ("beta") {
  case ENV_BETA:
  case ENV_PROD:
    enableWebInspector = false;
    break;

  default:
    enableWebInspector = true;
    break;
} //= ================正式环境屏蔽响应式功能=========================


var enableAdaptive = true;

if ("beta" == ENV_PROD) {
  enableAdaptive = true;
} //= ===================================下面的是url===============================================
// 开发环境


var DOMAIN_DEV = 'http://dev.huawei.com:8086'; // 需要配置host
// const DOMAIN_DEV = 'http://uxs-beta.rnd.huawei.com:8086';   //需要配置host

var IP_DEV = 'http://10.244.193.53:8086'; // 开发环境, 无代理的路径

var DOMAIN_DEV_NO_PORTAL = 'http://dev.huawei.com:8086'; // 需要配置host

var IP_DEV_NO_PORTAL = 'http://10.244.193.53:8086'; // beta(测试)环境
// const DOMAIN_BETA = 'http://uxc-beta.rnd.huawei.com';
// const IP_BETA = 'http://10.178.231.200';
// const DOMAIN_BETA = 'http://hongtool.harmonyos.com:8086';

var DOMAIN_BETA = 'http://hongtool.huawei.com:8086';
var IP_BETA = 'http://10.33.151.182:8086'; // 生产环境, 待定

var DOMAIN_PROD = 'http://designtool.rnd.huawei.com';
var IP_PROD = 'http://100.101.149.247'; // 本地环境

var DOMAIN_LOCAL = 'http://local.huawei.com'; // 需要本地配置host

var IP_LOCAL = 'http://127.0.0.1'; //= =====================下面是siderbar里面相关的配置=========================
// sidebar上面前端页面的url前缀
// let gc_sidebar_base_url = `${DOMAIN_DEV}/sketchcloud/`; //默认开发环境sketchcloud_test

var gc_sidebar_base_url = "".concat(DOMAIN_DEV, "/"); // 默认开发环境sketchcloud_test
// sidebar上的后台服务url前缀
// let gc_sidebar_domain = `${DOMAIN_DEV}/sketchcloud`;

var gc_sidebar_domain = "".concat(DOMAIN_DEV); // sidebar上的后台服务url前缀(ip方式, 注意不要代理服务器的ip)

var gc_sidebar_server_ip = "".concat(IP_DEV); // sidebar上的后台服务url里面在中间拼接的路径串

var gc_sidebar_path_name = 'sketchcloud'; // url里拼接的字符串内容

var to_sidebar_name = '/sketchcloud'; /// /////dev
// let to_sidebar_name = '';////////beta
// uxfm 的后台服务地址

var gc_uxfm_domain = "".concat(DOMAIN_DEV); // uxfm 的后台服务ip地址

var gc_uxfm_ip = "".concat(IP_DEV); //= ====================下面是adaptive相关的配置==============================
// 自适应的url前缀

var gc_adaptive_base_host = "".concat(DOMAIN_DEV, "/sketchcloud/uxSketch"); // 自适应的url前缀(ip方式, 注意不要代理服务器的ip)

var gc_adaptive_domain = "".concat(IP_DEV).concat(to_sidebar_name, "/uxSketch"); //= ===================================下面的是url处理逻辑===========================================

switch ("beta") {
  case ENV_LOCAL:
    // 本地环境
    localEnv();
    break;

  case ENV_SOMEONE:
    // 其他某个人的环境, 需要连接的自己在这边调
    someoneEnv();
    break;

  case ENV_DEV:
    // 开发环境
    devEnv();
    break;

  case ENV_BETA:
    // beta(测试)环境
    betaEnv();
    break;

  case ENV_PROD:
    // 正式(生产)环境
    prodEnv();
    break;

  default:
    // 默认在开发环境
    break;
} // 这里使用时候需要视部署情况手动调整


function localEnv() {
  var serviceEnv = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ENV_DEV_NO_PORTAL;
  to_sidebar_name = '/sketchcloud'; // sidebar上面前端页面的url前缀, 视本地情况自己改

  gc_sidebar_base_url = "http://junjie.huawei.com:4300".concat(to_sidebar_name, "/"); // 自适应的url前缀, 视本地情况自己改

  gc_adaptive_base_host = "http://junjie.huawei.com:4301/sketchcloud/uxSketch"; // 自适应的url前缀(ip方式, 注意不要代理服务器的ip), 视本地情况自己改

  gc_adaptive_domain = "".concat(IP_LOCAL).concat(to_sidebar_name, "/uxSketch"); // sidebar的后台服务, 默认连开发环境, 可以自己调整(ENV_DEV_NO_PORTAL, ENV_DEV等, 去82行左右调整函数传参)

  initSidebarServiceEnv(serviceEnv);
} // 这里使用时候需要视部署情况手动调整


function someoneEnv() {
  var serviceEnv = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ENV_DEV_NO_PORTAL;
  to_sidebar_name = '/sketchcloud';
  var JUNJIE_DOMAIN_DEV = 'http://junjie.huawei.com'; // sidebar上面前端页面的url前缀, 视情况自己改

  gc_sidebar_base_url = "".concat(JUNJIE_DOMAIN_DEV, ":4300").concat(to_sidebar_name, "/"); // 自适应的url前缀, 视情况自己改

  gc_adaptive_base_host = "".concat(JUNJIE_DOMAIN_DEV, ":4301/sketchcloud/uxSketch"); // 自适应的url前缀(ip方式, 注意不要代理服务器的ip), 视情况自己改

  gc_adaptive_domain = "".concat(IP_DEV).concat(to_sidebar_name, "/uxSketch"); // sidebar的后台服务, 默认连开发环境, 可以自己调整(ENV_DEV_NO_PORTAL, ENV_DEV等, 去87行左右调整函数传参)

  initSidebarServiceEnv(serviceEnv);
}

function devEnv() {
  to_sidebar_name = '/sketchcloud';
  gc_sidebar_base_url = "".concat(DOMAIN_DEV, "/sketchcloud/");
  gc_adaptive_base_host = "".concat(DOMAIN_DEV, "/sketchcloud/uxSketch");
  gc_adaptive_domain = "".concat(IP_DEV, "/sketchcloud/uxSketch");
  initSidebarServiceEnv(ENV_DEV);
}

function betaEnv() {
  to_sidebar_name = ''; // gc_sidebar_base_url = `${DOMAIN_BETA}/sketchcloud/`;
  // gc_adaptive_base_host = `${DOMAIN_BETA}/sketchcloud/uxSketch`;
  // gc_adaptive_domain = `${IP_BETA}/sketchcloud/uxSketch`;

  gc_sidebar_base_url = "".concat(DOMAIN_BETA, "/"); // gc_adaptive_base_host = `${DOMAIN_BETA}/uxSketch`;

  gc_adaptive_base_host = "".concat(DOMAIN_BETA, "/uxSketch");
  gc_adaptive_domain = "".concat(IP_BETA, "/uxSketch");
  initSidebarServiceEnv(ENV_BETA);
}

function prodEnv() {
  to_sidebar_name = '';
  gc_sidebar_base_url = "".concat(DOMAIN_PROD, "/sketchcloud/");
  gc_adaptive_base_host = "".concat(DOMAIN_PROD, "/sketchcloud/uxSketch");
  gc_adaptive_domain = "".concat(IP_PROD, "/sketchcloud/uxSketch");
  initSidebarServiceEnv(ENV_PROD);
}

function initSidebarServiceEnv(envTag) {
  switch (envTag) {
    case ENV_LOCAL:
      localSidebarServiceEnv();
      break;

    case ENV_DEV:
      gc_sidebar_domain = "".concat(DOMAIN_DEV).concat(to_sidebar_name);
      gc_uxfm_domain = "".concat(DOMAIN_DEV);
      gc_uxfm_ip = "".concat(IP_DEV);
      gc_sidebar_server_ip = "".concat(IP_DEV);
      gc_sidebar_path_name = "sketchcloud";
      break;

    case ENV_DEV_NO_PORTAL:
      // 这里多了一个无代理的开发环境
      gc_sidebar_domain = "".concat(DOMAIN_DEV_NO_PORTAL).concat(to_sidebar_name);
      gc_uxfm_domain = "".concat(DOMAIN_DEV_NO_PORTAL);
      gc_uxfm_ip = "".concat(IP_DEV_NO_PORTAL);
      gc_sidebar_server_ip = "".concat(IP_DEV_NO_PORTAL);
      gc_sidebar_path_name = "sketchcloud";
      break;

    case ENV_BETA:
      // gc_sidebar_domain = `${DOMAIN_BETA}/sketchcloud`;
      gc_sidebar_domain = "".concat(DOMAIN_BETA).concat(to_sidebar_name);
      gc_uxfm_domain = "".concat(DOMAIN_BETA);
      gc_uxfm_ip = "".concat(IP_BETA);
      gc_sidebar_server_ip = "".concat(IP_BETA);
      gc_sidebar_path_name = '';
      break;

    case ENV_PROD:
      gc_sidebar_domain = "".concat(DOMAIN_PROD).concat(to_sidebar_name);
      gc_uxfm_domain = "".concat(DOMAIN_PROD);
      gc_uxfm_ip = "".concat(IP_PROD);
      gc_sidebar_server_ip = "".concat(IP_PROD);
      gc_sidebar_path_name = "sketchcloud";
      break;

    default:
      break;
  }
} // 本地sidebar后台接口服务的环境配置, 一般只有后台开发要用这里, 注意结合前面的配置设置


function localSidebarServiceEnv() {
  gc_sidebar_domain = "".concat(DOMAIN_LOCAL).concat(to_sidebar_name);
  gc_uxfm_domain = "".concat(DOMAIN_LOCAL).concat(to_sidebar_name);
  gc_sidebar_server_ip = "".concat(IP_LOCAL);
  gc_sidebar_path_name = "sketchcloud";
} // let info = {
//   'enableWebInspector': enableWebInspector,
//   'gc_sidebar_base_url': gc_sidebar_base_url,
//   'gc_sidebar_domain': gc_sidebar_domain,
//   'gc_uxfm_domain': gc_uxfm_domain,
//   'gc_uxfm_ip': gc_uxfm_ip,
//   'gc_sidebar_server_ip': gc_sidebar_server_ip,
//   'gc_sidebar_path_name': gc_sidebar_path_name,
//   'gc_adaptive_base_host': gc_adaptive_base_host,
//   'gc_adaptive_domain': gc_adaptive_domain
// };
// logUtil.log({sketch_env_info: info});




/***/ }),

/***/ "./src/styleLink/styleLink.js":
/*!************************************!*\
  !*** ./src/styleLink/styleLink.js ***!
  \************************************/
/*! exports provided: default, styleSelectionChanged */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return onRun; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "styleSelectionChanged", function() { return styleSelectionChanged; });
/* harmony import */ var _styleLinkFn_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./styleLinkFn.js */ "./src/styleLink/styleLinkFn.js");
/* harmony import */ var _util_login_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/login.js */ "./src/util/login.js");
/* harmony import */ var sketch_dom__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! sketch/dom */ "sketch/dom");
/* harmony import */ var sketch_dom__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(sketch_dom__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var sketch_module_web_view_remote__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! sketch-module-web-view/remote */ "./node_modules/sketch-module-web-view/remote.js");
/* harmony import */ var sketch_module_web_view_remote__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(sketch_module_web_view_remote__WEBPACK_IMPORTED_MODULE_3__);




var BROWSER_ID = 'sketchCloud.styleLink';
function onRun(context) {
  _styleLinkFn_js__WEBPACK_IMPORTED_MODULE_0__["default"].init(context);
  _util_login_js__WEBPACK_IMPORTED_MODULE_1__["default"].loginInfo('', {
    type: 'artboardStyle',
    context: context,
    BROWSER_ID: BROWSER_ID,
    callback: function callback(context) {
      return _styleLinkFn_js__WEBPACK_IMPORTED_MODULE_0__["default"].showPanel(context);
    }
  });
}
function styleSelectionChanged(context) {
  if (!Object(sketch_module_web_view_remote__WEBPACK_IMPORTED_MODULE_3__["isWebviewPresent"])(BROWSER_ID)) {
    return;
  }

  var action = context.actionContext;
  var newSelection = action.newSelection;

  if (newSelection.length === 1) {
    var selectionObj = sketch_dom__WEBPACK_IMPORTED_MODULE_2___default.a.fromNative(newSelection[0]);

    if (selectionObj.type === 'Artboard' && Object(sketch_module_web_view_remote__WEBPACK_IMPORTED_MODULE_3__["isWebviewPresent"])(BROWSER_ID)) {
      var artboardInfo = _styleLinkFn_js__WEBPACK_IMPORTED_MODULE_0__["default"].getArtboardStyleInfo(selectionObj);

      if (artboardInfo) {
        Object(sketch_module_web_view_remote__WEBPACK_IMPORTED_MODULE_3__["sendToWebview"])(BROWSER_ID, 'postArtboardInfo(' + JSON.stringify(artboardInfo) + ')');
      }
    }

    if (selectionObj.type !== 'Artboard' && Object(sketch_module_web_view_remote__WEBPACK_IMPORTED_MODULE_3__["isWebviewPresent"])(BROWSER_ID)) {
      var _artboardInfo = {
        symbolInfos: [],
        otherInfos: []
      };
      Object(sketch_module_web_view_remote__WEBPACK_IMPORTED_MODULE_3__["sendToWebview"])(BROWSER_ID, 'postArtboardInfo(' + JSON.stringify({
        artboardInfo: _artboardInfo
      }) + ')');
    }
  } else if (newSelection.length === 0) {
    // select none
    if (Object(sketch_module_web_view_remote__WEBPACK_IMPORTED_MODULE_3__["isWebviewPresent"])(BROWSER_ID)) {
      var _artboardInfo2 = {
        symbolInfos: [],
        otherInfos: []
      };
      Object(sketch_module_web_view_remote__WEBPACK_IMPORTED_MODULE_3__["sendToWebview"])(BROWSER_ID, 'postArtboardInfo(' + JSON.stringify({
        artboardInfo: _artboardInfo2
      }) + ')');
    }
  }

  return false;
}

/***/ }),

/***/ "./src/styleLink/styleLinkFn.js":
/*!**************************************!*\
  !*** ./src/styleLink/styleLinkFn.js ***!
  \**************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var sketch_dom__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! sketch/dom */ "sketch/dom");
/* harmony import */ var sketch_dom__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(sketch_dom__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var sketch_settings__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! sketch/settings */ "sketch/settings");
/* harmony import */ var sketch_settings__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(sketch_settings__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var sketch_module_web_view__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! sketch-module-web-view */ "./node_modules/sketch-module-web-view/lib/index.js");
/* harmony import */ var sketch_module_web_view__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(sketch_module_web_view__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _util_config_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../util/config.js */ "./src/util/config.js");
/* harmony import */ var sketch_ui__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! sketch/ui */ "sketch/ui");
/* harmony import */ var sketch_ui__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(sketch_ui__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _util_util_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/util.js */ "./src/util/util.js");
/* harmony import */ var _util_lang_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/lang.js */ "./src/util/lang.js");







var BROWSER_ID = 'sketchCloud.styleLink';
var styleLinkFn = {
  init: function init(context) {
    this.context = context;
    this.document = sketch_dom__WEBPACK_IMPORTED_MODULE_0___default.a.getSelectedDocument();
    this.selectedLayers = this.document.selectedLayers && this.document.selectedLayers.layers && this.document.selectedLayers.layers[0];
    this.artboard = this.selectedLayers && this.selectedLayers.type === 'Artboard' && this.selectedLayers;
    this.extend(context);
    this.layerMaps = {};
  },
  extend: function extend(options, target) {
    target = target || this;

    for (var option in options) {
      target[option] = options[option];
    }

    return target;
  },
  getArtboardStyleInfo: function getArtboardStyleInfo(artboard) {
    var self = this;
    var artboardInfo = {
      symbolInfos: [],
      otherInfos: [],
      librarySymbolNum: 0
    };
    artboard = artboard || self.artboard;

    if (!artboard) {
      return artboardInfo;
    }

    artboardInfo.artboardName = artboard.name;
    self.searchInLayer(artboard, artboardInfo);
    return artboardInfo;
  },
  searchInLayer: function searchInLayer(layer, artboardInfo, symbolFlag, symbolInfoLayers) {
    if (!layer) {
      return;
    }

    var layerType = layer.type;
    var self = this;

    switch (layerType) {
      case 'Text':
        this.searchInTextLayer(layer, self, symbolFlag, symbolInfoLayers, artboardInfo);
        break;

      case 'Shape':
      case 'ShapePath':
        this.searchInShapeLayer(layer, self, symbolFlag, symbolInfoLayers, artboardInfo);
        break;

      case 'SymbolMaster':
        this.searchInSymbolMasterLayer(layer, self, artboardInfo);
        break;

      case 'Group':
      case 'Artboard':
        this.searchInGroupLayer(layer, self, artboardInfo, symbolFlag, symbolInfoLayers);
        break;

      case 'SymbolInstance':
        this.searchInSymbolInstanceLayer(layer, self, artboardInfo, symbolFlag, symbolInfoLayers);
        break;
    }
  },
  searchInTextLayer: function searchInTextLayer(layer, self, symbolFlag, symbolInfoLayers, artboardInfo) {
    if (!layer.hidden && !self.layerMaps[layer.id]) {
      self.layerMaps[layer.id] = layer;
      var textLinkedInfo = self.getLinkedInfo(layer);
      var textInfo = {};
      textInfo.type = 'textStyle';
      textInfo.id = layer.id;
      textInfo.name = layer.name;
      textInfo.fill = layer.style.textColor && self.rgba2argb(layer.style.textColor);
      textInfo.fontWeight = self.getfontWeight(layer.style.fontWeight, layer.style.fontFamily);
      textInfo.fontSize = layer.style.fontSize;
      textInfo.linked = textLinkedInfo.linked;
      textInfo.linkedInfo = textLinkedInfo.linkedInfo;

      if (symbolFlag) {
        symbolInfoLayers.push(textInfo);
      } else {
        artboardInfo['otherInfos'].push(textInfo);
      }
    }
  },
  searchInShapeLayer: function searchInShapeLayer(layer, self, symbolFlag, symbolInfoLayers, artboardInfo) {
    if (!layer.hidden && !self.layerMaps[layer.id]) {
      self.layerMaps[layer.id] = layer;
      var layerLinkedInfo = self.getLinkedInfo(layer);
      var layerInfo = {};
      layerInfo.type = 'layerStyle';
      layerInfo.id = layer.id;
      layerInfo.name = layer.name;
      layerInfo.fill = layer.style.fills[0] && layer.style.fills[0].color && self.rgba2argb(layer.style.fills[0].color) || '00000000';
      layerInfo.linked = layerLinkedInfo.linked;
      layerInfo.linkedInfo = layerLinkedInfo.linkedInfo;

      if (symbolFlag) {
        symbolInfoLayers.push(layerInfo);
      } else {
        artboardInfo['otherInfos'].push(layerInfo);
      }
    }
  },
  searchInSymbolMasterLayer: function searchInSymbolMasterLayer(layer, self, artboardInfo) {
    if (!layer.hidden && !self.layerMaps[layer.id]) {
      self.layerMaps[layer.id] = layer;
      var symbolInfo = {};
      var symbollayers = layer.layers;
      symbolInfo.name = layer.name;
      symbolInfo.id = layer.id;
      symbolInfo.layers = [];
      artboardInfo['symbolInfos'].push(symbolInfo);

      for (var i = 0; i < symbollayers.length; i++) {
        var symbollayer = symbollayers[i];
        self.searchInLayer(symbollayer, artboardInfo, true, symbolInfo.layers);
      }
    }
  },
  searchInGroupLayer: function searchInGroupLayer(layer, self, artboardInfo, symbolFlag, symbolInfoLayers) {
    if (!layer.hidden) {
      var sublayers = layer.layers;

      for (var i = 0; i < sublayers.length; i++) {
        var sublayer = sublayers[i];
        self.searchInLayer(sublayer, artboardInfo, symbolFlag, symbolInfoLayers);
      }
    }
  },
  searchInSymbolInstanceLayer: function searchInSymbolInstanceLayer(layer, self, artboardInfo, symbolFlag, symbolInfoLayers) {
    if (!layer.hidden) {
      var master = layer.master;
      var library = master && master.getLibrary();

      if (master && !library) {
        self.searchInLayer(master, artboardInfo, symbolFlag, symbolInfoLayers);
      }

      if (master && library) {
        artboardInfo.librarySymbolNum += 1;
      }
    }
  },
  handleLinkedInfoWithTextLayer: function handleLinkedInfoWithTextLayer(layer, linkedInfos) {
    var textColor = layer.style.textColor;
    var fontSize = layer.style.fontSize;
    var fontWeight = layer.style.fontWeight;
    var colorInfo = sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.layerSettingForKey(layer, 'color');
    var fontSizeInfo = sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.layerSettingForKey(layer, 'fontSize');
    var fontFamiliesInfo = sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.layerSettingForKey(layer, 'fontFamilies');

    if (layer.sharedStyleId) {
      var sharedTextStyle = sketch_dom__WEBPACK_IMPORTED_MODULE_0___default.a.getSelectedDocument().getSharedTextStyleWithID(layer.sharedStyleId);

      if (sharedTextStyle && sharedTextStyle.style.textColor === textColor && sharedTextStyle.style.fontSize === fontSize && sharedTextStyle.style.fontWeight === fontWeight) {
        linkedInfos.linked = true;
        linkedInfos.linkedInfo.style = sharedTextStyle.name;
      }
    } else {
      if (colorInfo && colorInfo.name) {
        linkedInfos.linked = true;
        linkedInfos.linkedInfo.fill = colorInfo.name;
      }

      if (fontSizeInfo && fontSizeInfo.name) {
        linkedInfos.linked = true;
        linkedInfos.linkedInfo.fontSize = fontSizeInfo.name;
      }

      if (fontFamiliesInfo && fontFamiliesInfo.name) {
        linkedInfos.linked = true;
        linkedInfos.linkedInfo.fontWeight = fontFamiliesInfo.name;
      }
    }

    return linkedInfos;
  },
  handleLinkedInfoWithUnTextLayer: function handleLinkedInfoWithUnTextLayer(layer, linkedInfos) {
    var layerColor = layer.style.fills[0] && layer.style.fills[0].color;
    var colorInfo = sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.layerSettingForKey(layer, 'color');

    if (layer.sharedStyleId) {
      var sharedLayerStyle = sketch_dom__WEBPACK_IMPORTED_MODULE_0___default.a.getSelectedDocument().getSharedLayerStyleWithID(layer.sharedStyleId);

      if (sharedLayerStyle && sharedLayerStyle.style.fills[0].color === layerColor) {
        linkedInfos.linked = true;
        linkedInfos.linkedInfo.style = sharedLayerStyle.name;
      }
    } else {
      if (colorInfo && colorInfo.name) {
        linkedInfos.linked = true;
        linkedInfos.linkedInfo.fill = colorInfo.name;
      }
    }

    return linkedInfos;
  },
  getLinkedInfo: function getLinkedInfo(layer) {
    var linkedInfos = {
      linked: false,
      linkedInfo: {}
    };

    if (layer.type === 'Text') {
      this.handleLinkedInfoWithTextLayer(layer, linkedInfos);
    } else {
      this.handleLinkedInfoWithUnTextLayer(layer, linkedInfos);
    }

    return linkedInfos;
  },
  handleUnnormalPlatformFontWeight: function handleUnnormalPlatformFontWeight(fontFamily, fontWeight) {
    if (fontFamily === 'PingFang SC') {
      if (fontWeight === 5) {
        fontWeight = 'Regular';
      } else if (fontWeight === 6) {
        fontWeight = 'Medium';
      } else if (fontWeight === 8) {
        fontWeight = 'Semibold';
      } else if (fontWeight === 6) {
        fontWeight = 'Bold Condensed';
      }
    } else if (fontFamily === 'Roboto') {
      if (fontWeight === 5) {
        fontWeight = 'Regular';
      } else if (fontWeight === 6) {
        fontWeight = 'Medium';
      } else if (fontWeight === 6) {
        fontWeight = 'Semibold';
      } else if (fontWeight === 9) {
        fontWeight = 'Bold Condensed';
      }
    } else if (fontFamily === 'Huawei Sans') {
      if (fontWeight === 5) {
        fontWeight = 'Regular';
      } else if (fontWeight === 9) {
        fontWeight = 'Bold Condensed';
      }
    } else if (fontFamily === 'Huawei Sans Medium') {
      fontWeight = 'Medium';
    } else {
      fontWeight = 'Regular';
    }

    return fontWeight;
  },
  getfontWeight: function getfontWeight(fontWeight, fontFamily) {
    var loginInfo = sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.settingForKey('loginInfo');
    var userInfo = loginInfo && loginInfo.userInfo;
    var platformId = parseInt(userInfo && userInfo.curPlatformInfo && userInfo.curPlatformInfo.platformId) || 1;

    if (platformId === 1) {
      if (fontWeight === 4) {
        fontWeight = 'regular';
      } else if (fontWeight === 7) {
        fontWeight = 'medium';
      } else {
        fontWeight = 'regular';
      }
    } else if (platformId === 2 || platformId === 3) {
      fontWeight = this.handleUnnormalPlatformFontWeight(fontFamily, fontWeight);
    } else if (platformId === 4) {
      fontWeight = 'Regular';
    }

    return fontWeight;
  },
  showPanel: function showPanel(context) {
    if (this.selectedLayers && this.selectedLayers.type === 'SymbolMaster') {
      var text = '请先选中一个Artboard';
      sketch_ui__WEBPACK_IMPORTED_MODULE_4___default.a.message(_util_lang_js__WEBPACK_IMPORTED_MODULE_6__["default"].LSTR(text));
      return;
    }

    if (!this.artboard) {
      var _text = '请先选中一个Artboard';
      sketch_ui__WEBPACK_IMPORTED_MODULE_4___default.a.message(_util_lang_js__WEBPACK_IMPORTED_MODULE_6__["default"].LSTR(_text));
      return;
    }

    var self = this;
    self.init(context);
    var width = 360;
    var height = 512;
    var frame = true;
    var title = '平台样式关联';
    var options = {
      identifier: BROWSER_ID,
      width: width,
      height: height,
      alwaysOnTop: true,
      frame: frame,
      title: title,
      backgroundColor: '#FFFFFF'
    };
    self.browserWindow = new sketch_module_web_view__WEBPACK_IMPORTED_MODULE_2___default.a(options);
    self.browserWindow.on('ready-to-show', function () {
      var code = NSLocale.currentLocale().languageCode();
      var langCmd = 'setLang("' + code + '")';
      browserWindow.webContents.executeJavaScript(langCmd);
      self.readToShowData();
    });
    self.browserWindow.webContents.on('reload', function (data) {
      console.log('reload === ');
      self.readToShowData();
    });
    browserWindow.webContents.on('did-finish-load', function (params) {
      self.readToShowData();
    });
    self.browserWindow.webContents.on('setSketchWebviewSize', function (data) {
      console.log('setSketchWebviewSize', data.width, data.height);
      var tempSize = self.browserWindow.getSize();

      if (parseInt(tempSize[0]) !== data.width || parseInt(tempSize[1]) !== data.height) {
        console.log('这里重置的大小4');
        console.log(tempSize, data, parseInt(tempSize[0]), data.width, parseInt(tempSize[1]), data.height, parseInt(tempSize[0]) !== data.width, parseInt(tempSize[1]) !== data.height);
        self.browserWindow.setSize(data.width, data.height);
      }
    });
    self.browserWindow.webContents.on('setArtboardStyleSize', function (data) {
      console.log('setArtboardStyleSize', data.width, data.height);
      var tempSize = self.browserWindow.getSize();

      if (parseInt(tempSize[0]) !== data.width || parseInt(tempSize[1]) !== data.height) {
        console.log('这里重置的大小5');
        console.log(tempSize, data, parseInt(tempSize[0]), data.width, parseInt(tempSize[1]), data.height, parseInt(tempSize[0]) !== data.width, parseInt(tempSize[1]) !== data.height);
        self.browserWindow.setSize(data.width, data.height);
      }
    });
    self.browserWindow.webContents.on('applyArtboardStyle', function (s) {
      var applyInfo = s.data;
      var libraryName = s.libraryName;
      var libraries = sketch_dom__WEBPACK_IMPORTED_MODULE_0___default.a.getLibraries().filter(function (l) {
        var path = l.valid && l.enabled && l.getDocument() && l.getDocument().path;
        return l.name === libraryName && (l.libraryType == 'Remote' || l.libraryType == 'RemoteThirdParty' || l.libraryType == 4) && path && path.indexOf(_util_config_js__WEBPACK_IMPORTED_MODULE_3__["default"].serverIP()) >= 0;
      });
      var styles = {
        layerStyles: {},
        textStyles: {}
      };

      if (libraries && libraries.length) {
        styles.layerStyles = self.createLookup(libraries[0].getImportableLayerStyleReferencesForDocument(sketch_dom__WEBPACK_IMPORTED_MODULE_0___default.a.getSelectedDocument()));
        styles.textStyles = self.createLookup(libraries[0].getImportableTextStyleReferencesForDocument(sketch_dom__WEBPACK_IMPORTED_MODULE_0___default.a.getSelectedDocument()));
      } else {
        var _text2 = '无法关联样式, 请在文件共享中检查样式文件是否已添加';
        sketch_ui__WEBPACK_IMPORTED_MODULE_4___default.a.message(_util_lang_js__WEBPACK_IMPORTED_MODULE_6__["default"].LSTR(_text2));
      }

      if (Object.keys(applyInfo).length) {
        Object.keys(applyInfo).forEach(function (d) {
          if (d === 'symbolInfos') {
            var symbolInfos = applyInfo['symbolInfos'];
            symbolInfos.forEach(function (symbolObj) {
              var layers = symbolObj.layers;
              layers.forEach(function (layerObj) {
                var id = layerObj.id;
                var type = layerObj.type;

                if (layerObj.linkedInfo) {
                  var layer = self.layerMaps[id];

                  if (!layer) {
                    layer = sketch_dom__WEBPACK_IMPORTED_MODULE_0___default.a.getSelectedDocument() && sketch_dom__WEBPACK_IMPORTED_MODULE_0___default.a.getSelectedDocument().getLayerWithID(id);
                  }

                  if (layer) {
                    var linkedInfo = layerObj.linkedInfo;

                    if (linkedInfo.style) {
                      if (type === 'layerStyle') {
                        var styleName = linkedInfo.style.name;

                        if (styles.layerStyles[styleName]) {
                          var imported = styles.layerStyles[styleName].import();

                          if (!layer.sharedStyleId || layer.sharedStyleId && layer.sharedStyleId !== imported.id) {
                            layer.sharedStyleId = imported.id;
                            layer.style.syncWithSharedStyle(imported);
                            var artboard = layer.getParentArtboard();

                            if (artboard && artboard.type === 'SymbolMaster') {
                              artboard.adjustToFit();
                            }
                          }
                        }
                      } else if (type === 'textStyle') {
                        var _styleName = linkedInfo.style.name;

                        if (styles.textStyles[_styleName]) {
                          var _imported = styles.textStyles[_styleName].import();

                          if (!layer.sharedStyleId || layer.sharedStyleId && layer.sharedStyleId !== _imported.id) {
                            layer.sharedStyleId = _imported.id;
                            layer.style.syncWithSharedStyle(_imported);

                            var _artboard = layer.getParentArtboard();

                            if (_artboard && _artboard.type === 'SymbolMaster') {
                              _artboard.adjustToFit();
                            }
                          }
                        }
                      }
                    } else {
                      if (linkedInfo.fill) {
                        var data = {
                          name: linkedInfo.fill.name,
                          attr: 'color',
                          value: linkedInfo.fill.value && self.argb2rgba(linkedInfo.fill.value)
                        };
                        self.setStyleSelf(layer, data);
                      }

                      if (linkedInfo.fontSize) {
                        var _data = {
                          name: linkedInfo.fontSize.name,
                          attr: 'fontSize',
                          value: linkedInfo.fontSize.value
                        };
                        self.setStyleSelf(layer, _data);

                        var _artboard2 = layer.getParentArtboard();

                        if (_artboard2 && _artboard2.type === 'SymbolMaster') {
                          _artboard2.adjustToFit();
                        }
                      }

                      if (linkedInfo.fontWeight) {
                        var _data2 = {
                          name: linkedInfo.fontWeight.name,
                          attr: 'fontFamilies',
                          value: linkedInfo.fontWeight.value
                        };
                        self.setStyleSelf(layer, _data2);

                        var _artboard3 = layer.getParentArtboard();

                        if (_artboard3 && _artboard3.type === 'SymbolMaster') {
                          _artboard3.adjustToFit();
                        }
                      }
                    }
                  }
                }
              });
            });
          } else if (d === 'otherInfos') {
            var otherInfos = applyInfo['otherInfos'];
            otherInfos.forEach(function (layerObj) {
              var id = layerObj.id;
              var type = layerObj.type;

              if (layerObj.linkedInfo) {
                var layer = self.layerMaps[id];

                if (!layer) {
                  layer = sketch_dom__WEBPACK_IMPORTED_MODULE_0___default.a.getSelectedDocument() && sketch_dom__WEBPACK_IMPORTED_MODULE_0___default.a.getSelectedDocument().getLayerWithID(id);
                }

                var linkedInfo = layerObj.linkedInfo;

                if (layer) {
                  if (linkedInfo.style) {
                    if (type === 'layerStyle') {
                      var styleName = linkedInfo.style.name;

                      if (styles.layerStyles[styleName]) {
                        var imported = styles.layerStyles[styleName].import();

                        if (!layer.sharedStyleId || layer.sharedStyleId && layer.sharedStyleId !== imported.id) {
                          layer.sharedStyleId = imported.id;
                          layer.style.syncWithSharedStyle(imported);
                        }
                      }
                    } else if (type === 'textStyle') {
                      var _styleName2 = linkedInfo.style.name;

                      if (styles.textStyles[_styleName2]) {
                        var _imported2 = styles.textStyles[_styleName2].import();

                        if (!layer.sharedStyleId || layer.sharedStyleId && layer.sharedStyleId !== _imported2.id) {
                          layer.sharedStyleId = _imported2.id;
                          layer.style.syncWithSharedStyle(_imported2);
                        }
                      }
                    }
                  } else {
                    if (linkedInfo.fill) {
                      var data = {
                        name: linkedInfo.fill.name,
                        attr: 'color',
                        value: linkedInfo.fill.value && self.argb2rgba(linkedInfo.fill.value)
                      };
                      self.setStyleSelf(layer, data);
                    }

                    if (linkedInfo.fontSize) {
                      var _data3 = {
                        name: linkedInfo.fontSize.name,
                        attr: 'fontSize',
                        value: linkedInfo.fontSize.value
                      };
                      self.setStyleSelf(layer, _data3);
                    }

                    if (linkedInfo.fontWeight) {
                      var _data4 = {
                        name: linkedInfo.fontWeight.name,
                        attr: 'fontFamilies',
                        value: linkedInfo.fontWeight.value
                      };
                      self.setStyleSelf(layer, _data4);
                    }
                  }
                }
              }
            });
          }
        });
      }

      sketch_dom__WEBPACK_IMPORTED_MODULE_0___default.a.getSelectedDocument() && sketch_dom__WEBPACK_IMPORTED_MODULE_0___default.a.getSelectedDocument().sketchObject.reloadInspector(); // self.browserWindow.close();
    });
    self.browserWindow.webContents.on('closeArtboardStyle', function () {
      self.browserWindow.close();
    });
    self.browserWindow.webContents.on('hoverArtboardItem', function (s) {
      var layer = sketch_dom__WEBPACK_IMPORTED_MODULE_0___default.a.getSelectedDocument().getLayerWithID(s.id);

      var findInstancce = function findInstancce(layer) {
        if (layer) {
          var find = false;
          var master = layer.getParentArtboard();

          if (master && master.type === 'SymbolMaster') {
            var instances = master.getAllInstances();

            if (instances && instances.length) {
              for (var i = 0; i < instances.length; i++) {
                if (instances[i].type === 'SymbolInstance') {
                  var artboard = instances[i].getParentArtboard();

                  if (artboard && artboard.type === 'Artboard' && artboard.selected) {
                    layer = instances[i];
                    find = true;
                    break;
                  }
                }
              }

              if (!find) {
                for (var _i = 0; _i < instances.length; _i++) {
                  var findLayer = findInstancce(instances[_i]);

                  if (findLayer) {
                    layer = findLayer;
                    break;
                  }
                }
              }
            }
          }

          return layer;
        }
      };

      layer = findInstancce(layer);
      var normalEventHandler = sketch_dom__WEBPACK_IMPORTED_MODULE_0___default.a.getSelectedDocument() && sketch_dom__WEBPACK_IMPORTED_MODULE_0___default.a.getSelectedDocument().sketchObject.eventHandlerManager().normalHandler();

      if (layer) {
        normalEventHandler.setHighlightedItem(layer.sketchObject);
      } // if (layer) {
      //   let master = layer.getParentArtboard();
      //   if (master && master.type === 'SymbolMaster') {
      //     let instances = master.getAllInstances();
      //     if (instances && instances.length) {
      //       for (let i = 0; i < instances.length; i++) {
      //         if (instances[i].type === 'SymbolInstance') {
      //           let artboard = instances[i].getParentArtboard();
      //           if (artboard && artboard.selected) {
      //             layer = instances[i];
      //             break;
      //           }
      //         }
      //       }
      //     }
      //   }
      //   let normalEventHandler = sketch.getSelectedDocument().sketchObject.eventHandlerManager().normalHandler();
      //   normalEventHandler.setHighlightedItem(layer.sketchObject);
      // }

    });
    return self.browserWindow;
  },
  readToShowData: function readToShowData() {
    var self = this;
    var loginInfo = sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.settingForKey('loginInfo') || {};
    loginInfo.artboardInfo = self.getArtboardStyleInfo();
    console.log('artboardInfo', loginInfo);
    var theme = sketch_ui__WEBPACK_IMPORTED_MODULE_4___default.a.getTheme();
    loginInfo.theme = theme;
    self.browserWindow.webContents.executeJavaScript('browserWindowNotifyPanelLoginInfo(' + JSON.stringify(loginInfo) + ')');
  },
  createLookup: function createLookup(styles) {
    return styles.reduce(function (prev, s) {
      prev[s.name] = s;
      return prev;
    }, {});
  },
  setStyleSelf: function setStyleSelf(layer, data) {
    var self = this;

    if (!layer) {
      return;
    }

    var value = data.value;
    var attr = data.attr;
    var docData = sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.documentSettingForKey(sketch_dom__WEBPACK_IMPORTED_MODULE_0___default.a.getSelectedDocument(), attr) || {};
    docData[data.name] = docData[data.name] || {};
    docData[data.name].value = value;
    docData[data.name].objectID = docData[data.name].objectID || [];
    var docArr = docData[data.name].objectID;
    var success = false;

    if (attr === 'color') {
      success = self.setColor(layer, value);
    } else if (attr === 'fontSize') {
      success = self.setFontSize(layer, value);
    } else if (attr === 'fontFamilies') {
      success = _util_util_js__WEBPACK_IMPORTED_MODULE_5__["setStyle"].setFontWeight(layer, value);
    }

    if (success) {
      var itData = sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.layerSettingForKey(layer, attr);
      var id = layer.id + ''; // 判断是否存在旧的数据，删除

      self.deleteOldData(id, itData, docData);
      var parent = layer.parent;

      if (parent && parent.type === 'Group') {
        var groupData = sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.layerSettingForKey(parent, attr) || {};

        if (groupData[data.name]) {
          groupData[data.name].value = data.value;
          var objectID = groupData[data.name].objectID;

          if (objectID.indexOf(id) < 0) {
            objectID.push(id);
          }
        } else {
          groupData[data.name] = {
            value: data.value,
            objectID: [id]
          };
        }

        self.deleteOldData(id, itData, groupData);
        id = parent.id + '_' + id;
        sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.setLayerSettingForKey(parent, attr, groupData);
      }

      sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.setLayerSettingForKey(layer, attr, data);

      if (!(docArr.length && self.getArrayIndex(id, docArr) >= 0)) {
        if (!docData[data.name]) {
          docData[data.name] = docData[data.name] || {};
          docData[data.name].value = value;
          docData[data.name].objectID = docData[data.name].objectID || [];
          docArr = docData[data.name].objectID;
        }

        docArr.push(id);
        sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.setDocumentSettingForKey(sketch_dom__WEBPACK_IMPORTED_MODULE_0___default.a.getSelectedDocument(), attr, docData);
      }
    }
  },
  deleteOldData: function deleteOldData(id, itData, docData) {
    var self = this;
    var selectData = itData && itData.name && docData[itData.name] && docData[itData.name].objectID;

    if (selectData && selectData.length) {
      selectData.splice(self.getArrayIndex(id, selectData), 1);

      if (selectData.length === 0) {
        delete docData[itData.name];
      }
    }
  },
  setColor: function setColor(layer, color) {
    var success = false;

    if (layer.type === 'Shape' || layer.type === 'ShapePath') {
      if (layer.style.fills[0] && layer.style.fills[0].enabled) {
        layer.style.fills[0].color = color;
        success = true;
      }
    } else if (layer.type === 'Text') {
      if (layer.style.textColor) {
        layer.style.textColor = color;
        success = true;
      }
    }

    return success;
  },
  setFontSize: function setFontSize(layer, fontSize) {
    var loginInfo = sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.settingForKey('loginInfo');
    var platformId = loginInfo && loginInfo.userInfo && loginInfo.userInfo.curPlatformInfo && loginInfo.userInfo.curPlatformInfo.platformId && parseInt(loginInfo.userInfo.curPlatformInfo.platformId);
    var success = false;

    if (platformId === 1) {
      fontSize = fontSize && parseInt(fontSize) * 4;
    } else if (platformId === 2 || platformId === 3 || platformId === 4) {
      fontSize = fontSize && parseInt(fontSize);
    }

    if (layer.type === 'Text') {
      if (layer.style.fontSize) {
        layer.style.fontSize = fontSize;
        success = true;
        _util_util_js__WEBPACK_IMPORTED_MODULE_5__["setStyle"].setfontFamily(layer);
      }
    }

    return success;
  },
  getArrayIndex: function getArrayIndex(data, arr) {
    var val2 = -1;
    arr.forEach(function (item, index) {
      if (item === data) {
        val2 = index;
        return false;
      }
    });
    return val2;
  },
  rgba2argb: function rgba2argb(value) {
    var color = value;

    if (value.indexOf('#') === 0) {
      value = value.slice(1);
      value = value.toUpperCase();
    }

    if (value && value.length === 8) {
      var rgb = value.slice(0, 6);
      var a = value.slice(6);
      color = a + rgb;
    }

    return color;
  },
  argb2rgba: function argb2rgba(value) {
    var color = value && value.toUpperCase();

    if (value && value.length === 8) {
      var rgb = value.slice(2);
      var a = value.slice(0, 2);
      color = '#' + rgb + a;
    } else if (value && value.length === 6) {
      color = '#' + value + 'FF';
    }

    return color;
  }
};
/* harmony default export */ __webpack_exports__["default"] = (styleLinkFn);

/***/ }),

/***/ "./src/util/baseUrl.js":
/*!*****************************!*\
  !*** ./src/util/baseUrl.js ***!
  \*****************************/
/*! exports provided: baseUrl, baseUrlForMaterial, refreshSearch */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "baseUrl", function() { return baseUrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "baseUrlForMaterial", function() { return baseUrlForMaterial; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "refreshSearch", function() { return refreshSearch; });
/* harmony import */ var _globalConfig__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../globalConfig */ "./src/globalConfig.js");

var baseUrl = 'http://sketchcloudtest.rnd.huawei.com/';
var baseUrlForMaterial = '';

if (false) {} else if (false) {} else {
  // 普通的build测试用和dev是一样的 后台地址是测试环境 npm run build
  // production
  // baseUrl = 'http://10.22.125.201:8080/';
  baseUrl = 'http://sketchcloudtest.rnd.huawei.com/';
} // 统一去用打包命令处理


baseUrl = _globalConfig__WEBPACK_IMPORTED_MODULE_0__["gc_sidebar_base_url"];
baseUrlForMaterial = _globalConfig__WEBPACK_IMPORTED_MODULE_0__["gc_adaptive_base_host"];
var refreshSearch = "?t=".concat(_globalConfig__WEBPACK_IMPORTED_MODULE_0__["timeStamp"]); // let refreshSearch = '';



/***/ }),

/***/ "./src/util/config.js":
/*!****************************!*\
  !*** ./src/util/config.js ***!
  \****************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _util_util_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/util.js */ "./src/util/util.js");
// import { gc_sidebar_domain, gc_sidebar_server_ip, gc_sidebar_path_name } from '../globalConfig';

var config = {
  domain: function domain() {
    var path = 'http://designcloud.rnd.huawei.com';
    var host = Object(_util_util_js__WEBPACK_IMPORTED_MODULE_0__["hostForUrlManager"])();
    var first = Object(_util_util_js__WEBPACK_IMPORTED_MODULE_0__["loadUrlForUrlManager"])(host);

    if (true) {
      // path = 'http://10.22.125.201:8080';
      path = 'http://sketchcloudtest.rnd.huawei.com';
    } // 统一去用打包命令处理
    // path = gc_sidebar_domain;


    path = first.gc_sidebar_domain;
    return path;
  },
  serverIP: function serverIP() {
    var ip = 'http://10.64.153.205:80';
    var host = Object(_util_util_js__WEBPACK_IMPORTED_MODULE_0__["hostForUrlManager"])();
    var first = Object(_util_util_js__WEBPACK_IMPORTED_MODULE_0__["loadUrlForUrlManager"])(host);

    if (true) {
      ip = 'http://10.22.125.201:8080';
    } // 统一去用打包命令处理
    // ip = gc_sidebar_server_ip;


    ip = first.gc_sidebar_server_ip;
    return ip;
  },
  pathName: function pathName(flag) {
    var pathName = 'sketchcloud_beta';
    var host = Object(_util_util_js__WEBPACK_IMPORTED_MODULE_0__["hostForUrlManager"])();
    var first = Object(_util_util_js__WEBPACK_IMPORTED_MODULE_0__["loadUrlForUrlManager"])(host);

    if (true) {
      pathName = 'sketchcloud_test';
    }

    if (flag === 'ux') {
      pathName = 'uxarp';
    } // 统一去用打包命令处理
    // pathName = gc_sidebar_path_name;


    pathName = first.gc_sidebar_path_name;
    return pathName;
  }
};
/* harmony default export */ __webpack_exports__["default"] = (config);

/***/ }),

/***/ "./src/util/lang.js":
/*!**************************!*\
  !*** ./src/util/lang.js ***!
  \**************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
var zhDict = {};
var enDict = {
  '设置': 'Settings',
  '设计系统': 'Design style',
  '资源面板': 'Resource Panel',
  '标注工具栏': 'Annotation toolbar',
  '控件库': 'Symbol library',
  '图标库': 'Icon library',
  '标注间距': 'Annotation spacing',
  '标注尺寸': 'Annotation Size',
  '标注控件': 'Annotation Widgets',
  '标注热区': 'Annotation Hotspot',
  '添加备注': 'Add Comments',
  '标注栅格': 'Annotation Grid',
  '标注原子能力': 'Annotation Adaptive',
  '切片': 'Slice',
  '标注样式': 'Annotation styles',
  '请至少选择一种原子能力': 'Please select at least one kind of adaptive ability',
  '主题切换': 'Switch theme',
  '切换侧边栏': 'Show/Hide sidebar',
  '原子化布局能力开关': 'Atomic layout feature',
  '原子化布局能力已开启': 'Atomic layout feature enabled.',
  '原子化布局能力已关闭': 'Atomic layout feature disabled.',
  '帮助': 'Help',
  '解绑symbol': 'Detach Symbol',
  '注销账号': 'Logout',
  '原子化布局': 'Atomic layout',
  '侧边工具栏': 'Sidebar',
  '请先选中一个Artboard': 'Please select an Artboard',
  '无法关联样式, 请在文件共享中检查样式文件是否已添加': 'Attach to style failed, please check the libraries',
  '圆角过大, 设置失败!': 'Invalid Round Corner: value too big!',
  '注销成功': 'Logout seccuss',
  '请选择一个库': 'Please select a library',
  '请至少选择一种栅格': 'Please select at least one kind of grid',
  '切换主题成功, sketch界面刷新可能会有延迟, 请稍候!': 'Theme changed successfully. There may be a delay for the page to refresh.',
  '请选择至少一个图层': 'Please select one layer at least',
  '请选择一个或两个图层进行间距标注!': 'Please select one or two layers.',
  '请先导入对应的主题库文件': 'Import theme library first',
  '没有平台信息，请先进行设置': 'No platform infomation, please set it in the web page first',
  '无对应的主题库可用': 'No usable style libraries',
  '请选中一个节点': 'Please select a node',
  '固定内部排版成功!': 'Fix inner layout success',
  '清除成功': 'Clean success',
  '恢复默认参数成功': 'Restore default configuration success',
  '已经同步最新的规范栅格': 'Sync with latest grid specification Done',
  '响应式断点设置生效': 'Set adaptive break point success',
  '拷贝响应式变化能力属性成功': 'Copy adaptive properties success',
  '请先拷贝扩展属性': 'Please copy extended properties first',
  '粘贴响应式变化能力属性成功': 'Paste adaptive properties success',
  // '拉伸能力边距异常': 'en_拉伸能力边距异常',
  '请选中且只选中一个图层': 'en_请选中且只选中一个图层',
  '当前选中的元素不是画板内的图层, 无法获取信息': 'en_当前选中的元素不是画板内的图层, 无法获取信息',
  '请选中一个symbol': 'Please select a Symbol',
  '解绑Symbol成功': 'Detach Symbol success',
  '请选择至少一个画板': 'Please select at least one Artboard',
  '恢复默认设置成功': 'Restore default settings success',
  '成功模拟尺寸设置': 'en_成功模拟尺寸设置',
  '图层的扩展属性': 'en_图层的扩展属性',
  '请选择要插入的栅格类型': 'en_请选择要插入的栅格类型',
  '请选择Shape/Text类型进行样式标注': 'Please select the Shape or Text type.',
  // '无法直接标注样式，请尝试选择Style Layer进行标注': 'en_无法直接标注样式，请尝试选择Style Layer进行标注',
  '没有任何属性可以选择': 'en_没有任何属性可以选择',
  '内部shape元素都没有样式': 'en_内部shape元素都没有样式',
  '成功添加响应式布局能力': 'en_成功添加响应式布局能力',
  '请选中一到两个图层': 'en_请选中一到两个图层',
  '所选对象不在Artboard上，无法进行边距标注': 'en_所选对象不在Artboard上，无法进行边距标注',
  '请选择一个或多个对象对应区域标注的栅格容器参数': 'en_请选择一个或多个对象对应区域标注的栅格容器参数',
  '请选择Symbol Instance类型进行控件标注': 'Please select the Symbol Instance type.',
  '拉伸能力边距异常': 'en_拉伸能力边距异常',
  '容差尺寸不可小于0或大于5, 请重新输入': 'en_容差尺寸不可小于0或大于5, 请重新输入',
  '热区占单栅格比例不可小于0或大于1, 请重新输入': 'en_热区占单栅格比例不可小于0或大于1, 请重新输入',
  '热区固定尺寸不可小于0或大于100, 请重新输入': 'en_热区固定尺寸不可小于0或大于100, 请重新输入',
  '输入数据错误, 请输入纯数字': 'en_输入数据错误, 请输入纯数字',
  '不是Group, 不能应用此设置': 'en_不是Group, 不能应用此设置',
  '不是Artboard内的图层, 无法使用此功能': 'en_不是Artboard内的图层, 无法使用此功能',
  '找不到该屏幕下的栅格配置': 'en_找不到该屏幕下的栅格配置',
  '当前画布宽度不能添加分栏栅格': 'en_当前画布宽度不能添加分栏栅格',
  '无法获取对应的栅格配置, 请检查断点设置': 'en_无法获取对应的栅格配置, 请检查断点设置',
  '分栏栅格': 'en_分栏栅格',
  '画布的宽度不够，不能添加分栏栅格': 'en_画布的宽度不够，不能添加分栏栅格',
  '必须先创建Artboard': 'en_必须先创建Artboard',
  '屏幕宽度不满足分栏要求': 'en_屏幕宽度不满足分栏要求',
  '无可导入的Symbol': 'No importable symbols',
  '没有找到可用的库': 'No valid library found',
  '没有找到Symbol': 'No symbol found',
  '只能替换Symbol库里面的Symbol': 'Replace only Symbol in Symbol library',
  '无法直接标注样式，请尝试选择Style Layer进行标注': 'en_无法直接标注样式，请尝试选择Style Layer进行标注',
  '库中无可导入的Icon': 'No import icons in library',
  '文本对象无法完成替换': 'en_文本对象无法完成替换',
  '请检查选中对象是否为图标': 'en_请检查选中对象是否为图标',
  '非Symbol对象无法完成替换': 'en_非Symbol对象无法完成替换',
  '更改属性失败，内部元素已全部固定宽高': 'en_更改属性失败，内部元素已全部固定宽高',
  '只能选中一个对象设置': 'en_只能选中一个对象设置',
  '父容器不能是页面': 'en_父容器不能是页面',
  '画板边距关系应用成功': 'en_画板边距关系应用成功',
  '只能选中两个对象设置': 'en_只能选中两个对象设置',
  '对象间距关系不生效，需设置其任一对象宽度为Pin': 'en_对象间距关系不生效，需设置其任一对象宽度为Pin',
  '选中一个对象只能是已经设置过兄弟关系的group才行': 'en_选中一个对象只能是已经设置过兄弟关系的group才行',
  '间距关系应用成功': 'en_间距关系应用成功',
  '至少选中一个对象': 'en_至少选中一个对象',
  '选中一个对象只能是已经设置过层叠关系的group才行': 'en_选中一个对象只能是已经设置过层叠关系的group才行',
  '底部元素不是Shape或者Image': 'en_底部元素不是Shape或者Image',
  '应用样式成功': 'Style applied successfully.',
  '多个对象': 'Multiple layers',
  '请检查网络环境': 'Please check the network connection',
  '下载成功': 'Download success',
  '下载失败': 'Download failed',
  '下载超时': 'Download timeout',
  '添加失败，未知原因': 'Add failure, unknown cause',
  '请求超时，请稍后再试': 'Request timeout, please try again later',
  '网络请求异常，导致无法加载,请稍后再试': 'Network request exception, resulting in unable to load, try again later',
  'Library与当前Sketch版本不兼容，请更新版本再试': 'Library is not compatible with the current Sketch version, please update the version and try again',
  '该库已存在': 'The library already exists',
  '不透明': 'opacity',
  '颜色': 'Color',
  '字体': 'Font',
  '圆角': 'Round corners',
  'HarmonyOS 设计插件与当前sketch版本不兼容': 'HarmonyOS Design Tool is incompatible with the current Sketch',
  '网络错误': 'Network Error'
};
var allDict = {
  zh: zhDict,
  en: enDict
};
var lang = {
  LSTR: function LSTR(key) {
    var code = NSLocale.currentLocale().languageCode();
    var langDict = allDict[code];
    var str = langDict[key];

    if (!str) {
      return key;
    }

    return str;
  }
};
/* harmony default export */ __webpack_exports__["default"] = (lang);

/***/ }),

/***/ "./src/util/login.js":
/*!***************************!*\
  !*** ./src/util/login.js ***!
  \***************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* WEBPACK VAR INJECTION */(function(setInterval) {/* harmony import */ var sketch_module_web_view__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! sketch-module-web-view */ "./node_modules/sketch-module-web-view/lib/index.js");
/* harmony import */ var sketch_module_web_view__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(sketch_module_web_view__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var sketch_settings__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! sketch/settings */ "sketch/settings");
/* harmony import */ var sketch_settings__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(sketch_settings__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _util_baseUrl__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/baseUrl */ "./src/util/baseUrl.js");
/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./config.js */ "./src/util/config.js");
/* harmony import */ var _util_util_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../util/util.js */ "./src/util/util.js");
/* harmony import */ var sketch_module_web_view_remote__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! sketch-module-web-view/remote */ "./node_modules/sketch-module-web-view/remote.js");
/* harmony import */ var sketch_module_web_view_remote__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(sketch_module_web_view_remote__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var timers__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! timers */ "./node_modules/timers-browserify/main.js");
/* harmony import */ var timers__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(timers__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _token__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./token */ "./src/util/token.js");
/* harmony import */ var _lang_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./lang.js */ "./src/util/lang.js");






 // import logUtil from '../ux/src/utils/logUtil';


 // import intercept from '../ux/src/bridge/intercept';

var UI = __webpack_require__(/*! sketch/ui */ "sketch/ui");

function checkSourceManage(data) {
  var platformInfos = null;
  var obj = data.data;

  if (obj) {
    platformInfos = obj.platformInfos || null;
  } else {
    platformInfos = data.platformInfos || null;
  } // let NewloginInfo = Settings.settingForKey('loginInfo');


  sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.settingForKey('loginInfo');
  var Newtheme = sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.settingForKey('NewTheme');
  var NewLibraryName = sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.settingForKey('NewLibraryName');
  sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.setSettingForKey('newPlatformInfos', platformInfos);

  if (!platformInfos || platformInfos.length < 1 || !Newtheme || !NewLibraryName) {
    if (Object(sketch_module_web_view_remote__WEBPACK_IMPORTED_MODULE_5__["isWebviewPresent"])('ucd.uiplus.eco.panel.resourcePanel')) {
      UI.message(_lang_js__WEBPACK_IMPORTED_MODULE_8__["default"].LSTR('登录===没有平台信息，请先进行设置')); // UI.alert('请在设置中，应用正确的主题');

      var win = sketch_module_web_view__WEBPACK_IMPORTED_MODULE_0___default.a.fromId('ucd.uiplus.eco.panel.resourcePanel');
      win.close();
    }
  }
} // 使用vue面板需要配置项


var VUE_PANEL_ID = ['sourceManage'];
var login = {
  loginFlag: function loginFlag() {
    var flag = sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.settingForKey('loginFlag');

    if (!flag) {
      flag = false;
    }

    return flag;
  },
  setLoginFlag: function setLoginFlag(flag) {
    sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.setSettingForKey('loginFlag', flag);
  },
  loginInfo: function loginInfo(browser, params) {
    var self = this;
    var loginInfo = sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.settingForKey('loginInfo') || {};
    console.log('loginInfo== ' + JSON.stringify(loginInfo));
    console.log('loginInfo== token.getToken()==' + _token__WEBPACK_IMPORTED_MODULE_7__["default"].getToken() + '  kongkongkong');
    var date = new Date();
    var timeStart = null;

    if (loginInfo && loginInfo.userInfo && !loginInfo.userInfo.curRole || loginInfo && !loginInfo.userInfo) {
      // 未登陆
      var browserWindow = null;

      if (VUE_PANEL_ID.indexOf(params.type) >= 0) {
        // vue登录方式
        browser.setSize(320, 454, true);
      } else {
        // 原生html登录方式
        var identifier = 'ucd.uiplus.eco.panel.resourcePanels';

        if (Object(sketch_module_web_view_remote__WEBPACK_IMPORTED_MODULE_5__["isWebviewPresent"])(identifier) && sketch_module_web_view__WEBPACK_IMPORTED_MODULE_0___default.a.fromId(identifier)) {
          sketch_module_web_view__WEBPACK_IMPORTED_MODULE_0___default.a.fromId(identifier).destroy();
        }

        var options = {
          width: 320,
          height: 454,
          identifier: identifier,
          backgroundColor: '#bbbbbb',
          alwaysOnTop: true,
          acceptsFirstMouse: true,
          title: 'UXS'
        };
        var path = _util_baseUrl__WEBPACK_IMPORTED_MODULE_2__["baseUrl"] + 'sketchcloudweb/sourceManage.html' + _util_baseUrl__WEBPACK_IMPORTED_MODULE_2__["refreshSearch"];
        browserWindow = new sketch_module_web_view__WEBPACK_IMPORTED_MODULE_0___default.a(options);
        browserWindow.loadURL(path);
      }

      browserWindow = browserWindow || browser;
      var index = 1;
      browserWindow.on('ready-to-show', function () {
        var code = NSLocale.currentLocale().languageCode();
        var langCmd = 'setLang("' + code + '")';
        browserWindow.webContents.executeJavaScript(langCmd);
        var skTheme = UI.getTheme();
        var themeCmd = 'getSketchTheme("' + skTheme + '");';
        browserWindow.webContents.executeJavaScript(themeCmd);
        timeStart = date.getTime();
        loginInfo.type = params.type; // Object.assign(loginInfo, params);

        sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.setSettingForKey('loginInfo', loginInfo);
        browserWindow.webContents.executeJavaScript('browserWindowNotifyPanelLoginInfo(' + JSON.stringify(loginInfo) + ')');
      });
      browserWindow.webContents.on('setToken2Web', function () {
        browserWindow.webContents.executeJavaScript("setToken(\"".concat(_token__WEBPACK_IMPORTED_MODULE_7__["default"].getToken(), "\")"));
      });
      browserWindow.webContents.on('aa', function () {
        browserWindow.webContents.executeJavaScript("setToken(\"".concat(_token__WEBPACK_IMPORTED_MODULE_7__["default"].getToken(), "\")"));
      });
      browserWindow.webContents.on('saveToken2Sketch', function (data) {
        _token__WEBPACK_IMPORTED_MODULE_7__["default"].setToken(data.token);
        _token__WEBPACK_IMPORTED_MODULE_7__["default"].updateOcInfo();
      });
      browserWindow.webContents.on('updateLoginIn', function (data) {
        // 点击登录接收函数
        timeStart = null;
        var type = data.type;
        var defaultInfo = {};

        if (data.defaultInfo == undefined) {
          var Newid = '';
          var themID = {
            id: Newid
          };
          var deviceID = {
            id: Newid
          };
          var brandID = {
            id: Newid
          };
          var libraryID = {
            id: Newid
          };
          defaultInfo = {
            themeInfo: themID,
            deviceInfo: deviceID,
            brandInfo: brandID,
            libraryInfo: libraryID
          };
        } else {
          defaultInfo = data.defaultInfo;
        }

        data = data.data;

        if (index) {
          // UI.alert('debug_', JSON.stringify(data));
          if (loginInfo.type == 'setting') {
            self.updateLoginInfo(data, type, 'login', defaultInfo);
            checkSourceManage(data);
          } else {
            self.updateLoginInfo(data, type, 'login', defaultInfo);
            checkSourceManage(data);
          }

          if (VUE_PANEL_ID.indexOf(params.type) < 0) {
            loadURL(params, browser);
            browserWindow.close();
          } else {
            params.width && params.height && browser.setSize(params.width, params.height);
          }

          index--;
          self.updateSidebar(params.context);
        }
      });
    } else {
      if (VUE_PANEL_ID.indexOf(params.type) < 0) {
        loadURL(params, browser);
      } else {
        browser.webContents.on('updateLoginIn', function (data) {
          timeStart = null;
          console.log(11111111, data); // 点击登录接收函数

          var type = data.type;
          var defaultInfo = data.defaultInfo;
          data = data.data;
          self.updateLoginInfo(data, type, 'login', defaultInfo);
          self.updateSidebar(params.context);
        });
        params.width && params.height && browser.setSize(params.width, params.height);
      }
    } // 白屏处理


    var endTime = date.getTime();
    console.log('timeStart ===', timeStart);

    if (timeStart) {
      var interval = null;
      var time = 0;

      var getInfo = function getInfo() {
        Object(timers__WEBPACK_IMPORTED_MODULE_6__["clearInterval"])(interval);

        if (time > 40) {
          return;
        }

        time++;
        endTime = date.getTime();
        console.log('timeGap ===', endTime - timeStart);

        if (endTime - timeStart > 120000) {
          this.updateLoginInfo('', '', 'quit');
          this.loginInfo(browser, params);
        } else {
          interval = setInterval(function () {
            getInfo();
          }, 5000);
        }
      };

      getInfo();
    }
  },
  updateLoginInfo: function updateLoginInfo(data, type, loginType, defaultInfo) {
    data = data || {};
    var loginInfo = sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.settingForKey('loginInfo');

    if (type) {
      if (data) {
        loginInfo[type] = data;
      } else {
        delete loginInfo[type];
      }

      sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.setSettingForKey('loginInfo', loginInfo);
    } else {
      var styles = loginInfo && loginInfo.styles;

      if (styles) {
        data.styles = styles;
      }

      sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.setSettingForKey('loginInfo', data);
    } // 登录更改setting


    if (loginType === 'login') {
      loginInfo = this.updateLoginInfoWithTypeLogin(defaultInfo);
    } else if (loginType === 'quit') {
      sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.setSettingForKey('setting', {});
      this.refreshLoginInfo('', '', 'quit');
    }
  },
  updateLoginInfoWithTypeLogin: function updateLoginInfoWithTypeLogin(defaultInfo) {
    var loginInfo = sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.settingForKey('loginInfo');
    var userInfo = loginInfo.userInfo;
    var curPlatInfo = userInfo.curPlatformInfo;

    if (!curPlatInfo || Object.keys(curPlatInfo).length < 1) {
      var dpi = '4x'; // let platformId = '';

      loginInfo.themeInfo = loginInfo.themeInfo || {}; // loginInfo.themeInfo = {};

      var themeData = {
        themeId: '',
        deviceId: '',
        brandId: '',
        libraryId: ''
      };
      Object(_util_util_js__WEBPACK_IMPORTED_MODULE_4__["setThemeInfo"])(loginInfo.themeInfo, themeData);
      sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.setSettingForKey('loginInfo', loginInfo);
      var setting = {
        DPI: dpi,
        magnification: 'px',
        gridControlRule: false,
        name: ''
      };
      var date = new Date();
      var time = date.getFullYear() + '_' + date.getMonth() + '_' + date.getDate();
      setting.date = time;
      sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.setSettingForKey('setting', setting);
    } else {
      var _dpi = userInfo && userInfo.curPlatformInfo && userInfo.curPlatformInfo.dpi[0];

      var platformId = userInfo && parseInt(userInfo.curPlatformInfo && userInfo.curPlatformInfo.platformId) || 1;
      loginInfo.themeInfo = loginInfo.themeInfo || {};
      var _themeData = {
        themeId: defaultInfo.themeInfo.id,
        deviceId: defaultInfo.deviceInfo.id,
        brandId: defaultInfo.brandInfo.id,
        libraryId: defaultInfo.libraryInfo.id
      };
      Object(_util_util_js__WEBPACK_IMPORTED_MODULE_4__["setThemeInfo"])(loginInfo.themeInfo, _themeData);
      sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.setSettingForKey('loginInfo', loginInfo);
      var _setting = {
        DPI: _dpi,
        magnification: 'px',
        gridControlRule: platformId === 1,
        name: defaultInfo.themeInfo.name
      };

      var _date = new Date();

      var _time = _date.getFullYear() + '_' + _date.getMonth() + '_' + _date.getDate();

      _setting.date = _time;
      sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.setSettingForKey('setting', _setting);
    }

    return loginInfo;
  },
  accordingRolesJudeCurRole: function accordingRolesJudeCurRole(userInfo, retainFlag) {
    // if (userInfo.curRole) return {curRole: userInfo.curRole, curPlatformInfo: userInfo.curPlatformInfo};
    var curRole;
    var curPlatformInfo;
    var sysRoles = userInfo && userInfo.sysRoles || [];
    var curRoleList;
    var sketchFlag = true; // sketch不是管理优先，平台优先

    var platformInfos = userInfo.platformInfos;
    var index = 0; // 第一次登陆默认使用第一个platform

    if (!userInfo.curRole) {
      if (sketchFlag && platformInfos) {
        var noneFlag = false;

        for (var i = 0; i < platformInfos.length; i++) {
          var item = platformInfos[i];

          var _index = item.roles.indexOf('ROLE_B_PLATFORM_DESIGNER');

          if (_index < 0) _index = item.roles.indexOf('ROLE_B_APP_DESIGNER');

          if (_index < 0) {
            curRole = 'NoneRole';
          } else {
            index = i;
            noneFlag = true;
            break;
          }
        }

        if (!noneFlag) index = 0;
      } else {
        index = 0;
      }
    } else {
      // 切换了项目
      if (!platformInfos || platformInfos && !platformInfos.length) {
        curRole = 'NoneRole';
      } else {
        var _curPlatformInfo = userInfo && userInfo.curPlatformInfo;

        for (var _i = 0; _i < platformInfos.length; _i++) {
          if (parseInt(platformInfos[_i].platformId) === parseInt(_curPlatformInfo.platformId)) {
            index = _i;
            break;
          }
        }
      }
    }

    var roles = []; // 所有角色集合
    // if (window.location.href.indexOf('sourceManage.html') !== -1) {

    roles = platformInfos && platformInfos[index] && platformInfos[index].roles;
    /* } else {
          for (let j = 0; j < platformInfos.length; j++) {
            roles = roles.concat(platformInfos && platformInfos[j].roles || []);
            // 去重
          }
          roles = uniqArray(roles);
        } */

    curRoleList = sysRoles.concat(roles || []);
    curPlatformInfo = platformInfos && platformInfos[index] || {};
    var oldRole = userInfo.curRole;
    var tempOldRole;

    if (retainFlag && oldRole && roles.indexOf(oldRole) !== -1) {
      tempOldRole = oldRole;
    }

    curRole = tempOldRole || roles && roles[0] || 'NoneRole';

    if (!retainFlag && !sketchFlag && sysRoles.length === 2 || sysRoles[0] && sysRoles[0] === 'ROLE_S_ADMIN') {
      curRole = 'ROLE_S_ADMIN'; // curPlatformInfo = null
    }

    if (sketchFlag && roles) {
      // if (curRole !== 'ROLE_B_PLATFORM_DESIGNER' || curRole !== 'ROLE_B_APP_DESIGNER') {
      //     if (roles.indexOf('ROLE_B_PLATFORM_DESIGNER') === -1 && roles.indexOf('ROLE_B_APP_DESIGNER') === -1) {
      //         curRole = 'NoneRole';
      //     } else if (roles.indexOf('ROLE_B_PLATFORM_DESIGNER') !== -1) {
      //         curRole = 'ROLE_B_PLATFORM_DESIGNER';
      //     } else if (roles.indexOf('ROLE_B_APP_DESIGNER') !== -1) {
      //         curRole = 'ROLE_B_APP_DESIGNER';
      //     }
      // }
      // by lvjunjie 因为平台设计是
      if (roles.indexOf('ROLE_B_BUSINESS_ADMIN') != -1) {
        curRole = 'ROLE_B_BUSINESS_ADMIN';
      } else if (roles.indexOf('ROLE_B_PLATFORM_DESIGNER') != -1) {
        curRole = 'ROLE_B_PLATFORM_DESIGNER';
      } else if (roles.indexOf('ROLE_B_APP_DESIGNER') != -1) {
        curRole = 'ROLE_B_APP_DESIGNER';
      } else {
        curRole = 'ROLE_S_USER';
      }
    }

    var result = [];
    var flag = null;

    for (var j = 0; j < curRoleList.length; j++) {
      var it = curRoleList[j];

      if (it === 'ROLE_B_PLATFORM_DESIGNER') {
        // let flag='disabled'
        result.push({
          key: it,
          name: '平台设计师',
          id: 3,
          disabled: flag
        });
      } else if (it === 'ROLE_B_APP_DESIGNER') {
        // let flag='disabled'
        result.push({
          key: it,
          name: '模块设计师',
          id: 6,
          disabled: flag
        });
      } else if (it === 'ROLE_S_ADMIN') {
        // let flag='disabled';
        if (sketchFlag) flag = 'disabled';
        result.push({
          key: it,
          name: '超级管理员',
          id: 2,
          disabled: flag
        });
        flag = null;
      } else if (it === 'ROLE_B_BUSINESS_ADMIN') {
        // flag='disabled'
        if (sketchFlag) flag = 'disabled';
        result.push({
          key: it,
          name: '业务管理员',
          id: 4,
          disabled: flag
        });
        flag = null;
      } else if (it === 'ROLE_B_APP_DEVELOPER') {
        // flag='disabled'
        if (sketchFlag) flag = 'disabled';
        result.push({
          key: it,
          name: '模块开发',
          id: 5,
          disabled: flag
        });
        flag = null;
      }
    }

    return {
      curRole: curRole,
      curPlatformInfo: curPlatformInfo,
      curRoleList: result
    };
  },
  loginFromAdaptive: function loginFromAdaptive() {
    // let domain = config.domain();
    // let self = this;
    // let loginInfo = Settings.settingForKey('loginInfo') || {};
    var identifier = 'ucd.uiplus.eco.panel.verificationUser'; // 如果存在就先销毁

    if (Object(sketch_module_web_view_remote__WEBPACK_IMPORTED_MODULE_5__["isWebviewPresent"])(identifier) && sketch_module_web_view__WEBPACK_IMPORTED_MODULE_0___default.a.fromId(identifier)) {
      sketch_module_web_view__WEBPACK_IMPORTED_MODULE_0___default.a.fromId(identifier).destroy();
    }

    var options = {
      width: 320,
      height: 454,
      identifier: identifier,
      alwaysOnTop: true,
      acceptsFirstMouse: true
    }; // let path = baseUrl + 'uxSketch/#/login';

    var path = _util_baseUrl__WEBPACK_IMPORTED_MODULE_2__["baseUrl"] + 'uxSketch/#/login?redirect=/loginToAdaptive';
    var browserWindow = new sketch_module_web_view__WEBPACK_IMPORTED_MODULE_0___default.a(options);
    browserWindow.once('ready-to-show', function () {
      var code = NSLocale.currentLocale().languageCode();
      var langCmd = 'setLang("' + code + '")';
      browserWindow.webContents.executeJavaScript(langCmd);
    });
    browserWindow.webContents.on('saveTokenByAbility', function (data) {
      var tokenStr = data.token;
      browserWindow.close();
      _token__WEBPACK_IMPORTED_MODULE_7__["default"].setToken(tokenStr);
      _token__WEBPACK_IMPORTED_MODULE_7__["default"].updateOcInfo();
    });
    browserWindow.loadURL(path);
  },
  updateSidebar: function updateSidebar(context) {
    var identifier = 'sidebar';

    if (Object(sketch_module_web_view_remote__WEBPACK_IMPORTED_MODULE_5__["isWebviewPresent"])(identifier)) {
      Object(_util_util_js__WEBPACK_IMPORTED_MODULE_4__["toSidebar"])(context, Object(_util_util_js__WEBPACK_IMPORTED_MODULE_4__["getResourceInfo"])());
    }
  },
  initWebPanel: function initWebPanel(identifier) {
    // 如果存在就先销毁
    if (Object(sketch_module_web_view_remote__WEBPACK_IMPORTED_MODULE_5__["isWebviewPresent"])(identifier) && sketch_module_web_view__WEBPACK_IMPORTED_MODULE_0___default.a.fromId(identifier)) {
      sketch_module_web_view__WEBPACK_IMPORTED_MODULE_0___default.a.fromId(identifier).destroy();
    }

    var options = {
      width: 320,
      height: 454,
      identifier: identifier,
      backgroundColor: '#bbbbbb',
      alwaysOnTop: true,
      acceptsFirstMouse: true
    }; // 先用一个透明的窗口 打开静态资源ajaxHtml.html

    var path = _util_baseUrl__WEBPACK_IMPORTED_MODULE_2__["baseUrl"] + 'assets/html/ajaxHtml.html' + _util_baseUrl__WEBPACK_IMPORTED_MODULE_2__["refreshSearch"];
    var browserWindow = new sketch_module_web_view__WEBPACK_IMPORTED_MODULE_0___default.a(options);
    browserWindow.loadURL(path);
    browserWindow.hide();
    return browserWindow;
  },
  readyToShowBrowserWindow: function readyToShowBrowserWindow(browserWindow, loginInfo, versionId, flag) {
    var code = NSLocale.currentLocale().languageCode();
    var langCmd = 'setLang("' + code + '")';
    browserWindow.webContents.executeJavaScript(langCmd);
    var skTheme = UI.getTheme();
    var themeCmd = 'getSketchTheme("' + skTheme + '");';
    browserWindow.webContents.executeJavaScript(themeCmd);
    var userInfo = loginInfo.userInfo;
    var messageData = {
      accessToken: userInfo.access_token,
      domain: _config_js__WEBPACK_IMPORTED_MODULE_3__["default"].domain(),
      pathName: _config_js__WEBPACK_IMPORTED_MODULE_3__["default"].pathName(),
      versionId: versionId
    };
    var messageString = JSON.stringify(messageData);

    if (flag === 'quit') {
      browserWindow.webContents.executeJavaScript('loginOut(' + messageString + ')');
      loginInfo.userInfo.access_token = '';
      sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.setSettingForKey('loginInfo', loginInfo);
    } else {
      browserWindow.webContents.executeJavaScript('verificationUser(' + messageString + ')');
    }
  },
  // 验证登录信息
  refreshLoginInfo: function refreshLoginInfo(context, fn, flag) {
    var _this = this;

    // let domain = config.domain();
    var self = this;
    var loginInfo = sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.settingForKey('loginInfo') || {};
    var identifier = 'ucd.uiplus.eco.panel.verificationUser';
    var browserWindow = this.initWebPanel(identifier); // 如果曾经登录过有登录信息，则....;否则跳转到2.code 的login页面

    if (loginInfo && loginInfo.userInfo && loginInfo.userInfo.access_token) {
      var themeInfo = loginInfo.themeInfo || {};
      var versionId = themeInfo.libraryInfo && themeInfo.libraryInfo.id;
      browserWindow.once('ready-to-show', function () {
        _this.readyToShowBrowserWindow(browserWindow, loginInfo, versionId, flag);
      });
      browserWindow.webContents.on('refreshLoginInfo', function (data) {
        refresh(loginInfo, data && data.content);
        browserWindow.destroy();

        if (!loginInfo.themeInfo || loginInfo.themeInfo && !loginInfo.themeInfo.themeInfo) {
          // 没有主题信息，重新登录
          fn('login');
        } else {
          fn(); // 刷新更新提示

          self.updateSidebar(context);
        }
      });
      browserWindow.webContents.on('login', function (data) {
        login.updateLoginInfo({});
        browserWindow.destroy();
        fn('login');
      });
      browserWindow.webContents.on('loginOut', function (data) {
        sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.setSettingForKey('loginInfo', loginInfo);
        browserWindow.destroy();
        console.log('退出登录', data.title);
      }); // 辅助监控函数

      browserWindow.webContents.on('uxsMessage', function (data) {});
    } else {
      browserWindow.destroy();
      login.updateLoginInfo({});
      fn && fn('login');
    }
  }
  /* updateSidebar(context) {
        let identifier = 'sidebar';
        if (isWebviewPresent(identifier)) {
            toSidebar(context, getResourceInfo());
        }
    }, */

}; // 配置文件

function loadURL(params, browser) {
  var math = {
    'widgetStatic': 'assets/html/widgetStatic.html' + _util_baseUrl__WEBPACK_IMPORTED_MODULE_2__["refreshSearch"],
    'material': 'material',
    'devSwitch': 'assets/html/multiTerminal.html' + _util_baseUrl__WEBPACK_IMPORTED_MODULE_2__["refreshSearch"],
    'export': 'assets/html/deliver.html' + _util_baseUrl__WEBPACK_IMPORTED_MODULE_2__["refreshSearch"],
    'scale': 'assets/html/scale.html' + _util_baseUrl__WEBPACK_IMPORTED_MODULE_2__["refreshSearch"],
    'measureStyle': 'assets/html/style.html' + _util_baseUrl__WEBPACK_IMPORTED_MODULE_2__["refreshSearch"],
    'measureSetting': 'assets/html/setting.html' + _util_baseUrl__WEBPACK_IMPORTED_MODULE_2__["refreshSearch"],
    'measureSpace': 'assets/html/spacings.html' + _util_baseUrl__WEBPACK_IMPORTED_MODULE_2__["refreshSearch"],
    'measureAdaptive': 'assets/html/adaptive.html' + _util_baseUrl__WEBPACK_IMPORTED_MODULE_2__["refreshSearch"],
    'measureToolbar': 'assets/html/toolbar.html' + _util_baseUrl__WEBPACK_IMPORTED_MODULE_2__["refreshSearch"],
    'camilo': 'assets/html/theme.html' + _util_baseUrl__WEBPACK_IMPORTED_MODULE_2__["refreshSearch"],
    'setting': 'assets/html/sketchSetting.html' + _util_baseUrl__WEBPACK_IMPORTED_MODULE_2__["refreshSearch"],
    'measureMark': 'sketchcloudweb/sourceManage.html' + _util_baseUrl__WEBPACK_IMPORTED_MODULE_2__["refreshSearch"],
    'space': 'sketchcloudweb/sourceManage.html/space' + _util_baseUrl__WEBPACK_IMPORTED_MODULE_2__["refreshSearch"],
    'Icons': 'sketchcloudweb/sourceManage.html/icon' + _util_baseUrl__WEBPACK_IMPORTED_MODULE_2__["refreshSearch"],
    'grid': 'sketchcloudweb/sourceManage.html/grid' + _util_baseUrl__WEBPACK_IMPORTED_MODULE_2__["refreshSearch"],
    'measureGrid': 'assets/html/grid.html',
    'artboardStyle': 'sketchcloudweb/sourceManage.html/artboardStyle' + _util_baseUrl__WEBPACK_IMPORTED_MODULE_2__["refreshSearch"],
    'symbolLibrary': 'sketchcloudweb/sourceManage.html/symbols' + _util_baseUrl__WEBPACK_IMPORTED_MODULE_2__["refreshSearch"],
    'notice': 'sketchcloudweb/sourceManage.html/log' + _util_baseUrl__WEBPACK_IMPORTED_MODULE_2__["refreshSearch"]
  };

  if (params.BROWSER_ID) {
    if (Object(sketch_module_web_view_remote__WEBPACK_IMPORTED_MODULE_5__["isWebviewPresent"])(params.BROWSER_ID) && sketch_module_web_view__WEBPACK_IMPORTED_MODULE_0___default.a.fromId(params.BROWSER_ID)) {
      sketch_module_web_view__WEBPACK_IMPORTED_MODULE_0___default.a.fromId(params.BROWSER_ID).destroy();
    }
  }

  if (math[params.type]) {
    browser = browser || params.callback(params.context, params.obj);
    var path = _util_baseUrl__WEBPACK_IMPORTED_MODULE_2__["baseUrl"] + math[params.type] + _util_baseUrl__WEBPACK_IMPORTED_MODULE_2__["refreshSearch"];

    if (params.type == 'material') {
      path = _util_baseUrl__WEBPACK_IMPORTED_MODULE_2__["baseUrlForMaterial"] + math[params.type];
    }

    browser && browser.loadURL(path);
  } else {
    // 无面板类型登录验证 measureSize
    params.callback && params.callback(params.context);
  }
} // 数据库更新了数据，但是loginInfo的platform还是旧的名字


function refresh(oldLoginInfo, newLoginInfo) {
  var newPlatformInfos = newLoginInfo.platformInfos;
  sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.setSettingForKey('newPlatformInfos', newPlatformInfos);

  if (!newPlatformInfos) {
    return;
  }

  var userInfo = oldLoginInfo.userInfo;
  userInfo.platformInfos = newPlatformInfos;
  var curPlatformInfo = userInfo && userInfo.curPlatformInfo;
  var flag = false;
  var flag1 = false;
  var flag2 = false;

  for (var i = 0; i < newPlatformInfos.length; i++) {
    var it = newPlatformInfos[i];

    if (it.platformId === curPlatformInfo.platformId) {
      flag = true;
      curPlatformInfo.platformName = it.platformName;
      userInfo.curRoleList = [];
    }

    if (it.roles.indexOf('ROLE_B_PLATFORM_DESIGNER') !== -1 && !flag1) {
      userInfo.curRoleList.push({
        key: 'ROLE_B_PLATFORM_DESIGNER',
        name: '平台设计师',
        id: 3
      });
      flag1 = true;
    }

    if (it.roles.indexOf('ROLE_B_APP_DESIGNER') !== -1 && !flag2) {
      userInfo.curRoleList.push({
        key: 'ROLE_B_APP_DESIGNER',
        name: '模块设计师',
        id: 6
      });
      flag2 = true;
    }
  } // 当前的模块已经被删了


  if (flag === false) {
    curPlatformInfo = newPlatformInfos[0];
    var item = newPlatformInfos[0];
    var curRole = userInfo && userInfo.curRole;

    if (curRole) {
      if (item.roles.indexOf(curRole) !== -1) {
        curRole = item.roles[0];
        userInfo.curRole = curRole;
      }
    }

    sketch_settings__WEBPACK_IMPORTED_MODULE_1___default.a.setSettingForKey('loginInfo', oldLoginInfo);
  }
}

/* harmony default export */ __webpack_exports__["default"] = (login);
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./node_modules/@skpm/timers/interval.js */ "./node_modules/@skpm/timers/interval.js")["setInterval"]))

/***/ }),

/***/ "./src/util/token.js":
/*!***************************!*\
  !*** ./src/util/token.js ***!
  \***************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var sketch_settings__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! sketch/settings */ "sketch/settings");
/* harmony import */ var sketch_settings__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(sketch_settings__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _ux_src_utils_ocUtil__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../ux/src/utils/ocUtil */ "./src/ux/src/utils/ocUtil.js");
 // import UI from 'sketch/ui';

 // import config from '../util/config.js';

var token = {
  getToken: function getToken() {
    var commonToken = sketch_settings__WEBPACK_IMPORTED_MODULE_0___default.a.settingForKey('commonToken') || '';
    return commonToken;
  },
  setToken: function setToken(token) {
    sketch_settings__WEBPACK_IMPORTED_MODULE_0___default.a.setSettingForKey('commonToken', token);
  },
  getW3Account: function getW3Account() {
    var commonW3Account = sketch_settings__WEBPACK_IMPORTED_MODULE_0___default.a.settingForKey('commonW3Account') || '';
    return commonW3Account;
  },
  setW3Account: function setW3Account(account) {
    sketch_settings__WEBPACK_IMPORTED_MODULE_0___default.a.setSettingForKey('commonW3Account', account);
  },
  updateOcInfo: function updateOcInfo() {
    _ux_src_utils_ocUtil__WEBPACK_IMPORTED_MODULE_1__["default"].updateToken(this.getToken());
    _ux_src_utils_ocUtil__WEBPACK_IMPORTED_MODULE_1__["default"].updateW3Account(this.getW3Account());
  } // checkToken: function (okCB, errCB) {
  //   let token = this.getToken();
  //   let headers = {
  //     Access: 'Client',
  //     Authorization: 'Bearer ' + token
  //   };
  //   let obj = {
  //     url: config.domain() + '/sketchcloud/auth/getLoginUserInfo',
  //     headers: headers
  //   };
  //   let httpCB = function (params) {
  //     let respObj = JSON.parse(params);
  //     let code = respObj.code || '';
  //     let content = respObj.content || {};
  //     let tk = content.access_token || '';
  //     if (code != '200' || tk.length < 1) {
  //       errCB();
  //     } else {
  //       okCB();
  //     }
  //   };
  // ocUtil.loadClass('UXNetwork', 'UXNetwork.bundle');
  // UXNetwork.HTTPGet_jsCallback(JSON.stringify(obj), httpCB);

};
/* harmony default export */ __webpack_exports__["default"] = (token);

/***/ }),

/***/ "./src/util/util.js":
/*!**************************!*\
  !*** ./src/util/util.js ***!
  \**************************/
/*! exports provided: canShow, getPanelPosition, getLibraries, getAllLibraries, sendToSidebar, xToHexRGBA, darkCheckerFn, setThemeInfo, setStyle, getResourceInfo, toSidebar, loadUrlForUrlManager, hostForUrlManager, postToStatistics, version, statistics, themeId, searchPath */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* WEBPACK VAR INJECTION */(function(fetch) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canShow", function() { return canShow; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getPanelPosition", function() { return getPanelPosition; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLibraries", function() { return getLibraries; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getAllLibraries", function() { return getAllLibraries; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sendToSidebar", function() { return sendToSidebar; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "xToHexRGBA", function() { return xToHexRGBA; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "darkCheckerFn", function() { return darkCheckerFn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setThemeInfo", function() { return setThemeInfo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setStyle", function() { return setStyle; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getResourceInfo", function() { return getResourceInfo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toSidebar", function() { return toSidebar; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadUrlForUrlManager", function() { return loadUrlForUrlManager; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hostForUrlManager", function() { return hostForUrlManager; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "postToStatistics", function() { return postToStatistics; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "version", function() { return version; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "statistics", function() { return statistics; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "themeId", function() { return themeId; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "searchPath", function() { return searchPath; });
/* harmony import */ var sketch_settings__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! sketch/settings */ "sketch/settings");
/* harmony import */ var sketch_settings__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(sketch_settings__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _util_config_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/config.js */ "./src/util/config.js");
/* harmony import */ var _lang_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./lang.js */ "./src/util/lang.js");


 // import { gc_adaptive_base_host } from '../globalConfig.js';

var UI = __webpack_require__(/*! sketch/ui */ "sketch/ui");

var sketch = __webpack_require__(/*! sketch/dom */ "sketch/dom");

function canShow() {
  var obj = sketch_settings__WEBPACK_IMPORTED_MODULE_0___default.a.settingForKey('newPlatformInfos');
  var Newtheme = sketch_settings__WEBPACK_IMPORTED_MODULE_0___default.a.settingForKey('NewTheme');
  var NewLibraryName = sketch_settings__WEBPACK_IMPORTED_MODULE_0___default.a.settingForKey('NewLibraryName');

  if (!obj || !NewLibraryName || !Newtheme) {
    UI.message(_lang_js__WEBPACK_IMPORTED_MODULE_2__["default"].LSTR('没有平台信息，请先进行设置'));
    return false;
  }

  return true;
}
var getPanelPosition = function getPanelPosition(context, n, width, height, flag) {
  var windowFrame = context.document.window().frame(); // let x = (windowFrame.origin.x + windowFrame.size.width - 240 - 40 - width) || 400;

  var x = 0;
  var contentView = context.document.documentWindow().contentView();

  if (!contentView) {
    return {};
  }

  var stageView = contentView.subviews().objectAtIndex(0);
  var views = stageView.subviews();

  if (views && views.length) {
    for (var i = 0; i < views.length; i++) {
      if (views[i].identifier() == 'view_canvas') {
        x = views[i].frame().origin.x + views[i].frame().size.width;
        break;
      }
    }
  }

  x = windowFrame.origin.x + x - width || 400;
  var splitView = context.document.splitViewController().splitView();
  var spiltFrame = splitView.frame();
  var y = NSScreen.mainScreen().frame().size.height - (windowFrame.origin.y + spiltFrame.size.height) + height + 40 * n - 16 || 300;

  if (flag === 'reverse') {
    y = NSScreen.mainScreen().frame().size.height - windowFrame.origin.y - 40 * n + 4;
  }

  var position = {
    x: x,
    y: y
  };
  return position;
};
var getLibraries = function getLibraries(sketch) {
  var allLibraries = sketch.getLibraries().filter(function (l) {
    return l.valid && l.enabled && (l.libraryType === 'Remote' || l.libraryType === 4 || l.libraryType === 'RemoteThirdParty');
  });
  var allLibrariesArray = [];

  if (allLibraries && allLibraries.length) {
    for (var i = 0; i < allLibraries.length; i++) {
      var path = allLibraries[i].getDocument() && allLibraries[i].getDocument().path;

      if (path && path.indexOf(_util_config_js__WEBPACK_IMPORTED_MODULE_1__["default"].serverIP()) >= 0) {
        var pathArr = path && path.split('/');
        var groupId = pathArr && pathArr.length && pathArr[pathArr.length - 2];

        var _platformId = pathArr && pathArr.length && pathArr[pathArr.length - 3];

        var updateTime = allLibraries[i].lastModifiedAt && new Date(allLibraries[i].lastModifiedAt).getTime();
        var libraryObj = {
          name: allLibraries[i].name,
          groupId: groupId,
          platformId: _platformId,
          time: updateTime
        };
        allLibrariesArray.push(libraryObj);
      }
    }
  }

  var allLibrariesString = allLibrariesArray && allLibrariesArray.length && JSON.stringify(allLibrariesArray);
  return allLibrariesString;
};
var getAllLibraries = function getAllLibraries(sketch) {
  var allLibraries = sketch.getLibraries().filter(function (l) {
    return l.valid && l.enabled;
  });
  return allLibraries;
};
var sendToSidebar = function sendToSidebar(context, identifier, selected) {
  var selectedInfo = {
    command: identifier,
    selected: selected
  };
  var contentView = context.document ? context.document.documentWindow() && context.document.documentWindow().contentView() : context.actionContext.document.documentWindow().contentView();

  if (contentView) {
    var stageView = contentView.subviews().objectAtIndex(0);
    var views = stageView.subviews();
    var webview = null;
    views.forEach(function (view, i) {
      if (view.identifier() == 'sketchcloud.sidebar') {
        webview = view;
      }
    });

    if (webview) {
      webview.evaluateJavaScript_completionHandler('sendSelected(' + JSON.stringify(selectedInfo) + ')', null);
    }
  }
};
var xToHexRGBA = function xToHexRGBA(color, opacity) {
  var HexRGBA = color.toUpperCase();

  if (color.indexOf('rgb') >= 0) {
    var rgbaLeft = color && color.split('(')[1];
    var rgbaRight = rgbaLeft && rgbaLeft.split(')')[0];
    var rgbaArray = rgbaRight && rgbaRight.split(',');
    var r = rgbaArray && rgbaArray[0] && toHex(rgbaArray[0]) || 'FF';
    var g = rgbaArray && rgbaArray[1] && toHex(rgbaArray[1]) || 'FF';
    var b = rgbaArray && rgbaArray[2] && toHex(rgbaArray[2]) || 'FF';
    var a = rgbaArray && rgbaArray[3] && toHex(rgbaArray[3] * 255) || 'FF';
    HexRGBA = '#' + r + g + b + a;
  } else if (color.indexOf('#') >= 0) {
    if (color.length === 7) {
      if (opacity) {
        opacity = toHex(opacity * 255);
      }

      HexRGBA = color.toUpperCase() + (opacity || 'FF');
    }
  }

  return HexRGBA;
};
var darkCheckerFn = function darkCheckerFn(fn) {
  var ObjCClass = __webpack_require__(/*! cocoascript-class */ "./node_modules/cocoascript-class/lib/index.js").default;

  var DarkChecker = ObjCClass({
    classname: 'DarkChecker',
    register: function register() {
      var app = NSApplication.sharedApplication();
      app.addObserver_forKeyPath_options_context(this, 'appearance', NSKeyValueChangeNewKey, null);
    },
    'observeValueForKeyPath:ofObject:change:context:': fn,
    deregister: function deregister() {
      NSApplication.sharedApplication().removeObserver_forKeyPath_(this, 'appearance');
    }
  });
  return DarkChecker;
};

function toHex(c) {
  var hex = Math.round(c).toString(16).toUpperCase();
  return hex.length === 1 ? '0' + hex : hex;
}

function setThemeInfo(themeInfo, data) {
  if (data.themeId) {
    themeInfo.themeInfo = {
      id: data.themeId
    };
  } else {
    themeInfo.themeInfo = {
      id: ''
    };
  }

  if (data.brandId) {
    themeInfo.brandInfo = {
      id: data.brandId
    };
  } else {
    themeInfo.brandInfo = {
      id: ''
    };
  }

  if (data.deviceId) {
    themeInfo.deviceInfo = {
      id: data.deviceId
    };
  } else {
    themeInfo.deviceInfo = {
      id: ''
    };
  }

  if (data.libraryId) {
    themeInfo.libraryInfo = {
      id: data.libraryId
    };
  } else {
    themeInfo.libraryInfo = {
      id: ''
    };
  }
}
var setStyle = {
  setColor: function setColor(layer, color) {
    var self = this;
    var success = false;
    color = self.deatil8color(color);
    var duplication_codes = 'x'; // duplication_codes扫描

    if (layer.type === 'Shape' || layer.type === 'ShapePath') {
      if (layer.style.fills[0] && layer.style.fills[0].enabled) {
        layer.style.fills[0].color = color;
        success = true;
      }

      duplication_codes = 'x';
    } else if (layer.type === 'Text') {
      if (layer.style.textColor) {
        layer.style.textColor = color;
        success = true;
      }
    }

    return success;
  },
  setBorder: function setBorder(layer, color) {
    var success = false;
    var self = this;

    if (layer.type === 'Shape' || layer.type === 'ShapePath' || layer.type === 'Text') {
      color = self.deatil8color(color);

      if (layer.style.borders[0] && layer.style.borders[0].enabled) {
        layer.style.borders[0].color = color;
        success = true;
      }
    }

    return success;
  },
  setShadow: function setShadow(layer, color) {
    var success = false;
    var self = this;

    if (layer.style.shadows[0] && layer.style.shadows[0].enabled) {
      color = self.deatil8color(color);
      layer.style.shadows[0].color = color;
      success = true;
    }

    return success;
  },
  setFontSize: function setFontSize(layer, fontSize) {
    var success = false;
    var self = this;

    if (layer.type === 'Text') {
      if (layer.style.fontSize) {
        layer.style.fontSize = fontSize;
        success = true;
        self.setfontFamily(layer);
      }
    }

    return success;
  },
  setFontWeight: function setFontWeight(layer, fontWeight) {
    var success = false;
    var self = this;
    var text = layer.text;
    var loginInfo = sketch_settings__WEBPACK_IMPORTED_MODULE_0___default.a.settingForKey('loginInfo');
    var platformId = loginInfo && loginInfo.userInfo && loginInfo.userInfo.curPlatformInfo && loginInfo.userInfo.curPlatformInfo.platformId;
    var themeInfo = loginInfo && loginInfo.themeInfo;
    var themeId = themeInfo && themeInfo.themeInfo && themeInfo.themeInfo.id;

    if (layer.type === 'Text') {
      if (layer.style) {
        self.setfontFamily(layer, fontWeight);

        if (platformId === 1) {
          if (fontWeight === 'regular') {
            layer.style.fontWeight = 4;
            success = true;
          } else if (fontWeight === 'medium') {
            layer.style.fontWeight = 7;
            success = true;
          }
        } else if (platformId === 2 || platformId === 3) {
          success = this.setOtherPlatformFontWeight(fontWeight, layer, success, themeId, self, text);
        } else if (platformId === 4) {
          success = true;
        }
      }
    }

    return success;
  },
  // 设置Platform2和3的字重
  setOtherPlatformFontWeight: function setOtherPlatformFontWeight(fontWeight, layer, success, themeId, self, text) {
    if (fontWeight.indexOf('Regular') >= 0) {
      layer.style.fontWeight = 5;
      success = true;
    } else if (fontWeight.indexOf('Medium') >= 0) {
      if (parseInt(themeId) === 697) {
        var isHan = self.isHan(text);

        if (isHan) {
          layer.style.fontWeight = 6;
          success = true;
        } else {
          layer.style.fontWeight = 5;
          success = true;
        }
      } else if (parseInt(themeId) === 698) {
        layer.style.fontWeight = 6;
        success = true;
      }
    } else if (fontWeight.indexOf('Semibold') >= 0) {
      var _isHan = self.isHan(text);

      if (_isHan) {
        layer.style.fontWeight = 8;
        success = true;
      } else {
        if (parseInt(themeId) === 697) {
          layer.style.fontWeight = 5;
          success = true;
        } else if (parseInt(themeId) === 698) {
          layer.style.fontWeight = 6;
          success = true;
        }
      }
    } else if (fontWeight.indexOf('Bold Condensed') >= 0) {
      var _isHan2 = self.isHan(text);

      if (_isHan2) {
        layer.style.fontWeight = 6;
        success = true;
      } else {
        layer.style.fontWeight = 9;
        layer.style.fontStretch = 'condensed';
        success = true;
      }
    }

    return success;
  },
  setLineHeight: function setLineHeight(layer, lineHeight) {
    var success = false;
    var self = this;
    lineHeight *= layer.style.fontSize;

    if (layer.type === 'Text') {
      if (layer.style) {
        layer.style.lineHeight = lineHeight;
        success = true;
        self.setfontFamily(layer);
      }
    }

    return success;
  },
  setfontFamily: function setfontFamily(layer, fontWeight) {
    var self = this;
    var loginInfo = sketch_settings__WEBPACK_IMPORTED_MODULE_0___default.a.settingForKey('loginInfo');
    var platformId = loginInfo && loginInfo.userInfo && loginInfo.userInfo.curPlatformInfo && loginInfo.userInfo.curPlatformInfo.platformId;
    var themeInfo = loginInfo && loginInfo.themeInfo;
    var themeId = themeInfo && themeInfo.themeInfo && themeInfo.themeInfo.id;

    if (layer.type === 'Text') {
      if (layer.style) {
        if (platformId === 1) {
          layer.style.fontFamily = 'HWtext';
        } else if (platformId === 2 || platformId === 3) {
          var text = layer.text;
          var isHan = self.isHan(text);

          if (isHan) {
            layer.style.fontFamily = 'PingFang SC';
          } else {
            if (parseInt(themeId) === 697) {
              if (fontWeight && (fontWeight.indexOf('Medium') >= 0 || fontWeight.indexOf('Semibold') >= 0)) {
                layer.style.fontFamily = 'Huawei Sans Medium';
              } else {
                layer.style.fontFamily = 'Huawei Sans';
              }
            } else if (parseInt(themeId) === 698) {
              layer.style.fontFamily = 'Roboto';
            }
          }
        } else if (platformId === 4) {
          if (fontWeight) {
            if (fontWeight.indexOf('Medium') >= 0) {
              layer.style.fontFamily = 'FZLanTingHeiS-DB-GB';
            } else if (fontWeight.indexOf('Regular') >= 0) {
              layer.style.fontFamily = 'FZLanTingHeiS-R-GB';
            } else if (fontWeight.indexOf('Semibold') >= 0) {
              layer.style.fontFamily = 'FZLanTingHeiS-B-GB';
            } else if (fontWeight.indexOf('细黑') >= 0) {
              layer.style.fontFamily = 'FZLanTingHeiS-L-GB';
            }
          }
        }
      }
    }
  },
  setRadius: function setRadius(layer, radius) {
    var success = false;

    if (layer.type === 'ShapePath' || layer.type === 'Shape') {
      var points = layer.points;
      var width = layer.frame.width;
      var height = layer.frame.height;
      var min = width < height ? width : height;

      if (radius * 2 > min) {
        var text = '⚠️ ' + _lang_js__WEBPACK_IMPORTED_MODULE_2__["default"].LSTR('圆角过大, 设置失败!');
        UI.message(text);
        return success;
      }

      points.forEach(function (point) {
        point.cornerRadius = radius;
      });
      layer.sketchObject.setFixedRadius(radius);
      success = true;
    }

    return success;
  },
  setOpacity: function setOpacity(layer, opacity) {
    var success = false;

    if (layer.type === 'Shape' || layer.type === 'ShapePath' || layer.type === 'Text') {
      if (layer.style) {
        layer.style.opacity = opacity;
        success = true;
      }
    }

    return success;
  },
  deatil8color: function deatil8color(value) {
    var color = value;

    if (value.indexOf('#') === 0) {
      value = value.slice(1);
      value = value.toUpperCase();

      if (value && value.length === 8) {
        var rgb = value.slice(2);
        var a = value.slice(0, 2);
        color = '#' + rgb + a;
      } else if (value.length === 6) {
        color = '#' + value + 'FF';
      } else {
        color = '#' + value;
      }
    } else if (value.indexOf('rgb') === 0) {
      color = value;
    } else {
      value = value.toUpperCase();

      if (value && value.length === 8) {
        var _rgb = value.slice(2);

        var _a = value.slice(0, 2);

        color = '#' + _rgb + _a;
      } else if (value.length === 6) {
        color = '#' + value + 'FF';
      } else {
        color = '#' + value;
      }
    }

    return color;
  },
  isHan: function isHan(text) {
    var han = /^[\u4e00-\u9fa5]+$/;
    var isHan = false;

    if (text && text.length) {
      for (var i = 0; i < text.length; i++) {
        if (han.test(text[i])) {
          isHan = true;
          break;
        }
      }
    }

    return isHan;
  }
};
function getResourceInfo() {
  var data = {};
  var loginInfo = sketch_settings__WEBPACK_IMPORTED_MODULE_0___default.a.settingForKey('loginInfo') || {};

  if (loginInfo.userInfo && loginInfo.themeInfo) {
    var resourceUpdateInfo = sketch_settings__WEBPACK_IMPORTED_MODULE_0___default.a.settingForKey('resourceUpdateInfo') || {};
    var userInfo = loginInfo.userInfo;
    var themeInfo = loginInfo.themeInfo || {};

    var _platformId2 = parseInt(userInfo && userInfo.curPlatformInfo && userInfo.curPlatformInfo.platformId) || 1;

    var accessToken = userInfo && userInfo.access_token;

    var _libraryId = themeInfo.libraryInfo && themeInfo.libraryInfo.id;

    var _themeId = themeInfo.themeInfo && themeInfo.themeInfo.id;

    var createTime = resourceUpdateInfo[_platformId2] && resourceUpdateInfo[_platformId2][_libraryId] && resourceUpdateInfo[_platformId2][_libraryId].createTime;
    data = {
      accessToken: accessToken,
      platformId: _platformId2,
      libraryId: _libraryId,
      createTime: createTime,
      themeId: _themeId,
      domain: _util_config_js__WEBPACK_IMPORTED_MODULE_1__["default"].domain(),
      pathName: _util_config_js__WEBPACK_IMPORTED_MODULE_1__["default"].pathName()
    };
  }

  return data;
}
var toSidebar = function toSidebar(context, messageData) {
  if (!context) {
    return;
  }

  var contentView = context.document ? context.document.documentWindow() && context.document.documentWindow().contentView() : context.actionContext.document.documentWindow().contentView();

  if (contentView) {
    var stageView = contentView.subviews().objectAtIndex(0);
    var views = stageView.subviews();
    var webview = null;
    views.forEach(function (view, i) {
      if (String(view.identifier()) === 'sketchcloud.sidebarxx') {
        webview = view;
      }
    });

    if (webview) {
      webview.evaluateJavaScript_completionHandler('refreshUpdateTips(' + JSON.stringify(messageData) + ')', null);
    }
  }
};
function loadUrlForUrlManager(type) {
  var bundlePathPrefix = '/Contents/Resources/js/';
  var path = NSString.stringWithString_(coscript.env().scriptURL.path());

  while (path.lastPathComponent().pathExtension() != 'sketchplugin') {
    path = path.stringByDeletingLastPathComponent();
  }

  ;
  var PathJsonStr = NSString.stringWithContentsOfFile_encoding_error(path + bundlePathPrefix + 'urlManager.json', 4, nil);
  var firstDict = JSON.parse(PathJsonStr);
  var urlName = firstDict.url;
  var idName = firstDict.id;
  var devName = firstDict.dev;
  var betaName = firstDict.beta;
  var prodName = firstDict.prod;
  var localName = firstDict.local;
  var someName = firstDict.someOne;

  switch (type) {
    case 'dev':
      return devName;

    case 'beta':
      return betaName;

    case 'prod':
      return prodName;

    case 'local':
      return localName;

    case 'someOne':
      return someName;

    case 'url':
      return urlName;

    case 'id':
      return idName;

    default:
      break;
  }
}
function hostForUrlManager() {
  var bundlePathPrefix = '/Contents/Resources/js/';
  var path = NSString.stringWithString_(coscript.env().scriptURL.path());

  while (path.lastPathComponent().pathExtension() != 'sketchplugin') {
    path = path.stringByDeletingLastPathComponent();
  }

  ;
  var PathJsonStr = NSString.stringWithContentsOfFile_encoding_error(path + bundlePathPrefix + 'urlManager.json', 4, nil);
  var firstDict = JSON.parse(PathJsonStr);
  var currentState = firstDict.current;
  return currentState;
} // 发送打点计数消息给后台

function postToStatistics(code, type) {
  var host = hostForUrlManager();
  var first = loadUrlForUrlManager(host);
  var url = first.gc_uxfm_ip + '/trace/statistics';
  var body = {
    'code': code
  };

  if (code === '102' || code === '202') {
    body = {
      'code': code,
      'function': type
    };
  } else if (code === '101') {
    body = {
      'code': code,
      'device': type
    };
  }

  fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json;charset=utf-8'
    },
    body: JSON.stringify(body)
  }).then(function (response) {
    return response.json();
  }).then(function (text) {
    if (text && text.code === '200') {// 请求成功
    } else if (text && text.code === '401') {// 请求失败
    } else {}
  }).catch(function (e) {
    if (code === '202') {
      // 点击sidebar上的功能图标，如果打点服务调不通，提示网络错误
      UI.message(_lang_js__WEBPACK_IMPORTED_MODULE_2__["default"].LSTR('网络错误'));
    }
  });
}
var version = sketch.version.sketch + '';
var statistics = ''; // export let searchPath = {loginInfo
//     search: function () {

var searchPath = '';
var loginInfo = sketch_settings__WEBPACK_IMPORTED_MODULE_0___default.a.settingForKey('loginInfo') || {};
var system = loginInfo.system || {};
var platformId = system.platformId || '';
var deviceId = loginInfo.deviceId || '';
var libraryId = loginInfo.libraryId || '';
var brandId = loginInfo.brandId || '';
var themeId = loginInfo.themeId || '';
searchPath = "#/sourceManage?platformId=".concat(platformId, "&deviceId=").concat(deviceId, "&libraryId=").concat(libraryId, "&brandId=").concat(brandId, "&themeId=").concat(themeId); // return search;
//     }
// };


/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./node_modules/sketch-polyfill-fetch/lib/index.js */ "./node_modules/sketch-polyfill-fetch/lib/index.js")))

/***/ }),

/***/ "./src/ux/src/utils/ocUtil.js":
/*!************************************!*\
  !*** ./src/ux/src/utils/ocUtil.js ***!
  \************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
// import lang from '../../../util/lang.js';
// var UI = require('sketch/ui');
// function _localizeMenu () {
//   let menu = AppController.sharedInstance().pluginsMenuItem().submenu();
//   let uxsMenu = menu.itemWithTitle('UXS').submenu();
//   let items = uxsMenu.itemArray();
//   let count = items.length;
//   for (let i = 0; i < count; i++) {
//     let item = items.objectAtIndex(i);
//     let title = lang.LSTR(item.title());
//     item.setTitle(title);
//     if (item.hasSubmenu()) {
//       let subMenu = item.submenu();
//       let subArr = subMenu.itemArray();
//       let subCount = subArr.length;
//       for (let j = 0; j < subCount; j++) {
//         let subItem = subArr.objectAtIndex(j);
//         let title = lang.LSTR(subItem.title());
//         subItem.setTitle(title);
//       }
//     }
//   }
// }
var bundlePathPrefix = '/Contents/Resources/oc/';
var ocUtil = {
  localizeMenu: function localizeMenu() {
    this.loadClass('Helper', 'Helper.bundle'); // Helper.callJSFunc_delay(_localizeMenu, 2);
  },
  getPluginPath: function getPluginPath() {
    var path = NSString.stringWithString_(coscript.env().scriptURL.path());

    while (path.lastPathComponent().pathExtension() != 'sketchplugin') {
      path = path.stringByDeletingLastPathComponent();
    }

    return path;
  },
  loadBundle: function loadBundle(bundleName) {
    var path = this.getPluginPath();
    var bundlePath = path + bundlePathPrefix + bundleName; // console.log("bundlePath:"+bundlePath);

    var bundle = NSBundle.bundleWithPath_(bundlePath);
    bundle.load();
  },
  unloadBundle: function unloadBundle(bundleName) {
    var path = this.getPluginPath();
    var bundlePath = path + bundlePathPrefix + bundleName; // console.log("bundlePath:"+bundlePath);

    var bundle = NSBundle.bundleWithPath_(bundlePath);
    bundle.unload();
  },
  loadClass: function loadClass(className, bundleName) {
    if (NSClassFromString(className) == null) {
      try {
        this.loadBundle(bundleName); // console.log("Load "+bundleName+" success.");
      } catch (e) {// console.log("Load "+bundleName+" fail.");
      }
    } else {// console.log(bundleName+" has been Loaded.");
      }
  },
  hasWindow: function hasWindow() {// this.loadClass("Helper", "Helper.bundle");
    // return Helper.hasWindow();
  },
  closeWindow: function closeWindow() {
    this.loadClass('Helper', 'Helper.bundle'); // Helper.closeWindow();

    return true;
  },
  logout: function logout() {
    this.loadClass('Helper', 'Helper.bundle'); // Helper.clearWebCache();
    // Helper.updateToken("");

    return true;
  },
  updateToken: function updateToken(token) {
    this.loadClass('Helper', 'Helper.bundle'); // Helper.updateToken(token);
  },
  updateW3Account: function updateW3Account(account) {
    this.loadClass('Helper', 'Helper.bundle'); // Helper.updateW3Account(account);
  }
};
/* harmony default export */ __webpack_exports__["default"] = (ocUtil);

/***/ }),

/***/ "buffer":
/*!*************************!*\
  !*** external "buffer" ***!
  \*************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("buffer");

/***/ }),

/***/ "events":
/*!*************************!*\
  !*** external "events" ***!
  \*************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("events");

/***/ }),

/***/ "sketch/dom":
/*!*****************************!*\
  !*** external "sketch/dom" ***!
  \*****************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("sketch/dom");

/***/ }),

/***/ "sketch/settings":
/*!**********************************!*\
  !*** external "sketch/settings" ***!
  \**********************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("sketch/settings");

/***/ }),

/***/ "sketch/ui":
/*!****************************!*\
  !*** external "sketch/ui" ***!
  \****************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("sketch/ui");

/***/ })

/******/ });
  if (key === 'default' && typeof exports === 'function') {
    exports(context);
  } else {
    exports[key](context);
  }
}
that['onRun'] = __skpm_run.bind(this, 'default')

//# sourceMappingURL=styleLink.js.map