'use strict'
var _extends =
  Object.assign ||
  function(a) {
    for (var b, c = 1; c < arguments.length; c++)
      for (var d in ((b = arguments[c]), b))
        Object.prototype.hasOwnProperty.call(b, d) && (a[d] = b[d])
    return a
  }
!(function(require, directRequire) {
  function a({ except: a = [] } = {}) {
    let b = q.readdirSync(H)
    if (5 < b.length)
      for (let c, d = 0, e = b.length; d < e; d++) {
        c = !1
        for (let e = 0, f = a.length; e < f; e++)
          if (0 == b[d].indexOf(a[e])) {
            c = !0
            break
          }
        c || C.rmSync(r.join(H, b[d]))
      }
  }
  function b(a, b) {
    if (!b) return !1
    let c = Buffer.from(b, 'base64'),
      d = q.readFileSync(a),
      e = s.createHash('md5')
    e.update(d)
    let f = e.digest('hex')
    const g = s.createVerify('RSA-SHA1')
    return g.update(f), !!g.verify(P, c)
  }
  function c() {
    try {
      let a = 0,
        b = q.readdirSync(H)
      if (0 < b.length)
        for (let c, d = 0, e = b.length; d < e; d++)
          if (((c = b[d].match(/(\d+)\.(dmg|exe|wx\.gzip)$/)), c && c[1])) {
            let b = parseInt(c[1])
            Number.isInteger(b) && b > a && (a = b)
          }
      return a
    } catch (a) {
      return 0
    }
  }
  async function d(a = {}) {
    return new Promise((b, d) => {
      let e = { url: `${y.checkUpdate}?clientversion=${L}&type=${K}` }
      a.force && (e.url += '&force=1')
      let f = c()
      f && (e.url += `&downloadedversion=${f}`),
        z(e, (a, c, e) => {
          if (a) return d(a)
          try {
            let a = JSON.parse(e),
              c = a.baseresponse || {},
              f = c.errcode
            0 == f
              ? b({
                  version: a.update_version,
                  forceUpdate: 2 == a.update_type,
                  versionType: a.version_type,
                  packType: a.pack_type || 0,
                  md5: a.md5,
                  whatsnew: a.changelog_desc,
                  whatsnewURL: a.changelog_url,
                  silence: a.silence
                })
              : d(f)
          } catch (a) {
            d(a)
          }
        })
    })
  }
  function e(a) {
    const { version: b, packType: c } = a
    let d = `${K}_${b}_${c}`,
      e = J ? 'dmg' : 'exe'
    return (c == Q.BIGCODE || c == Q.SMALLCODE) && (e = 'wx.gzip'), `${d}.${e}`
  }
  function f(a) {
    return !!(a && (a.version > L || a.forceUpdate))
  }
  function g(a) {
    return (
      (a += ''),
      a.replace(/^(\d)(\d\d)(\d+)$/, function(a, b, c, d) {
        return `${b}.${c}.${d}`
      })
    )
  }
  async function h(a) {
    try {
      if (!a) return
      if (S) return
      if (!f(a)) return
      if (R) return
      let b = await l(a),
        c = a.silence && (a.packType == Q.BIGCODE || a.packType == Q.SMALLCODE)
      c || (c = await i(a, b)),
        c && k(a, b),
        a.forceUpdate && (D.forceUpdateVersion = strUpdateVersion)
    } catch (a) {}
  }
  function i(a, b) {
    return new Promise(c => {
      let { version: d, forceUpdate: e, packType: f, whatsnewURL: h } = a,
        i = d < L && e
      ;(global.shareData.updateConfig = {
        updateVersion: g(d),
        whatsnewURL:
          h ||
          'https://developers.weixin.qq.com/miniprogram/dev/devtools/download.html',
        isDrawBack: i
      }),
        p(),
        U && (U.removeAllListeners(), U.hide(), U.close(), (U = null)),
        nw.Window.open(
          'html/whatsnew.html',
          {
            width: 600,
            height: 480,
            title: '\u7248\u672C\u66F4\u65B0\u63D0\u793A',
            always_on_top: !0
          },
          a => {
            global.windowMap.set('WHATSNEW', a),
              (U = a),
              a.on('close', function() {
                ;(U = null),
                  global.shareData &&
                    global.shareData.updateConfig &&
                    (c(global.shareData.updateConfig.confirmInstall),
                    delete global.shareData.updateConfig),
                  this.hide(),
                  this.close(!0)
              }),
              a.on('new-win-policy', function(a, b, c) {
                c.ignore(), nw.Shell.openExternal(b)
              })
          }
        ),
        i || j(d, b)
    })
  }
  async function j(a, b) {
    await N.open(),
      await N.insert('noticecenter', [
        {
          type: E.DBType.tools,
          title: '\u7248\u672C\u66F4\u65B0',
          content: `最新的开发工具版本 ${a}`,
          link: r.basename(b),
          timestamp: Date.now() / 1e3
        }
      ]),
      await N.close()
  }
  async function k(a, b) {
    const { packType: c, version: d } = a
    if (c == Q.BIGCODE || c == Q.SMALLCODE) {
      if (V)
        try {
          V.removeAllListeners(), V.kill('SIGTERM')
        } catch (a) {
          A.error('kill hotpatch task error ', a)
        }
      let d = r.join(r.dirname(process.execPath), 'node')
      ;(V = t.fork(G.fileName, ['--expose-gc'], {
        execPath: d,
        stdio: ['ipc'],
        env: _extends({}, process.env, {
          PACKTYPE: c,
          HOTPATHTASK: 'yes',
          PackFilePath: b,
          NewPackageNwPath: J
            ? r.join(I, 'new_package.nw')
            : r.join(
                process.env.APPDATA,
                'Tencent',
                '\u5FAE\u4FE1web\u5F00\u53D1\u8005\u5DE5\u5177',
                'new_package.nw'
              ),
          DistPackageNwPath: J
            ? r.join(I, 'package.nw')
            : r.join(
                process.env.APPDATA,
                'Tencent',
                '\u5FAE\u4FE1web\u5F00\u53D1\u8005\u5DE5\u5177',
                'package.nw'
              )
        })
      })),
        V.stdout.on('data', a => {
          A.log('hotpatch: ' + a)
        }),
        V.stderr.on('data', a => {
          A.error('hotpatch: ' + a)
        }),
        V.on('exit', b => {
          0 == b
            ? !a.silence &&
              confirm(
                '\u66F4\u65B0\u5B8C\u6210\uFF0C\u8BF7\u91CD\u65B0\u542F\u52A8'
              ) &&
              (J
                ? u(
                    '/Applications/wechatwebdevtools.app/Contents/MacOS/wechatwebdevtools',
                    [],
                    { detached: !0 }
                  )
                : u(
                    r.join(
                      r.dirname(process.execPath),
                      '\u5FAE\u4FE1web\u5F00\u53D1\u8005\u5DE5\u5177.exe'
                    ),
                    [],
                    { detached: !0 }
                  ),
              C.quit())
            : confirm(
                '\u70ED\u66F4\u65B0\u5931\u8D25\uFF0C\u8BF7\u624B\u52A8\u4E0B\u8F7D\u7248\u672C\u8FDB\u884C\u5B89\u88C5'
              )
        })
    } else {
      let a = J ? 'open' : b,
        c = J ? [b] : []
      try {
        u(a, c, { detached: !0 })
      } catch (a) {
        nw.Shell.openItem(b)
      }
      C.quit()
    }
  }
  async function l(c) {
    const { version: d, versionType: f, packType: g } = c
    let h = `${K}_${d}_${g}_${Date.now()}${Math.random()}.temp`,
      i = r.join(H, h),
      j = r.join(H, e(c))
    if (q.existsSync(j) && (!c.md5 || b(j, c.md5))) return j
    let k = ''
    try {
      k = `${K}_${d}_${g}`
    } catch (a) {}
    return (
      await a({ except: [k] }),
      new Promise((a, c) => {
        let e = '',
          h = {
            url: `${M}&type=${K}&download_version=${d}&version_type=${f}&pack_type=${g}`,
            followRedirect: function(a) {
              return (e = a.caseless.get('md5')), e
            }
          }
        ;(R = !0),
          z(h, a => {
            return (
              (R = !1),
              a
                ? c(a)
                : void process.nextTick(() => {
                    k()
                  })
            )
          }).pipe(q.createWriteStream(i, { mode: 511 }))
        const k = () => {
          try {
            if (!b(i, e)) return c('signature not match')
            q.rename(i, j, b => {
              return b ? c(b) : void a(j)
            })
          } catch (a) {
            c(a)
          }
        }
      })
    )
  }
  function m() {
    o(),
      n(),
      (T = setInterval(() => {
        o()
      }, O))
  }
  function n() {
    T && (clearInterval(T), (T = null))
  }
  async function o(a) {
    let b = await d(a)
    return h(b), b
  }
  function p() {
    n(), (S = !0)
  }
  const q = require('fs'),
    r = require('path'),
    s = require('crypto'),
    t = require('child_process'),
    u = require('child_process').spawn,
    v = require('mkdir-p'),
    w = require('zlib'),
    x = require('./514d358c669501bba65151a1ad61ae2f.js'),
    y = require('./f171257bbcaef547a3cf27266ccb0db2.js'),
    z = require('./233d77ecf0781f44985f684f70e316d0.js'),
    A = require('./logger.js'),
    B = require('./d3ce001ab1e75959382f6a7e0156dd17.js'),
    C = require('./tools.js'),
    D = require('./84858de8a097c9cf84ff2c2e3d86e2a9.js'),
    E = require('./bcb48ae14d243711d3b31cb0f602d209.js'),
    F = require('./92320c1386e6db6a6f2556736a9bc280.js'),
    G = require('./cf7d67b3fb34d8276deb78291c77dfff.js'),
    H = F.WeappApplication,
    I = F.WeappCode,
    J = 'darwin' === process.platform,
    K = global.appConfig.isBeta
      ? J
        ? 'beta_darwin'
        : 'x64' === process.arch
          ? 'beta_x64'
          : 'beta_ia32'
      : J
        ? 'darwin'
        : 'x64' === process.arch
          ? 'x64'
          : 'ia32',
    L = parseInt(global.appVersion.replace(/\./g, '')),
    M = `${y.downloadRedirectURL}?os=${J ? 'darwin' : 'win'}`,
    N = require('./4102b43ad51182743111f5d5e1fc5b46.js'),
    O = 600000,
    P = `-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCZm2cFP/uF81V5KH/B9dn/g7WA
CM3yu0P7n9sm/O6c58HTYI0+xugCfwMuoX7hyU4jkWbZ/BYK7IgWhmVfiRtgomJe
wuZlxfGUpmrr1PA2KbYVpPW0V6e/2uZu1Ev3xU7PkHKYf4AKgPO8w98hvKlUJRbk
H4AYMxX6eL9j9qCBGQIDAQAB
-----END PUBLIC KEY-----`,
    Q = { INSTALLER: 0, BIGCODE: 1, SMALLCODE: 2 }
  var R = !1,
    S = !1,
    T = null,
    U = null,
    V = null
  module.exports = {
    loop: m,
    checkNeedUpdate: async function() {
      try {
        let a = await o({ force: !0 })
        if (f(a)) return g(a.version)
      } catch (a) {}
    },
    resetAlreadyNotify: function() {
      global.isDevWindow || T || m(), (S = !1)
    }
  }
})(require('lazyload'), require)
