'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) {
  async function a(a, b, c, d, e = {}) {
    const f = e.onProgressUpdate || E,
      g = async b => {
        return await m(a, b, { noWarnings: !0 })
      },
      k = 'weapp:///',
      n = i.join(b, 'app.json'),
      o = j.readFileSync(n, 'utf8'),
      p = await v(a)
    if (!p.pages) throw new Error('no pages defined.')
    let q = p.pages.map(a => {
        return a + '.js'
      }),
      x = await u.getFileList(a, p)
    if (((x = x.length ? x.map(a => a + '.js') : []), p.subPackages)) {
      const a = []
      for (const b of p.subPackages)
        b &&
          b.root &&
          b.pages &&
          a.push(...b.pages.map(a => i.posix.join(b.root, a + '.js')))
      q = [...q, ...a]
    }
    q = q.filter(a => {
      return 0 > x.findIndex(b => b === a)
    })
    const y = l.sync('**/*.js', {
      cwd: b,
      ignore: [
        ...[
          'node_modules/**/*',
          '**/node_modules/**',
          '**/.git/**',
          '.git/**/*',
          '**/.svn/**',
          '.svn/**/*',
          '.DS_Store',
          '**/.DS_Store'
        ],
        'app.js',
        ...x,
        ...q
      ],
      nocase: !0,
      dot: !0,
      nodir: !0
    })
    let z
    try {
      z = await g('app.js')
    } catch (a) {
      throw new Error('getjs app.js fail,' + a)
    }
    let A = [';' + z, ';require("app.js");', `//# sourceURL=${k}app.js\n`].join(
        '\n'
      ),
      B = i.join(c, 'app.js')
    h.sync(i.dirname(B)),
      j.writeFileSync(B, A, 'utf-8'),
      (A = o),
      (B = i.join(c, 'app.json')),
      h.sync(i.dirname(B)),
      j.writeFileSync(B, A, 'utf-8'),
      f('preparefile', '\u51C6\u5907 Components \u6587\u4EF6')
    for (const f of x) {
      const d = i.join(b, f)
      if (!j.existsSync(d)) throw new Error(f + ' does not exists')
      if (j.lstatSync(d).isDirectory()) throw new Error(f + ' is a directory')
      const e = f.replace(/\.js$/i, ''),
        l = (await r(a, e)) || {}
      try {
        z = await g(encodeURI(f))
      } catch (a) {
        throw new Error('getjs ' + d + ' fail,' + a)
      }
      if (p.plugins && l.usingComponents)
        for (const a in l.usingComponents)
          l.usingComponents[a] = l.usingComponents[a].replace(
            /^plugin:\/\/([^\/]*)\/(.*)/,
            (a, b, c, d, e) => {
              const f = p.plugins[b]
              return f ? `plugin://${f.provider}/${c}` : e
            }
          )
      ;(A = [
        `;var __wxAppCode__ = __wxAppCode__ || {}; __wxAppCode__["${e}.json"] = ${JSON.stringify(
          l
        )}; var __wxRoute = "${e.replace(
          /"/g,
          '\\"'
        )}"; var __wxRouteBegin = true; var __wxAppCurrentFile__ ="${f.replace(
          /"/g,
          '\\"'
        )}"; ` + z,
        `;require("${f.replace(/"/g, '\\"')}");`,
        `//# sourceURL=${k}${f}\n`
      ].join('\n')),
        (B = i.join(c, f)),
        h.sync(i.dirname(B)),
        j.writeFileSync(B, A, 'utf-8')
    }
    f('preparefile', '\u51C6\u5907 Page \u6587\u4EF6')
    for (const f of q) {
      const d = i.join(b, f)
      if (!j.existsSync(d)) throw new Error(f + ' does not exists')
      if (j.lstatSync(d).isDirectory()) throw new Error(f + ' is a directory')
      const e = f.replace(/\.js$/i, ''),
        l = (await r(a, e)) || {}
      try {
        z = await g(encodeURI(f))
      } catch (a) {
        throw new Error('getjs ' + d + ' fail,' + a)
      }
      if (p.plugins && l.usingComponents)
        for (const a in l.usingComponents)
          l.usingComponents[a] = l.usingComponents[a].replace(
            /^plugin:\/\/([^\/]*)\/(.*)/,
            (a, b, c, d, e) => {
              const f = p.plugins[b]
              return f ? `plugin://${f.provider}/${c}` : e
            }
          )
      ;(A = [
        `;var __wxAppCode__ = __wxAppCode__ || {}; __wxAppCode__["${e}.json"] = ${JSON.stringify(
          l
        )}; var __wxRoute = "${e.replace(
          /"/g,
          '\\"'
        )}"; var __wxRouteBegin = true; var __wxAppCurrentFile__ ="${f.replace(
          /"/g,
          '\\"'
        )}"; ` + z,
        `;require("${f.replace(/"/g, '\\"')}");`,
        `//# sourceURL=${k}${f}\n`
      ].join('\n')),
        (B = i.join(c, f)),
        h.sync(i.dirname(B)),
        j.writeFileSync(B, A, 'utf-8')
    }
    f('preparefile', '\u51C6\u5907 JS \u6587\u4EF6')
    for (const f of y) {
      const a = i.join(b, f)
      if (!j.existsSync(a)) throw new Error(f + ' does not exists')
      if (j.lstatSync(a).isDirectory()) throw new Error(f + ' is a directory')
      try {
        z = await g(encodeURI(f))
      } catch (b) {
        throw new Error('getjs ' + a + ' fail,' + b)
      }
      ;(A = [
        ';var __wxAppData = __wxAppData || {}; var __wxRoute; var __wxRouteBegin; var __wxAppCode__ = __wxAppCode__ || {}; var global = global || {}; var __wxAppCurrentFile__; var Component = Component || function() {}; var Behavior = Behavior || function() {}; ' +
          z,
        `//# sourceURL=${k}${f}\n`
      ].join('\n')),
        (B = i.join(c, f)),
        h.sync(i.dirname(B)),
        j.writeFileSync(B, A, 'utf-8')
    }
    let C
    try {
      C = await s(a)
    } catch (a) {
      throw new Error('getWxAppCode fail,' + a)
    }
    ;(B = i.join(d, 'wxappcode.js')),
      j.writeFileSync(
        B,
        `;var __wxAppCode__ = __wxAppCode__ || {}; ${C.join(
          ';\n'
        )};\n//# sourceURL=[__wxAppCode__]`,
        'utf-8'
      )
    let D
    try {
      D = await t(a, { app: !0, cut: !0 })
    } catch (a) {
      throw new Error('transWXMLToJS fail,' + a)
    }
    const F = D.code
    ;(B = i.join(d, 'wxmlxcjs.js')),
      j.writeFileSync(B, `${F}\n//# sourceURL=[__wxmlXCJS__]`, 'utf-8')
    let G
    try {
      if (p.plugins) {
        let b = []
        for (const c in p.plugins) {
          const { provider: d, version: e } = p.plugins[c],
            f = await w.getServiceCode(a, { pluginId: d, version: e })
          b.push(`;${f};\n`)
        }
        G = b.join('\n')
      }
    } catch (a) {
      throw new Error('getWxPluginCode fail,' + a)
    }
    return (
      (B = i.join(d, 'wxplugincode.js')),
      j.writeFileSync(B, `${G}\n//# sourceURL=[__wxPluginCode__]`, 'utf-8'),
      ['app.json', ...y, 'app.js', ...x, ...q]
    )
  }
  function b() {
    if (!0 === x) return void (C = !0)
    if (x) {
      try {
        x.destroy()
      } catch (a) {}
      x = null
    }
  }
  const {
      RemoteTempDir: c,
      RemoteDir: d,
      RemoteDataDir: e
    } = require('./a148d3a11fd5268109e21fb40c9d527b.js'),
    {
      commonError: f,
      randomId: g
    } = require('./46d7303eb986fa402d60bf5e929aa077.js'),
    h = require('mkdir-p'),
    i = require('path'),
    j = require('fs'),
    k = require('rmdir'),
    l = require('glob'),
    m = require('./87c0ac209c25d8bb448550638bb17663.js'),
    { RemoteDebug: n } = require('./6c6f4dde020ed24929c4c4367c42d34d.js'),
    o = require('./bc78839ccca8df9e5ceeb7fae11b7be2.js'),
    p = o.getState.bind(o),
    q = o.subscribe.bind(o),
    r = require('./d260ebf687a29f24aed49f66b233ab7d.js'),
    s = require('./334bc661e13bd1837a230f0835d0a1ee.js'),
    t = require('./3e4c71c2a2cc438e1b3afc3fb10bd4b6.js'),
    u = require('./6b5520e429c60abf5d2f924c0fa05fd0.js'),
    v = require('./1dea83a77e99a7c94f6b6f01f5c175b0.js'),
    w = require('./b6d8659542036f6a35f417e0693e56db.js')
  let x = !1,
    y = [],
    z = [],
    A = null,
    B = null,
    C = !1,
    D = { mode: 'server' }
  const E = function() {}
  let F = null
  const G = {
    getStatus() {
      if (!x || !0 === x) return null
      const a = D.mode
      return {
        messager:
          'server' === a
            ? {
                compressionSavedBytes: x.messager.compressionSavedBytes,
                status: x.messager.status,
                inSpeed: x.messager.inSpeed,
                outSpeed: x.messager.outSpeed,
                outDebugMessageSpeed: x.messager.outDebugMessageSpeed,
                inDebugMessageSpeed: x.messager.inDebugMessageSpeed,
                outDebugMessageCount: x.messager.outDebugMessageCount,
                inDebugMessageCount: x.messager.inDebugMessageCount,
                inCount: x.messager.inCount,
                outCount: x.messager.outCount,
                inBytesCount: x.messager.inBytesCount,
                outBytesCount: x.messager.outBytesCount,
                sendQueueLength: x.messager.sendQueue.length,
                cachedDebugMessagesCount: x.messager.debugMessagesToSend.length,
                unconfirmedMessagesCount: (() => {
                  const a = x.messager.cachedDebugMessageSendGroups
                  let b = 0
                  for (const c of a)
                    b += (
                      ((c && !c.confirmed && c.sendDebugMessageRequest) || {})
                        .debug_message || []
                    ).length
                  return b
                })()
              }
            : {
                status: x.messager.status,
                inDebugMessageSpeed: x.messager.inDebugMessageSpeed,
                outDebugMessageSpeed: x.messager.outDebugMessageSpeed,
                outDebugMessageCount: x.messager.outDebugMessageCount,
                inDebugMessageCount: x.messager.inDebugMessageCount,
                inBytesCount: x.messager.inBytesCount,
                outBytesCount: x.messager.outBytesCount,
                cachedDebugMessagesCount: x.messager.debugMessagesToSend.length,
                unconfirmedMessagesCount: x.messager.unconfirmedMessagesCount
              },
        _debugger: { status: x.debuggerStatus },
        dirs: { dir: x.dir, tempDir: x.tempDir },
        client: {
          deviceInfo: x.deviceInfo,
          networkType: x.clientNetworkType,
          networkSpeed: x.clientNetworkSpeed,
          networkInterval: x.clientNetworkInterval
        },
        currentSyncSdkName: (() => {
          let a = x.currentSyncSdkName
          if (!a && x.syncCallIds) {
            const b = Object.keys(x.syncCallIds)
            0 < b.length && (a = x.syncCallIds[b[0]])
          }
          return a
        })()
      }
    },
    subscribeChange(a) {
      y.push(a)
    },
    subscribeEvent(a) {
      z.push(a)
    },
    changeDebuggerStatus(a) {
      x && !0 !== x && x.changeDebuggerStatus(a)
    },
    onAskForRetry(a) {
      A = a
    },
    onOpenEditorFile(a) {
      B = a
    },
    endDebug() {
      x && !0 !== x && x.destroy()
    },
    getInstance() {
      return x && !0 !== x ? x : null
    }
  }
  module.exports = {
    init: async function(j, l = {}, m = {}) {
      return new Promise(async (o, r) => {
        const s = m.onProgressUpdate || E
        if (
          (s('remotedebug', '\u521D\u59CB\u5316\u8C03\u8BD5\u73AF\u5883'), x)
        ) {
          console.warn('already an instance')
          const a = p()
          return a &&
            a.window &&
            a.window.remoteDebugWindow &&
            !a.window.remoteDebugWindow.show
            ? (console.warn('shall be destroyed'),
              b(),
              r('\u8BF7\u91CD\u65B0\u5C1D\u8BD5\u4E00\u6B21\u3002'))
            : r(f('remote debug instance already exists'))
        }
        const t = g(),
          u = i.join(d, j.appid || t, t),
          v = i.join(c, j.appid || t, t),
          w = i.join(e, j.appid || t),
          G = () => {
            try {
              k(u), k(v)
            } catch (a) {}
          }
        try {
          x = !0
          const { projectpath: c, miniprogramRoot: d } = j
          h.sync(u), h.sync(v), h.sync(w)
          const e = i.join(c, d || '')
          s('remotedebug', '\u51C6\u5907\u6587\u4EF6')
          const f = await a(j, e, u, v, { onProgressUpdate: s })
          if (C) {
            C = !1
            throw 'Aborted. Please retry'
          }
          x = new n({
            files: f,
            dir: u,
            tempDir: v,
            dataDir: w,
            initialRoomInfo: _extends({}, l),
            config: _extends({}, m),
            mode: m.remoteDebugLocal ? m.remoteDebugLocal : 'server',
            clientProxyPort: m.clientProxyPort
          })
          const g = m.onStatusUpdate || E,
            k = m.onEvent || E
          x.onAskForRetry(a => {
            return new Promise(async b => {
              A ? b(await A(a)) : b(!1)
            })
          }),
            x.onOpenEditorFile((...a) => {
              B && B(...a)
            }),
            x.onAskForChoosingAndroidDevice(a => {
              return new Promise(async b => {
                console.log(a),
                  setTimeout(() => {
                    b(0)
                  }, 1e3)
              })
            }),
            x.onAskForAndroidAuthorize(a => {
              return new Promise(async b => {
                console.log(a),
                  setTimeout(() => {
                    b(!0)
                  }, 1e3)
              })
            })
          let t
          x.once('initsuccess', a => {
            return C
              ? ((C = !1), x.destroy(), r('abort'))
              : void ((t = !0),
                o(_extends({}, a)),
                'function' == typeof F && (F(), (F = null)),
                (F = q(() => {
                  const a = p()
                  a &&
                    a.window &&
                    a.window.remoteDebugWindow &&
                    a.window.remoteDebugWindow.show &&
                    (console.log('subscribed remote window shown'),
                    'function' == typeof F &&
                      (F(),
                      (F = q(() => {
                        const a = p()
                        a &&
                          a.window &&
                          a.window.remoteDebugWindow &&
                          !a.window.remoteDebugWindow.show &&
                          (console.warn('shall automatically be destroyed'),
                          'function' == typeof F && (F(), (F = null)),
                          b())
                      }))))
                })))
          })
          const H = a => {
            ;(C = !1),
              (y = []),
              (z = []),
              (A = null),
              (B = null),
              G(),
              'function' == typeof F && (F(), (F = null)),
              void 0 === t && ((t = !1), r(a)),
              x && x.destroy(),
              (x = null)
          }
          x.once('initfail', H),
            x.once('destroy', a => {
              ;(C = !1), x && x.removeAllListeners(), (x = null)
              for (const b of y) b(!0)
              ;(y = []),
                (z = []),
                (A = null),
                (B = null),
                G(),
                'function' == typeof F && (F(), (F = null)),
                void 0 === t && ((t = !1), r(a))
            })
          let I
          x.on('statuschange', () => {
            I ||
              (I = setTimeout(() => {
                I = void 0
                for (const a of y) a()
                const a = x && x.messager && x.messager.status
                g(a, 4 < a)
              }, 400))
          }),
            x.on('event', a => {
              for (const b of z) b(a)
              a && k(a)
            }),
            (D = { mode: m.remoteDebugLocal ? m.remoteDebugLocal : 'server' })
          try {
            s('remotedebug', '\u521D\u59CB\u5316\u8C03\u8BD5\u5B9E\u4F8B'),
              await x.init(),
              s('remotedebug', '\u7B49\u5F85\u8FDB\u7A0B')
          } catch (a) {
            throw (H(a), a)
          }
        } catch (a) {
          G(), (x = null), r(f(a))
        }
      })
    },
    onUrlRequest: function(a) {
      if (!x || !0 === x) return void console.warn('no active instance')
      const b = a.replace(/^\/*remotedebug\/+/i, '').toLowerCase()
      switch (!0) {
        case b.startsWith('registersyncpid/'): {
          const a = b.replace(/^\/*registersyncpid\/+/g, '')
          let [c, d] = a.split('/')
          if (
            ((c = parseInt(c, 10)), (d = parseInt(d, 10)), isNaN(c) || isNaN(d))
          )
            return void console.warn('invalid pid or sdkid')
          x.registerSyncPid(c, d)
          break
        }
        default:
          console.warn('invalid request href')
      }
    },
    destroy: b,
    model: G
  }
})(require('lazyload'), require)
