web-ext 10.4.0 → 10.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/lib/cmd/build.js.map +1 -1
  2. package/lib/cmd/docs.js.map +1 -1
  3. package/lib/cmd/dump-config.js.map +1 -1
  4. package/lib/cmd/index.js.map +1 -1
  5. package/lib/cmd/lint.js +2 -0
  6. package/lib/cmd/lint.js.map +1 -1
  7. package/lib/cmd/run.js.map +1 -1
  8. package/lib/cmd/sign.js.map +1 -1
  9. package/lib/config.js.map +1 -1
  10. package/lib/errors.js.map +1 -1
  11. package/lib/extension-runners/chromium.js +1 -2
  12. package/lib/extension-runners/chromium.js.map +1 -1
  13. package/lib/extension-runners/firefox-android.js.map +1 -1
  14. package/lib/extension-runners/firefox-desktop.js.map +1 -1
  15. package/lib/extension-runners/index.js.map +1 -1
  16. package/lib/firefox/index.js.map +1 -1
  17. package/lib/firefox/package-identifiers.js.map +1 -1
  18. package/lib/firefox/preferences.js.map +1 -1
  19. package/lib/firefox/rdp-client.js +2 -2
  20. package/lib/firefox/rdp-client.js.map +1 -1
  21. package/lib/firefox/remote.js.map +1 -1
  22. package/lib/main.js.map +1 -1
  23. package/lib/program.js +6 -1
  24. package/lib/program.js.map +1 -1
  25. package/lib/util/adb.js.map +1 -1
  26. package/lib/util/artifacts.js.map +1 -1
  27. package/lib/util/expand-prefs.js.map +1 -1
  28. package/lib/util/file-exists.js.map +1 -1
  29. package/lib/util/file-filter.js.map +1 -1
  30. package/lib/util/is-directory.js.map +1 -1
  31. package/lib/util/logger.js.map +1 -1
  32. package/lib/util/manifest.js +1 -1
  33. package/lib/util/manifest.js.map +1 -1
  34. package/lib/util/promisify.js.map +1 -1
  35. package/lib/util/stdin.js.map +1 -1
  36. package/lib/util/submit-addon.js +6 -3
  37. package/lib/util/submit-addon.js.map +1 -1
  38. package/lib/util/temp-dir.js.map +1 -1
  39. package/lib/util/updates.js.map +1 -1
  40. package/lib/watcher.js.map +1 -1
  41. package/package.json +12 -19
@@ -1 +1 @@
1
- {"version":3,"file":"firefox-android.js","names":["path","readline","withTempDir","DefaultADBUtils","MultiExtensionsReloadError","UsageError","WebExtError","findFreeTcpPort","createLogger","isTTY","setRawMode","log","import","meta","url","ignoredParams","profilePath","keepProfileChanges","browserConsole","preInstall","startUrl","args","DEFAULT_ADB_HOST","getIgnoredParamsWarningsMessage","optionName","FirefoxAndroidExtensionRunner","unixSocketDiscoveryRetryInterval","unixSocketDiscoveryMaxTime","params","adbUtils","exiting","selectedAdbDevice","selectedFirefoxApk","selectedArtifactsDir","selectedRDPSocketFile","selectedTCPPort","cleanupCallbacks","adbExtensionsPathBySourceDir","reloadableExtensions","remoteFirefox","constructor","Set","Map","printIgnoredParamsWarnings","run","adbBin","adbHost","adbPort","ADBUtils","adbDevicesDiscoveryAndSelect","apkPackagesDiscoveryAndSelect","adbForceStopSelectedPackage","adbPrepareProfileDir","Promise","all","adbStartSelectedPackage","buildAndPushExtensions","adbDiscoveryAndForwardRDPUnixSocket","rdpInstallExtensions","getName","reloadAllExtensions","runnerName","reloadErrors","sourceDir","extensions","res","reloadExtensionBySourceDir","reloadError","Error","set","size","extensionSourceDir","addonId","get","buildAndPushExtension","reloadAddon","error","registerCleanup","fn","add","exit","debug","clearArtifactsDir","getDeviceProfileDir","Object","keys","forEach","ignoredParam","warn","adbDevice","devices","discoverDevices","length","devicesMsg","map","dev","join","info","foundDevices","filter","device","JSON","stringify","firefoxApk","packages","discoverInstalledFirefoxAPKs","pkgsListMsg","pkgs","pkg","filteredPackages","line","pkgsList","amForceStopAPK","customPrefs","firefoxApp","adbRemoveOldArtifacts","profile","createProfile","app","foundOldArtifacts","detectOrRemoveOldArtifacts","getOrCreateArtifactsDir","deviceProfileDir","runShellCommand","pushFile","profileDir","firefoxApkComponent","startFirefoxAPK","buildSourceDir","tmpDir","extensionPath","extFileName","basename","adbExtensionPath","adbDiscoveryTimeout","stdin","process","handleCtrlC","str","key","ctrl","name","setUserAbortDiscovery","emitKeypressEvents","on","discoverRDPUnixSocket","maxDiscoveryTime","retryInterval","removeListener","tcpPort","forwardSocketSpec","startsWith","substr","setupForward","firefoxClient","port","client","extension","installTemporaryAddon","then","installResult","addon","id"],"sources":["../../src/extension-runners/firefox-android.js"],"sourcesContent":["/**\n * This module provide an ExtensionRunner subclass that manage an extension executed\n * in a Firefox for Android instance.\n */\n\nimport path from 'path';\nimport readline from 'readline';\n\nimport { withTempDir } from '../util/temp-dir.js';\nimport DefaultADBUtils from '../util/adb.js';\nimport {\n MultiExtensionsReloadError,\n UsageError,\n WebExtError,\n} from '../errors.js';\nimport { findFreeTcpPort } from '../firefox/remote.js';\nimport { createLogger } from '../util/logger.js';\nimport { isTTY, setRawMode } from '../util/stdin.js';\n\nconst log = createLogger(import.meta.url);\n\nconst ignoredParams = {\n profilePath: '--profile-path',\n keepProfileChanges: '--keep-profile-changes',\n browserConsole: '--browser-console',\n preInstall: '--pre-install',\n startUrl: '--start-url',\n args: '--args',\n};\n\n// Default adbHost to 127.0.0.1 to prevent issues with nodejs 17\n// (because if not specified adbkit may default to ipv6 while\n// adb may still only be listening on the ipv4 address),\n// see https://github.com/mozilla/web-ext/issues/2337.\nconst DEFAULT_ADB_HOST = '127.0.0.1';\n\nconst getIgnoredParamsWarningsMessage = (optionName) => {\n return `The Firefox for Android target does not support ${optionName}`;\n};\n\n/**\n * Implements an IExtensionRunner which manages a Firefox for Android instance.\n */\nexport class FirefoxAndroidExtensionRunner {\n // Wait 3s before the next unix socket discovery loop.\n static unixSocketDiscoveryRetryInterval = 3 * 1000;\n // Wait for at most 3 minutes before giving up.\n static unixSocketDiscoveryMaxTime = 3 * 60 * 1000;\n\n params;\n adbUtils;\n exiting;\n selectedAdbDevice;\n selectedFirefoxApk;\n selectedArtifactsDir;\n selectedRDPSocketFile;\n selectedTCPPort;\n cleanupCallbacks;\n adbExtensionsPathBySourceDir;\n reloadableExtensions;\n remoteFirefox;\n\n constructor(params) {\n this.params = params;\n this.cleanupCallbacks = new Set();\n this.adbExtensionsPathBySourceDir = new Map();\n this.reloadableExtensions = new Map();\n\n // Print warning for not currently supported options (e.g. preInstall,\n // cloned profiles, browser console).\n this.printIgnoredParamsWarnings();\n }\n\n async run() {\n const {\n adbBin,\n adbHost = DEFAULT_ADB_HOST,\n adbPort,\n ADBUtils = DefaultADBUtils,\n } = this.params;\n\n this.adbUtils = new ADBUtils({\n adbBin,\n adbHost,\n adbPort,\n });\n\n await this.adbDevicesDiscoveryAndSelect();\n await this.apkPackagesDiscoveryAndSelect();\n await this.adbForceStopSelectedPackage();\n\n // Create profile prefs (with enabled remote RDP server), prepare the\n // artifacts and temporary directory on the selected device, and\n // push the profile preferences to the remote profile dir.\n await this.adbPrepareProfileDir();\n\n // NOTE: running Firefox for Android on the Android Emulator can be\n // pretty slow, we can run the following 3 steps in parallel to speed up\n // it a bit.\n await Promise.all([\n // Start Firefox for Android instance if not started yet.\n // (Fennec would run in an temporary profile and so it is explicitly\n // stopped, Fenix runs on its usual profile and so it may be already\n // running).\n this.adbStartSelectedPackage(),\n\n // Build and push to devices all the extension xpis\n // and keep track of the xpi built and uploaded by extension sourceDir.\n this.buildAndPushExtensions(),\n\n // Wait for RDP unix socket file created and\n // Create an ADB forward connection on a free tcp port\n this.adbDiscoveryAndForwardRDPUnixSocket(),\n ]);\n\n // Connect to RDP socket on the local tcp server, install all the pushed extension\n // and keep track of the built and installed extension by extension sourceDir.\n await this.rdpInstallExtensions();\n }\n\n // Method exported from the IExtensionRunner interface.\n\n /**\n * Returns the runner name.\n */\n getName() {\n return 'Firefox Android';\n }\n\n /**\n * Reloads all the extensions, collect any reload error and resolves to\n * an array composed by a single ExtensionRunnerReloadResult object.\n */\n async reloadAllExtensions() {\n const runnerName = this.getName();\n const reloadErrors = new Map();\n\n for (const { sourceDir } of this.params.extensions) {\n const [res] = await this.reloadExtensionBySourceDir(sourceDir);\n if (res.reloadError instanceof Error) {\n reloadErrors.set(sourceDir, res.reloadError);\n }\n }\n\n if (reloadErrors.size > 0) {\n return [\n {\n runnerName,\n reloadError: new MultiExtensionsReloadError(reloadErrors),\n },\n ];\n }\n\n return [{ runnerName }];\n }\n\n /**\n * Reloads a single extension, collect any reload error and resolves to\n * an array composed by a single ExtensionRunnerReloadResult object.\n */\n async reloadExtensionBySourceDir(extensionSourceDir) {\n const runnerName = this.getName();\n const addonId = this.reloadableExtensions.get(extensionSourceDir);\n\n if (!addonId) {\n return [\n {\n sourceDir: extensionSourceDir,\n reloadError: new WebExtError(\n 'Extension not reloadable: ' +\n `no addonId has been mapped to \"${extensionSourceDir}\"`,\n ),\n runnerName,\n },\n ];\n }\n\n try {\n await this.buildAndPushExtension(extensionSourceDir);\n await this.remoteFirefox.reloadAddon(addonId);\n } catch (error) {\n return [\n {\n sourceDir: extensionSourceDir,\n reloadError: error,\n runnerName,\n },\n ];\n }\n\n return [{ runnerName, sourceDir: extensionSourceDir }];\n }\n\n /**\n * Register a callback to be called when the runner has been exited\n * (e.g. the Firefox instance exits or the user has requested web-ext\n * to exit).\n */\n registerCleanup(fn) {\n this.cleanupCallbacks.add(fn);\n }\n\n /**\n * Exits the runner, by closing the managed Firefox instance.\n */\n async exit() {\n const { adbUtils, selectedAdbDevice, selectedArtifactsDir } = this;\n\n this.exiting = true;\n\n // If a Firefox for Android instance has been started,\n // we should ensure that it has been stopped when we exit.\n await this.adbForceStopSelectedPackage();\n\n if (selectedArtifactsDir) {\n log.debug('Cleaning up artifacts directory on the Android device...');\n await adbUtils.clearArtifactsDir(selectedAdbDevice);\n }\n\n // Call all the registered cleanup callbacks.\n for (const fn of this.cleanupCallbacks) {\n try {\n fn();\n } catch (error) {\n log.error(error);\n }\n }\n }\n\n // Private helper methods.\n\n getDeviceProfileDir() {\n return `${this.selectedArtifactsDir}/profile`;\n }\n\n printIgnoredParamsWarnings() {\n Object.keys(ignoredParams).forEach((ignoredParam) => {\n if (this.params[ignoredParam]) {\n log.warn(getIgnoredParamsWarningsMessage(ignoredParams[ignoredParam]));\n }\n });\n }\n\n async adbDevicesDiscoveryAndSelect() {\n const { adbUtils } = this;\n const { adbDevice } = this.params;\n let devices = [];\n\n log.debug('Listing android devices');\n devices = await adbUtils.discoverDevices();\n\n if (devices.length === 0) {\n throw new UsageError(\n 'No Android device found through ADB. ' +\n 'Make sure the device is connected and USB debugging is enabled.',\n );\n }\n\n if (!adbDevice) {\n const devicesMsg = devices.map((dev) => ` - ${dev}`).join('\\n');\n log.info(`\\nAndroid devices found:\\n${devicesMsg}`);\n throw new UsageError(\n 'Select an android device using --android-device=<name>',\n );\n }\n\n const foundDevices = devices.filter((device) => {\n return device === adbDevice;\n });\n\n if (foundDevices.length === 0) {\n const devicesMsg = JSON.stringify(devices);\n throw new UsageError(\n `Android device ${adbDevice} was not found in list: ${devicesMsg}`,\n );\n }\n\n this.selectedAdbDevice = foundDevices[0];\n log.info(`Selected ADB device: ${this.selectedAdbDevice}`);\n }\n\n async apkPackagesDiscoveryAndSelect() {\n const {\n adbUtils,\n selectedAdbDevice,\n params: { firefoxApk },\n } = this;\n // Discovery and select a Firefox for Android version.\n const packages = await adbUtils.discoverInstalledFirefoxAPKs(\n selectedAdbDevice,\n firefoxApk,\n );\n\n if (packages.length === 0) {\n throw new UsageError(\n 'No Firefox packages were found on the selected Android device',\n );\n }\n\n const pkgsListMsg = (pkgs) => {\n return pkgs.map((pkg) => ` - ${pkg}`).join('\\n');\n };\n\n if (!firefoxApk) {\n log.info(`\\nPackages found:\\n${pkgsListMsg(packages)}`);\n\n if (packages.length > 1) {\n throw new UsageError('Select one of the packages using --firefox-apk');\n }\n\n // If only one APK has been found, select it even if it has not been\n // specified explicitly on the comment line.\n this.selectedFirefoxApk = packages[0];\n log.info(`Selected Firefox for Android APK: ${this.selectedFirefoxApk}`);\n return;\n }\n\n const filteredPackages = packages.filter((line) => line === firefoxApk);\n\n if (filteredPackages.length === 0) {\n const pkgsList = pkgsListMsg(filteredPackages);\n throw new UsageError(\n `Package ${firefoxApk} was not found in list: ${pkgsList}`,\n );\n }\n\n this.selectedFirefoxApk = filteredPackages[0];\n log.debug(`Selected Firefox for Android APK: ${this.selectedFirefoxApk}`);\n }\n\n async adbForceStopSelectedPackage() {\n const { adbUtils, selectedAdbDevice, selectedFirefoxApk } = this;\n\n log.info(`Stopping existing instances of ${selectedFirefoxApk}...`);\n await adbUtils.amForceStopAPK(selectedAdbDevice, selectedFirefoxApk);\n }\n\n async adbPrepareProfileDir() {\n const {\n adbUtils,\n selectedAdbDevice,\n selectedFirefoxApk,\n params: { customPrefs, firefoxApp, adbRemoveOldArtifacts },\n } = this;\n // Create the preferences file and the Fennec temporary profile.\n log.debug(`Preparing a temporary profile for ${selectedFirefoxApk}...`);\n\n const profile = await firefoxApp.createProfile({\n app: 'fennec',\n customPrefs,\n });\n\n // Check if there are any artifacts dirs from previous runs and\n // automatically remove them if adbRemoteOldArtifacts is true.\n const foundOldArtifacts = await adbUtils.detectOrRemoveOldArtifacts(\n selectedAdbDevice,\n adbRemoveOldArtifacts,\n );\n\n if (foundOldArtifacts) {\n if (adbRemoveOldArtifacts) {\n log.info(\n 'Old web-ext artifacts have been found and removed ' +\n `from ${selectedAdbDevice} device`,\n );\n } else {\n log.warn(\n `Old artifacts directories have been found on ${selectedAdbDevice} ` +\n 'device. Use --adb-remove-old-artifacts to remove them automatically.',\n );\n }\n }\n\n // Choose a artifacts dir name for the assets pushed to the\n // Android device.\n this.selectedArtifactsDir =\n await adbUtils.getOrCreateArtifactsDir(selectedAdbDevice);\n\n const deviceProfileDir = this.getDeviceProfileDir();\n\n await adbUtils.runShellCommand(selectedAdbDevice, [\n 'mkdir',\n '-p',\n deviceProfileDir,\n ]);\n await adbUtils.pushFile(\n selectedAdbDevice,\n path.join(profile.profileDir, 'user.js'),\n `${deviceProfileDir}/user.js`,\n );\n\n log.debug(`Created temporary profile at ${deviceProfileDir}.`);\n }\n\n async adbStartSelectedPackage() {\n const {\n adbUtils,\n selectedFirefoxApk,\n selectedAdbDevice,\n params: { firefoxApkComponent },\n } = this;\n\n const deviceProfileDir = this.getDeviceProfileDir();\n\n log.info(`Starting ${selectedFirefoxApk}...`);\n\n log.debug(`Using profile ${deviceProfileDir} (ignored by Fenix)`);\n\n await adbUtils.startFirefoxAPK(\n selectedAdbDevice,\n selectedFirefoxApk,\n firefoxApkComponent,\n deviceProfileDir,\n );\n }\n\n async buildAndPushExtension(sourceDir) {\n const {\n adbUtils,\n selectedAdbDevice,\n selectedArtifactsDir,\n params: { buildSourceDir },\n } = this;\n\n await withTempDir(async (tmpDir) => {\n const { extensionPath } = await buildSourceDir(sourceDir, tmpDir.path());\n\n const extFileName = path.basename(extensionPath, '.zip');\n\n let adbExtensionPath = this.adbExtensionsPathBySourceDir.get(sourceDir);\n\n if (!adbExtensionPath) {\n adbExtensionPath = `${selectedArtifactsDir}/${extFileName}.xpi`;\n }\n\n log.debug(`Uploading ${extFileName} on the android device`);\n\n await adbUtils.pushFile(\n selectedAdbDevice,\n extensionPath,\n adbExtensionPath,\n );\n\n log.debug(`Upload completed: ${adbExtensionPath}`);\n\n this.adbExtensionsPathBySourceDir.set(sourceDir, adbExtensionPath);\n });\n }\n\n async buildAndPushExtensions() {\n for (const { sourceDir } of this.params.extensions) {\n await this.buildAndPushExtension(sourceDir);\n }\n }\n\n async adbDiscoveryAndForwardRDPUnixSocket() {\n const {\n adbUtils,\n selectedAdbDevice,\n selectedFirefoxApk,\n params: { adbDiscoveryTimeout },\n } = this;\n\n const stdin = this.params.stdin || process.stdin;\n\n const { unixSocketDiscoveryRetryInterval } = FirefoxAndroidExtensionRunner;\n\n let { unixSocketDiscoveryMaxTime } = FirefoxAndroidExtensionRunner;\n\n if (typeof adbDiscoveryTimeout === 'number') {\n unixSocketDiscoveryMaxTime = adbDiscoveryTimeout;\n }\n\n const handleCtrlC = (str, key) => {\n if (key.ctrl && key.name === 'c') {\n adbUtils.setUserAbortDiscovery(true);\n }\n };\n\n // TODO: use noInput property to decide if we should\n // disable direct keypress handling.\n if (isTTY(stdin)) {\n readline.emitKeypressEvents(stdin);\n setRawMode(stdin, true);\n\n stdin.on('keypress', handleCtrlC);\n }\n\n try {\n // Got a debugger socket file to connect.\n this.selectedRDPSocketFile = await adbUtils.discoverRDPUnixSocket(\n selectedAdbDevice,\n selectedFirefoxApk,\n {\n maxDiscoveryTime: unixSocketDiscoveryMaxTime,\n retryInterval: unixSocketDiscoveryRetryInterval,\n },\n );\n } finally {\n if (isTTY(stdin)) {\n stdin.removeListener('keypress', handleCtrlC);\n }\n }\n\n log.debug(`RDP Socket File selected: ${this.selectedRDPSocketFile}`);\n\n const tcpPort = await findFreeTcpPort();\n\n // Log the chosen tcp port at info level (useful to the user to be able\n // to connect the Firefox DevTools to the Firefox for Android instance).\n log.info(`You can connect to this Android device on TCP port ${tcpPort}`);\n\n const forwardSocketSpec = this.selectedRDPSocketFile.startsWith('@')\n ? `localabstract:${this.selectedRDPSocketFile.substr(1)}`\n : `localfilesystem:${this.selectedRDPSocketFile}`;\n\n await adbUtils.setupForward(\n selectedAdbDevice,\n forwardSocketSpec,\n `tcp:${tcpPort}`,\n );\n\n this.selectedTCPPort = tcpPort;\n }\n\n async rdpInstallExtensions() {\n const {\n selectedTCPPort,\n params: { extensions, firefoxClient },\n } = this;\n\n const remoteFirefox = (this.remoteFirefox = await firefoxClient({\n port: selectedTCPPort,\n }));\n\n // Exit and cleanup the extension runner if the connection to the\n // remote Firefox for Android instance has been closed.\n remoteFirefox.client.on('end', () => {\n if (!this.exiting) {\n log.info('Exiting the device because Firefox for Android disconnected');\n this.exit();\n }\n });\n\n // Install all the temporary addons.\n for (const extension of extensions) {\n const { sourceDir } = extension;\n const adbExtensionPath = this.adbExtensionsPathBySourceDir.get(sourceDir);\n\n if (!adbExtensionPath) {\n throw new WebExtError(\n `ADB extension path for \"${sourceDir}\" was unexpectedly empty`,\n );\n }\n\n const addonId = await remoteFirefox\n .installTemporaryAddon(adbExtensionPath)\n .then((installResult) => {\n return installResult.addon.id;\n });\n\n if (!addonId) {\n throw new WebExtError(\n 'Received an empty addonId from ' +\n `remoteFirefox.installTemporaryAddon(\"${adbExtensionPath}\")`,\n );\n }\n\n this.reloadableExtensions.set(extension.sourceDir, addonId);\n }\n }\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;;AAEA,OAAOA,IAAI,MAAM,MAAM;AACvB,OAAOC,QAAQ,MAAM,UAAU;AAE/B,SAASC,WAAW,QAAQ,qBAAqB;AACjD,OAAOC,eAAe,MAAM,gBAAgB;AAC5C,SACEC,0BAA0B,EAC1BC,UAAU,EACVC,WAAW,QACN,cAAc;AACrB,SAASC,eAAe,QAAQ,sBAAsB;AACtD,SAASC,YAAY,QAAQ,mBAAmB;AAChD,SAASC,KAAK,EAAEC,UAAU,QAAQ,kBAAkB;AAEpD,MAAMC,GAAG,GAAGH,YAAY,CAACI,MAAM,CAACC,IAAI,CAACC,GAAG,CAAC;AAEzC,MAAMC,aAAa,GAAG;EACpBC,WAAW,EAAE,gBAAgB;EAC7BC,kBAAkB,EAAE,wBAAwB;EAC5CC,cAAc,EAAE,mBAAmB;EACnCC,UAAU,EAAE,eAAe;EAC3BC,QAAQ,EAAE,aAAa;EACvBC,IAAI,EAAE;AACR,CAAC;;AAED;AACA;AACA;AACA;AACA,MAAMC,gBAAgB,GAAG,WAAW;AAEpC,MAAMC,+BAA+B,GAAIC,UAAU,IAAK;EACtD,OAAO,mDAAmDA,UAAU,EAAE;AACxE,CAAC;;AAED;AACA;AACA;AACA,OAAO,MAAMC,6BAA6B,CAAC;EACzC;EACA,OAAOC,gCAAgC,GAAG,CAAC,GAAG,IAAI;EAClD;EACA,OAAOC,0BAA0B,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI;EAEjDC,MAAM;EACNC,QAAQ;EACRC,OAAO;EACPC,iBAAiB;EACjBC,kBAAkB;EAClBC,oBAAoB;EACpBC,qBAAqB;EACrBC,eAAe;EACfC,gBAAgB;EAChBC,4BAA4B;EAC5BC,oBAAoB;EACpBC,aAAa;EAEbC,WA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;QACvE,IAAI,CAACjB,IAAI,CAAC,CAAC;MACb;IACF,CAAC,CAAC;;IAEF;IACA,KAAK,MAAM6E,SAAS,IAAI7F,UAAU,EAAE;MAClC,MAAM;QAAED;MAAU,CAAC,GAAG8F,SAAS;MAC/B,MAAMxB,gBAAgB,GAAG,IAAI,CAAChG,4BAA4B,CAACoC,GAAG,CAACV,SAAS,CAAC;MAEzE,IAAI,CAACsE,gBAAgB,EAAE;QACrB,MAAM,IAAI/H,WAAW,CACnB,2BAA2ByD,SAAS,0BACtC,CAAC;MACH;MAEA,MAAMS,OAAO,GAAG,MAAMjC,aAAa,CAChCuH,qBAAqB,CAACzB,gBAAgB,CAAC,CACvC0B,IAAI,CAAEC,aAAa,IAAK;QACvB,OAAOA,aAAa,CAACC,KAAK,CAACC,EAAE;MAC/B,CAAC,CAAC;MAEJ,IAAI,CAAC1F,OAAO,EAAE;QACZ,MAAM,IAAIlE,WAAW,CACnB,iCAAiC,GAC/B,wCAAwC+H,gBAAgB,IAC5D,CAAC;MACH;MAEA,IAAI,CAAC/F,oBAAoB,CAAC+B,GAAG,CAACwF,SAAS,CAAC9F,SAAS,EAAES,OAAO,CAAC;IAC7D;EACF;AACF","ignoreList":[]}
1
+ {"version":3,"file":"firefox-android.js","names":[],"sources":["../../src/extension-runners/firefox-android.js"],"sourcesContent":["/**\n * This module provide an ExtensionRunner subclass that manage an extension executed\n * in a Firefox for Android instance.\n */\n\nimport path from 'path';\nimport readline from 'readline';\n\nimport { withTempDir } from '../util/temp-dir.js';\nimport DefaultADBUtils from '../util/adb.js';\nimport {\n MultiExtensionsReloadError,\n UsageError,\n WebExtError,\n} from '../errors.js';\nimport { findFreeTcpPort } from '../firefox/remote.js';\nimport { createLogger } from '../util/logger.js';\nimport { isTTY, setRawMode } from '../util/stdin.js';\n\nconst log = createLogger(import.meta.url);\n\nconst ignoredParams = {\n profilePath: '--profile-path',\n keepProfileChanges: '--keep-profile-changes',\n browserConsole: '--browser-console',\n preInstall: '--pre-install',\n startUrl: '--start-url',\n args: '--args',\n};\n\n// Default adbHost to 127.0.0.1 to prevent issues with nodejs 17\n// (because if not specified adbkit may default to ipv6 while\n// adb may still only be listening on the ipv4 address),\n// see https://github.com/mozilla/web-ext/issues/2337.\nconst DEFAULT_ADB_HOST = '127.0.0.1';\n\nconst getIgnoredParamsWarningsMessage = (optionName) => {\n return `The Firefox for Android target does not support ${optionName}`;\n};\n\n/**\n * Implements an IExtensionRunner which manages a Firefox for Android instance.\n */\nexport class FirefoxAndroidExtensionRunner {\n // Wait 3s before the next unix socket discovery loop.\n static unixSocketDiscoveryRetryInterval = 3 * 1000;\n // Wait for at most 3 minutes before giving up.\n static unixSocketDiscoveryMaxTime = 3 * 60 * 1000;\n\n params;\n adbUtils;\n exiting;\n selectedAdbDevice;\n selectedFirefoxApk;\n selectedArtifactsDir;\n selectedRDPSocketFile;\n selectedTCPPort;\n cleanupCallbacks;\n adbExtensionsPathBySourceDir;\n reloadableExtensions;\n remoteFirefox;\n\n constructor(params) {\n this.params = params;\n this.cleanupCallbacks = new Set();\n this.adbExtensionsPathBySourceDir = new Map();\n this.reloadableExtensions = new Map();\n\n // Print warning for not currently supported options (e.g. preInstall,\n // cloned profiles, browser console).\n this.printIgnoredParamsWarnings();\n }\n\n async run() {\n const {\n adbBin,\n adbHost = DEFAULT_ADB_HOST,\n adbPort,\n ADBUtils = DefaultADBUtils,\n } = this.params;\n\n this.adbUtils = new ADBUtils({\n adbBin,\n adbHost,\n adbPort,\n });\n\n await this.adbDevicesDiscoveryAndSelect();\n await this.apkPackagesDiscoveryAndSelect();\n await this.adbForceStopSelectedPackage();\n\n // Create profile prefs (with enabled remote RDP server), prepare the\n // artifacts and temporary directory on the selected device, and\n // push the profile preferences to the remote profile dir.\n await this.adbPrepareProfileDir();\n\n // NOTE: running Firefox for Android on the Android Emulator can be\n // pretty slow, we can run the following 3 steps in parallel to speed up\n // it a bit.\n await Promise.all([\n // Start Firefox for Android instance if not started yet.\n // (Fennec would run in an temporary profile and so it is explicitly\n // stopped, Fenix runs on its usual profile and so it may be already\n // running).\n this.adbStartSelectedPackage(),\n\n // Build and push to devices all the extension xpis\n // and keep track of the xpi built and uploaded by extension sourceDir.\n this.buildAndPushExtensions(),\n\n // Wait for RDP unix socket file created and\n // Create an ADB forward connection on a free tcp port\n this.adbDiscoveryAndForwardRDPUnixSocket(),\n ]);\n\n // Connect to RDP socket on the local tcp server, install all the pushed extension\n // and keep track of the built and installed extension by extension sourceDir.\n await this.rdpInstallExtensions();\n }\n\n // Method exported from the IExtensionRunner interface.\n\n /**\n * Returns the runner name.\n */\n getName() {\n return 'Firefox Android';\n }\n\n /**\n * Reloads all the extensions, collect any reload error and resolves to\n * an array composed by a single ExtensionRunnerReloadResult object.\n */\n async reloadAllExtensions() {\n const runnerName = this.getName();\n const reloadErrors = new Map();\n\n for (const { sourceDir } of this.params.extensions) {\n const [res] = await this.reloadExtensionBySourceDir(sourceDir);\n if (res.reloadError instanceof Error) {\n reloadErrors.set(sourceDir, res.reloadError);\n }\n }\n\n if (reloadErrors.size > 0) {\n return [\n {\n runnerName,\n reloadError: new MultiExtensionsReloadError(reloadErrors),\n },\n ];\n }\n\n return [{ runnerName }];\n }\n\n /**\n * Reloads a single extension, collect any reload error and resolves to\n * an array composed by a single ExtensionRunnerReloadResult object.\n */\n async reloadExtensionBySourceDir(extensionSourceDir) {\n const runnerName = this.getName();\n const addonId = this.reloadableExtensions.get(extensionSourceDir);\n\n if (!addonId) {\n return [\n {\n sourceDir: extensionSourceDir,\n reloadError: new WebExtError(\n 'Extension not reloadable: ' +\n `no addonId has been mapped to \"${extensionSourceDir}\"`,\n ),\n runnerName,\n },\n ];\n }\n\n try {\n await this.buildAndPushExtension(extensionSourceDir);\n await this.remoteFirefox.reloadAddon(addonId);\n } catch (error) {\n return [\n {\n sourceDir: extensionSourceDir,\n reloadError: error,\n runnerName,\n },\n ];\n }\n\n return [{ runnerName, sourceDir: extensionSourceDir }];\n }\n\n /**\n * Register a callback to be called when the runner has been exited\n * (e.g. the Firefox instance exits or the user has requested web-ext\n * to exit).\n */\n registerCleanup(fn) {\n this.cleanupCallbacks.add(fn);\n }\n\n /**\n * Exits the runner, by closing the managed Firefox instance.\n */\n async exit() {\n const { adbUtils, selectedAdbDevice, selectedArtifactsDir } = this;\n\n this.exiting = true;\n\n // If a Firefox for Android instance has been started,\n // we should ensure that it has been stopped when we exit.\n await this.adbForceStopSelectedPackage();\n\n if (selectedArtifactsDir) {\n log.debug('Cleaning up artifacts directory on the Android device...');\n await adbUtils.clearArtifactsDir(selectedAdbDevice);\n }\n\n // Call all the registered cleanup callbacks.\n for (const fn of this.cleanupCallbacks) {\n try {\n fn();\n } catch (error) {\n log.error(error);\n }\n }\n }\n\n // Private helper methods.\n\n getDeviceProfileDir() {\n return `${this.selectedArtifactsDir}/profile`;\n }\n\n printIgnoredParamsWarnings() {\n Object.keys(ignoredParams).forEach((ignoredParam) => {\n if (this.params[ignoredParam]) {\n log.warn(getIgnoredParamsWarningsMessage(ignoredParams[ignoredParam]));\n }\n });\n }\n\n async adbDevicesDiscoveryAndSelect() {\n const { adbUtils } = this;\n const { adbDevice } = this.params;\n let devices = [];\n\n log.debug('Listing android devices');\n devices = await adbUtils.discoverDevices();\n\n if (devices.length === 0) {\n throw new UsageError(\n 'No Android device found through ADB. ' +\n 'Make sure the device is connected and USB debugging is enabled.',\n );\n }\n\n if (!adbDevice) {\n const devicesMsg = devices.map((dev) => ` - ${dev}`).join('\\n');\n log.info(`\\nAndroid devices found:\\n${devicesMsg}`);\n throw new UsageError(\n 'Select an android device using --android-device=<name>',\n );\n }\n\n const foundDevices = devices.filter((device) => {\n return device === adbDevice;\n });\n\n if (foundDevices.length === 0) {\n const devicesMsg = JSON.stringify(devices);\n throw new UsageError(\n `Android device ${adbDevice} was not found in list: ${devicesMsg}`,\n );\n }\n\n this.selectedAdbDevice = foundDevices[0];\n log.info(`Selected ADB device: ${this.selectedAdbDevice}`);\n }\n\n async apkPackagesDiscoveryAndSelect() {\n const {\n adbUtils,\n selectedAdbDevice,\n params: { firefoxApk },\n } = this;\n // Discovery and select a Firefox for Android version.\n const packages = await adbUtils.discoverInstalledFirefoxAPKs(\n selectedAdbDevice,\n firefoxApk,\n );\n\n if (packages.length === 0) {\n throw new UsageError(\n 'No Firefox packages were found on the selected Android device',\n );\n }\n\n const pkgsListMsg = (pkgs) => {\n return pkgs.map((pkg) => ` - ${pkg}`).join('\\n');\n };\n\n if (!firefoxApk) {\n log.info(`\\nPackages found:\\n${pkgsListMsg(packages)}`);\n\n if (packages.length > 1) {\n throw new UsageError('Select one of the packages using --firefox-apk');\n }\n\n // If only one APK has been found, select it even if it has not been\n // specified explicitly on the comment line.\n this.selectedFirefoxApk = packages[0];\n log.info(`Selected Firefox for Android APK: ${this.selectedFirefoxApk}`);\n return;\n }\n\n const filteredPackages = packages.filter((line) => line === firefoxApk);\n\n if (filteredPackages.length === 0) {\n const pkgsList = pkgsListMsg(filteredPackages);\n throw new UsageError(\n `Package ${firefoxApk} was not found in list: ${pkgsList}`,\n );\n }\n\n this.selectedFirefoxApk = filteredPackages[0];\n log.debug(`Selected Firefox for Android APK: ${this.selectedFirefoxApk}`);\n }\n\n async adbForceStopSelectedPackage() {\n const { adbUtils, selectedAdbDevice, selectedFirefoxApk } = this;\n\n log.info(`Stopping existing instances of ${selectedFirefoxApk}...`);\n await adbUtils.amForceStopAPK(selectedAdbDevice, selectedFirefoxApk);\n }\n\n async adbPrepareProfileDir() {\n const {\n adbUtils,\n selectedAdbDevice,\n selectedFirefoxApk,\n params: { customPrefs, firefoxApp, adbRemoveOldArtifacts },\n } = this;\n // Create the preferences file and the Fennec temporary profile.\n log.debug(`Preparing a temporary profile for ${selectedFirefoxApk}...`);\n\n const profile = await firefoxApp.createProfile({\n app: 'fennec',\n customPrefs,\n });\n\n // Check if there are any artifacts dirs from previous runs and\n // automatically remove them if adbRemoteOldArtifacts is true.\n const foundOldArtifacts = await adbUtils.detectOrRemoveOldArtifacts(\n selectedAdbDevice,\n adbRemoveOldArtifacts,\n );\n\n if (foundOldArtifacts) {\n if (adbRemoveOldArtifacts) {\n log.info(\n 'Old web-ext artifacts have been found and removed ' +\n `from ${selectedAdbDevice} device`,\n );\n } else {\n log.warn(\n `Old artifacts directories have been found on ${selectedAdbDevice} ` +\n 'device. Use --adb-remove-old-artifacts to remove them automatically.',\n );\n }\n }\n\n // Choose a artifacts dir name for the assets pushed to the\n // Android device.\n this.selectedArtifactsDir =\n await adbUtils.getOrCreateArtifactsDir(selectedAdbDevice);\n\n const deviceProfileDir = this.getDeviceProfileDir();\n\n await adbUtils.runShellCommand(selectedAdbDevice, [\n 'mkdir',\n '-p',\n deviceProfileDir,\n ]);\n await adbUtils.pushFile(\n selectedAdbDevice,\n path.join(profile.profileDir, 'user.js'),\n `${deviceProfileDir}/user.js`,\n );\n\n log.debug(`Created temporary profile at ${deviceProfileDir}.`);\n }\n\n async adbStartSelectedPackage() {\n const {\n adbUtils,\n selectedFirefoxApk,\n selectedAdbDevice,\n params: { firefoxApkComponent },\n } = this;\n\n const deviceProfileDir = this.getDeviceProfileDir();\n\n log.info(`Starting ${selectedFirefoxApk}...`);\n\n log.debug(`Using profile ${deviceProfileDir} (ignored by Fenix)`);\n\n await adbUtils.startFirefoxAPK(\n selectedAdbDevice,\n selectedFirefoxApk,\n firefoxApkComponent,\n deviceProfileDir,\n );\n }\n\n async buildAndPushExtension(sourceDir) {\n const {\n adbUtils,\n selectedAdbDevice,\n selectedArtifactsDir,\n params: { buildSourceDir },\n } = this;\n\n await withTempDir(async (tmpDir) => {\n const { extensionPath } = await buildSourceDir(sourceDir, tmpDir.path());\n\n const extFileName = path.basename(extensionPath, '.zip');\n\n let adbExtensionPath = this.adbExtensionsPathBySourceDir.get(sourceDir);\n\n if (!adbExtensionPath) {\n adbExtensionPath = `${selectedArtifactsDir}/${extFileName}.xpi`;\n }\n\n log.debug(`Uploading ${extFileName} on the android device`);\n\n await adbUtils.pushFile(\n selectedAdbDevice,\n extensionPath,\n adbExtensionPath,\n );\n\n log.debug(`Upload completed: ${adbExtensionPath}`);\n\n this.adbExtensionsPathBySourceDir.set(sourceDir, adbExtensionPath);\n });\n }\n\n async buildAndPushExtensions() {\n for (const { sourceDir } of this.params.extensions) {\n await this.buildAndPushExtension(sourceDir);\n }\n }\n\n async adbDiscoveryAndForwardRDPUnixSocket() {\n const {\n adbUtils,\n selectedAdbDevice,\n selectedFirefoxApk,\n params: { adbDiscoveryTimeout },\n } = this;\n\n const stdin = this.params.stdin || process.stdin;\n\n const { unixSocketDiscoveryRetryInterval } = FirefoxAndroidExtensionRunner;\n\n let { unixSocketDiscoveryMaxTime } = FirefoxAndroidExtensionRunner;\n\n if (typeof adbDiscoveryTimeout === 'number') {\n unixSocketDiscoveryMaxTime = adbDiscoveryTimeout;\n }\n\n const handleCtrlC = (str, key) => {\n if (key.ctrl && key.name === 'c') {\n adbUtils.setUserAbortDiscovery(true);\n }\n };\n\n // TODO: use noInput property to decide if we should\n // disable direct keypress handling.\n if (isTTY(stdin)) {\n readline.emitKeypressEvents(stdin);\n setRawMode(stdin, true);\n\n stdin.on('keypress', handleCtrlC);\n }\n\n try {\n // Got a debugger socket file to connect.\n this.selectedRDPSocketFile = await adbUtils.discoverRDPUnixSocket(\n selectedAdbDevice,\n selectedFirefoxApk,\n {\n maxDiscoveryTime: unixSocketDiscoveryMaxTime,\n retryInterval: unixSocketDiscoveryRetryInterval,\n },\n );\n } finally {\n if (isTTY(stdin)) {\n stdin.removeListener('keypress', handleCtrlC);\n }\n }\n\n log.debug(`RDP Socket File selected: ${this.selectedRDPSocketFile}`);\n\n const tcpPort = await findFreeTcpPort();\n\n // Log the chosen tcp port at info level (useful to the user to be able\n // to connect the Firefox DevTools to the Firefox for Android instance).\n log.info(`You can connect to this Android device on TCP port ${tcpPort}`);\n\n const forwardSocketSpec = this.selectedRDPSocketFile.startsWith('@')\n ? `localabstract:${this.selectedRDPSocketFile.substr(1)}`\n : `localfilesystem:${this.selectedRDPSocketFile}`;\n\n await adbUtils.setupForward(\n selectedAdbDevice,\n forwardSocketSpec,\n `tcp:${tcpPort}`,\n );\n\n this.selectedTCPPort = tcpPort;\n }\n\n async rdpInstallExtensions() {\n const {\n selectedTCPPort,\n params: { extensions, firefoxClient },\n } = this;\n\n const remoteFirefox = (this.remoteFirefox = await firefoxClient({\n port: selectedTCPPort,\n }));\n\n // Exit and cleanup the extension runner if the connection to the\n // remote Firefox for Android instance has been closed.\n remoteFirefox.client.on('end', () => {\n if (!this.exiting) {\n log.info('Exiting the device because Firefox for Android disconnected');\n this.exit();\n }\n });\n\n // Install all the temporary addons.\n for (const extension of extensions) {\n const { sourceDir } = extension;\n const adbExtensionPath = this.adbExtensionsPathBySourceDir.get(sourceDir);\n\n if (!adbExtensionPath) {\n throw new WebExtError(\n `ADB extension path for \"${sourceDir}\" was unexpectedly empty`,\n );\n }\n\n const addonId = await remoteFirefox\n .installTemporaryAddon(adbExtensionPath)\n .then((installResult) => {\n return installResult.addon.id;\n });\n\n if (!addonId) {\n throw new WebExtError(\n 'Received an empty addonId from ' +\n `remoteFirefox.installTemporaryAddon(\"${adbExtensionPath}\")`,\n );\n }\n\n this.reloadableExtensions.set(extension.sourceDir, addonId);\n }\n }\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;;AAEA,OAAO,IAAI,MAAM,MAAM;AACvB,OAAO,QAAQ,MAAM,UAAU;AAE/B,SAAS,WAAW,QAAQ,qBAAqB;AACjD,OAAO,eAAe,MAAM,gBAAgB;AAC5C,SACE,0BAA0B,EAC1B,UAAU,EACV,WAAW,QACN,cAAc;AACrB,SAAS,eAAe,QAAQ,sBAAsB;AACtD,SAAS,YAAY,QAAQ,mBAAmB;AAChD,SAAS,KAAK,EAAE,UAAU,QAAQ,kBAAkB;AAEpD,MAAM,GAAG,GAAG,YAAY,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC;AAEzC,MAAM,aAAa,GAAG;EACpB,WAAW,EAAE,gBAAgB;EAC7B,kBAAkB,E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gB,GAAG,IAAI,CAAC,4BAA4B,CAAC,GAAG,CAAC,SAAS,CAAC;MAEzE,IAAI,CAAC,gBAAgB,EAAE;QACrB,MAAM,IAAI,WAAW,CACnB,2BAA2B,SAAS,0BACtC,CAAC;MACH;MAEA,MAAM,OAAO,GAAG,MAAM,aAAa,CAChC,qBAAqB,CAAC,gBAAgB,CAAC,CACvC,IAAI,CAAE,aAAa,IAAK;QACvB,OAAO,aAAa,CAAC,KAAK,CAAC,EAAE;MAC/B,CAAC,CAAC;MAEJ,IAAI,CAAC,OAAO,EAAE;QACZ,MAAM,IAAI,WAAW,CACnB,iCAAiC,GAC/B,wCAAwC,gBAAgB,IAC5D,CAAC;MACH;MAEA,IAAI,CAAC,oBAAoB,CAAC,GAAG,CAAC,SAAS,CAAC,SAAS,EAAE,OAAO,CAAC;IAC7D;EACF;AACF","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"firefox-desktop.js","names":["MultiExtensionsReloadError","RemoteTempInstallNotSupported","WebExtError","createLogger","log","import","meta","url","FirefoxDesktopExtensionRunner","cleanupCallbacks","params","profile","reloadableExtensions","remoteFirefox","runningInfo","constructor","Map","Set","getName","run","setupProfileDir","startFirefoxInstance","reloadAllExtensions","runnerName","reloadErrors","sourceDir","extensions","res","reloadExtensionBySourceDir","reloadError","Error","set","size","extensionSourceDir","addonId","get","reloadAddon","error","registerCleanup","fn","add","exit","firefox","kill","customPrefs","keepProfileChanges","preInstall","profilePath","firefoxApp","debug","useProfile","copyProfile","createProfile","extension","installExtension","asProxy","extensionPath","manifestData","browserConsole","devtools","firefoxBinary","startUrl","firefoxClient","args","binaryArgs","push","urls","Array","isArray","on","cleanupCb","port","debuggerPort","installTemporaryAddon","then","installResult","addon","id","String"],"sources":["../../src/extension-runners/firefox-desktop.js"],"sourcesContent":["/**\n * This module provide an ExtensionRunner subclass that manage an extension executed\n * in a Firefox for Desktop instance.\n */\n\nimport {\n MultiExtensionsReloadError,\n RemoteTempInstallNotSupported,\n WebExtError,\n} from '../errors.js';\nimport { createLogger } from '../util/logger.js';\n\nconst log = createLogger(import.meta.url);\n\n/**\n * Implements an IExtensionRunner which manages a Firefox Desktop instance.\n */\nexport class FirefoxDesktopExtensionRunner {\n cleanupCallbacks;\n params;\n profile;\n // Map extensions sourceDir to their related addon ids.\n reloadableExtensions;\n remoteFirefox;\n runningInfo;\n\n constructor(params) {\n this.params = params;\n\n this.reloadableExtensions = new Map();\n this.cleanupCallbacks = new Set();\n }\n\n // Method exported from the IExtensionRunner interface.\n\n /**\n * Returns the runner name.\n */\n getName() {\n return 'Firefox Desktop';\n }\n\n /**\n * Setup the Firefox Profile and run a Firefox Desktop instance.\n */\n async run() {\n // Get a firefox profile with the custom Prefs set (a new or a cloned one).\n // Pre-install extensions as proxy if needed (and disable auto-reload if you do)\n await this.setupProfileDir();\n\n // (if reload is enabled):\n // - Connect to the firefox instance on RDP\n // - Install any extension if needed (if not installed as proxy)\n // - Keep track of the extension id assigned in a map with the sourceDir as a key\n await this.startFirefoxInstance();\n }\n\n /**\n * Reloads all the extensions, collect any reload error and resolves to\n * an array composed by a single ExtensionRunnerReloadResult object.\n */\n async reloadAllExtensions() {\n const runnerName = this.getName();\n const reloadErrors = new Map();\n for (const { sourceDir } of this.params.extensions) {\n const [res] = await this.reloadExtensionBySourceDir(sourceDir);\n if (res.reloadError instanceof Error) {\n reloadErrors.set(sourceDir, res.reloadError);\n }\n }\n\n if (reloadErrors.size > 0) {\n return [\n {\n runnerName,\n reloadError: new MultiExtensionsReloadError(reloadErrors),\n },\n ];\n }\n\n return [{ runnerName }];\n }\n\n /**\n * Reloads a single extension, collect any reload error and resolves to\n * an array composed by a single ExtensionRunnerReloadResult object.\n */\n async reloadExtensionBySourceDir(extensionSourceDir) {\n const runnerName = this.getName();\n const addonId = this.reloadableExtensions.get(extensionSourceDir);\n\n if (!addonId) {\n return [\n {\n sourceDir: extensionSourceDir,\n reloadError: new WebExtError(\n 'Extension not reloadable: ' +\n `no addonId has been mapped to \"${extensionSourceDir}\"`,\n ),\n runnerName,\n },\n ];\n }\n\n try {\n await this.remoteFirefox.reloadAddon(addonId);\n } catch (error) {\n return [\n {\n sourceDir: extensionSourceDir,\n reloadError: error,\n runnerName,\n },\n ];\n }\n\n return [{ runnerName, sourceDir: extensionSourceDir }];\n }\n\n /**\n * Register a callback to be called when the runner has been exited\n * (e.g. the Firefox instance exits or the user has requested web-ext\n * to exit).\n */\n registerCleanup(fn) {\n this.cleanupCallbacks.add(fn);\n }\n\n /**\n * Exits the runner, by closing the managed Firefox instance.\n */\n async exit() {\n if (!this.runningInfo || !this.runningInfo.firefox) {\n throw new WebExtError('No firefox instance is currently running');\n }\n\n this.runningInfo.firefox.kill();\n }\n\n // Private helper methods.\n\n async setupProfileDir() {\n const {\n customPrefs,\n extensions,\n keepProfileChanges,\n preInstall,\n profilePath,\n firefoxApp,\n } = this.params;\n\n if (profilePath) {\n if (keepProfileChanges) {\n log.debug(`Using Firefox profile from ${profilePath}`);\n this.profile = await firefoxApp.useProfile(profilePath, {\n customPrefs,\n });\n } else {\n log.debug(`Copying Firefox profile from ${profilePath}`);\n this.profile = await firefoxApp.copyProfile(profilePath, {\n customPrefs,\n });\n }\n } else {\n log.debug('Creating new Firefox profile');\n this.profile = await firefoxApp.createProfile({ customPrefs });\n }\n\n // preInstall the extensions if needed.\n if (preInstall) {\n for (const extension of extensions) {\n await firefoxApp.installExtension({\n asProxy: true,\n extensionPath: extension.sourceDir,\n manifestData: extension.manifestData,\n profile: this.profile,\n });\n }\n }\n }\n\n async startFirefoxInstance() {\n const {\n browserConsole,\n devtools,\n extensions,\n firefoxBinary,\n preInstall,\n startUrl,\n firefoxApp,\n firefoxClient,\n args,\n } = this.params;\n\n const binaryArgs = [];\n\n if (browserConsole) {\n binaryArgs.push('-jsconsole');\n }\n if (startUrl) {\n const urls = Array.isArray(startUrl) ? startUrl : [startUrl];\n for (const url of urls) {\n binaryArgs.push('--url', url);\n }\n }\n\n if (args) {\n binaryArgs.push(...args);\n }\n\n this.runningInfo = await firefoxApp.run(this.profile, {\n firefoxBinary,\n binaryArgs,\n extensions,\n devtools,\n });\n\n this.runningInfo.firefox.on('close', () => {\n for (const cleanupCb of this.cleanupCallbacks) {\n try {\n cleanupCb();\n } catch (error) {\n log.error(`Exception on executing cleanup callback: ${error}`);\n }\n }\n });\n\n if (!preInstall) {\n const remoteFirefox = (this.remoteFirefox = await firefoxClient({\n port: this.runningInfo.debuggerPort,\n }));\n\n // Install all the temporary addons.\n for (const extension of extensions) {\n try {\n const addonId = await remoteFirefox\n .installTemporaryAddon(extension.sourceDir, devtools)\n .then((installResult) => {\n return installResult.addon.id;\n });\n\n if (!addonId) {\n throw new WebExtError(\n 'Unexpected missing addonId in the installAsTemporaryAddon result',\n );\n }\n\n this.reloadableExtensions.set(extension.sourceDir, addonId);\n } catch (error) {\n if (error instanceof RemoteTempInstallNotSupported) {\n log.debug(`Caught: ${String(error)}`);\n throw new WebExtError(\n 'Temporary add-on installation is not supported in this version' +\n ' of Firefox (you need Firefox 49 or higher). For older Firefox' +\n ' versions, use --pre-install',\n );\n } else {\n throw error;\n }\n }\n }\n }\n }\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;;AAEA,SACEA,0BAA0B,EAC1BC,6BAA6B,EAC7BC,WAAW,QACN,cAAc;AACrB,SAASC,YAAY,QAAQ,mBAAmB;AAEhD,MAAMC,GAAG,GAAGD,YAAY,CAACE,MAAM,CAACC,IAAI,CAACC,GAAG,CAAC;;AAEzC;AACA;AACA;AACA,OAAO,MAAMC,6BAA6B,CAAC;EACzCC,gBAAgB;EAChBC,MAAM;EACNC,OAAO;EACP;EACAC,oBAAoB;EACpBC,aAAa;EACbC,WAAW;EAEXC,WAAWA,CAACL,MAAM,EAAE;IAClB,IAAI,CAACA,MAAM,GAAGA,MAAM;IAEpB,IAAI,CAACE,oBAAoB,GAAG,IAAII,GAAG,CAAC,CAAC;IACrC,IAAI,CAACP,gBAAgB,GAAG,IAAIQ,GAAG,CAAC,C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M;YACL,MAAMmC,KAAK;UACb;QACF;MACF;IACF;EACF;AACF","ignoreList":[]}
1
+ {"version":3,"file":"firefox-desktop.js","names":[],"sources":["../../src/extension-runners/firefox-desktop.js"],"sourcesContent":["/**\n * This module provide an ExtensionRunner subclass that manage an extension executed\n * in a Firefox for Desktop instance.\n */\n\nimport {\n MultiExtensionsReloadError,\n RemoteTempInstallNotSupported,\n WebExtError,\n} from '../errors.js';\nimport { createLogger } from '../util/logger.js';\n\nconst log = createLogger(import.meta.url);\n\n/**\n * Implements an IExtensionRunner which manages a Firefox Desktop instance.\n */\nexport class FirefoxDesktopExtensionRunner {\n cleanupCallbacks;\n params;\n profile;\n // Map extensions sourceDir to their related addon ids.\n reloadableExtensions;\n remoteFirefox;\n runningInfo;\n\n constructor(params) {\n this.params = params;\n\n this.reloadableExtensions = new Map();\n this.cleanupCallbacks = new Set();\n }\n\n // Method exported from the IExtensionRunner interface.\n\n /**\n * Returns the runner name.\n */\n getName() {\n return 'Firefox Desktop';\n }\n\n /**\n * Setup the Firefox Profile and run a Firefox Desktop instance.\n */\n async run() {\n // Get a firefox profile with the custom Prefs set (a new or a cloned one).\n // Pre-install extensions as proxy if needed (and disable auto-reload if you do)\n await this.setupProfileDir();\n\n // (if reload is enabled):\n // - Connect to the firefox instance on RDP\n // - Install any extension if needed (if not installed as proxy)\n // - Keep track of the extension id assigned in a map with the sourceDir as a key\n await this.startFirefoxInstance();\n }\n\n /**\n * Reloads all the extensions, collect any reload error and resolves to\n * an array composed by a single ExtensionRunnerReloadResult object.\n */\n async reloadAllExtensions() {\n const runnerName = this.getName();\n const reloadErrors = new Map();\n for (const { sourceDir } of this.params.extensions) {\n const [res] = await this.reloadExtensionBySourceDir(sourceDir);\n if (res.reloadError instanceof Error) {\n reloadErrors.set(sourceDir, res.reloadError);\n }\n }\n\n if (reloadErrors.size > 0) {\n return [\n {\n runnerName,\n reloadError: new MultiExtensionsReloadError(reloadErrors),\n },\n ];\n }\n\n return [{ runnerName }];\n }\n\n /**\n * Reloads a single extension, collect any reload error and resolves to\n * an array composed by a single ExtensionRunnerReloadResult object.\n */\n async reloadExtensionBySourceDir(extensionSourceDir) {\n const runnerName = this.getName();\n const addonId = this.reloadableExtensions.get(extensionSourceDir);\n\n if (!addonId) {\n return [\n {\n sourceDir: extensionSourceDir,\n reloadError: new WebExtError(\n 'Extension not reloadable: ' +\n `no addonId has been mapped to \"${extensionSourceDir}\"`,\n ),\n runnerName,\n },\n ];\n }\n\n try {\n await this.remoteFirefox.reloadAddon(addonId);\n } catch (error) {\n return [\n {\n sourceDir: extensionSourceDir,\n reloadError: error,\n runnerName,\n },\n ];\n }\n\n return [{ runnerName, sourceDir: extensionSourceDir }];\n }\n\n /**\n * Register a callback to be called when the runner has been exited\n * (e.g. the Firefox instance exits or the user has requested web-ext\n * to exit).\n */\n registerCleanup(fn) {\n this.cleanupCallbacks.add(fn);\n }\n\n /**\n * Exits the runner, by closing the managed Firefox instance.\n */\n async exit() {\n if (!this.runningInfo || !this.runningInfo.firefox) {\n throw new WebExtError('No firefox instance is currently running');\n }\n\n this.runningInfo.firefox.kill();\n }\n\n // Private helper methods.\n\n async setupProfileDir() {\n const {\n customPrefs,\n extensions,\n keepProfileChanges,\n preInstall,\n profilePath,\n firefoxApp,\n } = this.params;\n\n if (profilePath) {\n if (keepProfileChanges) {\n log.debug(`Using Firefox profile from ${profilePath}`);\n this.profile = await firefoxApp.useProfile(profilePath, {\n customPrefs,\n });\n } else {\n log.debug(`Copying Firefox profile from ${profilePath}`);\n this.profile = await firefoxApp.copyProfile(profilePath, {\n customPrefs,\n });\n }\n } else {\n log.debug('Creating new Firefox profile');\n this.profile = await firefoxApp.createProfile({ customPrefs });\n }\n\n // preInstall the extensions if needed.\n if (preInstall) {\n for (const extension of extensions) {\n await firefoxApp.installExtension({\n asProxy: true,\n extensionPath: extension.sourceDir,\n manifestData: extension.manifestData,\n profile: this.profile,\n });\n }\n }\n }\n\n async startFirefoxInstance() {\n const {\n browserConsole,\n devtools,\n extensions,\n firefoxBinary,\n preInstall,\n startUrl,\n firefoxApp,\n firefoxClient,\n args,\n } = this.params;\n\n const binaryArgs = [];\n\n if (browserConsole) {\n binaryArgs.push('-jsconsole');\n }\n if (startUrl) {\n const urls = Array.isArray(startUrl) ? startUrl : [startUrl];\n for (const url of urls) {\n binaryArgs.push('--url', url);\n }\n }\n\n if (args) {\n binaryArgs.push(...args);\n }\n\n this.runningInfo = await firefoxApp.run(this.profile, {\n firefoxBinary,\n binaryArgs,\n extensions,\n devtools,\n });\n\n this.runningInfo.firefox.on('close', () => {\n for (const cleanupCb of this.cleanupCallbacks) {\n try {\n cleanupCb();\n } catch (error) {\n log.error(`Exception on executing cleanup callback: ${error}`);\n }\n }\n });\n\n if (!preInstall) {\n const remoteFirefox = (this.remoteFirefox = await firefoxClient({\n port: this.runningInfo.debuggerPort,\n }));\n\n // Install all the temporary addons.\n for (const extension of extensions) {\n try {\n const addonId = await remoteFirefox\n .installTemporaryAddon(extension.sourceDir, devtools)\n .then((installResult) => {\n return installResult.addon.id;\n });\n\n if (!addonId) {\n throw new WebExtError(\n 'Unexpected missing addonId in the installAsTemporaryAddon result',\n );\n }\n\n this.reloadableExtensions.set(extension.sourceDir, addonId);\n } catch (error) {\n if (error instanceof RemoteTempInstallNotSupported) {\n log.debug(`Caught: ${String(error)}`);\n throw new WebExtError(\n 'Temporary add-on installation is not supported in this version' +\n ' of Firefox (you need Firefox 49 or higher). For older Firefox' +\n ' versions, use --pre-install',\n );\n } else {\n throw error;\n }\n }\n }\n }\n }\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;;AAEA,SACE,0BAA0B,EAC1B,6BAA6B,EAC7B,WAAW,QACN,cAAc;AACrB,SAAS,YAAY,QAAQ,mBAAmB;AAEhD,MAAM,GAAG,GAAG,YAAY,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC;;AAEzC;AACA;AACA;AACA,OAAO,MAAM,6BAA6B,CAAC;EACzC,gBAAgB;EAChB,MAAM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"file":"index.js","names":["readline","WebExtError","createLogger","createFileFilter","defaultFileFilterCreator","isTTY","setRawMode","defaultSourceWatcher","log","import","meta","url","createExtensionRunner","config","target","FirefoxDesktopExtensionRunner","params","FirefoxAndroidExtensionRunner","ChromiumExtensionRunner","MultiExtensionRunner","extensionRunners","constructor","runners","getName","run","promises","runner","push","Promise","all","reloadAllExtensions","debug","reloadPromise","then","runnerName","error","reloadError","results","handleReloadResults","reloadExtensionBySourceDir","sourceDir","registerCleanup","cleanupCallback","resolve","exit","Error","message","stack","defaultWatcherCreator","reloadExtension","watchFile","watchIgnored","artifactsDir","ignoreFiles","onSourceChange","fileFilter","onChange","shouldWatchFile","file","wantFile","defaultReloadStrategy","extensionRunner","noInput","createWatcher","stdin","process","kill","allowInput","watcher","watchedSourceDir","close","pause","emitKeypressEvents","keypressUsageInfo","info","userExit","keyPressed","once","str","key","ctrl","name","pid","catch","err","warn"],"sources":["../../src/extension-runners/index.js"],"sourcesContent":["import readline from 'readline';\n\nimport { WebExtError } from '../errors.js';\nimport { createLogger } from '../util/logger.js';\nimport { createFileFilter as defaultFileFilterCreator } from '../util/file-filter.js';\nimport { isTTY, setRawMode } from '../util/stdin.js';\nimport defaultSourceWatcher from '../watcher.js';\n\nconst log = createLogger(import.meta.url);\n\nexport async function createExtensionRunner(config) {\n switch (config.target) {\n case 'firefox-desktop': {\n const { FirefoxDesktopExtensionRunner } =\n await import('./firefox-desktop.js');\n return new FirefoxDesktopExtensionRunner(config.params);\n }\n case 'firefox-android': {\n const { FirefoxAndroidExtensionRunner } =\n await import('./firefox-android.js');\n return new FirefoxAndroidExtensionRunner(config.params);\n }\n case 'chromium': {\n const { ChromiumExtensionRunner } = await import('./chromium.js');\n return new ChromiumExtensionRunner(config.params);\n }\n default:\n throw new WebExtError(`Unknown target: \"${config.target}\"`);\n }\n}\n\n/**\n * Implements an IExtensionRunner which allow the caller to\n * manage multiple extension runners at the same time (e.g. by running\n * a Firefox Desktop instance alongside to a Firefox for Android instance).\n */\nexport class MultiExtensionRunner {\n extensionRunners;\n\n constructor(params) {\n this.extensionRunners = params.runners;\n }\n\n // Method exported from the IExtensionRunner interface.\n\n /**\n * Returns the runner name.\n */\n getName() {\n return 'Multi Extension Runner';\n }\n\n /**\n * Call the `run` method on all the managed extension runners,\n * and awaits that all the runners has been successfully started.\n */\n async run() {\n const promises = [];\n for (const runner of this.extensionRunners) {\n promises.push(runner.run());\n }\n\n await Promise.all(promises);\n }\n\n /**\n * Reloads all the extensions on all the managed extension runners,\n * collect any reload error, and resolves to an array composed by\n * a ExtensionRunnerReloadResult object per managed runner.\n *\n * Any detected reload error is also logged on the terminal.\n */\n async reloadAllExtensions() {\n log.debug('Reloading all reloadable add-ons');\n\n const promises = [];\n for (const runner of this.extensionRunners) {\n const reloadPromise = runner.reloadAllExtensions().then(\n () => {\n return { runnerName: runner.getName() };\n },\n (error) => {\n return {\n runnerName: runner.getName(),\n reloadError: error,\n };\n },\n );\n\n promises.push(reloadPromise);\n }\n\n return await Promise.all(promises).then((results) => {\n this.handleReloadResults(results);\n return results;\n });\n }\n\n /**\n * Reloads a single extension on all the managed extension runners,\n * collect any reload error and resolves to an array composed by\n * a ExtensionRunnerReloadResult object per managed runner.\n *\n * Any detected reload error is also logged on the terminal.\n */\n async reloadExtensionBySourceDir(sourceDir) {\n log.debug(`Reloading add-on at ${sourceDir}`);\n\n const promises = [];\n for (const runner of this.extensionRunners) {\n const reloadPromise = runner.reloadExtensionBySourceDir(sourceDir).then(\n () => {\n return { runnerName: runner.getName(), sourceDir };\n },\n (error) => {\n return {\n runnerName: runner.getName(),\n reloadError: error,\n sourceDir,\n };\n },\n );\n\n promises.push(reloadPromise);\n }\n\n return await Promise.all(promises).then((results) => {\n this.handleReloadResults(results);\n return results;\n });\n }\n\n /**\n * Register a callback to be called when all the managed runners has been exited.\n */\n registerCleanup(cleanupCallback) {\n const promises = [];\n\n // Create a promise for every extension runner managed by this instance,\n // the promise will be resolved when the particular runner calls its\n // registered cleanup callbacks.\n for (const runner of this.extensionRunners) {\n promises.push(\n new Promise((resolve) => {\n runner.registerCleanup(resolve);\n }),\n );\n }\n\n // Wait for all the created promises to be resolved or rejected\n // (once each one of the runners has cleaned up) and then call\n // the cleanup callback registered to this runner.\n Promise.all(promises).then(cleanupCallback, cleanupCallback);\n }\n\n /**\n * Exits all the managed runner has been exited.\n */\n async exit() {\n const promises = [];\n for (const runner of this.extensionRunners) {\n promises.push(runner.exit());\n }\n\n await Promise.all(promises);\n }\n\n // Private helper methods.\n\n handleReloadResults(results) {\n for (const { runnerName, reloadError, sourceDir } of results) {\n if (reloadError instanceof Error) {\n let message = 'Error occurred while reloading';\n if (sourceDir) {\n message += ` \"${sourceDir}\" `;\n }\n\n message += `on \"${runnerName}\" - ${reloadError.message}`;\n\n log.error(`\\n${message}`);\n log.debug(reloadError.stack);\n }\n }\n }\n}\n\n// defaultWatcherCreator types and implementation.\n\nexport function defaultWatcherCreator({\n reloadExtension,\n sourceDir,\n watchFile,\n watchIgnored,\n artifactsDir,\n ignoreFiles,\n onSourceChange = defaultSourceWatcher,\n createFileFilter = defaultFileFilterCreator,\n}) {\n const fileFilter = createFileFilter({ sourceDir, artifactsDir, ignoreFiles });\n return onSourceChange({\n sourceDir,\n watchFile,\n watchIgnored,\n artifactsDir,\n onChange: () => reloadExtension(sourceDir),\n shouldWatchFile: (file) => fileFilter.wantFile(file),\n });\n}\n\n// defaultReloadStrategy types and implementation.\n\nexport function defaultReloadStrategy(\n {\n artifactsDir,\n extensionRunner,\n ignoreFiles,\n noInput = false,\n sourceDir,\n watchFile,\n watchIgnored,\n },\n {\n createWatcher = defaultWatcherCreator,\n stdin = process.stdin,\n kill = process.kill,\n } = {},\n) {\n const allowInput = !noInput;\n if (!allowInput) {\n log.debug('Input has been disabled because of noInput==true');\n }\n\n const watcher = createWatcher({\n reloadExtension: (watchedSourceDir) => {\n extensionRunner.reloadExtensionBySourceDir(watchedSourceDir);\n },\n sourceDir,\n watchFile,\n watchIgnored,\n artifactsDir,\n ignoreFiles,\n });\n\n extensionRunner.registerCleanup(() => {\n watcher.close();\n if (allowInput) {\n if (isTTY(stdin)) {\n setRawMode(stdin, false);\n }\n stdin.pause();\n }\n });\n\n if (allowInput && isTTY(stdin)) {\n readline.emitKeypressEvents(stdin);\n setRawMode(stdin, true);\n\n const keypressUsageInfo = 'Press R to reload (and Ctrl-C to quit)';\n\n // NOTE: this `Promise.resolve().then(...)` is basically used to spawn a \"co-routine\"\n // that is executed before the callback attached to the Promise returned by this function\n // (and it allows the `run` function to not be stuck in the while loop).\n Promise.resolve().then(async function () {\n log.info(keypressUsageInfo);\n\n let userExit = false;\n\n while (!userExit) {\n const keyPressed = await new Promise((resolve) => {\n stdin.once('keypress', (str, key) => resolve(key));\n });\n\n if (keyPressed.ctrl && keyPressed.name === 'c') {\n userExit = true;\n } else if (keyPressed.name === 'z') {\n // Prepare to suspend.\n\n // NOTE: Switch the raw mode off before suspending (needed to make the keypress event\n // to work correctly when the nodejs process is resumed).\n setRawMode(stdin, false);\n\n log.info('\\nweb-ext has been suspended on user request');\n kill(process.pid, 'SIGTSTP');\n\n // Prepare to resume.\n\n log.info(`\\nweb-ext has been resumed. ${keypressUsageInfo}`);\n\n // Switch the raw mode on on resume.\n setRawMode(stdin, true);\n } else if (keyPressed.name === 'r') {\n log.debug('Reloading installed extensions on user request');\n await extensionRunner.reloadAllExtensions().catch((err) => {\n log.warn(`\\nError reloading extension: ${err}`);\n log.debug(`Reloading extension error stack: ${err.stack}`);\n });\n }\n }\n\n log.info('\\nExiting web-ext on user request');\n extensionRunner.exit();\n });\n }\n}\n"],"mappings":"AAAA,OAAOA,QAAQ,MAAM,UAAU;AAE/B,SAASC,WAAW,QAAQ,cAAc;AAC1C,SAASC,YAAY,QAAQ,mBAAmB;AAChD,SAASC,gBAAgB,IAAIC,wBAAwB,QAAQ,wBAAwB;AACrF,SAASC,KAAK,EAAEC,UAAU,QAAQ,kBAAkB;AACpD,OAAOC,oBAAoB,MAAM,eAAe;AA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AAI,CAACD,OAAO,CAACiB,GAAG,EAAE,SAAS,CAAC;;UAE5B;;UAEA1E,GAAG,CAACkE,IAAI,CAAC,+BAA+BD,iBAAiB,EAAE,CAAC;;UAE5D;UACAnE,UAAU,CAAC0D,KAAK,EAAE,IAAI,CAAC;QACzB,CAAC,MAAM,IAAIY,UAAU,CAACK,IAAI,KAAK,GAAG,EAAE;UAClCzE,GAAG,CAACuB,KAAK,CAAC,gDAAgD,CAAC;UAC3D,MAAM8B,eAAe,CAAC/B,mBAAmB,CAAC,CAAC,CAACqD,KAAK,CAAEC,GAAG,IAAK;YACzD5E,GAAG,CAAC6E,IAAI,CAAC,gCAAgCD,GAAG,EAAE,CAAC;YAC/C5E,GAAG,CAACuB,KAAK,CAAC,oCAAoCqD,GAAG,CAACrC,KAAK,EAAE,CAAC;UAC5D,CAAC,CAAC;QACJ;MACF;MAEAvC,GAAG,CAACkE,IAAI,CAAC,mCAAmC,CAAC;MAC7Cb,eAAe,CAACjB,IAAI,CAAC,CAAC;IACxB,CAAC,CAAC;EACJ;AACF","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/extension-runners/index.js"],"sourcesContent":["import readline from 'readline';\n\nimport { WebExtError } from '../errors.js';\nimport { createLogger } from '../util/logger.js';\nimport { createFileFilter as defaultFileFilterCreator } from '../util/file-filter.js';\nimport { isTTY, setRawMode } from '../util/stdin.js';\nimport defaultSourceWatcher from '../watcher.js';\n\nconst log = createLogger(import.meta.url);\n\nexport async function createExtensionRunner(config) {\n switch (config.target) {\n case 'firefox-desktop': {\n const { FirefoxDesktopExtensionRunner } =\n await import('./firefox-desktop.js');\n return new FirefoxDesktopExtensionRunner(config.params);\n }\n case 'firefox-android': {\n const { FirefoxAndroidExtensionRunner } =\n await import('./firefox-android.js');\n return new FirefoxAndroidExtensionRunner(config.params);\n }\n case 'chromium': {\n const { ChromiumExtensionRunner } = await import('./chromium.js');\n return new ChromiumExtensionRunner(config.params);\n }\n default:\n throw new WebExtError(`Unknown target: \"${config.target}\"`);\n }\n}\n\n/**\n * Implements an IExtensionRunner which allow the caller to\n * manage multiple extension runners at the same time (e.g. by running\n * a Firefox Desktop instance alongside to a Firefox for Android instance).\n */\nexport class MultiExtensionRunner {\n extensionRunners;\n\n constructor(params) {\n this.extensionRunners = params.runners;\n }\n\n // Method exported from the IExtensionRunner interface.\n\n /**\n * Returns the runner name.\n */\n getName() {\n return 'Multi Extension Runner';\n }\n\n /**\n * Call the `run` method on all the managed extension runners,\n * and awaits that all the runners has been successfully started.\n */\n async run() {\n const promises = [];\n for (const runner of this.extensionRunners) {\n promises.push(runner.run());\n }\n\n await Promise.all(promises);\n }\n\n /**\n * Reloads all the extensions on all the managed extension runners,\n * collect any reload error, and resolves to an array composed by\n * a ExtensionRunnerReloadResult object per managed runner.\n *\n * Any detected reload error is also logged on the terminal.\n */\n async reloadAllExtensions() {\n log.debug('Reloading all reloadable add-ons');\n\n const promises = [];\n for (const runner of this.extensionRunners) {\n const reloadPromise = runner.reloadAllExtensions().then(\n () => {\n return { runnerName: runner.getName() };\n },\n (error) => {\n return {\n runnerName: runner.getName(),\n reloadError: error,\n };\n },\n );\n\n promises.push(reloadPromise);\n }\n\n return await Promise.all(promises).then((results) => {\n this.handleReloadResults(results);\n return results;\n });\n }\n\n /**\n * Reloads a single extension on all the managed extension runners,\n * collect any reload error and resolves to an array composed by\n * a ExtensionRunnerReloadResult object per managed runner.\n *\n * Any detected reload error is also logged on the terminal.\n */\n async reloadExtensionBySourceDir(sourceDir) {\n log.debug(`Reloading add-on at ${sourceDir}`);\n\n const promises = [];\n for (const runner of this.extensionRunners) {\n const reloadPromise = runner.reloadExtensionBySourceDir(sourceDir).then(\n () => {\n return { runnerName: runner.getName(), sourceDir };\n },\n (error) => {\n return {\n runnerName: runner.getName(),\n reloadError: error,\n sourceDir,\n };\n },\n );\n\n promises.push(reloadPromise);\n }\n\n return await Promise.all(promises).then((results) => {\n this.handleReloadResults(results);\n return results;\n });\n }\n\n /**\n * Register a callback to be called when all the managed runners has been exited.\n */\n registerCleanup(cleanupCallback) {\n const promises = [];\n\n // Create a promise for every extension runner managed by this instance,\n // the promise will be resolved when the particular runner calls its\n // registered cleanup callbacks.\n for (const runner of this.extensionRunners) {\n promises.push(\n new Promise((resolve) => {\n runner.registerCleanup(resolve);\n }),\n );\n }\n\n // Wait for all the created promises to be resolved or rejected\n // (once each one of the runners has cleaned up) and then call\n // the cleanup callback registered to this runner.\n Promise.all(promises).then(cleanupCallback, cleanupCallback);\n }\n\n /**\n * Exits all the managed runner has been exited.\n */\n async exit() {\n const promises = [];\n for (const runner of this.extensionRunners) {\n promises.push(runner.exit());\n }\n\n await Promise.all(promises);\n }\n\n // Private helper methods.\n\n handleReloadResults(results) {\n for (const { runnerName, reloadError, sourceDir } of results) {\n if (reloadError instanceof Error) {\n let message = 'Error occurred while reloading';\n if (sourceDir) {\n message += ` \"${sourceDir}\" `;\n }\n\n message += `on \"${runnerName}\" - ${reloadError.message}`;\n\n log.error(`\\n${message}`);\n log.debug(reloadError.stack);\n }\n }\n }\n}\n\n// defaultWatcherCreator types and implementation.\n\nexport function defaultWatcherCreator({\n reloadExtension,\n sourceDir,\n watchFile,\n watchIgnored,\n artifactsDir,\n ignoreFiles,\n onSourceChange = defaultSourceWatcher,\n createFileFilter = defaultFileFilterCreator,\n}) {\n const fileFilter = createFileFilter({ sourceDir, artifactsDir, ignoreFiles });\n return onSourceChange({\n sourceDir,\n watchFile,\n watchIgnored,\n artifactsDir,\n onChange: () => reloadExtension(sourceDir),\n shouldWatchFile: (file) => fileFilter.wantFile(file),\n });\n}\n\n// defaultReloadStrategy types and implementation.\n\nexport function defaultReloadStrategy(\n {\n artifactsDir,\n extensionRunner,\n ignoreFiles,\n noInput = false,\n sourceDir,\n watchFile,\n watchIgnored,\n },\n {\n createWatcher = defaultWatcherCreator,\n stdin = process.stdin,\n kill = process.kill,\n } = {},\n) {\n const allowInput = !noInput;\n if (!allowInput) {\n log.debug('Input has been disabled because of noInput==true');\n }\n\n const watcher = createWatcher({\n reloadExtension: (watchedSourceDir) => {\n extensionRunner.reloadExtensionBySourceDir(watchedSourceDir);\n },\n sourceDir,\n watchFile,\n watchIgnored,\n artifactsDir,\n ignoreFiles,\n });\n\n extensionRunner.registerCleanup(() => {\n watcher.close();\n if (allowInput) {\n if (isTTY(stdin)) {\n setRawMode(stdin, false);\n }\n stdin.pause();\n }\n });\n\n if (allowInput && isTTY(stdin)) {\n readline.emitKeypressEvents(stdin);\n setRawMode(stdin, true);\n\n const keypressUsageInfo = 'Press R to reload (and Ctrl-C to quit)';\n\n // NOTE: this `Promise.resolve().then(...)` is basically used to spawn a \"co-routine\"\n // that is executed before the callback attached to the Promise returned by this function\n // (and it allows the `run` function to not be stuck in the while loop).\n Promise.resolve().then(async function () {\n log.info(keypressUsageInfo);\n\n let userExit = false;\n\n while (!userExit) {\n const keyPressed = await new Promise((resolve) => {\n stdin.once('keypress', (str, key) => resolve(key));\n });\n\n if (keyPressed.ctrl && keyPressed.name === 'c') {\n userExit = true;\n } else if (keyPressed.name === 'z') {\n // Prepare to suspend.\n\n // NOTE: Switch the raw mode off before suspending (needed to make the keypress event\n // to work correctly when the nodejs process is resumed).\n setRawMode(stdin, false);\n\n log.info('\\nweb-ext has been suspended on user request');\n kill(process.pid, 'SIGTSTP');\n\n // Prepare to resume.\n\n log.info(`\\nweb-ext has been resumed. ${keypressUsageInfo}`);\n\n // Switch the raw mode on on resume.\n setRawMode(stdin, true);\n } else if (keyPressed.name === 'r') {\n log.debug('Reloading installed extensions on user request');\n await extensionRunner.reloadAllExtensions().catch((err) => {\n log.warn(`\\nError reloading extension: ${err}`);\n log.debug(`Reloading extension error stack: ${err.stack}`);\n });\n }\n }\n\n log.info('\\nExiting web-ext on user request');\n extensionRunner.exit();\n });\n }\n}\n"],"mappings":"AAAA,OAAO,QAAQ,MAAM,UAAU;AAE/B,SAAS,WAAW,QAAQ,cAAc;AAC1C,SAAS,YAAY,QAAQ,mBAAmB;AAChD,S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GAAG,EAAE;UAClC,GAAG,CAAC,KAAK,CAAC,gDAAgD,CAAC;UAC3D,MAAM,eAAe,CAAC,mBAAmB,CAAC,CAAC,CAAC,KAAK,CAAE,GAAG,IAAK;YACzD,GAAG,CAAC,IAAI,CAAC,gCAAgC,GAAG,EAAE,CAAC;YAC/C,GAAG,CAAC,KAAK,CAAC,oCAAoC,GAAG,CAAC,KAAK,EAAE,CAAC;UAC5D,CAAC,CAAC;QACJ;MACF;MAEA,GAAG,CAAC,IAAI,CAAC,mCAAmC,CAAC;MAC7C,eAAe,CAAC,IAAI,CAAC,CAAC;IACxB,CAAC,CAAC;EACJ;AACF","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["nodeFs","path","promisify","fs","default","defaultFxRunner","FirefoxProfile","fromEvent","isDirectory","isErrorWithCode","UsageError","WebExtError","getPrefs","defaultPrefGetter","getManifestId","findFreeTcpPort","defaultRemotePortFinder","createLogger","log","import","meta","url","defaultAsyncFsStat","stat","bind","defaultUserProfileCopier","copyFromUserProfile","defaultFirefoxEnv","XPCOM_DEBUG_BREAK","NS_TRACE_MALLOC_DISABLE_STACKS","run","profile","fxRunner","findRemotePort","firefoxBinary","binaryArgs","extensions","devtools","debug","remotePort","startsWith","flatpakAppId","substring","map","sourceDir","concat","results","binary","listen","foreground","env","process","verbose","firefox","args","join","on","error","info","stderr","data","toString","trim","stdout","debuggerPort","DEFAULT_PROFILES_NAMES","isDefaultProfile","profilePathOrName","ProfileFinder","Finder","fsStat","includes","baseProfileDir","locateUserDirectory","profilesIniPath","finder","readProfiles","normalizedProfileDirPath","normalize","resolve","sep","profiles","Name","Default","profileFullPath","IsRelative","Path","configureProfile","app","customPrefs","prefs","Object","keys","forEach","pref","setPreference","length","customPrefsStr","JSON","stringify","custom","updatePreferences","Promise","defaultCreateProfileFinder","userDirectoryPath","FxProfile","getPath","profileName","hasProfileName","filter","profileDef","warn","useProfile","profilePath","configureThisProfile","isFirefoxDefaultProfile","createProfileFinder","isForbiddenProfile","destinationDirectory","getProfilePath","profileIsDirPath","createProfile","copyProfile","profileDirectory","copy","copyByName","dirExists","name","installExtension","asProxy","manifestData","extensionPath","asyncFsStat","extensionsDir","mkdir","id","isDir","destPath","writeStream","createWriteStream","write","end","readStream","createReadStream","pipe","all"],"sources":["../../src/firefox/index.js"],"sourcesContent":["import nodeFs from 'fs';\nimport path from 'path';\nimport { promisify } from 'util';\nimport fs from 'fs/promises';\n\nimport { default as defaultFxRunner } from 'fx-runner';\nimport FirefoxProfile from 'firefox-profile';\nimport fromEvent from 'promise-toolbox/fromEvent';\n\nimport isDirectory from '../util/is-directory.js';\nimport { isErrorWithCode, UsageError, WebExtError } from '../errors.js';\nimport { getPrefs as defaultPrefGetter } from './preferences.js';\nimport { getManifestId } from '../util/manifest.js';\nimport { findFreeTcpPort as defaultRemotePortFinder } from './remote.js';\nimport { createLogger } from '../util/logger.js';\n\nconst log = createLogger(import.meta.url);\n\nconst defaultAsyncFsStat = fs.stat.bind(fs);\n\nconst defaultUserProfileCopier = FirefoxProfile.copyFromUserProfile;\n\nexport const defaultFirefoxEnv = {\n XPCOM_DEBUG_BREAK: 'stack',\n NS_TRACE_MALLOC_DISABLE_STACKS: '1',\n};\n\n/*\n * Runs Firefox with the given profile object and resolves a promise on exit.\n */\nexport async function run(\n profile,\n {\n fxRunner = defaultFxRunner,\n findRemotePort = defaultRemotePortFinder,\n firefoxBinary,\n binaryArgs,\n extensions,\n devtools,\n } = {},\n) {\n log.debug(`Running Firefox with profile at ${profile.path()}`);\n\n const remotePort = await findRemotePort();\n\n if (firefoxBinary && firefoxBinary.startsWith('flatpak:')) {\n const flatpakAppId = firefoxBinary.substring(8);\n log.debug(`Configuring Firefox with flatpak: appId=${flatpakAppId}`);\n\n // This should be resolved by the fx-runner.\n firefoxBinary = 'flatpak';\n binaryArgs = [\n 'run',\n `--filesystem=${profile.path()}`,\n ...extensions.map(({ sourceDir }) => `--filesystem=${sourceDir}:ro`),\n // We need to share the network namespace because we want to connect to\n // Firefox with the remote protocol. There is no way to tell flatpak to\n // only expose a port AFAIK.\n '--share=network',\n // Kill the entire sandbox when the launching process dies, which is what\n // we want since exiting web-ext involves `kill` and the process executed\n // here is `flatpak run`.\n '--die-with-parent',\n flatpakAppId,\n ].concat(...(binaryArgs || []));\n }\n\n const results = await fxRunner({\n // if this is falsey, fxRunner tries to find the default one.\n binary: firefoxBinary,\n 'binary-args': binaryArgs,\n // For Flatpak we need to respect the order of the command arguments because\n // we have arguments for Flapack (first) and then Firefox.\n 'binary-args-first': firefoxBinary === 'flatpak',\n // This ensures a new instance of Firefox is created. It has nothing\n // to do with the devtools remote debugger.\n 'no-remote': true,\n listen: remotePort,\n foreground: true,\n profile: profile.path(),\n env: {\n ...process.env,\n ...defaultFirefoxEnv,\n },\n verbose: true,\n });\n\n const firefox = results.process;\n\n log.debug(`Executing Firefox binary: ${results.binary}`);\n log.debug(`Firefox args: ${results.args.join(' ')}`);\n\n firefox.on('error', (error) => {\n // TODO: show a nice error when it can't find Firefox.\n // if (/No such file/.test(err) || err.code === 'ENOENT') {\n log.error(`Firefox error: ${error}`);\n throw error;\n });\n\n if (!devtools) {\n log.info('Use --verbose or --devtools to see logging');\n }\n if (devtools) {\n log.info('More info about WebExtensions debugging:');\n log.info('https://extensionworkshop.com/documentation/develop/debugging/');\n }\n\n firefox.stderr.on('data', (data) => {\n log.debug(`Firefox stderr: ${data.toString().trim()}`);\n });\n\n firefox.stdout.on('data', (data) => {\n log.debug(`Firefox stdout: ${data.toString().trim()}`);\n });\n\n firefox.on('close', () => {\n log.debug('Firefox closed');\n });\n\n return { firefox, debuggerPort: remotePort };\n}\n\n// isDefaultProfile types and implementation.\n\nconst DEFAULT_PROFILES_NAMES = ['default', 'dev-edition-default'];\n\n/*\n * Tests if a profile is a default Firefox profile (both as a profile name or\n * profile path).\n *\n * Returns a promise that resolves to true if the profile is one of default Firefox profile.\n */\nexport async function isDefaultProfile(\n profilePathOrName,\n ProfileFinder = FirefoxProfile.Finder,\n fsStat = fs.stat,\n) {\n if (DEFAULT_PROFILES_NAMES.includes(profilePathOrName)) {\n return true;\n }\n\n const baseProfileDir = ProfileFinder.locateUserDirectory();\n const profilesIniPath = path.join(baseProfileDir, 'profiles.ini');\n try {\n await fsStat(profilesIniPath);\n } catch (error) {\n if (isErrorWithCode('ENOENT', error)) {\n log.debug(`profiles.ini not found: ${error}`);\n\n // No profiles exist yet, default to false (the default profile name contains a\n // random generated component).\n return false;\n }\n\n // Re-throw any unexpected exception.\n throw error;\n }\n\n // Check for profile dir path.\n const finder = new ProfileFinder(baseProfileDir);\n const readProfiles = promisify((...args) => finder.readProfiles(...args));\n\n await readProfiles();\n\n const normalizedProfileDirPath = path.normalize(\n path.join(path.resolve(profilePathOrName), path.sep),\n );\n\n for (const profile of finder.profiles) {\n // Check if the profile dir path or name is one of the default profiles\n // defined in the profiles.ini file.\n if (\n DEFAULT_PROFILES_NAMES.includes(profile.Name) ||\n profile.Default === '1'\n ) {\n let profileFullPath;\n\n // Check for profile name.\n if (profile.Name === profilePathOrName) {\n return true;\n }\n\n // Check for profile path.\n if (profile.IsRelative === '1') {\n profileFullPath = path.join(baseProfileDir, profile.Path, path.sep);\n } else {\n profileFullPath = path.join(profile.Path, path.sep);\n }\n\n if (path.normalize(profileFullPath) === normalizedProfileDirPath) {\n return true;\n }\n }\n }\n\n // Profile directory not found.\n return false;\n}\n\n// configureProfile types and implementation.\n\n/*\n * Configures a profile with common preferences that are required to\n * activate extension development.\n *\n * Returns a promise that resolves with the original profile object.\n */\nexport function configureProfile(\n profile,\n { app = 'firefox', getPrefs = defaultPrefGetter, customPrefs = {} } = {},\n) {\n // Set default preferences. Some of these are required for the add-on to\n // operate, such as disabling signatures.\n const prefs = getPrefs(app);\n Object.keys(prefs).forEach((pref) => {\n profile.setPreference(pref, prefs[pref]);\n });\n if (Object.keys(customPrefs).length > 0) {\n const customPrefsStr = JSON.stringify(customPrefs, null, 2);\n log.info(`Setting custom Firefox preferences: ${customPrefsStr}`);\n Object.keys(customPrefs).forEach((custom) => {\n profile.setPreference(custom, customPrefs[custom]);\n });\n }\n profile.updatePreferences();\n return Promise.resolve(profile);\n}\n\nexport function defaultCreateProfileFinder({\n userDirectoryPath,\n FxProfile = FirefoxProfile,\n} = {}) {\n const finder = new FxProfile.Finder(userDirectoryPath);\n const readProfiles = promisify((...args) => finder.readProfiles(...args));\n const getPath = promisify((...args) => finder.getPath(...args));\n return async (profileName) => {\n try {\n await readProfiles();\n const hasProfileName =\n finder.profiles.filter((profileDef) => profileDef.Name === profileName)\n .length !== 0;\n if (hasProfileName) {\n return await getPath(profileName);\n }\n } catch (error) {\n if (!isErrorWithCode('ENOENT', error)) {\n throw error;\n }\n log.warn('Unable to find Firefox profiles.ini');\n }\n };\n}\n\n// useProfile types and implementation.\n\n// Use the target path as a Firefox profile without cloning it\n\nexport async function useProfile(\n profilePath,\n {\n app,\n configureThisProfile = configureProfile,\n isFirefoxDefaultProfile = isDefaultProfile,\n customPrefs = {},\n createProfileFinder = defaultCreateProfileFinder,\n } = {},\n) {\n const isForbiddenProfile = await isFirefoxDefaultProfile(profilePath);\n if (isForbiddenProfile) {\n throw new UsageError(\n 'Cannot use --keep-profile-changes on a default profile' +\n ` (\"${profilePath}\")` +\n ' because web-ext will make it insecure and unsuitable for daily use.' +\n '\\nSee https://github.com/mozilla/web-ext/issues/1005',\n );\n }\n\n let destinationDirectory;\n const getProfilePath = createProfileFinder();\n\n const profileIsDirPath = await isDirectory(profilePath);\n if (profileIsDirPath) {\n log.debug(`Using profile directory \"${profilePath}\"`);\n destinationDirectory = profilePath;\n } else {\n log.debug(`Assuming ${profilePath} is a named profile`);\n destinationDirectory = await getProfilePath(profilePath);\n if (!destinationDirectory) {\n throw new UsageError(\n `The request \"${profilePath}\" profile name ` +\n 'cannot be resolved to a profile path',\n );\n }\n }\n\n const profile = new FirefoxProfile({ destinationDirectory });\n return await configureThisProfile(profile, { app, customPrefs });\n}\n\n// createProfile types and implementation.\n\n/*\n * Creates a new temporary profile and resolves with the profile object.\n *\n * The profile will be deleted when the system process exits.\n */\nexport async function createProfile({\n app,\n configureThisProfile = configureProfile,\n customPrefs = {},\n} = {}) {\n const profile = new FirefoxProfile();\n return await configureThisProfile(profile, { app, customPrefs });\n}\n\n// copyProfile types and implementation.\n\n/*\n * Copies an existing Firefox profile and creates a new temporary profile.\n * The new profile will be configured with some preferences required to\n * activate extension development.\n *\n * It resolves with the new profile object.\n *\n * The temporary profile will be deleted when the system process exits.\n *\n * The existing profile can be specified as a directory path or a name of\n * one that exists in the current user's Firefox directory.\n */\nexport async function copyProfile(\n profileDirectory,\n {\n app,\n configureThisProfile = configureProfile,\n copyFromUserProfile = defaultUserProfileCopier,\n customPrefs = {},\n } = {},\n) {\n const copy = promisify(FirefoxProfile.copy);\n const copyByName = promisify(copyFromUserProfile);\n\n try {\n const dirExists = await isDirectory(profileDirectory);\n\n let profile;\n\n if (dirExists) {\n log.debug(`Copying profile directory from \"${profileDirectory}\"`);\n profile = await copy({ profileDirectory });\n } else {\n log.debug(`Assuming ${profileDirectory} is a named profile`);\n profile = await copyByName({ name: profileDirectory });\n }\n\n return configureThisProfile(profile, { app, customPrefs });\n } catch (error) {\n throw new WebExtError(\n `Could not copy Firefox profile from ${profileDirectory}: ${error}`,\n );\n }\n}\n\n// installExtension types and implementation.\n\n/*\n * Installs an extension into the given Firefox profile object.\n * Resolves when complete.\n *\n * The extension is copied into a special location and you need to turn\n * on some preferences to allow this. See extensions.autoDisableScopes in\n * ./preferences.js.\n *\n * When asProxy is true, a special proxy file will be installed. This is a\n * text file that contains the path to the extension source.\n */\nexport async function installExtension({\n asProxy = false,\n manifestData,\n profile,\n extensionPath,\n asyncFsStat = defaultAsyncFsStat,\n}) {\n // This more or less follows\n // https://github.com/saadtazi/firefox-profile-js/blob/master/lib/firefox_profile.js#L531\n // (which is broken for web extensions).\n // TODO: maybe uplift a patch that supports web extensions instead?\n\n if (!profile.extensionsDir) {\n throw new WebExtError('profile.extensionsDir was unexpectedly empty');\n }\n\n try {\n await asyncFsStat(profile.extensionsDir);\n } catch (error) {\n if (isErrorWithCode('ENOENT', error)) {\n log.debug(`Creating extensions directory: ${profile.extensionsDir}`);\n await fs.mkdir(profile.extensionsDir);\n } else {\n throw error;\n }\n }\n\n const id = getManifestId(manifestData);\n if (!id) {\n throw new UsageError(\n 'An explicit extension ID is required when installing to ' +\n 'a profile (applications.gecko.id not found in manifest.json)',\n );\n }\n\n if (asProxy) {\n log.debug(`Installing as an extension proxy; source: ${extensionPath}`);\n\n const isDir = await isDirectory(extensionPath);\n if (!isDir) {\n throw new WebExtError(\n 'proxy install: extensionPath must be the extension source ' +\n `directory; got: ${extensionPath}`,\n );\n }\n\n // Write a special extension proxy file containing the source\n // directory. See:\n // https://developer.mozilla.org/en-US/Add-ons/Setting_up_extension_development_environment#Firefox_extension_proxy_file\n const destPath = path.join(profile.extensionsDir, `${id}`);\n const writeStream = nodeFs.createWriteStream(destPath);\n writeStream.write(extensionPath);\n writeStream.end();\n return await fromEvent(writeStream, 'close');\n } else {\n // Write the XPI file to the profile.\n const readStream = nodeFs.createReadStream(extensionPath);\n const destPath = path.join(profile.extensionsDir, `${id}.xpi`);\n const writeStream = nodeFs.createWriteStream(destPath);\n\n log.debug(`Installing extension from ${extensionPath} to ${destPath}`);\n readStream.pipe(writeStream);\n\n return await Promise.all([\n fromEvent(readStream, 'close'),\n fromEvent(writeStream, 'close'),\n ]);\n }\n}\n"],"mappings":"AAAA,OAAOA,MAAM,MAAM,IAAI;AACvB,OAAOC,IAAI,MAAM,MAAM;AACvB,SAASC,SAAS,QAAQ,MAAM;AAChC,OAAOC,EAAE,MAAM,aAAa;AAE5B,SAASC,OAAO,IAAIC,eAAe,QAAQ,WAAW;AACtD,OAAOC,cAAc,MAAM,iBAAiB;AAC5C,OAAOC,SAAS,MAAM,2BAA2B;AAEjD,OAAOC,WAAW,MAAM,yBAAyB;AACjD,SAASC,eAAe,EAAEC,UAAU,EAAEC,WAAW,QAAQ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":[],"sources":["../../src/firefox/index.js"],"sourcesContent":["import nodeFs from 'fs';\nimport path from 'path';\nimport { promisify } from 'util';\nimport fs from 'fs/promises';\n\nimport { default as defaultFxRunner } from 'fx-runner';\nimport FirefoxProfile from 'firefox-profile';\nimport fromEvent from 'promise-toolbox/fromEvent';\n\nimport isDirectory from '../util/is-directory.js';\nimport { isErrorWithCode, UsageError, WebExtError } from '../errors.js';\nimport { getPrefs as defaultPrefGetter } from './preferences.js';\nimport { getManifestId } from '../util/manifest.js';\nimport { findFreeTcpPort as defaultRemotePortFinder } from './remote.js';\nimport { createLogger } from '../util/logger.js';\n\nconst log = createLogger(import.meta.url);\n\nconst defaultAsyncFsStat = fs.stat.bind(fs);\n\nconst defaultUserProfileCopier = FirefoxProfile.copyFromUserProfile;\n\nexport const defaultFirefoxEnv = {\n XPCOM_DEBUG_BREAK: 'stack',\n NS_TRACE_MALLOC_DISABLE_STACKS: '1',\n};\n\n/*\n * Runs Firefox with the given profile object and resolves a promise on exit.\n */\nexport async function run(\n profile,\n {\n fxRunner = defaultFxRunner,\n findRemotePort = defaultRemotePortFinder,\n firefoxBinary,\n binaryArgs,\n extensions,\n devtools,\n } = {},\n) {\n log.debug(`Running Firefox with profile at ${profile.path()}`);\n\n const remotePort = await findRemotePort();\n\n if (firefoxBinary && firefoxBinary.startsWith('flatpak:')) {\n const flatpakAppId = firefoxBinary.substring(8);\n log.debug(`Configuring Firefox with flatpak: appId=${flatpakAppId}`);\n\n // This should be resolved by the fx-runner.\n firefoxBinary = 'flatpak';\n binaryArgs = [\n 'run',\n `--filesystem=${profile.path()}`,\n ...extensions.map(({ sourceDir }) => `--filesystem=${sourceDir}:ro`),\n // We need to share the network namespace because we want to connect to\n // Firefox with the remote protocol. There is no way to tell flatpak to\n // only expose a port AFAIK.\n '--share=network',\n // Kill the entire sandbox when the launching process dies, which is what\n // we want since exiting web-ext involves `kill` and the process executed\n // here is `flatpak run`.\n '--die-with-parent',\n flatpakAppId,\n ].concat(...(binaryArgs || []));\n }\n\n const results = await fxRunner({\n // if this is falsey, fxRunner tries to find the default one.\n binary: firefoxBinary,\n 'binary-args': binaryArgs,\n // For Flatpak we need to respect the order of the command arguments because\n // we have arguments for Flapack (first) and then Firefox.\n 'binary-args-first': firefoxBinary === 'flatpak',\n // This ensures a new instance of Firefox is created. It has nothing\n // to do with the devtools remote debugger.\n 'no-remote': true,\n listen: remotePort,\n foreground: true,\n profile: profile.path(),\n env: {\n ...process.env,\n ...defaultFirefoxEnv,\n },\n verbose: true,\n });\n\n const firefox = results.process;\n\n log.debug(`Executing Firefox binary: ${results.binary}`);\n log.debug(`Firefox args: ${results.args.join(' ')}`);\n\n firefox.on('error', (error) => {\n // TODO: show a nice error when it can't find Firefox.\n // if (/No such file/.test(err) || err.code === 'ENOENT') {\n log.error(`Firefox error: ${error}`);\n throw error;\n });\n\n if (!devtools) {\n log.info('Use --verbose or --devtools to see logging');\n }\n if (devtools) {\n log.info('More info about WebExtensions debugging:');\n log.info('https://extensionworkshop.com/documentation/develop/debugging/');\n }\n\n firefox.stderr.on('data', (data) => {\n log.debug(`Firefox stderr: ${data.toString().trim()}`);\n });\n\n firefox.stdout.on('data', (data) => {\n log.debug(`Firefox stdout: ${data.toString().trim()}`);\n });\n\n firefox.on('close', () => {\n log.debug('Firefox closed');\n });\n\n return { firefox, debuggerPort: remotePort };\n}\n\n// isDefaultProfile types and implementation.\n\nconst DEFAULT_PROFILES_NAMES = ['default', 'dev-edition-default'];\n\n/*\n * Tests if a profile is a default Firefox profile (both as a profile name or\n * profile path).\n *\n * Returns a promise that resolves to true if the profile is one of default Firefox profile.\n */\nexport async function isDefaultProfile(\n profilePathOrName,\n ProfileFinder = FirefoxProfile.Finder,\n fsStat = fs.stat,\n) {\n if (DEFAULT_PROFILES_NAMES.includes(profilePathOrName)) {\n return true;\n }\n\n const baseProfileDir = ProfileFinder.locateUserDirectory();\n const profilesIniPath = path.join(baseProfileDir, 'profiles.ini');\n try {\n await fsStat(profilesIniPath);\n } catch (error) {\n if (isErrorWithCode('ENOENT', error)) {\n log.debug(`profiles.ini not found: ${error}`);\n\n // No profiles exist yet, default to false (the default profile name contains a\n // random generated component).\n return false;\n }\n\n // Re-throw any unexpected exception.\n throw error;\n }\n\n // Check for profile dir path.\n const finder = new ProfileFinder(baseProfileDir);\n const readProfiles = promisify((...args) => finder.readProfiles(...args));\n\n await readProfiles();\n\n const normalizedProfileDirPath = path.normalize(\n path.join(path.resolve(profilePathOrName), path.sep),\n );\n\n for (const profile of finder.profiles) {\n // Check if the profile dir path or name is one of the default profiles\n // defined in the profiles.ini file.\n if (\n DEFAULT_PROFILES_NAMES.includes(profile.Name) ||\n profile.Default === '1'\n ) {\n let profileFullPath;\n\n // Check for profile name.\n if (profile.Name === profilePathOrName) {\n return true;\n }\n\n // Check for profile path.\n if (profile.IsRelative === '1') {\n profileFullPath = path.join(baseProfileDir, profile.Path, path.sep);\n } else {\n profileFullPath = path.join(profile.Path, path.sep);\n }\n\n if (path.normalize(profileFullPath) === normalizedProfileDirPath) {\n return true;\n }\n }\n }\n\n // Profile directory not found.\n return false;\n}\n\n// configureProfile types and implementation.\n\n/*\n * Configures a profile with common preferences that are required to\n * activate extension development.\n *\n * Returns a promise that resolves with the original profile object.\n */\nexport function configureProfile(\n profile,\n { app = 'firefox', getPrefs = defaultPrefGetter, customPrefs = {} } = {},\n) {\n // Set default preferences. Some of these are required for the add-on to\n // operate, such as disabling signatures.\n const prefs = getPrefs(app);\n Object.keys(prefs).forEach((pref) => {\n profile.setPreference(pref, prefs[pref]);\n });\n if (Object.keys(customPrefs).length > 0) {\n const customPrefsStr = JSON.stringify(customPrefs, null, 2);\n log.info(`Setting custom Firefox preferences: ${customPrefsStr}`);\n Object.keys(customPrefs).forEach((custom) => {\n profile.setPreference(custom, customPrefs[custom]);\n });\n }\n profile.updatePreferences();\n return Promise.resolve(profile);\n}\n\nexport function defaultCreateProfileFinder({\n userDirectoryPath,\n FxProfile = FirefoxProfile,\n} = {}) {\n const finder = new FxProfile.Finder(userDirectoryPath);\n const readProfiles = promisify((...args) => finder.readProfiles(...args));\n const getPath = promisify((...args) => finder.getPath(...args));\n return async (profileName) => {\n try {\n await readProfiles();\n const hasProfileName =\n finder.profiles.filter((profileDef) => profileDef.Name === profileName)\n .length !== 0;\n if (hasProfileName) {\n return await getPath(profileName);\n }\n } catch (error) {\n if (!isErrorWithCode('ENOENT', error)) {\n throw error;\n }\n log.warn('Unable to find Firefox profiles.ini');\n }\n };\n}\n\n// useProfile types and implementation.\n\n// Use the target path as a Firefox profile without cloning it\n\nexport async function useProfile(\n profilePath,\n {\n app,\n configureThisProfile = configureProfile,\n isFirefoxDefaultProfile = isDefaultProfile,\n customPrefs = {},\n createProfileFinder = defaultCreateProfileFinder,\n } = {},\n) {\n const isForbiddenProfile = await isFirefoxDefaultProfile(profilePath);\n if (isForbiddenProfile) {\n throw new UsageError(\n 'Cannot use --keep-profile-changes on a default profile' +\n ` (\"${profilePath}\")` +\n ' because web-ext will make it insecure and unsuitable for daily use.' +\n '\\nSee https://github.com/mozilla/web-ext/issues/1005',\n );\n }\n\n let destinationDirectory;\n const getProfilePath = createProfileFinder();\n\n const profileIsDirPath = await isDirectory(profilePath);\n if (profileIsDirPath) {\n log.debug(`Using profile directory \"${profilePath}\"`);\n destinationDirectory = profilePath;\n } else {\n log.debug(`Assuming ${profilePath} is a named profile`);\n destinationDirectory = await getProfilePath(profilePath);\n if (!destinationDirectory) {\n throw new UsageError(\n `The request \"${profilePath}\" profile name ` +\n 'cannot be resolved to a profile path',\n );\n }\n }\n\n const profile = new FirefoxProfile({ destinationDirectory });\n return await configureThisProfile(profile, { app, customPrefs });\n}\n\n// createProfile types and implementation.\n\n/*\n * Creates a new temporary profile and resolves with the profile object.\n *\n * The profile will be deleted when the system process exits.\n */\nexport async function createProfile({\n app,\n configureThisProfile = configureProfile,\n customPrefs = {},\n} = {}) {\n const profile = new FirefoxProfile();\n return await configureThisProfile(profile, { app, customPrefs });\n}\n\n// copyProfile types and implementation.\n\n/*\n * Copies an existing Firefox profile and creates a new temporary profile.\n * The new profile will be configured with some preferences required to\n * activate extension development.\n *\n * It resolves with the new profile object.\n *\n * The temporary profile will be deleted when the system process exits.\n *\n * The existing profile can be specified as a directory path or a name of\n * one that exists in the current user's Firefox directory.\n */\nexport async function copyProfile(\n profileDirectory,\n {\n app,\n configureThisProfile = configureProfile,\n copyFromUserProfile = defaultUserProfileCopier,\n customPrefs = {},\n } = {},\n) {\n const copy = promisify(FirefoxProfile.copy);\n const copyByName = promisify(copyFromUserProfile);\n\n try {\n const dirExists = await isDirectory(profileDirectory);\n\n let profile;\n\n if (dirExists) {\n log.debug(`Copying profile directory from \"${profileDirectory}\"`);\n profile = await copy({ profileDirectory });\n } else {\n log.debug(`Assuming ${profileDirectory} is a named profile`);\n profile = await copyByName({ name: profileDirectory });\n }\n\n return configureThisProfile(profile, { app, customPrefs });\n } catch (error) {\n throw new WebExtError(\n `Could not copy Firefox profile from ${profileDirectory}: ${error}`,\n );\n }\n}\n\n// installExtension types and implementation.\n\n/*\n * Installs an extension into the given Firefox profile object.\n * Resolves when complete.\n *\n * The extension is copied into a special location and you need to turn\n * on some preferences to allow this. See extensions.autoDisableScopes in\n * ./preferences.js.\n *\n * When asProxy is true, a special proxy file will be installed. This is a\n * text file that contains the path to the extension source.\n */\nexport async function installExtension({\n asProxy = false,\n manifestData,\n profile,\n extensionPath,\n asyncFsStat = defaultAsyncFsStat,\n}) {\n // This more or less follows\n // https://github.com/saadtazi/firefox-profile-js/blob/master/lib/firefox_profile.js#L531\n // (which is broken for web extensions).\n // TODO: maybe uplift a patch that supports web extensions instead?\n\n if (!profile.extensionsDir) {\n throw new WebExtError('profile.extensionsDir was unexpectedly empty');\n }\n\n try {\n await asyncFsStat(profile.extensionsDir);\n } catch (error) {\n if (isErrorWithCode('ENOENT', error)) {\n log.debug(`Creating extensions directory: ${profile.extensionsDir}`);\n await fs.mkdir(profile.extensionsDir);\n } else {\n throw error;\n }\n }\n\n const id = getManifestId(manifestData);\n if (!id) {\n throw new UsageError(\n 'An explicit extension ID is required when installing to ' +\n 'a profile (applications.gecko.id not found in manifest.json)',\n );\n }\n\n if (asProxy) {\n log.debug(`Installing as an extension proxy; source: ${extensionPath}`);\n\n const isDir = await isDirectory(extensionPath);\n if (!isDir) {\n throw new WebExtError(\n 'proxy install: extensionPath must be the extension source ' +\n `directory; got: ${extensionPath}`,\n );\n }\n\n // Write a special extension proxy file containing the source\n // directory. See:\n // https://developer.mozilla.org/en-US/Add-ons/Setting_up_extension_development_environment#Firefox_extension_proxy_file\n const destPath = path.join(profile.extensionsDir, `${id}`);\n const writeStream = nodeFs.createWriteStream(destPath);\n writeStream.write(extensionPath);\n writeStream.end();\n return await fromEvent(writeStream, 'close');\n } else {\n // Write the XPI file to the profile.\n const readStream = nodeFs.createReadStream(extensionPath);\n const destPath = path.join(profile.extensionsDir, `${id}.xpi`);\n const writeStream = nodeFs.createWriteStream(destPath);\n\n log.debug(`Installing extension from ${extensionPath} to ${destPath}`);\n readStream.pipe(writeStream);\n\n return await Promise.all([\n fromEvent(readStream, 'close'),\n fromEvent(writeStream, 'close'),\n ]);\n }\n}\n"],"mappings":"AAAA,OAAO,MAAM,MAAM,IAAI;AACvB,OAAO,IAAI,MAAM,MAAM;AACvB,SAAS,SAAS,QAAQ,MAAM;AAChC,OAAO,EAAE,MAAM,aAAa;AAE5B,SAAS,OAAO,IAAI,eAAe,QAAQ,WAAW;AACtD,OAAO,cAAc,MAAM,iBAAiB;AAC5C,OAAO,SAAS,MAAM,2BAA2B;AAEjD,OAAO,WAAW,MAAM,yBAAyB;AACjD,SAAS,eAAe,EAAE,UAAU,EAAE,WAAW,QAAQ,cAAc;AACvE,SAAS,QAAQ,IAAI,iBAAiB,QAAQ,kBAAkB;AAChE,SAAS,aAAa,QAAQ,qBAAqB;AACnD,SAAS,eAAe,IAAI,uBAAuB,QAAQ,aAAa;AACxE,SAAS,YAAY,QAAQ,mBAAmB;AAEhD,MAAM,GAAG,G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Q,CAAC;IAEtD,GAAG,CAAC,KAAK,CAAC,6BAA6B,aAAa,OAAO,QAAQ,EAAE,CAAC;IACtE,UAAU,CAAC,IAAI,CAAC,WAAW,CAAC;IAE5B,OAAO,MAAM,OAAO,CAAC,GAAG,CAAC,CACvB,SAAS,CAAC,UAAU,EAAE,OAAO,CAAC,EAC9B,SAAS,CAAC,WAAW,EAAE,OAAO,CAAC,CAChC,CAAC;EACJ;AACF","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"package-identifiers.js","names":["defaultApkComponents"],"sources":["../../src/firefox/package-identifiers.js"],"sourcesContent":["// This list should have more specific identifiers listed first because of the\n// logic in `src/util/adb.js`, e.g. `some.id.debug` is more specific than `some.id`.\nexport default [\n 'org.mozilla.fennec',\n 'org.mozilla.fenix.debug',\n 'org.mozilla.fenix',\n 'org.mozilla.geckoview_example',\n 'org.mozilla.geckoview',\n 'org.mozilla.firefox',\n 'org.mozilla.reference.browser',\n];\n\nexport const defaultApkComponents = {\n 'org.mozilla.reference.browser': '.BrowserActivity',\n};\n"],"mappings":"AAAA;AACA;AACA,eAAe,CACb,oBAAoB,EACpB,yBAAyB,EACzB,mBAAmB,EACnB,+BAA+B,EAC/B,uBAAuB,EACvB,qBAAqB,EACrB,+BAA+B,CAChC;AAED,OAAO,MAAMA,oBAAoB,GAAG;EAClC,+BAA+B,EAAE;AACnC,CAAC","ignoreList":[]}
1
+ {"version":3,"file":"package-identifiers.js","names":[],"sources":["../../src/firefox/package-identifiers.js"],"sourcesContent":["// This list should have more specific identifiers listed first because of the\n// logic in `src/util/adb.js`, e.g. `some.id.debug` is more specific than `some.id`.\nexport default [\n 'org.mozilla.fennec',\n 'org.mozilla.fenix.debug',\n 'org.mozilla.fenix',\n 'org.mozilla.geckoview_example',\n 'org.mozilla.geckoview',\n 'org.mozilla.firefox',\n 'org.mozilla.reference.browser',\n];\n\nexport const defaultApkComponents = {\n 'org.mozilla.reference.browser': '.BrowserActivity',\n};\n"],"mappings":"AAAA;AACA;AACA,eAAe,CACb,oBAAoB,EACpB,yBAAyB,EACzB,mBAAmB,EACnB,+BAA+B,EAC/B,uBAAuB,EACvB,qBAAqB,EACrB,+BAA+B,CAChC;AAED,OAAO,MAAM,oBAAoB,GAAG;EAClC,+BAA+B,EAAE;AACnC,CAAC","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"preferences.js","names":["WebExtError","UsageError","createLogger","log","import","meta","url","nonOverridablePreferences","prefsCommon","prefsFennec","prefsFirefox","prefs","common","fennec","firefox","getPrefs","app","appPrefs","coerceCLICustomPreference","cliPrefs","customPrefs","pref","prefsAry","split","length","key","value","slice","join","test","parseInt","includes","warn"],"sources":["../../src/firefox/preferences.js"],"sourcesContent":["import { WebExtError, UsageError } from '../errors.js';\nimport { createLogger } from '../util/logger.js';\n\nconst log = createLogger(import.meta.url);\n\nexport const nonOverridablePreferences = [\n 'devtools.debugger.remote-enabled',\n 'devtools.debugger.prompt-connection',\n 'xpinstall.signatures.required',\n];\n\n// Preferences Maps\n\nconst prefsCommon = {\n // Allow debug output via dump to be printed to the system console\n 'browser.dom.window.dump.enabled': true,\n\n // From:\n // https://firefox-source-docs.mozilla.org/toolkit/components/telemetry/internals/preferences.html#data-choices-notification\n // This is the data submission master kill switch. If disabled, no policy is shown or upload takes place, ever.\n 'datareporting.policy.dataSubmissionEnabled': false,\n\n // Allow remote connections to the debugger.\n 'devtools.debugger.remote-enabled': true,\n // Disable the prompt for allowing connections.\n 'devtools.debugger.prompt-connection': false,\n // Allow extensions to log messages on browser's console.\n 'devtools.browserconsole.contentMessages': true,\n\n // Turn off platform logging because it is a lot of info.\n 'extensions.logging.enabled': false,\n\n // Disable extension updates and notifications.\n 'extensions.checkCompatibility.nightly': false,\n 'extensions.update.enabled': false,\n 'extensions.update.notifyUser': false,\n\n // From:\n // http://hg.mozilla.org/mozilla-central/file/1dd81c324ac7/build/automation.py.in//l372\n // Only load extensions from the application and user profile.\n // AddonManager.SCOPE_PROFILE + AddonManager.SCOPE_APPLICATION\n 'extensions.enabledScopes': 5,\n // Disable metadata caching for installed add-ons by default.\n 'extensions.getAddons.cache.enabled': false,\n // Disable installing any distribution add-ons.\n 'extensions.installDistroAddons': false,\n // Allow installing extensions dropped into the profile folder.\n 'extensions.autoDisableScopes': 10,\n\n // Disable app update.\n 'app.update.enabled': false,\n\n // Allow unsigned add-ons.\n 'xpinstall.signatures.required': false,\n\n // browser.link.open_newwindow is changed from 3 to 2 in:\n // https://github.com/saadtazi/firefox-profile-js/blob/cafc793d940a779d280103ae17d02a92de862efc/lib/firefox_profile.js#L32\n // Restore original value to avoid https://github.com/mozilla/web-ext/issues/1592\n 'browser.link.open_newwindow': 3,\n};\n\n// Prefs specific to Firefox for Android.\nconst prefsFennec = {\n 'browser.console.showInPanel': true,\n 'browser.firstrun.show.uidiscovery': false,\n 'devtools.remote.usb.enabled': true,\n};\n\n// Prefs specific to Firefox for desktop.\nconst prefsFirefox = {\n 'browser.startup.homepage': 'about:blank',\n 'startup.homepage_welcome_url': 'about:blank',\n 'startup.homepage_welcome_url.additional': '',\n 'devtools.errorconsole.enabled': true,\n 'devtools.chrome.enabled': true,\n 'devtools.debugger.show-content-scripts': true,\n\n // From:\n // http://hg.mozilla.org/mozilla-central/file/1dd81c324ac7/build/automation.py.in//l388\n // Make url-classifier updates so rare that they won't affect tests.\n 'urlclassifier.updateinterval': 172800,\n // Point the url-classifier to a nonexistent local URL for fast failures.\n 'browser.safebrowsing.provider.0.gethashURL':\n 'http://localhost/safebrowsing-dummy/gethash',\n 'browser.safebrowsing.provider.0.keyURL':\n 'http://localhost/safebrowsing-dummy/newkey',\n 'browser.safebrowsing.provider.0.updateURL':\n 'http://localhost/safebrowsing-dummy/update',\n\n // Disable self repair/SHIELD\n 'browser.selfsupport.url': 'https://localhost/selfrepair',\n // Disable Reader Mode UI tour\n 'browser.reader.detectedFirstArticle': true,\n\n // Set the policy firstURL to an empty string to prevent\n // the privacy info page to be opened on every \"web-ext run\".\n // (See #1114 for rationale)\n 'datareporting.policy.firstRunURL': '',\n\n // Prevent the terms-of-use modal from appearing on every \"web-ext run\". (See #3478)\n 'termsofuse.bypassNotification': true,\n};\n\nconst prefs = {\n common: prefsCommon,\n fennec: prefsFennec,\n firefox: prefsFirefox,\n};\n\n// Module exports\n\nexport function getPrefs(app = 'firefox') {\n const appPrefs = prefs[app];\n if (!appPrefs) {\n throw new WebExtError(`Unsupported application: ${app}`);\n }\n return {\n ...prefsCommon,\n ...appPrefs,\n };\n}\n\nexport function coerceCLICustomPreference(cliPrefs) {\n const customPrefs = {};\n\n for (const pref of cliPrefs) {\n const prefsAry = pref.split('=');\n\n if (prefsAry.length < 2) {\n throw new UsageError(\n `Incomplete custom preference: \"${pref}\". ` +\n 'Syntax expected: \"prefname=prefvalue\".',\n );\n }\n\n const key = prefsAry[0];\n let value = prefsAry.slice(1).join('=');\n\n if (/[^\\w{@}.-]/.test(key)) {\n throw new UsageError(`Invalid custom preference name: ${key}`);\n }\n\n if (value === `${parseInt(value)}`) {\n value = parseInt(value, 10);\n } else if (value === 'true' || value === 'false') {\n value = value === 'true';\n }\n\n if (nonOverridablePreferences.includes(key)) {\n log.warn(`'${key}' preference cannot be customized.`);\n continue;\n }\n customPrefs[`${key}`] = value;\n }\n\n return customPrefs;\n}\n"],"mappings":"AAAA,SAASA,WAAW,EAAEC,UAAU,QAAQ,cAAc;AACtD,SAASC,YAAY,QAAQ,mBAAmB;AAEhD,MAAMC,GAAG,GAAGD,YAAY,CAACE,MAAM,CAACC,IAAI,CAACC,GAAG,CAAC;AAEzC,OAAO,MAAMC,yBAAyB,GAAG,CACvC,kCAAkC,EAClC,qCAAqC,EACrC,+BAA+B,CAChC;;AAED;;AAEA,MAAMC,WAAW,GAAG;EAClB;EACA,iCAAiC,EAAE,IAAI;EAEvC;EACA;EACA;EACA,4CAA4C,EAAE,KAAK;EAEnD;EACA,kCAAkC,EAAE,IAAI;EACxC;EACA,qCAAqC,EAAE,KAAK;EAC5C;EACA,yCA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preferences.js","names":[],"sources":["../../src/firefox/preferences.js"],"sourcesContent":["import { WebExtError, UsageError } from '../errors.js';\nimport { createLogger } from '../util/logger.js';\n\nconst log = createLogger(import.meta.url);\n\nexport const nonOverridablePreferences = [\n 'devtools.debugger.remote-enabled',\n 'devtools.debugger.prompt-connection',\n 'xpinstall.signatures.required',\n];\n\n// Preferences Maps\n\nconst prefsCommon = {\n // Allow debug output via dump to be printed to the system console\n 'browser.dom.window.dump.enabled': true,\n\n // From:\n // https://firefox-source-docs.mozilla.org/toolkit/components/telemetry/internals/preferences.html#data-choices-notification\n // This is the data submission master kill switch. If disabled, no policy is shown or upload takes place, ever.\n 'datareporting.policy.dataSubmissionEnabled': false,\n\n // Allow remote connections to the debugger.\n 'devtools.debugger.remote-enabled': true,\n // Disable the prompt for allowing connections.\n 'devtools.debugger.prompt-connection': false,\n // Allow extensions to log messages on browser's console.\n 'devtools.browserconsole.contentMessages': true,\n\n // Turn off platform logging because it is a lot of info.\n 'extensions.logging.enabled': false,\n\n // Disable extension updates and notifications.\n 'extensions.checkCompatibility.nightly': false,\n 'extensions.update.enabled': false,\n 'extensions.update.notifyUser': false,\n\n // From:\n // http://hg.mozilla.org/mozilla-central/file/1dd81c324ac7/build/automation.py.in//l372\n // Only load extensions from the application and user profile.\n // AddonManager.SCOPE_PROFILE + AddonManager.SCOPE_APPLICATION\n 'extensions.enabledScopes': 5,\n // Disable metadata caching for installed add-ons by default.\n 'extensions.getAddons.cache.enabled': false,\n // Disable installing any distribution add-ons.\n 'extensions.installDistroAddons': false,\n // Allow installing extensions dropped into the profile folder.\n 'extensions.autoDisableScopes': 10,\n\n // Disable app update.\n 'app.update.enabled': false,\n\n // Allow unsigned add-ons.\n 'xpinstall.signatures.required': false,\n\n // browser.link.open_newwindow is changed from 3 to 2 in:\n // https://github.com/saadtazi/firefox-profile-js/blob/cafc793d940a779d280103ae17d02a92de862efc/lib/firefox_profile.js#L32\n // Restore original value to avoid https://github.com/mozilla/web-ext/issues/1592\n 'browser.link.open_newwindow': 3,\n};\n\n// Prefs specific to Firefox for Android.\nconst prefsFennec = {\n 'browser.console.showInPanel': true,\n 'browser.firstrun.show.uidiscovery': false,\n 'devtools.remote.usb.enabled': true,\n};\n\n// Prefs specific to Firefox for desktop.\nconst prefsFirefox = {\n 'browser.startup.homepage': 'about:blank',\n 'startup.homepage_welcome_url': 'about:blank',\n 'startup.homepage_welcome_url.additional': '',\n 'devtools.errorconsole.enabled': true,\n 'devtools.chrome.enabled': true,\n 'devtools.debugger.show-content-scripts': true,\n\n // From:\n // http://hg.mozilla.org/mozilla-central/file/1dd81c324ac7/build/automation.py.in//l388\n // Make url-classifier updates so rare that they won't affect tests.\n 'urlclassifier.updateinterval': 172800,\n // Point the url-classifier to a nonexistent local URL for fast failures.\n 'browser.safebrowsing.provider.0.gethashURL':\n 'http://localhost/safebrowsing-dummy/gethash',\n 'browser.safebrowsing.provider.0.keyURL':\n 'http://localhost/safebrowsing-dummy/newkey',\n 'browser.safebrowsing.provider.0.updateURL':\n 'http://localhost/safebrowsing-dummy/update',\n\n // Disable self repair/SHIELD\n 'browser.selfsupport.url': 'https://localhost/selfrepair',\n // Disable Reader Mode UI tour\n 'browser.reader.detectedFirstArticle': true,\n\n // Set the policy firstURL to an empty string to prevent\n // the privacy info page to be opened on every \"web-ext run\".\n // (See #1114 for rationale)\n 'datareporting.policy.firstRunURL': '',\n\n // Prevent the terms-of-use modal from appearing on every \"web-ext run\". (See #3478)\n 'termsofuse.bypassNotification': true,\n};\n\nconst prefs = {\n common: prefsCommon,\n fennec: prefsFennec,\n firefox: prefsFirefox,\n};\n\n// Module exports\n\nexport function getPrefs(app = 'firefox') {\n const appPrefs = prefs[app];\n if (!appPrefs) {\n throw new WebExtError(`Unsupported application: ${app}`);\n }\n return {\n ...prefsCommon,\n ...appPrefs,\n };\n}\n\nexport function coerceCLICustomPreference(cliPrefs) {\n const customPrefs = {};\n\n for (const pref of cliPrefs) {\n const prefsAry = pref.split('=');\n\n if (prefsAry.length < 2) {\n throw new UsageError(\n `Incomplete custom preference: \"${pref}\". ` +\n 'Syntax expected: \"prefname=prefvalue\".',\n );\n }\n\n const key = prefsAry[0];\n let value = prefsAry.slice(1).join('=');\n\n if (/[^\\w{@}.-]/.test(key)) {\n throw new UsageError(`Invalid custom preference name: ${key}`);\n }\n\n if (value === `${parseInt(value)}`) {\n value = parseInt(value, 10);\n } else if (value === 'true' || value === 'false') {\n value = value === 'true';\n }\n\n if (nonOverridablePreferences.includes(key)) {\n log.warn(`'${key}' preference cannot be customized.`);\n continue;\n }\n customPrefs[`${key}`] = value;\n }\n\n return customPrefs;\n}\n"],"mappings":"AAAA,SAAS,WAAW,EAAE,UAAU,QAAQ,cAAc;AACtD,SAAS,YAAY,QAAQ,mBAAmB;AAEhD,MAAM,GAAG,GAAG,YAAY,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC;AAEzC,OAAO,MAAM,yBAAyB,GAAG,CACvC,kCAAkC,EAClC,qCAAqC,EACrC,+BAA+B,CAChC;;AAED;;AAEA,MAAM,WAAW,GAAG;EAClB;EACA,iCAAiC,EAAE,IAAI;EAEvC;EACA;EACA;EACA,4CAA4C,EAAE,KAAK;EAEnD;EACA,kCAAkC,EAAE,IAAI;EACxC;EACA,qCAAqC,EAAE,KAAK;EAC5C;EACA,yCAAyC,EAAE,IAAI;EAE/C;EACA,4BAA4B,EAAE,KAAK;EAEnC;EACA,uCAAuC,EAAE,KAAK;EAC9C,2BAA2B,EAAE,KAAK;EAClC,8BAA8B,EAAE,KAAK;EAErC;EACA;EACA;EACA;EACA,0BAA0B,EAAE,CAAC;EAC7B;EACA,oCAAoC,EAAE,KAAK;EAC3C;EACA,gCAAgC,EAAE,KAAK;EACvC;EACA,8BAA8B,EAAE,EAAE;EAElC;EACA,oBAAoB,EAAE,KAAK;EAE3B;EACA,+BAA+B,EAAE,KAAK;EAEtC;EACA;EACA;EACA,6BAA6B,EAAE;AACjC,CAAC;;AAED;AACA,MAAM,WAAW,GA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AC;IACH;IAEA,MAAM,GAAG,GAAG,QAAQ,CAAC,CAAC,CAAC;IACvB,IAAI,KAAK,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC;IAEvC,IAAI,YAAY,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE;MAC1B,MAAM,IAAI,UAAU,CAAC,mCAAmC,GAAG,EAAE,CAAC;IAChE;IAEA,IAAI,KAAK,KAAK,GAAG,QAAQ,CAAC,KAAK,CAAC,EAAE,EAAE;MAClC,KAAK,GAAG,QAAQ,CAAC,KAAK,EAAE,EAAE,CAAC;IAC7B,CAAC,MAAM,IAAI,KAAK,KAAK,MAAM,IAAI,KAAK,KAAK,OAAO,EAAE;MAChD,KAAK,GAAG,KAAK,KAAK,MAAM;IAC1B;IAEA,IAAI,yBAAyB,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE;MAC3C,GAAG,CAAC,IAAI,CAAC,IAAI,GAAG,oCAAoC,CAAC;MACrD;IACF;IACA,WAAW,CAAC,GAAG,GAAG,EAAE,CAAC,GAAG,KAAK;EAC/B;EAEA,OAAO,WAAW;AACpB","ignoreList":[]}
@@ -195,9 +195,9 @@ export default class FirefoxRDPClient extends EventEmitter {
195
195
  const deferred = this._active.get(rdpData.from);
196
196
  this._active.delete(rdpData.from);
197
197
  if (rdpData.error) {
198
- deferred === null || deferred === void 0 || deferred.reject(rdpData);
198
+ deferred?.reject(rdpData);
199
199
  } else {
200
- deferred === null || deferred === void 0 || deferred.resolve(rdpData);
200
+ deferred?.resolve(rdpData);
201
201
  }
202
202
  this._flushPendingRequests();
203
203
  return;
@@ -1 +1 @@
1
- {"version":3,"file":"rdp-client.js","names":["net","EventEmitter","domain","DEFAULT_PORT","DEFAULT_HOST","UNSOLICITED_EVENTS","Set","parseRDPMessage","data","str","toString","sepIdx","indexOf","byteLen","parseInt","slice","isNaN","error","Error","fatal","length","msg","rdpMessage","JSON","parse","connectToFirefox","port","client","FirefoxRDPClient","connect","then","_incoming","_pending","_active","_rdpConnection","_onData","_onError","_onEnd","_onTimeout","constructor","Buffer","alloc","Map","args","onData","onError","onEnd","onTimeout","Promise","resolve","reject","d","create","once","run","conn","createConnection","host","on","_expectReply","disconnect","off","end","_rejectAllRequests","activeDeferred","values","clear","deferred","request","requestProps","to","type","push","_flushPendingRequests","filter","has","stringify","from","write","err","targetActor","set","_handleMessage","rdpData","emit","get","delete","_readMessage","String","concat"],"sources":["../../src/firefox/rdp-client.js"],"sourcesContent":["import net from 'net';\nimport EventEmitter from 'events';\nimport domain from 'domain';\n\nexport const DEFAULT_PORT = 6000;\nexport const DEFAULT_HOST = '127.0.0.1';\n\nconst UNSOLICITED_EVENTS = new Set([\n 'tabNavigated',\n 'styleApplied',\n 'propertyChange',\n 'networkEventUpdate',\n 'networkEvent',\n 'propertyChange',\n 'newMutations',\n 'frameUpdate',\n 'tabListChanged',\n]);\n\n// Parse RDP packets: BYTE_LENGTH + ':' + DATA.\nexport function parseRDPMessage(data) {\n const str = data.toString();\n const sepIdx = str.indexOf(':');\n if (sepIdx < 1) {\n return { data };\n }\n\n const byteLen = parseInt(str.slice(0, sepIdx));\n if (isNaN(byteLen)) {\n const error = new Error('Error parsing RDP message length');\n return { data, error, fatal: true };\n }\n\n if (data.length - (sepIdx + 1) < byteLen) {\n // Can't parse yet, will retry once more data has been received.\n return { data };\n }\n\n data = data.slice(sepIdx + 1);\n const msg = data.slice(0, byteLen);\n data = data.slice(byteLen);\n\n try {\n return { data, rdpMessage: JSON.parse(msg.toString()) };\n } catch (error) {\n return { data, error, fatal: false };\n }\n}\n\nexport async function connectToFirefox(port) {\n const client = new FirefoxRDPClient();\n return client.connect(port).then(() => client);\n}\n\nexport default class FirefoxRDPClient extends EventEmitter {\n _incoming;\n _pending;\n _active;\n _rdpConnection;\n _onData;\n _onError;\n _onEnd;\n _onTimeout;\n\n constructor() {\n super();\n this._incoming = Buffer.alloc(0);\n this._pending = [];\n this._active = new Map();\n\n this._onData = (...args) => this.onData(...args);\n this._onError = (...args) => this.onError(...args);\n this._onEnd = (...args) => this.onEnd(...args);\n this._onTimeout = (...args) => this.onTimeout(...args);\n }\n\n connect(port) {\n return new Promise((resolve, reject) => {\n // Create a domain to wrap the errors that may be triggered\n // by creating the client connection (e.g. ECONNREFUSED)\n // so that we can reject the promise returned instead of\n // exiting the entire process.\n const d = domain.create();\n d.once('error', reject);\n d.run(() => {\n const conn = net.createConnection({\n port,\n host: DEFAULT_HOST,\n });\n\n this._rdpConnection = conn;\n conn.on('data', this._onData);\n conn.on('error', this._onError);\n conn.on('end', this._onEnd);\n conn.on('timeout', this._onTimeout);\n\n // Resolve once the expected initial root message\n // has been received.\n this._expectReply('root', { resolve, reject });\n });\n });\n }\n\n disconnect() {\n if (!this._rdpConnection) {\n return;\n }\n\n const conn = this._rdpConnection;\n conn.off('data', this._onData);\n conn.off('error', this._onError);\n conn.off('end', this._onEnd);\n conn.off('timeout', this._onTimeout);\n conn.end();\n\n this._rejectAllRequests(new Error('RDP connection closed'));\n }\n\n _rejectAllRequests(error) {\n for (const activeDeferred of this._active.values()) {\n activeDeferred.reject(error);\n }\n this._active.clear();\n\n for (const { deferred } of this._pending) {\n deferred.reject(error);\n }\n this._pending = [];\n }\n\n async request(requestProps) {\n let request;\n\n if (typeof requestProps === 'string') {\n request = { to: 'root', type: requestProps };\n } else {\n request = requestProps;\n }\n\n if (request.to == null) {\n throw new Error(\n `Unexpected RDP request without target actor: ${request.type}`,\n );\n }\n\n return new Promise((resolve, reject) => {\n const deferred = { resolve, reject };\n this._pending.push({ request, deferred });\n this._flushPendingRequests();\n });\n }\n\n _flushPendingRequests() {\n this._pending = this._pending.filter(({ request, deferred }) => {\n if (this._active.has(request.to)) {\n // Keep in the pending requests until there are no requests\n // active on the target RDP actor.\n return true;\n }\n\n const conn = this._rdpConnection;\n if (!conn) {\n throw new Error('RDP connection closed');\n }\n\n try {\n let str = JSON.stringify(request);\n str = `${Buffer.from(str).length}:${str}`;\n conn.write(str);\n this._expectReply(request.to, deferred);\n } catch (err) {\n deferred.reject(err);\n }\n\n // Remove the pending request from the queue.\n return false;\n });\n }\n\n _expectReply(targetActor, deferred) {\n if (this._active.has(targetActor)) {\n throw new Error(`${targetActor} does already have an active request`);\n }\n\n this._active.set(targetActor, deferred);\n }\n\n _handleMessage(rdpData) {\n if (rdpData.from == null) {\n if (rdpData.error) {\n this.emit('rdp-error', rdpData);\n return;\n }\n\n this.emit(\n 'error',\n new Error(\n `Received an RDP message without a sender actor: ${JSON.stringify(\n rdpData,\n )}`,\n ),\n );\n return;\n }\n\n if (UNSOLICITED_EVENTS.has(rdpData.type)) {\n this.emit('unsolicited-event', rdpData);\n return;\n }\n\n if (this._active.has(rdpData.from)) {\n const deferred = this._active.get(rdpData.from);\n this._active.delete(rdpData.from);\n if (rdpData.error) {\n deferred?.reject(rdpData);\n } else {\n deferred?.resolve(rdpData);\n }\n this._flushPendingRequests();\n return;\n }\n\n this.emit(\n 'error',\n new Error(`Unexpected RDP message received: ${JSON.stringify(rdpData)}`),\n );\n }\n\n _readMessage() {\n const { data, rdpMessage, error, fatal } = parseRDPMessage(this._incoming);\n\n this._incoming = data;\n\n if (error) {\n this.emit(\n 'error',\n new Error(`Error parsing RDP packet: ${String(error)}`),\n );\n // Disconnect automatically on a fatal error.\n if (fatal) {\n this.disconnect();\n }\n // Caller can parse the next message if the error wasn't fatal\n // (e.g. the RDP packet that couldn't be parsed has been already\n // removed from the incoming data buffer).\n return !fatal;\n }\n\n if (!rdpMessage) {\n // Caller will need to wait more data to parse the next message.\n return false;\n }\n\n this._handleMessage(rdpMessage);\n // Caller can try to parse the next message from the remaining data.\n return true;\n }\n\n onData(data) {\n this._incoming = Buffer.concat([this._incoming, data]);\n while (this._readMessage()) {\n // Keep parsing and handling messages until readMessage\n // returns false.\n }\n }\n\n onError(error) {\n this.emit('error', error);\n }\n\n onEnd() {\n this.emit('end');\n }\n\n onTimeout() {\n this.emit('timeout');\n }\n}\n"],"mappings":"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A,IAAI,CAACG,UAAU,EAAE;MACf;MACA,OAAO,KAAK;IACd;IAEA,IAAI,CAAC4D,cAAc,CAAC5D,UAAU,CAAC;IAC/B;IACA,OAAO,IAAI;EACb;EAEAsB,MAAMA,CAACpC,IAAI,EAAE;IACX,IAAI,CAACuB,SAAS,GAAGS,MAAM,CAACiD,MAAM,CAAC,CAAC,IAAI,CAAC1D,SAAS,EAAEvB,IAAI,CAAC,CAAC;IACtD,OAAO,IAAI,CAAC+E,YAAY,CAAC,CAAC,EAAE;MAC1B;MACA;IAAA;EAEJ;EAEA1C,OAAOA,CAAC5B,KAAK,EAAE;IACb,IAAI,CAACmE,IAAI,CAAC,OAAO,EAAEnE,KAAK,CAAC;EAC3B;EAEA6B,KAAKA,CAAA,EAAG;IACN,IAAI,CAACsC,IAAI,CAAC,KAAK,CAAC;EAClB;EAEArC,SAASA,CAAA,EAAG;IACV,IAAI,CAACqC,IAAI,CAAC,SAAS,CAAC;EACtB;AACF","ignoreList":[]}
1
+ {"version":3,"file":"rdp-client.js","names":[],"sources":["../../src/firefox/rdp-client.js"],"sourcesContent":["import net from 'net';\nimport EventEmitter from 'events';\nimport domain from 'domain';\n\nexport const DEFAULT_PORT = 6000;\nexport const DEFAULT_HOST = '127.0.0.1';\n\nconst UNSOLICITED_EVENTS = new Set([\n 'tabNavigated',\n 'styleApplied',\n 'propertyChange',\n 'networkEventUpdate',\n 'networkEvent',\n 'propertyChange',\n 'newMutations',\n 'frameUpdate',\n 'tabListChanged',\n]);\n\n// Parse RDP packets: BYTE_LENGTH + ':' + DATA.\nexport function parseRDPMessage(data) {\n const str = data.toString();\n const sepIdx = str.indexOf(':');\n if (sepIdx < 1) {\n return { data };\n }\n\n const byteLen = parseInt(str.slice(0, sepIdx));\n if (isNaN(byteLen)) {\n const error = new Error('Error parsing RDP message length');\n return { data, error, fatal: true };\n }\n\n if (data.length - (sepIdx + 1) < byteLen) {\n // Can't parse yet, will retry once more data has been received.\n return { data };\n }\n\n data = data.slice(sepIdx + 1);\n const msg = data.slice(0, byteLen);\n data = data.slice(byteLen);\n\n try {\n return { data, rdpMessage: JSON.parse(msg.toString()) };\n } catch (error) {\n return { data, error, fatal: false };\n }\n}\n\nexport async function connectToFirefox(port) {\n const client = new FirefoxRDPClient();\n return client.connect(port).then(() => client);\n}\n\nexport default class FirefoxRDPClient extends EventEmitter {\n _incoming;\n _pending;\n _active;\n _rdpConnection;\n _onData;\n _onError;\n _onEnd;\n _onTimeout;\n\n constructor() {\n super();\n this._incoming = Buffer.alloc(0);\n this._pending = [];\n this._active = new Map();\n\n this._onData = (...args) => this.onData(...args);\n this._onError = (...args) => this.onError(...args);\n this._onEnd = (...args) => this.onEnd(...args);\n this._onTimeout = (...args) => this.onTimeout(...args);\n }\n\n connect(port) {\n return new Promise((resolve, reject) => {\n // Create a domain to wrap the errors that may be triggered\n // by creating the client connection (e.g. ECONNREFUSED)\n // so that we can reject the promise returned instead of\n // exiting the entire process.\n const d = domain.create();\n d.once('error', reject);\n d.run(() => {\n const conn = net.createConnection({\n port,\n host: DEFAULT_HOST,\n });\n\n this._rdpConnection = conn;\n conn.on('data', this._onData);\n conn.on('error', this._onError);\n conn.on('end', this._onEnd);\n conn.on('timeout', this._onTimeout);\n\n // Resolve once the expected initial root message\n // has been received.\n this._expectReply('root', { resolve, reject });\n });\n });\n }\n\n disconnect() {\n if (!this._rdpConnection) {\n return;\n }\n\n const conn = this._rdpConnection;\n conn.off('data', this._onData);\n conn.off('error', this._onError);\n conn.off('end', this._onEnd);\n conn.off('timeout', this._onTimeout);\n conn.end();\n\n this._rejectAllRequests(new Error('RDP connection closed'));\n }\n\n _rejectAllRequests(error) {\n for (const activeDeferred of this._active.values()) {\n activeDeferred.reject(error);\n }\n this._active.clear();\n\n for (const { deferred } of this._pending) {\n deferred.reject(error);\n }\n this._pending = [];\n }\n\n async request(requestProps) {\n let request;\n\n if (typeof requestProps === 'string') {\n request = { to: 'root', type: requestProps };\n } else {\n request = requestProps;\n }\n\n if (request.to == null) {\n throw new Error(\n `Unexpected RDP request without target actor: ${request.type}`,\n );\n }\n\n return new Promise((resolve, reject) => {\n const deferred = { resolve, reject };\n this._pending.push({ request, deferred });\n this._flushPendingRequests();\n });\n }\n\n _flushPendingRequests() {\n this._pending = this._pending.filter(({ request, deferred }) => {\n if (this._active.has(request.to)) {\n // Keep in the pending requests until there are no requests\n // active on the target RDP actor.\n return true;\n }\n\n const conn = this._rdpConnection;\n if (!conn) {\n throw new Error('RDP connection closed');\n }\n\n try {\n let str = JSON.stringify(request);\n str = `${Buffer.from(str).length}:${str}`;\n conn.write(str);\n this._expectReply(request.to, deferred);\n } catch (err) {\n deferred.reject(err);\n }\n\n // Remove the pending request from the queue.\n return false;\n });\n }\n\n _expectReply(targetActor, deferred) {\n if (this._active.has(targetActor)) {\n throw new Error(`${targetActor} does already have an active request`);\n }\n\n this._active.set(targetActor, deferred);\n }\n\n _handleMessage(rdpData) {\n if (rdpData.from == null) {\n if (rdpData.error) {\n this.emit('rdp-error', rdpData);\n return;\n }\n\n this.emit(\n 'error',\n new Error(\n `Received an RDP message without a sender actor: ${JSON.stringify(\n rdpData,\n )}`,\n ),\n );\n return;\n }\n\n if (UNSOLICITED_EVENTS.has(rdpData.type)) {\n this.emit('unsolicited-event', rdpData);\n return;\n }\n\n if (this._active.has(rdpData.from)) {\n const deferred = this._active.get(rdpData.from);\n this._active.delete(rdpData.from);\n if (rdpData.error) {\n deferred?.reject(rdpData);\n } else {\n deferred?.resolve(rdpData);\n }\n this._flushPendingRequests();\n return;\n }\n\n this.emit(\n 'error',\n new Error(`Unexpected RDP message received: ${JSON.stringify(rdpData)}`),\n );\n }\n\n _readMessage() {\n const { data, rdpMessage, error, fatal } = parseRDPMessage(this._incoming);\n\n this._incoming = data;\n\n if (error) {\n this.emit(\n 'error',\n new Error(`Error parsing RDP packet: ${String(error)}`),\n );\n // Disconnect automatically on a fatal error.\n if (fatal) {\n this.disconnect();\n }\n // Caller can parse the next message if the error wasn't fatal\n // (e.g. the RDP packet that couldn't be parsed has been already\n // removed from the incoming data buffer).\n return !fatal;\n }\n\n if (!rdpMessage) {\n // Caller will need to wait more data to parse the next message.\n return false;\n }\n\n this._handleMessage(rdpMessage);\n // Caller can try to parse the next message from the remaining data.\n return true;\n }\n\n onData(data) {\n this._incoming = Buffer.concat([this._incoming, data]);\n while (this._readMessage()) {\n // Keep parsing and handling messages until readMessage\n // returns false.\n }\n }\n\n onError(error) {\n this.emit('error', error);\n }\n\n onEnd() {\n this.emit('end');\n }\n\n onTimeout() {\n this.emit('timeout');\n }\n}\n"],"mappings":"AAAA,OAAO,GAAG,MAAM,KAAK;AACrB,OAAO,YAAY,MAAM,QAAQ;AACjC,OAAO,MAAM,MAAM,QAAQ;AAE3B,OAAO,MAAM,YAAY,GAAG,IAAI;AAChC,OAAO,MAAM,YAAY,GAAG,WAAW;AAEvC,MAAM,kBAAkB,GAAG,IAAI,GAAG,CAAC,CACjC,cAAc,EACd,cAAc,EACd,gBAAgB,EAChB,oBAAoB,EACpB,cAAc,EACd,gBAAgB,EAChB,cAAc,EACd,aAAa,EACb,gBAAgB,CACjB,CAAC;;AAEF;AACA,OAAO,SAAS,eAAe,CAAC,IAAI,EAAE;EACpC,MAAM,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC;EAC3B,MAAM,MAAM,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC;EAC/B,IAAI,MAAM,GAAG,CAAC,EAAE;IACd,OAAO;MAAE;IAAK,CAAC;EACjB;EAEA,MAAM,OAAO,GAAG,QAAQ,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;EAC9C,IAAI,KAAK,CAAC,OAAO,CAAC,EAAE;IAClB,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC,kCAAkC,CAAC;IAC3D,OAAO;MAAE,IAAI;MAAE,KAAK;MAAE,KAAK,EAAE;IAAK,CAAC;EACrC;EAEA,IAAI,IAAI,CAAC,MAAM,IAA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