web-ext 7.5.0 → 7.6.1
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.
- package/README.md +3 -2
- package/lib/cmd/build.js.map +1 -1
- package/lib/cmd/docs.js.map +1 -1
- package/lib/cmd/index.js.map +1 -1
- package/lib/cmd/lint.js.map +1 -1
- package/lib/cmd/run.js.map +1 -1
- package/lib/cmd/sign.js +3 -0
- package/lib/cmd/sign.js.map +1 -1
- package/lib/config.js.map +1 -1
- package/lib/errors.js.map +1 -1
- package/lib/extension-runners/chromium.js.map +1 -1
- package/lib/extension-runners/firefox-android.js.map +1 -1
- package/lib/extension-runners/firefox-desktop.js.map +1 -1
- package/lib/extension-runners/index.js.map +1 -1
- package/lib/firefox/index.js.map +1 -1
- package/lib/firefox/preferences.js.map +1 -1
- package/lib/firefox/rdp-client.js.map +1 -1
- package/lib/firefox/remote.js.map +1 -1
- package/lib/program.js +6 -1
- package/lib/program.js.map +1 -1
- package/lib/util/adb.js.map +1 -1
- package/lib/util/artifacts.js.map +1 -1
- package/lib/util/desktop-notifier.js.map +1 -1
- package/lib/util/file-exists.js.map +1 -1
- package/lib/util/file-filter.js.map +1 -1
- package/lib/util/is-directory.js.map +1 -1
- package/lib/util/logger.js.map +1 -1
- package/lib/util/manifest.js.map +1 -1
- package/lib/util/promisify.js.map +1 -1
- package/lib/util/stdin.js.map +1 -1
- package/lib/util/submit-addon.js.map +1 -1
- package/lib/util/temp-dir.js.map +1 -1
- package/lib/util/updates.js.map +1 -1
- package/lib/watcher.js.map +1 -1
- package/package.json +19 -19
|
@@ -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","constructor","_incoming","Buffer","alloc","_pending","_active","Map","_onData","args","onData","_onError","onError","_onEnd","onEnd","_onTimeout","onTimeout","Promise","resolve","reject","d","create","once","run","conn","createConnection","host","_rdpConnection","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":["/* @flow */\nimport net from 'net';\nimport EventEmitter from 'events';\nimport domain from 'domain';\n\nexport type RDPRequest = {\n to: string,\n type: string,\n};\n\nexport type RDPResult = {\n from: string,\n type: string,\n};\n\nexport type Deferred = {|\n resolve: Function,\n reject: Function,\n|};\n\ntype ParseResult = {|\n data: Buffer,\n rdpMessage?: Object,\n error?: Error,\n fatal?: boolean,\n|};\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: Buffer): ParseResult {\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 function connectToFirefox(port: number): Promise<FirefoxRDPClient> {\n const client = new FirefoxRDPClient();\n return client.connect(port).then(() => client);\n}\n\nexport default class FirefoxRDPClient extends EventEmitter {\n _incoming: Buffer;\n _pending: Array<{| request: RDPRequest, deferred: Deferred |}>;\n _active: Map<string, Deferred>;\n _rdpConnection: net.Socket;\n _onData: Function;\n _onError: Function;\n _onEnd: Function;\n _onTimeout: Function;\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: number): Promise<void> {\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(): void {\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: 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: string | RDPRequest): Promise<RDPResult> {\n let request: RDPRequest;\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(): void {\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: string, deferred: Deferred): void {\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: Object): void {\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(): boolean {\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 remining data.\n return true;\n }\n\n onData(data: Buffer) {\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: 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":"AACA,OAAOA,GAAG,MAAM,KAAK;AACrB,OAAOC,YAAY,MAAM,QAAQ;AACjC,OAAOC,MAAM,MAAM,QAAQ;AAwB3B,OAAO,MAAMC,YAAY,GAAG,IAAI;AAChC,OAAO,MAAMC,YAAY,GAAG,WAAW;AAEvC,MAAMC,kBAAkB,GAAG,IAAIC,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,SAASC,eAAe,CAACC,IAAY,EAAe;EACzD,MAAMC,GAAG,GAAGD,IAAI,CAACE,QAAQ,EAAE;EAC3B,MAAMC,MAAM,GAAGF,GAAG,CAACG,OAAO,CAAC,GAAG,CAAC;EAC/B,IAAID,MAAM,GAAG,CAAC,EAAE;IACd,OAAO;MAAEH;IAAK,CAAC;EACjB;EAEA,MAAMK,OAAO,GAAGC,QAAQ,CAACL,GAAG,CAACM,KAAK,CAAC,CAAC,EAAEJ,MAAM,CAAC,CAAC;EAC9C,IAAIK,KAAK,CAACH,OAAO,CAAC,EAAE;IAClB,MAAMI,KAAK,GAAG,IAAIC,KAAK,CAAC,kCAAkC,CAAC;IAC3D,OAAO;MAAEV,IAAI;MAAES,KAAK;MAAEE,KAAK,EAAE;IAAK,CAAC;EACrC;EAEA,IAAIX,IAAI,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AM,CAACvE,KAAK,CAAE,EAAC,CAAC,CACxD;MACD;MACA,IAAIE,KAAK,EAAE;QACT,IAAI,CAACyC,UAAU,EAAE;MACnB;MACA;MACA;MACA;MACA,OAAO,CAACzC,KAAK;IACf;IAEA,IAAI,CAACG,UAAU,EAAE;MACf;MACA,OAAO,KAAK;IACd;IAEA,IAAI,CAAC4D,cAAc,CAAC5D,UAAU,CAAC;IAC/B;IACA,OAAO,IAAI;EACb;EAEAkB,MAAM,CAAChC,IAAY,EAAE;IACnB,IAAI,CAACwB,SAAS,GAAGC,MAAM,CAACwD,MAAM,CAAC,CAAC,IAAI,CAACzD,SAAS,EAAExB,IAAI,CAAC,CAAC;IACtD,OAAO,IAAI,CAAC+E,YAAY,EAAE,EAAE;MAC1B;MACA;IAAA;EAEJ;EAEA7C,OAAO,CAACzB,KAAY,EAAE;IACpB,IAAI,CAACmE,IAAI,CAAC,OAAO,EAAEnE,KAAK,CAAC;EAC3B;EAEA2B,KAAK,GAAG;IACN,IAAI,CAACwC,IAAI,CAAC,KAAK,CAAC;EAClB;EAEAtC,SAAS,GAAG;IACV,IAAI,CAACsC,IAAI,CAAC,SAAS,CAAC;EACtB;AACF"}
|
|
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","constructor","_incoming","Buffer","alloc","_pending","_active","Map","_onData","args","onData","_onError","onError","_onEnd","onEnd","_onTimeout","onTimeout","Promise","resolve","reject","d","create","once","run","conn","createConnection","host","_rdpConnection","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":["/* @flow */\nimport net from 'net';\nimport EventEmitter from 'events';\nimport domain from 'domain';\n\nexport type RDPRequest = {\n to: string,\n type: string,\n};\n\nexport type RDPResult = {\n from: string,\n type: string,\n};\n\nexport type Deferred = {|\n resolve: Function,\n reject: Function,\n|};\n\ntype ParseResult = {|\n data: Buffer,\n rdpMessage?: Object,\n error?: Error,\n fatal?: boolean,\n|};\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: Buffer): ParseResult {\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 function connectToFirefox(port: number): Promise<FirefoxRDPClient> {\n const client = new FirefoxRDPClient();\n return client.connect(port).then(() => client);\n}\n\nexport default class FirefoxRDPClient extends EventEmitter {\n _incoming: Buffer;\n _pending: Array<{| request: RDPRequest, deferred: Deferred |}>;\n _active: Map<string, Deferred>;\n _rdpConnection: net.Socket;\n _onData: Function;\n _onError: Function;\n _onEnd: Function;\n _onTimeout: Function;\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: number): Promise<void> {\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(): void {\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: 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: string | RDPRequest): Promise<RDPResult> {\n let request: RDPRequest;\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(): void {\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: string, deferred: Deferred): void {\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: Object): void {\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(): boolean {\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 remining data.\n return true;\n }\n\n onData(data: Buffer) {\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: Error) {\n this.emit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5D,UAAU,CAAC;IAC/B;IACA,OAAO,IAAI;EACb;EAEAkB,MAAMA,CAAChC,IAAY,EAAE;IACnB,IAAI,CAACwB,SAAS,GAAGC,MAAM,CAACwD,MAAM,CAAC,CAAC,IAAI,CAACzD,SAAS,EAAExB,IAAI,CAAC,CAAC;IACtD,OAAO,IAAI,CAAC+E,YAAY,EAAE,EAAE;MAC1B;MACA;IAAA;EAEJ;EAEA7C,OAAOA,CAACzB,KAAY,EAAE;IACpB,IAAI,CAACmE,IAAI,CAAC,OAAO,EAAEnE,KAAK,CAAC;EAC3B;EAEA2B,KAAKA,CAAA,EAAG;IACN,IAAI,CAACwC,IAAI,CAAC,KAAK,CAAC;EAClB;EAEAtC,SAASA,CAAA,EAAG;IACV,IAAI,CAACsC,IAAI,CAAC,SAAS,CAAC;EACtB;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"remote.js","names":["net","FirefoxRDPClient","connectToFirefox","defaultFirefoxConnector","createLogger","isErrorWithCode","RemoteTempInstallNotSupported","UsageError","WebExtError","log","import","meta","url","requestErrorToMessage","err","Error","String","error","message","RemoteFirefox","constructor","client","checkedForAddonReloading","on","debug","info","JSON","stringify","rdpError","disconnect","addonRequest","addon","request","response","to","actor","type","getAddonsActor","addonsActor","Promise","reject","installTemporaryAddon","addonPath","openDevTools","getInstalledAddon","addonId","addons","id","map","a","checkForAddonReloading","requestTypes","indexOf","supportedRequestTypes","reloadAddon","process","stdout","write","Date","toTimeString","connect","port","connectWithMaxRetries","maxRetries","retryInterval","establishConnection","lastError","retries","resolve","setTimeout","stack","findFreeTcpPort","srv","createServer","listen","freeTcpPort","address","close"],"sources":["../../src/firefox/remote.js"],"sourcesContent":["/* @flow */\nimport net from 'net';\n\nimport FirefoxRDPClient, {\n connectToFirefox as defaultFirefoxConnector,\n} from './rdp-client.js';\nimport { createLogger } from '../util/logger.js';\nimport {\n isErrorWithCode,\n RemoteTempInstallNotSupported,\n UsageError,\n WebExtError,\n} from '../errors.js';\n\nconst log = createLogger(import.meta.url);\n\nexport type FirefoxConnectorFn = (port: number) => Promise<FirefoxRDPClient>;\n\nexport type FirefoxRDPAddonActor = {|\n id: string,\n actor: string,\n|};\n\nexport type FirefoxRDPResponseError = {|\n error: string,\n message: string,\n|};\n\nexport type FirefoxRDPResponseAddon = {|\n addon: FirefoxRDPAddonActor,\n|};\n\nexport type FirefoxRDPResponseRequestTypes = {|\n requestTypes: Array<string>,\n|};\n\n// NOTE: this type aliases Object to catch any other possible response.\nexport type FirefoxRDPResponseAny = Object;\n\nexport type FirefoxRDPResponseMaybe =\n | FirefoxRDPResponseRequestTypes\n | FirefoxRDPResponseAny;\n\n// Convert a request rejection to a message string.\nfunction requestErrorToMessage(err: Error | FirefoxRDPResponseError) {\n if (err instanceof Error) {\n return String(err);\n }\n return `${err.error}: ${err.message}`;\n}\n\nexport class RemoteFirefox {\n client: Object;\n checkedForAddonReloading: boolean;\n\n constructor(client: FirefoxRDPClient) {\n this.client = client;\n this.checkedForAddonReloading = false;\n\n client.on('disconnect', () => {\n log.debug('Received \"disconnect\" from Firefox client');\n });\n client.on('end', () => {\n log.debug('Received \"end\" from Firefox client');\n });\n client.on('unsolicited-event', (info) => {\n log.debug(`Received message from client: ${JSON.stringify(info)}`);\n });\n client.on('rdp-error', (rdpError) => {\n log.debug(`Received error from client: ${JSON.stringify(rdpError)}`);\n });\n client.on('error', (error) => {\n log.debug(`Received error from client: ${String(error)}`);\n });\n }\n\n disconnect() {\n this.client.disconnect();\n }\n\n async addonRequest(\n addon: FirefoxRDPAddonActor,\n request: string\n ): Promise<FirefoxRDPResponseMaybe> {\n try {\n const response = await this.client.request({\n to: addon.actor,\n type: request,\n });\n return response;\n } catch (err) {\n log.debug(`Client responded to '${request}' request with error:`, err);\n const message = requestErrorToMessage(err);\n throw new WebExtError(`Remote Firefox: addonRequest() error: ${message}`);\n }\n }\n\n async getAddonsActor(): Promise<string> {\n try {\n // getRoot should work since Firefox 55 (bug 1352157).\n const response = await this.client.request('getRoot');\n if (response.addonsActor == null) {\n return Promise.reject(\n new RemoteTempInstallNotSupported(\n 'This version of Firefox does not provide an add-ons actor for ' +\n 'remote installation.'\n )\n );\n }\n return response.addonsActor;\n } catch (err) {\n // Fallback to listTabs otherwise, Firefox 49 - 77 (bug 1618691).\n log.debug('Falling back to listTabs because getRoot failed', err);\n }\n\n try {\n const response = await this.client.request('listTabs');\n // addonsActor was added to listTabs in Firefox 49 (bug 1273183).\n if (response.addonsActor == null) {\n log.debug(\n 'listTabs returned a falsey addonsActor: ' +\n `${JSON.stringify(response)}`\n );\n return Promise.reject(\n new RemoteTempInstallNotSupported(\n 'This is an older version of Firefox that does not provide an ' +\n 'add-ons actor for remote installation. Try Firefox 49 or ' +\n 'higher.'\n )\n );\n }\n return response.addonsActor;\n } catch (err) {\n log.debug('listTabs error', err);\n const message = requestErrorToMessage(err);\n throw new WebExtError(`Remote Firefox: listTabs() error: ${message}`);\n }\n }\n\n async installTemporaryAddon(\n addonPath: string,\n openDevTools?: boolean\n ): Promise<FirefoxRDPResponseAddon> {\n const addonsActor = await this.getAddonsActor();\n\n try {\n const response = await this.client.request({\n to: addonsActor,\n type: 'installTemporaryAddon',\n addonPath,\n openDevTools,\n });\n log.debug(`installTemporaryAddon: ${JSON.stringify(response)}`);\n log.info(`Installed ${addonPath} as a temporary add-on`);\n return response;\n } catch (err) {\n const message = requestErrorToMessage(err);\n throw new WebExtError(`installTemporaryAddon: Error: ${message}`);\n }\n }\n\n async getInstalledAddon(addonId: string): Promise<FirefoxRDPAddonActor> {\n try {\n const response = await this.client.request('listAddons');\n for (const addon of response.addons) {\n if (addon.id === addonId) {\n return addon;\n }\n }\n log.debug(\n `Remote Firefox has these addons: ${response.addons.map((a) => a.id)}`\n );\n return Promise.reject(\n new WebExtError(\n 'The remote Firefox does not have your extension installed'\n )\n );\n } catch (err) {\n const message = requestErrorToMessage(err);\n throw new WebExtError(`Remote Firefox: listAddons() error: ${message}`);\n }\n }\n\n async checkForAddonReloading(\n addon: FirefoxRDPAddonActor\n ): Promise<FirefoxRDPAddonActor> {\n if (this.checkedForAddonReloading) {\n // We only need to check once if reload() is supported.\n return addon;\n } else {\n const response = await this.addonRequest(addon, 'requestTypes');\n\n if (response.requestTypes.indexOf('reload') === -1) {\n const supportedRequestTypes = JSON.stringify(response.requestTypes);\n log.debug(`Remote Firefox only supports: ${supportedRequestTypes}`);\n throw new UsageError(\n 'This Firefox version does not support add-on reloading. ' +\n 'Re-run with --no-reload'\n );\n } else {\n this.checkedForAddonReloading = true;\n return addon;\n }\n }\n }\n\n async reloadAddon(addonId: string): Promise<void> {\n const addon = await this.getInstalledAddon(addonId);\n await this.checkForAddonReloading(addon);\n await this.addonRequest(addon, 'reload');\n process.stdout.write(\n `\\rLast extension reload: ${new Date().toTimeString()}`\n );\n log.debug('\\n');\n }\n}\n\n// Connect types and implementation\n\nexport type ConnectOptions = {\n connectToFirefox: FirefoxConnectorFn,\n};\n\nexport async function connect(\n port: number,\n { connectToFirefox = defaultFirefoxConnector }: ConnectOptions = {}\n): Promise<RemoteFirefox> {\n log.debug(`Connecting to Firefox on port ${port}`);\n const client = await connectToFirefox(port);\n log.debug(`Connected to the remote Firefox debugger on port ${port}`);\n return new RemoteFirefox(client);\n}\n\n// ConnectWithMaxRetries types and implementation\n\nexport type ConnectWithMaxRetriesParams = {|\n maxRetries?: number,\n retryInterval?: number,\n port: number,\n|};\n\nexport type ConnectWithMaxRetriesDeps = {\n connectToFirefox: typeof connect,\n};\n\nexport async function connectWithMaxRetries(\n // A max of 250 will try connecting for 30 seconds.\n { maxRetries = 250, retryInterval = 120, port }: ConnectWithMaxRetriesParams,\n { connectToFirefox = connect }: ConnectWithMaxRetriesDeps = {}\n): Promise<RemoteFirefox> {\n async function establishConnection() {\n var lastError;\n\n for (let retries = 0; retries <= maxRetries; retries++) {\n try {\n return await connectToFirefox(port);\n } catch (error) {\n if (isErrorWithCode('ECONNREFUSED', error)) {\n // Wait for `retryInterval` ms.\n await new Promise((resolve) => {\n setTimeout(resolve, retryInterval);\n });\n\n lastError = error;\n log.debug(\n `Retrying Firefox (${retries}); connection error: ${error}`\n );\n } else {\n log.error(error.stack);\n throw error;\n }\n }\n }\n\n log.debug('Connect to Firefox debugger: too many retries');\n throw lastError;\n }\n\n log.debug('Connecting to the remote Firefox debugger');\n return establishConnection();\n}\n\nexport function findFreeTcpPort(): Promise<number> {\n return new Promise((resolve) => {\n const srv = net.createServer();\n // $FlowFixMe: signature for listen() is missing - see https://github.com/facebook/flow/pull/8290\n srv.listen(0, '127.0.0.1', () => {\n const freeTcpPort = srv.address().port;\n srv.close(() => resolve(freeTcpPort));\n });\n });\n}\n"],"mappings":"AACA,OAAOA,GAAG,MAAM,KAAK;AAErB,OAAOC,gBAAgB,IACrBC,gBAAgB,IAAIC,uBAAuB,QACtC,iBAAiB;AACxB,SAASC,YAAY,QAAQ,mBAAmB;AAChD,SACEC,eAAe,EACfC,6BAA6B,EAC7BC,UAAU,EACVC,WAAW,QACN,cAAc;AAErB,MAAMC,GAAG,GAAGL,YAAY,CAACM,MAAM,CAACC,IAAI,CAACC,GAAG,CAAC;AA6BzC;AACA,SAASC,qBAAqB,CAACC,GAAoC,EAAE;EACnE,IAAIA,GAAG,YAAYC,KAAK,EAAE;IACxB,OAAOC,MAAM,CAACF,GAAG,CAAC;EACpB;EACA,OAAQ,GAAEA,GAAG,CAACG,KAAM,KAAIH,GAAG,CAACI,OAAQ,EAAC;AACvC;AAEA,OAAO,MAAMC,aAAa,CAAC;EAIzBC,WAAW,CAACC,MAAwB,EAAE;IACpC,IAAI,CAACA,MAAM,GAAGA,MAAM;IACpB,IAAI,CAACC,wBAAwB,GAAG,KAAK;IAErCD,MAAM,CAACE,EAAE,CAAC,YAAY,EAAE,MAAM;MAC5Bd,GAAG,CAACe,KAAK,CAAC,2CAA2C,CAAC;IACxD,CAAC,CAAC;IACFH,MAAM,CAACE,EAAE,CAAC,KAAK,EAAE,MAAM;MACrBd,GAAG,CAACe,KAA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;IAEb,KAAK,IAAIC,OAAO,GAAG,CAAC,EAAEA,OAAO,IAAIJ,UAAU,EAAEI,OAAO,EAAE,EAAE;MACtD,IAAI;QACF,OAAO,MAAMjE,gBAAgB,CAAC2D,IAAI,CAAC;MACrC,CAAC,CAAC,OAAO5C,KAAK,EAAE;QACd,IAAIZ,eAAe,CAAC,cAAc,EAAEY,KAAK,CAAC,EAAE;UAC1C;UACA,MAAM,IAAIsB,OAAO,CAAE6B,OAAO,IAAK;YAC7BC,UAAU,CAACD,OAAO,EAAEJ,aAAa,CAAC;UACpC,CAAC,CAAC;UAEFE,SAAS,GAAGjD,KAAK;UACjBR,GAAG,CAACe,KAAK,CACN,qBAAoB2C,OAAQ,wBAAuBlD,KAAM,EAAC,CAC5D;QACH,CAAC,MAAM;UACLR,GAAG,CAACQ,KAAK,CAACA,KAAK,CAACqD,KAAK,CAAC;UACtB,MAAMrD,KAAK;QACb;MACF;IACF;IAEAR,GAAG,CAACe,KAAK,CAAC,+CAA+C,CAAC;IAC1D,MAAM0C,SAAS;EACjB;EAEAzD,GAAG,CAACe,KAAK,CAAC,2CAA2C,CAAC;EACtD,OAAOyC,mBAAmB,EAAE;AAC9B;AAEA,OAAO,SAASM,eAAe,GAAoB;EACjD,OAAO,IAAIhC,OAAO,CAAE6B,OAAO,IAAK;IAC9B,MAAMI,GAAG,GAAGxE,GAAG,CAACyE,YAAY,EAAE;IAC9B;IACAD,GAAG,CAACE,MAAM,CAAC,CAAC,EAAE,WAAW,EAAE,MAAM;MAC/B,MAAMC,WAAW,GAAGH,GAAG,CAACI,OAAO,EAAE,CAACf,IAAI;MACtCW,GAAG,CAACK,KAAK,CAAC,MAAMT,OAAO,CAACO,WAAW,CAAC,CAAC;IACvC,CAAC,CAAC;EACJ,CAAC,CAAC;AACJ"}
|
|
1
|
+
{"version":3,"file":"remote.js","names":["net","FirefoxRDPClient","connectToFirefox","defaultFirefoxConnector","createLogger","isErrorWithCode","RemoteTempInstallNotSupported","UsageError","WebExtError","log","import","meta","url","requestErrorToMessage","err","Error","String","error","message","RemoteFirefox","constructor","client","checkedForAddonReloading","on","debug","info","JSON","stringify","rdpError","disconnect","addonRequest","addon","request","response","to","actor","type","getAddonsActor","addonsActor","Promise","reject","installTemporaryAddon","addonPath","openDevTools","getInstalledAddon","addonId","addons","id","map","a","checkForAddonReloading","requestTypes","indexOf","supportedRequestTypes","reloadAddon","process","stdout","write","Date","toTimeString","connect","port","connectWithMaxRetries","maxRetries","retryInterval","establishConnection","lastError","retries","resolve","setTimeout","stack","findFreeTcpPort","srv","createServer","listen","freeTcpPort","address","close"],"sources":["../../src/firefox/remote.js"],"sourcesContent":["/* @flow */\nimport net from 'net';\n\nimport FirefoxRDPClient, {\n connectToFirefox as defaultFirefoxConnector,\n} from './rdp-client.js';\nimport { createLogger } from '../util/logger.js';\nimport {\n isErrorWithCode,\n RemoteTempInstallNotSupported,\n UsageError,\n WebExtError,\n} from '../errors.js';\n\nconst log = createLogger(import.meta.url);\n\nexport type FirefoxConnectorFn = (port: number) => Promise<FirefoxRDPClient>;\n\nexport type FirefoxRDPAddonActor = {|\n id: string,\n actor: string,\n|};\n\nexport type FirefoxRDPResponseError = {|\n error: string,\n message: string,\n|};\n\nexport type FirefoxRDPResponseAddon = {|\n addon: FirefoxRDPAddonActor,\n|};\n\nexport type FirefoxRDPResponseRequestTypes = {|\n requestTypes: Array<string>,\n|};\n\n// NOTE: this type aliases Object to catch any other possible response.\nexport type FirefoxRDPResponseAny = Object;\n\nexport type FirefoxRDPResponseMaybe =\n | FirefoxRDPResponseRequestTypes\n | FirefoxRDPResponseAny;\n\n// Convert a request rejection to a message string.\nfunction requestErrorToMessage(err: Error | FirefoxRDPResponseError) {\n if (err instanceof Error) {\n return String(err);\n }\n return `${err.error}: ${err.message}`;\n}\n\nexport class RemoteFirefox {\n client: Object;\n checkedForAddonReloading: boolean;\n\n constructor(client: FirefoxRDPClient) {\n this.client = client;\n this.checkedForAddonReloading = false;\n\n client.on('disconnect', () => {\n log.debug('Received \"disconnect\" from Firefox client');\n });\n client.on('end', () => {\n log.debug('Received \"end\" from Firefox client');\n });\n client.on('unsolicited-event', (info) => {\n log.debug(`Received message from client: ${JSON.stringify(info)}`);\n });\n client.on('rdp-error', (rdpError) => {\n log.debug(`Received error from client: ${JSON.stringify(rdpError)}`);\n });\n client.on('error', (error) => {\n log.debug(`Received error from client: ${String(error)}`);\n });\n }\n\n disconnect() {\n this.client.disconnect();\n }\n\n async addonRequest(\n addon: FirefoxRDPAddonActor,\n request: string\n ): Promise<FirefoxRDPResponseMaybe> {\n try {\n const response = await this.client.request({\n to: addon.actor,\n type: request,\n });\n return response;\n } catch (err) {\n log.debug(`Client responded to '${request}' request with error:`, err);\n const message = requestErrorToMessage(err);\n throw new WebExtError(`Remote Firefox: addonRequest() error: ${message}`);\n }\n }\n\n async getAddonsActor(): Promise<string> {\n try {\n // getRoot should work since Firefox 55 (bug 1352157).\n const response = await this.client.request('getRoot');\n if (response.addonsActor == null) {\n return Promise.reject(\n new RemoteTempInstallNotSupported(\n 'This version of Firefox does not provide an add-ons actor for ' +\n 'remote installation.'\n )\n );\n }\n return response.addonsActor;\n } catch (err) {\n // Fallback to listTabs otherwise, Firefox 49 - 77 (bug 1618691).\n log.debug('Falling back to listTabs because getRoot failed', err);\n }\n\n try {\n const response = await this.client.request('listTabs');\n // addonsActor was added to listTabs in Firefox 49 (bug 1273183).\n if (response.addonsActor == null) {\n log.debug(\n 'listTabs returned a falsey addonsActor: ' +\n `${JSON.stringify(response)}`\n );\n return Promise.reject(\n new RemoteTempInstallNotSupported(\n 'This is an older version of Firefox that does not provide an ' +\n 'add-ons actor for remote installation. Try Firefox 49 or ' +\n 'higher.'\n )\n );\n }\n return response.addonsActor;\n } catch (err) {\n log.debug('listTabs error', err);\n const message = requestErrorToMessage(err);\n throw new WebExtError(`Remote Firefox: listTabs() error: ${message}`);\n }\n }\n\n async installTemporaryAddon(\n addonPath: string,\n openDevTools?: boolean\n ): Promise<FirefoxRDPResponseAddon> {\n const addonsActor = await this.getAddonsActor();\n\n try {\n const response = await this.client.request({\n to: addonsActor,\n type: 'installTemporaryAddon',\n addonPath,\n openDevTools,\n });\n log.debug(`installTemporaryAddon: ${JSON.stringify(response)}`);\n log.info(`Installed ${addonPath} as a temporary add-on`);\n return response;\n } catch (err) {\n const message = requestErrorToMessage(err);\n throw new WebExtError(`installTemporaryAddon: Error: ${message}`);\n }\n }\n\n async getInstalledAddon(addonId: string): Promise<FirefoxRDPAddonActor> {\n try {\n const response = await this.client.request('listAddons');\n for (const addon of response.addons) {\n if (addon.id === addonId) {\n return addon;\n }\n }\n log.debug(\n `Remote Firefox has these addons: ${response.addons.map((a) => a.id)}`\n );\n return Promise.reject(\n new WebExtError(\n 'The remote Firefox does not have your extension installed'\n )\n );\n } catch (err) {\n const message = requestErrorToMessage(err);\n throw new WebExtError(`Remote Firefox: listAddons() error: ${message}`);\n }\n }\n\n async checkForAddonReloading(\n addon: FirefoxRDPAddonActor\n ): Promise<FirefoxRDPAddonActor> {\n if (this.checkedForAddonReloading) {\n // We only need to check once if reload() is supported.\n return addon;\n } else {\n const response = await this.addonRequest(addon, 'requestTypes');\n\n if (response.requestTypes.indexOf('reload') === -1) {\n const supportedRequestTypes = JSON.stringify(response.requestTypes);\n log.debug(`Remote Firefox only supports: ${supportedRequestTypes}`);\n throw new UsageError(\n 'This Firefox version does not support add-on reloading. ' +\n 'Re-run with --no-reload'\n );\n } else {\n this.checkedForAddonReloading = true;\n return addon;\n }\n }\n }\n\n async reloadAddon(addonId: string): Promise<void> {\n const addon = await this.getInstalledAddon(addonId);\n await this.checkForAddonReloading(addon);\n await this.addonRequest(addon, 'reload');\n process.stdout.write(\n `\\rLast extension reload: ${new Date().toTimeString()}`\n );\n log.debug('\\n');\n }\n}\n\n// Connect types and implementation\n\nexport type ConnectOptions = {\n connectToFirefox: FirefoxConnectorFn,\n};\n\nexport async function connect(\n port: number,\n { connectToFirefox = defaultFirefoxConnector }: ConnectOptions = {}\n): Promise<RemoteFirefox> {\n log.debug(`Connecting to Firefox on port ${port}`);\n const client = await connectToFirefox(port);\n log.debug(`Connected to the remote Firefox debugger on port ${port}`);\n return new RemoteFirefox(client);\n}\n\n// ConnectWithMaxRetries types and implementation\n\nexport type ConnectWithMaxRetriesParams = {|\n maxRetries?: number,\n retryInterval?: number,\n port: number,\n|};\n\nexport type ConnectWithMaxRetriesDeps = {\n connectToFirefox: typeof connect,\n};\n\nexport async function connectWithMaxRetries(\n // A max of 250 will try connecting for 30 seconds.\n { maxRetries = 250, retryInterval = 120, port }: ConnectWithMaxRetriesParams,\n { connectToFirefox = connect }: ConnectWithMaxRetriesDeps = {}\n): Promise<RemoteFirefox> {\n async function establishConnection() {\n var lastError;\n\n for (let retries = 0; retries <= maxRetries; retries++) {\n try {\n return await connectToFirefox(port);\n } catch (error) {\n if (isErrorWithCode('ECONNREFUSED', error)) {\n // Wait for `retryInterval` ms.\n await new Promise((resolve) => {\n setTimeout(resolve, retryInterval);\n });\n\n lastError = error;\n log.debug(\n `Retrying Firefox (${retries}); connection error: ${error}`\n );\n } else {\n log.error(error.stack);\n throw error;\n }\n }\n }\n\n log.debug('Connect to Firefox debugger: too many retries');\n throw lastError;\n }\n\n log.debug('Connecting to the remote Firefox debugger');\n return establishConnection();\n}\n\nexport function findFreeTcpPort(): Promise<number> {\n return new Promise((resolve) => {\n const srv = net.createServer();\n // $FlowFixMe: signature for listen() is missing - see https://github.com/facebook/flow/pull/8290\n srv.listen(0, '127.0.0.1', () => {\n const freeTcpPort = srv.address().port;\n srv.close(() => resolve(freeTcpPort));\n });\n });\n}\n"],"mappings":"AACA,OAAOA,GAAG,MAAM,KAAK;AAErB,OAAOC,gBAAgB,IACrBC,gBAAgB,IAAIC,uBAAuB,QACtC,iBAAiB;AACxB,SAASC,YAAY,QAAQ,mBAAmB;AAChD,SACEC,eAAe,EACfC,6BAA6B,EAC7BC,UAAU,EACVC,WAAW,QACN,cAAc;AAErB,MAAMC,GAAG,GAAGL,YAAY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IAC1D,MAAM0C,SAAS;EACjB;EAEAzD,GAAG,CAACe,KAAK,CAAC,2CAA2C,CAAC;EACtD,OAAOyC,mBAAmB,EAAE;AAC9B;AAEA,OAAO,SAASM,eAAeA,CAAA,EAAoB;EACjD,OAAO,IAAIhC,OAAO,CAAE6B,OAAO,IAAK;IAC9B,MAAMI,GAAG,GAAGxE,GAAG,CAACyE,YAAY,EAAE;IAC9B;IACAD,GAAG,CAACE,MAAM,CAAC,CAAC,EAAE,WAAW,EAAE,MAAM;MAC/B,MAAMC,WAAW,GAAGH,GAAG,CAACI,OAAO,EAAE,CAACf,IAAI;MACtCW,GAAG,CAACK,KAAK,CAAC,MAAMT,OAAO,CAACO,WAAW,CAAC,CAAC;IACvC,CAAC,CAAC;EACJ,CAAC,CAAC;AACJ"}
|
package/lib/program.js
CHANGED
|
@@ -467,6 +467,11 @@ Example: $0 --help run.
|
|
|
467
467
|
describe: 'Number of milliseconds to wait before giving up',
|
|
468
468
|
type: 'number'
|
|
469
469
|
},
|
|
470
|
+
'disable-progress-bar': {
|
|
471
|
+
describe: 'Disable the progress bar in sign-addon',
|
|
472
|
+
demandOption: false,
|
|
473
|
+
type: 'boolean'
|
|
474
|
+
},
|
|
470
475
|
channel: {
|
|
471
476
|
describe: 'The channel for which to sign the addon. Either ' + "'listed' or 'unlisted'",
|
|
472
477
|
type: 'string'
|
|
@@ -486,7 +491,7 @@ Example: $0 --help run.
|
|
|
486
491
|
},
|
|
487
492
|
firefox: {
|
|
488
493
|
alias: ['f', 'firefox-binary'],
|
|
489
|
-
describe: 'Path or alias to a Firefox executable such as firefox-bin ' + 'or firefox.exe. ' + 'If not specified, the default Firefox will be used. ' + 'You can specify the following aliases in lieu of a path: ' + 'firefox, beta, nightly, firefoxdeveloperedition. ' + 'For Flatpak, use `flatpak:org.mozilla.firefox` where ' + '`org.mozilla.firefox` is the application ID.',
|
|
494
|
+
describe: 'Path or alias to a Firefox executable such as firefox-bin ' + 'or firefox.exe. ' + 'If not specified, the default Firefox will be used. ' + 'You can specify the following aliases in lieu of a path: ' + 'firefox, beta, nightly, firefoxdeveloperedition (or deved). ' + 'For Flatpak, use `flatpak:org.mozilla.firefox` where ' + '`org.mozilla.firefox` is the application ID.',
|
|
490
495
|
demandOption: false,
|
|
491
496
|
type: 'string'
|
|
492
497
|
},
|
package/lib/program.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"program.js","names":["os","path","readFileSync","camelCase","decamelize","yargs","Parser","yargsParser","defaultCommands","UsageError","createLogger","consoleStream","defaultLogStream","coerceCLICustomPreference","checkForUpdates","defaultUpdateChecker","discoverConfigFiles","defaultConfigDiscovery","loadJSConfigFile","defaultLoadJSConfigFile","applyConfigToArgv","defaultApplyConfigToArgv","log","import","meta","url","envPrefix","defaultGlobalEnv","AMO_BASE_URL","Program","constructor","argv","absolutePackageDir","process","cwd","slice","programArgv","yargsInstance","verboseEnabled","shouldExitProgram","parserConfiguration","strict","wrap","terminalWidth","commands","options","command","name","description","executor","commandOptions","yargsForCmd","demandCommand","undefined","exitProcess","env","setGlobalOptions","Object","keys","forEach","key","global","demandOption","enableVerboseMode","logStream","version","makeVerbose","info","getArguments","validationInstance","getInternalMethods","getValidationInstance","requiredArguments","demandedOptions","getDemandedOptions","args","err","message","startsWith","configDiscovery","noConfigDiscovery","reload","noReload","input","noInput","ignoreFiles","length","startUrl","Array","isArray","firefoxPreview","checkRequiredArguments","adjustedArgv","cleanupProcessEnvConfigs","systemProcess","cmd","_","toOptionKey","k","replace","separator","filter","optKey","globalOpt","cmdOpt","debug","execute","getVersion","defaultVersionGetter","globalEnv","runCommand","verbose","webextVersion","configFiles","discoveredConfigs","push","config","resolve","niceFileList","map","f","homedir","join","configFileName","configObject","argvFromCLI","error","stack","String","code","exit","packageData","JSON","parse","git","branch","long","throwUsageErrorIfArray","errorMessage","value","main","runOptions","program","firefoxPreviewOption","describe","type","usage","help","alias","recommendCommands","default","requiresArg","coerce","arg","normalize","hidden","build","filename","sign","id","timeout","channel","run","target","choices","firefox","pref","devtools","lint","output","metadata","pretty","privileged","boring","docs"],"sources":["../src/program.js"],"sourcesContent":["/* @flow */\nimport os from 'os';\nimport path from 'path';\nimport { readFileSync } from 'fs';\n\nimport camelCase from 'camelcase';\nimport decamelize from 'decamelize';\nimport yargs from 'yargs';\nimport { Parser as yargsParser } from 'yargs/helpers';\n\nimport defaultCommands from './cmd/index.js';\nimport { UsageError } from './errors.js';\nimport {\n createLogger,\n consoleStream as defaultLogStream,\n} from './util/logger.js';\nimport { coerceCLICustomPreference } from './firefox/preferences.js';\nimport { checkForUpdates as defaultUpdateChecker } from './util/updates.js';\nimport {\n discoverConfigFiles as defaultConfigDiscovery,\n loadJSConfigFile as defaultLoadJSConfigFile,\n applyConfigToArgv as defaultApplyConfigToArgv,\n} from './config.js';\n\nconst log = createLogger(import.meta.url);\nconst envPrefix = 'WEB_EXT';\n// Default to \"development\" (the value actually assigned will be interpolated\n// by babel-plugin-transform-inline-environment-variables).\nconst defaultGlobalEnv = process.env.WEBEXT_BUILD_ENV || 'development';\n\ntype ProgramOptions = {\n absolutePackageDir?: string,\n};\n\nexport type VersionGetterFn = (absolutePackageDir: string) => Promise<string>;\n\n// TODO: add pipes to Flow type after https://github.com/facebook/flow/issues/2405 is fixed\n\ntype ExecuteOptions = {\n checkForUpdates?: Function,\n systemProcess?: typeof process,\n logStream?: typeof defaultLogStream,\n getVersion?: VersionGetterFn,\n applyConfigToArgv?: typeof defaultApplyConfigToArgv,\n discoverConfigFiles?: typeof defaultConfigDiscovery,\n loadJSConfigFile?: typeof defaultLoadJSConfigFile,\n shouldExitProgram?: boolean,\n globalEnv?: string | void,\n};\n\nexport const AMO_BASE_URL = 'https://addons.mozilla.org/api/v5/';\n\n/*\n * The command line program.\n */\nexport class Program {\n absolutePackageDir: string;\n yargs: any;\n commands: { [key: string]: Function };\n shouldExitProgram: boolean;\n verboseEnabled: boolean;\n options: Object;\n programArgv: Array<string>;\n demandedOptions: Object;\n\n constructor(\n argv: ?Array<string>,\n { absolutePackageDir = process.cwd() }: ProgramOptions = {}\n ) {\n // This allows us to override the process argv which is useful for\n // testing.\n // NOTE: process.argv.slice(2) removes the path to node and web-ext\n // executables from the process.argv array.\n argv = argv || process.argv.slice(2);\n this.programArgv = argv;\n\n // NOTE: always initialize yargs explicitly with the package dir\n // to avoid side-effects due to yargs looking for its configuration\n // section from a package.json file stored in an arbitrary directory\n // (e.g. in tests yargs would end up loading yargs config from the\n // mocha package.json). web-ext package.json doesn't contain any yargs\n // section as it is deprecated and we configure yargs using\n // yargs.parserConfiguration. See web-ext#469 for rationale.\n const yargsInstance = yargs(argv, absolutePackageDir);\n\n this.absolutePackageDir = absolutePackageDir;\n this.verboseEnabled = false;\n this.shouldExitProgram = true;\n\n this.yargs = yargsInstance;\n this.yargs.parserConfiguration({\n 'boolean-negation': true,\n });\n this.yargs.strict();\n this.yargs.wrap(this.yargs.terminalWidth());\n\n this.commands = {};\n this.options = {};\n }\n\n command(\n name: string,\n description: string,\n executor: Function,\n commandOptions: Object = {}\n ): Program {\n this.options[camelCase(name)] = commandOptions;\n\n this.yargs.command(name, description, (yargsForCmd) => {\n if (!commandOptions) {\n return;\n }\n return (\n yargsForCmd\n // Make sure the user does not add any extra commands. For example,\n // this would be a mistake because lint does not accept arguments:\n // web-ext lint ./src/path/to/file.js\n .demandCommand(\n 0,\n 0,\n undefined,\n 'This command does not take any arguments'\n )\n .strict()\n .exitProcess(this.shouldExitProgram)\n // Calling env() will be unnecessary after\n // https://github.com/yargs/yargs/issues/486 is fixed\n .env(envPrefix)\n .options(commandOptions)\n );\n });\n this.commands[name] = executor;\n return this;\n }\n\n setGlobalOptions(options: Object): Program {\n // This is a convenience for setting global options.\n // An option is only global (i.e. available to all sub commands)\n // with the `global` flag so this makes sure every option has it.\n this.options = { ...this.options, ...options };\n Object.keys(options).forEach((key) => {\n options[key].global = true;\n if (options[key].demandOption === undefined) {\n // By default, all options should be \"demanded\" otherwise\n // yargs.strict() will think they are missing when declared.\n options[key].demandOption = true;\n }\n });\n this.yargs.options(options);\n return this;\n }\n\n enableVerboseMode(logStream: typeof defaultLogStream, version: string): void {\n if (this.verboseEnabled) {\n return;\n }\n\n logStream.makeVerbose();\n log.info('Version:', version);\n this.verboseEnabled = true;\n }\n\n // Retrieve the yargs argv object and apply any further fix needed\n // on the output of the yargs options parsing.\n getArguments(): Object {\n // To support looking up required parameters via config files, we need to\n // temporarily disable the requiredArguments validation. Otherwise yargs\n // would exit early. Validation is enforced by the checkRequiredArguments()\n // method, after reading configuration files.\n //\n // This is an undocumented internal API of yargs! Unit tests to avoid\n // regressions are located at: tests/functional/test.cli.sign.js\n //\n // Replace hack if possible: https://github.com/mozilla/web-ext/issues/1930\n const validationInstance = this.yargs\n .getInternalMethods()\n .getValidationInstance();\n const { requiredArguments } = validationInstance;\n // Initialize demandedOptions (which is going to be set to an object with one\n // property for each mandatory global options, then the arrow function below\n // will receive as its demandedOptions parameter a new one that also includes\n // all mandatory options for the sub command selected).\n this.demandedOptions = this.yargs.getDemandedOptions();\n validationInstance.requiredArguments = (args, demandedOptions) => {\n this.demandedOptions = demandedOptions;\n };\n let argv;\n try {\n argv = this.yargs.argv;\n } catch (err) {\n if (\n err.name === 'YError' &&\n err.message.startsWith('Unknown argument: ')\n ) {\n throw new UsageError(err.message);\n }\n throw err;\n }\n validationInstance.requiredArguments = requiredArguments;\n\n // Yargs boolean options doesn't define the no* counterpart\n // with negate-boolean on Yargs 15. Define as expected by the\n // web-ext execute method.\n if (argv.configDiscovery != null) {\n argv.noConfigDiscovery = !argv.configDiscovery;\n }\n if (argv.reload != null) {\n argv.noReload = !argv.reload;\n }\n\n // Yargs doesn't accept --no-input as a valid option if there isn't a\n // --input option defined to be negated, to fix that the --input is\n // defined and hidden from the yargs help output and we define here\n // the negated argument name that we expect to be set in the parsed\n // arguments (and fix https://github.com/mozilla/web-ext/issues/1860).\n if (argv.input != null) {\n argv.noInput = !argv.input;\n }\n\n // Replacement for the \"requiresArg: true\" parameter until the following bug\n // is fixed: https://github.com/yargs/yargs/issues/1098\n if (argv.ignoreFiles && !argv.ignoreFiles.length) {\n throw new UsageError('Not enough arguments following: ignore-files');\n }\n\n if (argv.startUrl && !argv.startUrl.length) {\n throw new UsageError('Not enough arguments following: start-url');\n }\n\n if (Array.isArray(argv.firefoxPreview) && !argv.firefoxPreview.length) {\n argv.firefoxPreview = ['mv3'];\n }\n\n return argv;\n }\n\n // getArguments() disables validation of required parameters, to allow us to\n // read parameters from config files first. Before the program continues, it\n // must call checkRequiredArguments() to ensure that required parameters are\n // defined (in the CLI or in a config file).\n checkRequiredArguments(adjustedArgv: Object): void {\n const validationInstance = this.yargs\n .getInternalMethods()\n .getValidationInstance();\n validationInstance.requiredArguments(adjustedArgv, this.demandedOptions);\n }\n\n // Remove WEB_EXT_* environment vars that are not a global cli options\n // or an option supported by the current command (See #793).\n cleanupProcessEnvConfigs(systemProcess: typeof process) {\n const cmd = yargsParser(this.programArgv)._[0];\n const env = systemProcess.env || {};\n const toOptionKey = (k) =>\n decamelize(camelCase(k.replace(envPrefix, '')), { separator: '-' });\n\n if (cmd) {\n Object.keys(env)\n .filter((k) => k.startsWith(envPrefix))\n .forEach((k) => {\n const optKey = toOptionKey(k);\n const globalOpt = this.options[optKey];\n const cmdOpt = this.options[cmd] && this.options[cmd][optKey];\n\n if (!globalOpt && !cmdOpt) {\n log.debug(`Environment ${k} not supported by web-ext ${cmd}`);\n delete env[k];\n }\n });\n }\n }\n\n async execute({\n checkForUpdates = defaultUpdateChecker,\n systemProcess = process,\n logStream = defaultLogStream,\n getVersion = defaultVersionGetter,\n applyConfigToArgv = defaultApplyConfigToArgv,\n discoverConfigFiles = defaultConfigDiscovery,\n loadJSConfigFile = defaultLoadJSConfigFile,\n shouldExitProgram = true,\n globalEnv = defaultGlobalEnv,\n }: ExecuteOptions = {}): Promise<void> {\n this.shouldExitProgram = shouldExitProgram;\n this.yargs.exitProcess(this.shouldExitProgram);\n\n this.cleanupProcessEnvConfigs(systemProcess);\n const argv = this.getArguments();\n\n const cmd = argv._[0];\n\n const version = await getVersion(this.absolutePackageDir);\n const runCommand = this.commands[cmd];\n\n if (argv.verbose) {\n this.enableVerboseMode(logStream, version);\n }\n\n let adjustedArgv = { ...argv, webextVersion: version };\n\n try {\n if (cmd === undefined) {\n throw new UsageError('No sub-command was specified in the args');\n }\n if (!runCommand) {\n throw new UsageError(`Unknown command: ${cmd}`);\n }\n if (globalEnv === 'production') {\n checkForUpdates({ version });\n }\n\n const configFiles = [];\n\n if (argv.configDiscovery) {\n log.debug(\n 'Discovering config files. ' + 'Set --no-config-discovery to disable'\n );\n const discoveredConfigs = await discoverConfigFiles();\n configFiles.push(...discoveredConfigs);\n } else {\n log.debug('Not discovering config files');\n }\n\n if (argv.config) {\n configFiles.push(path.resolve(argv.config));\n }\n\n if (configFiles.length) {\n const niceFileList = configFiles\n .map((f) => f.replace(process.cwd(), '.'))\n .map((f) => f.replace(os.homedir(), '~'))\n .join(', ');\n log.info(\n 'Applying config file' +\n `${configFiles.length !== 1 ? 's' : ''}: ` +\n `${niceFileList}`\n );\n }\n\n configFiles.forEach((configFileName) => {\n const configObject = loadJSConfigFile(configFileName);\n adjustedArgv = applyConfigToArgv({\n argv: adjustedArgv,\n argvFromCLI: argv,\n configFileName,\n configObject,\n options: this.options,\n });\n });\n\n if (adjustedArgv.verbose) {\n // Ensure that the verbose is enabled when specified in a config file.\n this.enableVerboseMode(logStream, version);\n }\n\n this.checkRequiredArguments(adjustedArgv);\n\n await runCommand(adjustedArgv, { shouldExitProgram });\n } catch (error) {\n if (!(error instanceof UsageError) || adjustedArgv.verbose) {\n log.error(`\\n${error.stack}\\n`);\n } else {\n log.error(`\\n${String(error)}\\n`);\n }\n if (error.code) {\n log.error(`Error code: ${error.code}\\n`);\n }\n\n log.debug(`Command executed: ${cmd}`);\n\n if (this.shouldExitProgram) {\n systemProcess.exit(1);\n } else {\n throw error;\n }\n }\n }\n}\n\n//A defintion of type of argument for defaultVersionGetter\ntype VersionGetterOptions = {\n globalEnv?: string,\n};\n\nexport async function defaultVersionGetter(\n absolutePackageDir: string,\n { globalEnv = defaultGlobalEnv }: VersionGetterOptions = {}\n): Promise<string> {\n if (globalEnv === 'production') {\n log.debug('Getting the version from package.json');\n const packageData: any = readFileSync(\n path.join(absolutePackageDir, 'package.json')\n );\n return JSON.parse(packageData).version;\n } else {\n log.debug('Getting version from the git revision');\n // This branch is only reached during development.\n // git-rev-sync is in devDependencies, and lazily imported using require.\n // This also avoids logspam from https://github.com/mozilla/web-ext/issues/1916\n // eslint-disable-next-line import/no-extraneous-dependencies\n const git = await import('git-rev-sync');\n return `${git.branch(absolutePackageDir)}-${git.long(absolutePackageDir)}`;\n }\n}\n\n// TODO: add pipes to Flow type after https://github.com/facebook/flow/issues/2405 is fixed\n\ntype MainParams = {\n getVersion?: VersionGetterFn,\n commands?: Object,\n argv: Array<any>,\n runOptions?: Object,\n};\n\nexport function throwUsageErrorIfArray(errorMessage: string): any {\n return (value: any): any => {\n if (Array.isArray(value)) {\n throw new UsageError(errorMessage);\n }\n return value;\n };\n}\n\nexport async function main(\n absolutePackageDir: string,\n {\n getVersion = defaultVersionGetter,\n commands = defaultCommands,\n argv,\n runOptions = {},\n }: MainParams = {}\n): Promise<any> {\n const program = new Program(argv, { absolutePackageDir });\n const version = await getVersion(absolutePackageDir);\n\n // This is an option shared by some commands but not all of them, hence why\n // it isn't a global option.\n const firefoxPreviewOption = {\n describe:\n 'Turn on developer preview features in Firefox' + ' (defaults to \"mv3\")',\n demandOption: false,\n type: 'array',\n };\n\n // yargs uses magic camel case expansion to expose options on the\n // final argv object. For example, the 'artifacts-dir' option is alternatively\n // available as argv.artifactsDir.\n program.yargs\n .usage(\n `Usage: $0 [options] command\n\nOption values can also be set by declaring an environment variable prefixed\nwith $${envPrefix}_. For example: $${envPrefix}_SOURCE_DIR=/path is the same as\n--source-dir=/path.\n\nTo view specific help for any given command, add the command name.\nExample: $0 --help run.\n`\n )\n .help('help')\n .alias('h', 'help')\n .env(envPrefix)\n .version(version)\n .demandCommand(1, 'You must specify a command')\n .strict()\n .recommendCommands();\n\n program.setGlobalOptions({\n 'source-dir': {\n alias: 's',\n describe: 'Web extension source directory.',\n default: process.cwd(),\n requiresArg: true,\n type: 'string',\n coerce: (arg) => (arg != null ? path.resolve(arg) : undefined),\n },\n 'artifacts-dir': {\n alias: 'a',\n describe: 'Directory where artifacts will be saved.',\n default: path.join(process.cwd(), 'web-ext-artifacts'),\n normalize: true,\n requiresArg: true,\n type: 'string',\n },\n verbose: {\n alias: 'v',\n describe: 'Show verbose output',\n type: 'boolean',\n demandOption: false,\n },\n 'ignore-files': {\n alias: 'i',\n describe:\n 'A list of glob patterns to define which files should be ' +\n 'ignored. (Example: --ignore-files=path/to/first.js ' +\n 'path/to/second.js \"**/*.log\")',\n demandOption: false,\n // The following option prevents yargs>=11 from parsing multiple values,\n // so the minimum value requirement is enforced in execute instead.\n // Upstream bug: https://github.com/yargs/yargs/issues/1098\n // requiresArg: true,\n type: 'array',\n },\n 'no-input': {\n describe: 'Disable all features that require standard input',\n type: 'boolean',\n demandOption: false,\n },\n input: {\n // This option is defined to make yargs to accept the --no-input\n // defined above, but we hide it from the yargs help output.\n hidden: true,\n type: 'boolean',\n demandOption: false,\n },\n config: {\n alias: 'c',\n describe: 'Path to a CommonJS config file to set ' + 'option defaults',\n default: undefined,\n demandOption: false,\n requiresArg: true,\n type: 'string',\n },\n 'config-discovery': {\n describe:\n 'Discover config files in home directory and ' +\n 'working directory. Disable with --no-config-discovery.',\n demandOption: false,\n default: true,\n type: 'boolean',\n },\n });\n\n program\n .command(\n 'build',\n 'Create an extension package from source',\n commands.build,\n {\n 'as-needed': {\n describe: 'Watch for file changes and re-build as needed',\n type: 'boolean',\n },\n filename: {\n alias: 'n',\n describe: 'Name of the created extension package file.',\n default: undefined,\n normalize: false,\n demandOption: false,\n requiresArg: true,\n type: 'string',\n coerce: (arg) =>\n arg == null\n ? undefined\n : throwUsageErrorIfArray(\n 'Multiple --filename/-n option are not allowed'\n )(arg),\n },\n 'overwrite-dest': {\n alias: 'o',\n describe: 'Overwrite destination package if it exists.',\n type: 'boolean',\n },\n }\n )\n .command(\n 'sign',\n 'Sign the extension so it can be installed in Firefox',\n commands.sign,\n {\n 'amo-base-url': {\n describe:\n 'Signing API URL prefix - only used with `use-submission-api`',\n default: AMO_BASE_URL,\n demandOption: true,\n type: 'string',\n },\n 'api-key': {\n describe: 'API key (JWT issuer) from addons.mozilla.org',\n demandOption: true,\n type: 'string',\n },\n 'api-secret': {\n describe: 'API secret (JWT secret) from addons.mozilla.org',\n demandOption: true,\n type: 'string',\n },\n 'api-url-prefix': {\n describe: 'Signing API URL prefix',\n default: 'https://addons.mozilla.org/api/v4',\n demandOption: true,\n type: 'string',\n },\n 'api-proxy': {\n describe:\n 'Use a proxy to access the signing API. ' +\n 'Example: https://yourproxy:6000 ',\n demandOption: false,\n type: 'string',\n },\n 'use-submission-api': {\n describe: 'Sign using the addon submission API',\n demandOption: false,\n type: 'boolean',\n },\n id: {\n describe:\n 'A custom ID for the extension. This has no effect if the ' +\n 'extension already declares an explicit ID in its manifest.',\n demandOption: false,\n type: 'string',\n },\n timeout: {\n describe: 'Number of milliseconds to wait before giving up',\n type: 'number',\n },\n channel: {\n describe:\n 'The channel for which to sign the addon. Either ' +\n \"'listed' or 'unlisted'\",\n type: 'string',\n },\n 'amo-metadata': {\n describe:\n 'Path to a JSON file containing an object with metadata ' +\n 'to be passed to the API. ' +\n 'See https://addons-server.readthedocs.io' +\n '/en/latest/topics/api/addons.html for details. ' +\n 'Only used with `use-submission-api`',\n type: 'string',\n },\n }\n )\n .command('run', 'Run the extension', commands.run, {\n target: {\n alias: 't',\n describe:\n 'The extensions runners to enable. Specify this option ' +\n 'multiple times to run against multiple targets.',\n default: 'firefox-desktop',\n demandOption: false,\n type: 'array',\n choices: ['firefox-desktop', 'firefox-android', 'chromium'],\n },\n firefox: {\n alias: ['f', 'firefox-binary'],\n describe:\n 'Path or alias to a Firefox executable such as firefox-bin ' +\n 'or firefox.exe. ' +\n 'If not specified, the default Firefox will be used. ' +\n 'You can specify the following aliases in lieu of a path: ' +\n 'firefox, beta, nightly, firefoxdeveloperedition. ' +\n 'For Flatpak, use `flatpak:org.mozilla.firefox` where ' +\n '`org.mozilla.firefox` is the application ID.',\n demandOption: false,\n type: 'string',\n },\n 'firefox-profile': {\n alias: 'p',\n describe:\n 'Run Firefox using a copy of this profile. The profile ' +\n 'can be specified as a directory or a name, such as one ' +\n 'you would see in the Profile Manager. If not specified, ' +\n 'a new temporary profile will be created.',\n demandOption: false,\n type: 'string',\n },\n 'chromium-binary': {\n describe:\n 'Path or alias to a Chromium executable such as ' +\n 'google-chrome, google-chrome.exe or opera.exe etc. ' +\n 'If not specified, the default Google Chrome will be used.',\n demandOption: false,\n type: 'string',\n },\n 'chromium-profile': {\n describe: 'Path to a custom Chromium profile',\n demandOption: false,\n type: 'string',\n },\n 'profile-create-if-missing': {\n describe: 'Create the profile directory if it does not already exist',\n demandOption: false,\n type: 'boolean',\n },\n 'keep-profile-changes': {\n describe:\n 'Run Firefox directly in custom profile. Any changes to ' +\n 'the profile will be saved.',\n demandOption: false,\n type: 'boolean',\n },\n reload: {\n describe:\n 'Reload the extension when source files change.' +\n 'Disable with --no-reload.',\n demandOption: false,\n default: true,\n type: 'boolean',\n },\n 'watch-file': {\n alias: ['watch-files'],\n describe:\n 'Reload the extension only when the contents of this' +\n ' file changes. This is useful if you use a custom' +\n ' build process for your extension',\n demandOption: false,\n type: 'array',\n },\n 'watch-ignored': {\n describe:\n 'Paths and globs patterns that should not be ' +\n 'watched for changes. This is useful if you want ' +\n 'to explicitly prevent web-ext from watching part ' +\n 'of the extension directory tree, ' +\n 'e.g. the node_modules folder.',\n demandOption: false,\n type: 'array',\n },\n 'pre-install': {\n describe:\n 'Pre-install the extension into the profile before ' +\n 'startup. This is only needed to support older versions ' +\n 'of Firefox.',\n demandOption: false,\n type: 'boolean',\n },\n pref: {\n describe:\n 'Launch firefox with a custom preference ' +\n '(example: --pref=general.useragent.locale=fr-FR). ' +\n 'You can repeat this option to set more than one ' +\n 'preference.',\n demandOption: false,\n requiresArg: true,\n type: 'array',\n coerce: (arg) =>\n arg != null ? coerceCLICustomPreference(arg) : undefined,\n },\n 'start-url': {\n alias: ['u', 'url'],\n describe: 'Launch firefox at specified page',\n demandOption: false,\n type: 'array',\n },\n devtools: {\n describe:\n 'Open the DevTools for the installed add-on ' +\n '(Firefox 106 and later)',\n demandOption: false,\n type: 'boolean',\n },\n 'browser-console': {\n alias: ['bc'],\n describe: 'Open the DevTools Browser Console.',\n demandOption: false,\n type: 'boolean',\n },\n args: {\n alias: ['arg'],\n describe: 'Additional CLI options passed to the Browser binary',\n demandOption: false,\n type: 'array',\n },\n 'firefox-preview': firefoxPreviewOption,\n // Firefox for Android CLI options.\n 'adb-bin': {\n describe: 'Specify a custom path to the adb binary',\n demandOption: false,\n type: 'string',\n requiresArg: true,\n },\n 'adb-host': {\n describe: 'Connect to adb on the specified host',\n demandOption: false,\n type: 'string',\n requiresArg: true,\n },\n 'adb-port': {\n describe: 'Connect to adb on the specified port',\n demandOption: false,\n type: 'string',\n requiresArg: true,\n },\n 'adb-device': {\n alias: ['android-device'],\n describe: 'Connect to the specified adb device name',\n demandOption: false,\n type: 'string',\n requiresArg: true,\n },\n 'adb-discovery-timeout': {\n describe: 'Number of milliseconds to wait before giving up',\n demandOption: false,\n type: 'number',\n requiresArg: true,\n },\n 'adb-remove-old-artifacts': {\n describe: 'Remove old artifacts directories from the adb device',\n demandOption: false,\n type: 'boolean',\n },\n 'firefox-apk': {\n describe:\n 'Run a specific Firefox for Android APK. ' +\n 'Example: org.mozilla.fennec_aurora',\n demandOption: false,\n type: 'string',\n requiresArg: true,\n },\n 'firefox-apk-component': {\n describe:\n 'Run a specific Android Component (defaults to <firefox-apk>/.App)',\n demandOption: false,\n type: 'string',\n requiresArg: true,\n },\n })\n .command('lint', 'Validate the extension source', commands.lint, {\n output: {\n alias: 'o',\n describe: 'The type of output to generate',\n type: 'string',\n default: 'text',\n choices: ['json', 'text'],\n },\n metadata: {\n describe: 'Output only metadata as JSON',\n type: 'boolean',\n default: false,\n },\n 'warnings-as-errors': {\n describe: 'Treat warnings as errors by exiting non-zero for warnings',\n alias: 'w',\n type: 'boolean',\n default: false,\n },\n pretty: {\n describe: 'Prettify JSON output',\n type: 'boolean',\n default: false,\n },\n privileged: {\n describe: 'Treat your extension as a privileged extension',\n type: 'boolean',\n default: false,\n },\n 'self-hosted': {\n describe:\n 'Your extension will be self-hosted. This disables messages ' +\n 'related to hosting on addons.mozilla.org.',\n type: 'boolean',\n default: false,\n },\n boring: {\n describe: 'Disables colorful shell output',\n type: 'boolean',\n default: false,\n },\n 'firefox-preview': firefoxPreviewOption,\n })\n .command(\n 'docs',\n 'Open the web-ext documentation in a browser',\n commands.docs,\n {}\n );\n\n return program.execute({ getVersion, ...runOptions });\n}\n"],"mappings":"AACA,OAAOA,EAAE,MAAM,IAAI;AACnB,OAAOC,IAAI,MAAM,MAAM;AACvB,SAASC,YAAY,QAAQ,IAAI;AAEjC,OAAOC,SAAS,MAAM,WAAW;AACjC,OAAOC,UAAU,MAAM,YAAY;AACnC,OAAOC,KAAK,MAAM,OAAO;AACzB,SAASC,MAAM,IAAIC,WAAW,QAAQ,eAAe;AAErD,OAAOC,eAAe,MAAM,gBAAgB;AAC5C,SAASC,UAAU,QAAQ,aAAa;AACxC,SACEC,YAAY,EACZC,aAAa,IAAIC,gBAAgB,QAC5B,kBAAkB;AACzB,SAASC,yBAAyB,QAAQ,0BAA0B;AACpE,SAASC,eAAe,IAAIC,oBAAoB,QAAQ,mBAAmB;AAC3E,SACEC,mBAAmB,IAAIC,sBAAsB,EAC7CC,gBAAgB,IAAIC,uBAAuB,EAC3CC,iBAAiB,IAAIC,wBAAwB,QACxC,aAAa;AAEpB,MAAMC,GAAG,GAAGZ,YAAY,CAACa,MAAM,CAACC,IAAI,CAACC,GAAG,CAAC;AAC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IACf;EACF,CAAC,CAAC,CACDzG,OAAO,CAAC,MAAM,EAAE,+BAA+B,EAAEF,QAAQ,CAAC4H,IAAI,EAAE;IAC/DC,MAAM,EAAE;MACNrB,KAAK,EAAE,GAAG;MACVJ,QAAQ,EAAE,gCAAgC;MAC1CC,IAAI,EAAE,QAAQ;MACdK,OAAO,EAAE,MAAM;MACfc,OAAO,EAAE,CAAC,MAAM,EAAE,MAAM;IAC1B,CAAC;IACDM,QAAQ,EAAE;MACR1B,QAAQ,EAAE,8BAA8B;MACxCC,IAAI,EAAE,SAAS;MACfK,OAAO,EAAE;IACX,CAAC;IACD,oBAAoB,EAAE;MACpBN,QAAQ,EAAE,2DAA2D;MACrEI,KAAK,EAAE,GAAG;MACVH,IAAI,EAAE,SAAS;MACfK,OAAO,EAAE;IACX,CAAC;IACDqB,MAAM,EAAE;MACN3B,QAAQ,EAAE,sBAAsB;MAChCC,IAAI,EAAE,SAAS;MACfK,OAAO,EAAE;IACX,CAAC;IACDsB,UAAU,EAAE;MACV5B,QAAQ,EAAE,gDAAgD;MAC1DC,IAAI,EAAE,SAAS;MACfK,OAAO,EAAE;IACX,CAAC;IACD,aAAa,EAAE;MACbN,QAAQ,EACN,6DAA6D,GAC7D,2CAA2C;MAC7CC,IAAI,EAAE,SAAS;MACfK,OAAO,EAAE;IACX,CAAC;IACDuB,MAAM,EAAE;MACN7B,QAAQ,EAAE,gCAAgC;MAC1CC,IAAI,EAAE,SAAS;MACfK,OAAO,EAAE;IACX,CAAC;IACD,iBAAiB,EAAEP;EACrB,CAAC,CAAC,CACDjG,OAAO,CACN,MAAM,EACN,6CAA6C,EAC7CF,QAAQ,CAACkI,IAAI,EACb,CAAC,CAAC,CACH;EAEH,OAAOhC,OAAO,CAACpC,OAAO,CAAC;IAAEC,UAAU;IAAE,GAAGkC;EAAW,CAAC,CAAC;AACvD"}
|
|
1
|
+
{"version":3,"file":"program.js","names":["os","path","readFileSync","camelCase","decamelize","yargs","Parser","yargsParser","defaultCommands","UsageError","createLogger","consoleStream","defaultLogStream","coerceCLICustomPreference","checkForUpdates","defaultUpdateChecker","discoverConfigFiles","defaultConfigDiscovery","loadJSConfigFile","defaultLoadJSConfigFile","applyConfigToArgv","defaultApplyConfigToArgv","log","import","meta","url","envPrefix","defaultGlobalEnv","AMO_BASE_URL","Program","constructor","argv","absolutePackageDir","process","cwd","slice","programArgv","yargsInstance","verboseEnabled","shouldExitProgram","parserConfiguration","strict","wrap","terminalWidth","commands","options","command","name","description","executor","commandOptions","yargsForCmd","demandCommand","undefined","exitProcess","env","setGlobalOptions","Object","keys","forEach","key","global","demandOption","enableVerboseMode","logStream","version","makeVerbose","info","getArguments","validationInstance","getInternalMethods","getValidationInstance","requiredArguments","demandedOptions","getDemandedOptions","args","err","message","startsWith","configDiscovery","noConfigDiscovery","reload","noReload","input","noInput","ignoreFiles","length","startUrl","Array","isArray","firefoxPreview","checkRequiredArguments","adjustedArgv","cleanupProcessEnvConfigs","systemProcess","cmd","_","toOptionKey","k","replace","separator","filter","optKey","globalOpt","cmdOpt","debug","execute","getVersion","defaultVersionGetter","globalEnv","runCommand","verbose","webextVersion","configFiles","discoveredConfigs","push","config","resolve","niceFileList","map","f","homedir","join","configFileName","configObject","argvFromCLI","error","stack","String","code","exit","packageData","JSON","parse","git","branch","long","throwUsageErrorIfArray","errorMessage","value","main","runOptions","program","firefoxPreviewOption","describe","type","usage","help","alias","recommendCommands","default","requiresArg","coerce","arg","normalize","hidden","build","filename","sign","id","timeout","channel","run","target","choices","firefox","pref","devtools","lint","output","metadata","pretty","privileged","boring","docs"],"sources":["../src/program.js"],"sourcesContent":["/* @flow */\nimport os from 'os';\nimport path from 'path';\nimport { readFileSync } from 'fs';\n\nimport camelCase from 'camelcase';\nimport decamelize from 'decamelize';\nimport yargs from 'yargs';\nimport { Parser as yargsParser } from 'yargs/helpers';\n\nimport defaultCommands from './cmd/index.js';\nimport { UsageError } from './errors.js';\nimport {\n createLogger,\n consoleStream as defaultLogStream,\n} from './util/logger.js';\nimport { coerceCLICustomPreference } from './firefox/preferences.js';\nimport { checkForUpdates as defaultUpdateChecker } from './util/updates.js';\nimport {\n discoverConfigFiles as defaultConfigDiscovery,\n loadJSConfigFile as defaultLoadJSConfigFile,\n applyConfigToArgv as defaultApplyConfigToArgv,\n} from './config.js';\n\nconst log = createLogger(import.meta.url);\nconst envPrefix = 'WEB_EXT';\n// Default to \"development\" (the value actually assigned will be interpolated\n// by babel-plugin-transform-inline-environment-variables).\nconst defaultGlobalEnv = process.env.WEBEXT_BUILD_ENV || 'development';\n\ntype ProgramOptions = {\n absolutePackageDir?: string,\n};\n\nexport type VersionGetterFn = (absolutePackageDir: string) => Promise<string>;\n\n// TODO: add pipes to Flow type after https://github.com/facebook/flow/issues/2405 is fixed\n\ntype ExecuteOptions = {\n checkForUpdates?: Function,\n systemProcess?: typeof process,\n logStream?: typeof defaultLogStream,\n getVersion?: VersionGetterFn,\n applyConfigToArgv?: typeof defaultApplyConfigToArgv,\n discoverConfigFiles?: typeof defaultConfigDiscovery,\n loadJSConfigFile?: typeof defaultLoadJSConfigFile,\n shouldExitProgram?: boolean,\n globalEnv?: string | void,\n};\n\nexport const AMO_BASE_URL = 'https://addons.mozilla.org/api/v5/';\n\n/*\n * The command line program.\n */\nexport class Program {\n absolutePackageDir: string;\n yargs: any;\n commands: { [key: string]: Function };\n shouldExitProgram: boolean;\n verboseEnabled: boolean;\n options: Object;\n programArgv: Array<string>;\n demandedOptions: Object;\n\n constructor(\n argv: ?Array<string>,\n { absolutePackageDir = process.cwd() }: ProgramOptions = {}\n ) {\n // This allows us to override the process argv which is useful for\n // testing.\n // NOTE: process.argv.slice(2) removes the path to node and web-ext\n // executables from the process.argv array.\n argv = argv || process.argv.slice(2);\n this.programArgv = argv;\n\n // NOTE: always initialize yargs explicitly with the package dir\n // to avoid side-effects due to yargs looking for its configuration\n // section from a package.json file stored in an arbitrary directory\n // (e.g. in tests yargs would end up loading yargs config from the\n // mocha package.json). web-ext package.json doesn't contain any yargs\n // section as it is deprecated and we configure yargs using\n // yargs.parserConfiguration. See web-ext#469 for rationale.\n const yargsInstance = yargs(argv, absolutePackageDir);\n\n this.absolutePackageDir = absolutePackageDir;\n this.verboseEnabled = false;\n this.shouldExitProgram = true;\n\n this.yargs = yargsInstance;\n this.yargs.parserConfiguration({\n 'boolean-negation': true,\n });\n this.yargs.strict();\n this.yargs.wrap(this.yargs.terminalWidth());\n\n this.commands = {};\n this.options = {};\n }\n\n command(\n name: string,\n description: string,\n executor: Function,\n commandOptions: Object = {}\n ): Program {\n this.options[camelCase(name)] = commandOptions;\n\n this.yargs.command(name, description, (yargsForCmd) => {\n if (!commandOptions) {\n return;\n }\n return (\n yargsForCmd\n // Make sure the user does not add any extra commands. For example,\n // this would be a mistake because lint does not accept arguments:\n // web-ext lint ./src/path/to/file.js\n .demandCommand(\n 0,\n 0,\n undefined,\n 'This command does not take any arguments'\n )\n .strict()\n .exitProcess(this.shouldExitProgram)\n // Calling env() will be unnecessary after\n // https://github.com/yargs/yargs/issues/486 is fixed\n .env(envPrefix)\n .options(commandOptions)\n );\n });\n this.commands[name] = executor;\n return this;\n }\n\n setGlobalOptions(options: Object): Program {\n // This is a convenience for setting global options.\n // An option is only global (i.e. available to all sub commands)\n // with the `global` flag so this makes sure every option has it.\n this.options = { ...this.options, ...options };\n Object.keys(options).forEach((key) => {\n options[key].global = true;\n if (options[key].demandOption === undefined) {\n // By default, all options should be \"demanded\" otherwise\n // yargs.strict() will think they are missing when declared.\n options[key].demandOption = true;\n }\n });\n this.yargs.options(options);\n return this;\n }\n\n enableVerboseMode(logStream: typeof defaultLogStream, version: string): void {\n if (this.verboseEnabled) {\n return;\n }\n\n logStream.makeVerbose();\n log.info('Version:', version);\n this.verboseEnabled = true;\n }\n\n // Retrieve the yargs argv object and apply any further fix needed\n // on the output of the yargs options parsing.\n getArguments(): Object {\n // To support looking up required parameters via config files, we need to\n // temporarily disable the requiredArguments validation. Otherwise yargs\n // would exit early. Validation is enforced by the checkRequiredArguments()\n // method, after reading configuration files.\n //\n // This is an undocumented internal API of yargs! Unit tests to avoid\n // regressions are located at: tests/functional/test.cli.sign.js\n //\n // Replace hack if possible: https://github.com/mozilla/web-ext/issues/1930\n const validationInstance = this.yargs\n .getInternalMethods()\n .getValidationInstance();\n const { requiredArguments } = validationInstance;\n // Initialize demandedOptions (which is going to be set to an object with one\n // property for each mandatory global options, then the arrow function below\n // will receive as its demandedOptions parameter a new one that also includes\n // all mandatory options for the sub command selected).\n this.demandedOptions = this.yargs.getDemandedOptions();\n validationInstance.requiredArguments = (args, demandedOptions) => {\n this.demandedOptions = demandedOptions;\n };\n let argv;\n try {\n argv = this.yargs.argv;\n } catch (err) {\n if (\n err.name === 'YError' &&\n err.message.startsWith('Unknown argument: ')\n ) {\n throw new UsageError(err.message);\n }\n throw err;\n }\n validationInstance.requiredArguments = requiredArguments;\n\n // Yargs boolean options doesn't define the no* counterpart\n // with negate-boolean on Yargs 15. Define as expected by the\n // web-ext execute method.\n if (argv.configDiscovery != null) {\n argv.noConfigDiscovery = !argv.configDiscovery;\n }\n if (argv.reload != null) {\n argv.noReload = !argv.reload;\n }\n\n // Yargs doesn't accept --no-input as a valid option if there isn't a\n // --input option defined to be negated, to fix that the --input is\n // defined and hidden from the yargs help output and we define here\n // the negated argument name that we expect to be set in the parsed\n // arguments (and fix https://github.com/mozilla/web-ext/issues/1860).\n if (argv.input != null) {\n argv.noInput = !argv.input;\n }\n\n // Replacement for the \"requiresArg: true\" parameter until the following bug\n // is fixed: https://github.com/yargs/yargs/issues/1098\n if (argv.ignoreFiles && !argv.ignoreFiles.length) {\n throw new UsageError('Not enough arguments following: ignore-files');\n }\n\n if (argv.startUrl && !argv.startUrl.length) {\n throw new UsageError('Not enough arguments following: start-url');\n }\n\n if (Array.isArray(argv.firefoxPreview) && !argv.firefoxPreview.length) {\n argv.firefoxPreview = ['mv3'];\n }\n\n return argv;\n }\n\n // getArguments() disables validation of required parameters, to allow us to\n // read parameters from config files first. Before the program continues, it\n // must call checkRequiredArguments() to ensure that required parameters are\n // defined (in the CLI or in a config file).\n checkRequiredArguments(adjustedArgv: Object): void {\n const validationInstance = this.yargs\n .getInternalMethods()\n .getValidationInstance();\n validationInstance.requiredArguments(adjustedArgv, this.demandedOptions);\n }\n\n // Remove WEB_EXT_* environment vars that are not a global cli options\n // or an option supported by the current command (See #793).\n cleanupProcessEnvConfigs(systemProcess: typeof process) {\n const cmd = yargsParser(this.programArgv)._[0];\n const env = systemProcess.env || {};\n const toOptionKey = (k) =>\n decamelize(camelCase(k.replace(envPrefix, '')), { separator: '-' });\n\n if (cmd) {\n Object.keys(env)\n .filter((k) => k.startsWith(envPrefix))\n .forEach((k) => {\n const optKey = toOptionKey(k);\n const globalOpt = this.options[optKey];\n const cmdOpt = this.options[cmd] && this.options[cmd][optKey];\n\n if (!globalOpt && !cmdOpt) {\n log.debug(`Environment ${k} not supported by web-ext ${cmd}`);\n delete env[k];\n }\n });\n }\n }\n\n async execute({\n checkForUpdates = defaultUpdateChecker,\n systemProcess = process,\n logStream = defaultLogStream,\n getVersion = defaultVersionGetter,\n applyConfigToArgv = defaultApplyConfigToArgv,\n discoverConfigFiles = defaultConfigDiscovery,\n loadJSConfigFile = defaultLoadJSConfigFile,\n shouldExitProgram = true,\n globalEnv = defaultGlobalEnv,\n }: ExecuteOptions = {}): Promise<void> {\n this.shouldExitProgram = shouldExitProgram;\n this.yargs.exitProcess(this.shouldExitProgram);\n\n this.cleanupProcessEnvConfigs(systemProcess);\n const argv = this.getArguments();\n\n const cmd = argv._[0];\n\n const version = await getVersion(this.absolutePackageDir);\n const runCommand = this.commands[cmd];\n\n if (argv.verbose) {\n this.enableVerboseMode(logStream, version);\n }\n\n let adjustedArgv = { ...argv, webextVersion: version };\n\n try {\n if (cmd === undefined) {\n throw new UsageError('No sub-command was specified in the args');\n }\n if (!runCommand) {\n throw new UsageError(`Unknown command: ${cmd}`);\n }\n if (globalEnv === 'production') {\n checkForUpdates({ version });\n }\n\n const configFiles = [];\n\n if (argv.configDiscovery) {\n log.debug(\n 'Discovering config files. ' + 'Set --no-config-discovery to disable'\n );\n const discoveredConfigs = await discoverConfigFiles();\n configFiles.push(...discoveredConfigs);\n } else {\n log.debug('Not discovering config files');\n }\n\n if (argv.config) {\n configFiles.push(path.resolve(argv.config));\n }\n\n if (configFiles.length) {\n const niceFileList = configFiles\n .map((f) => f.replace(process.cwd(), '.'))\n .map((f) => f.replace(os.homedir(), '~'))\n .join(', ');\n log.info(\n 'Applying config file' +\n `${configFiles.length !== 1 ? 's' : ''}: ` +\n `${niceFileList}`\n );\n }\n\n configFiles.forEach((configFileName) => {\n const configObject = loadJSConfigFile(configFileName);\n adjustedArgv = applyConfigToArgv({\n argv: adjustedArgv,\n argvFromCLI: argv,\n configFileName,\n configObject,\n options: this.options,\n });\n });\n\n if (adjustedArgv.verbose) {\n // Ensure that the verbose is enabled when specified in a config file.\n this.enableVerboseMode(logStream, version);\n }\n\n this.checkRequiredArguments(adjustedArgv);\n\n await runCommand(adjustedArgv, { shouldExitProgram });\n } catch (error) {\n if (!(error instanceof UsageError) || adjustedArgv.verbose) {\n log.error(`\\n${error.stack}\\n`);\n } else {\n log.error(`\\n${String(error)}\\n`);\n }\n if (error.code) {\n log.error(`Error code: ${error.code}\\n`);\n }\n\n log.debug(`Command executed: ${cmd}`);\n\n if (this.shouldExitProgram) {\n systemProcess.exit(1);\n } else {\n throw error;\n }\n }\n }\n}\n\n//A defintion of type of argument for defaultVersionGetter\ntype VersionGetterOptions = {\n globalEnv?: string,\n};\n\nexport async function defaultVersionGetter(\n absolutePackageDir: string,\n { globalEnv = defaultGlobalEnv }: VersionGetterOptions = {}\n): Promise<string> {\n if (globalEnv === 'production') {\n log.debug('Getting the version from package.json');\n const packageData: any = readFileSync(\n path.join(absolutePackageDir, 'package.json')\n );\n return JSON.parse(packageData).version;\n } else {\n log.debug('Getting version from the git revision');\n // This branch is only reached during development.\n // git-rev-sync is in devDependencies, and lazily imported using require.\n // This also avoids logspam from https://github.com/mozilla/web-ext/issues/1916\n // eslint-disable-next-line import/no-extraneous-dependencies\n const git = await import('git-rev-sync');\n return `${git.branch(absolutePackageDir)}-${git.long(absolutePackageDir)}`;\n }\n}\n\n// TODO: add pipes to Flow type after https://github.com/facebook/flow/issues/2405 is fixed\n\ntype MainParams = {\n getVersion?: VersionGetterFn,\n commands?: Object,\n argv: Array<any>,\n runOptions?: Object,\n};\n\nexport function throwUsageErrorIfArray(errorMessage: string): any {\n return (value: any): any => {\n if (Array.isArray(value)) {\n throw new UsageError(errorMessage);\n }\n return value;\n };\n}\n\nexport async function main(\n absolutePackageDir: string,\n {\n getVersion = defaultVersionGetter,\n commands = defaultCommands,\n argv,\n runOptions = {},\n }: MainParams = {}\n): Promise<any> {\n const program = new Program(argv, { absolutePackageDir });\n const version = await getVersion(absolutePackageDir);\n\n // This is an option shared by some commands but not all of them, hence why\n // it isn't a global option.\n const firefoxPreviewOption = {\n describe:\n 'Turn on developer preview features in Firefox' + ' (defaults to \"mv3\")',\n demandOption: false,\n type: 'array',\n };\n\n // yargs uses magic camel case expansion to expose options on the\n // final argv object. For example, the 'artifacts-dir' option is alternatively\n // available as argv.artifactsDir.\n program.yargs\n .usage(\n `Usage: $0 [options] command\n\nOption values can also be set by declaring an environment variable prefixed\nwith $${envPrefix}_. For example: $${envPrefix}_SOURCE_DIR=/path is the same as\n--source-dir=/path.\n\nTo view specific help for any given command, add the command name.\nExample: $0 --help run.\n`\n )\n .help('help')\n .alias('h', 'help')\n .env(envPrefix)\n .version(version)\n .demandCommand(1, 'You must specify a command')\n .strict()\n .recommendCommands();\n\n program.setGlobalOptions({\n 'source-dir': {\n alias: 's',\n describe: 'Web extension source directory.',\n default: process.cwd(),\n requiresArg: true,\n type: 'string',\n coerce: (arg) => (arg != null ? path.resolve(arg) : undefined),\n },\n 'artifacts-dir': {\n alias: 'a',\n describe: 'Directory where artifacts will be saved.',\n default: path.join(process.cwd(), 'web-ext-artifacts'),\n normalize: true,\n requiresArg: true,\n type: 'string',\n },\n verbose: {\n alias: 'v',\n describe: 'Show verbose output',\n type: 'boolean',\n demandOption: false,\n },\n 'ignore-files': {\n alias: 'i',\n describe:\n 'A list of glob patterns to define which files should be ' +\n 'ignored. (Example: --ignore-files=path/to/first.js ' +\n 'path/to/second.js \"**/*.log\")',\n demandOption: false,\n // The following option prevents yargs>=11 from parsing multiple values,\n // so the minimum value requirement is enforced in execute instead.\n // Upstream bug: https://github.com/yargs/yargs/issues/1098\n // requiresArg: true,\n type: 'array',\n },\n 'no-input': {\n describe: 'Disable all features that require standard input',\n type: 'boolean',\n demandOption: false,\n },\n input: {\n // This option is defined to make yargs to accept the --no-input\n // defined above, but we hide it from the yargs help output.\n hidden: true,\n type: 'boolean',\n demandOption: false,\n },\n config: {\n alias: 'c',\n describe: 'Path to a CommonJS config file to set ' + 'option defaults',\n default: undefined,\n demandOption: false,\n requiresArg: true,\n type: 'string',\n },\n 'config-discovery': {\n describe:\n 'Discover config files in home directory and ' +\n 'working directory. Disable with --no-config-discovery.',\n demandOption: false,\n default: true,\n type: 'boolean',\n },\n });\n\n program\n .command(\n 'build',\n 'Create an extension package from source',\n commands.build,\n {\n 'as-needed': {\n describe: 'Watch for file changes and re-build as needed',\n type: 'boolean',\n },\n filename: {\n alias: 'n',\n describe: 'Name of the created extension package file.',\n default: undefined,\n normalize: false,\n demandOption: false,\n requiresArg: true,\n type: 'string',\n coerce: (arg) =>\n arg == null\n ? undefined\n : throwUsageErrorIfArray(\n 'Multiple --filename/-n option are not allowed'\n )(arg),\n },\n 'overwrite-dest': {\n alias: 'o',\n describe: 'Overwrite destination package if it exists.',\n type: 'boolean',\n },\n }\n )\n .command(\n 'sign',\n 'Sign the extension so it can be installed in Firefox',\n commands.sign,\n {\n 'amo-base-url': {\n describe:\n 'Signing API URL prefix - only used with `use-submission-api`',\n default: AMO_BASE_URL,\n demandOption: true,\n type: 'string',\n },\n 'api-key': {\n describe: 'API key (JWT issuer) from addons.mozilla.org',\n demandOption: true,\n type: 'string',\n },\n 'api-secret': {\n describe: 'API secret (JWT secret) from addons.mozilla.org',\n demandOption: true,\n type: 'string',\n },\n 'api-url-prefix': {\n describe: 'Signing API URL prefix',\n default: 'https://addons.mozilla.org/api/v4',\n demandOption: true,\n type: 'string',\n },\n 'api-proxy': {\n describe:\n 'Use a proxy to access the signing API. ' +\n 'Example: https://yourproxy:6000 ',\n demandOption: false,\n type: 'string',\n },\n 'use-submission-api': {\n describe: 'Sign using the addon submission API',\n demandOption: false,\n type: 'boolean',\n },\n id: {\n describe:\n 'A custom ID for the extension. This has no effect if the ' +\n 'extension already declares an explicit ID in its manifest.',\n demandOption: false,\n type: 'string',\n },\n timeout: {\n describe: 'Number of milliseconds to wait before giving up',\n type: 'number',\n },\n 'disable-progress-bar': {\n describe: 'Disable the progress bar in sign-addon',\n demandOption: false,\n type: 'boolean',\n },\n channel: {\n describe:\n 'The channel for which to sign the addon. Either ' +\n \"'listed' or 'unlisted'\",\n type: 'string',\n },\n 'amo-metadata': {\n describe:\n 'Path to a JSON file containing an object with metadata ' +\n 'to be passed to the API. ' +\n 'See https://addons-server.readthedocs.io' +\n '/en/latest/topics/api/addons.html for details. ' +\n 'Only used with `use-submission-api`',\n type: 'string',\n },\n }\n )\n .command('run', 'Run the extension', commands.run, {\n target: {\n alias: 't',\n describe:\n 'The extensions runners to enable. Specify this option ' +\n 'multiple times to run against multiple targets.',\n default: 'firefox-desktop',\n demandOption: false,\n type: 'array',\n choices: ['firefox-desktop', 'firefox-android', 'chromium'],\n },\n firefox: {\n alias: ['f', 'firefox-binary'],\n describe:\n 'Path or alias to a Firefox executable such as firefox-bin ' +\n 'or firefox.exe. ' +\n 'If not specified, the default Firefox will be used. ' +\n 'You can specify the following aliases in lieu of a path: ' +\n 'firefox, beta, nightly, firefoxdeveloperedition (or deved). ' +\n 'For Flatpak, use `flatpak:org.mozilla.firefox` where ' +\n '`org.mozilla.firefox` is the application ID.',\n demandOption: false,\n type: 'string',\n },\n 'firefox-profile': {\n alias: 'p',\n describe:\n 'Run Firefox using a copy of this profile. The profile ' +\n 'can be specified as a directory or a name, such as one ' +\n 'you would see in the Profile Manager. If not specified, ' +\n 'a new temporary profile will be created.',\n demandOption: false,\n type: 'string',\n },\n 'chromium-binary': {\n describe:\n 'Path or alias to a Chromium executable such as ' +\n 'google-chrome, google-chrome.exe or opera.exe etc. ' +\n 'If not specified, the default Google Chrome will be used.',\n demandOption: false,\n type: 'string',\n },\n 'chromium-profile': {\n describe: 'Path to a custom Chromium profile',\n demandOption: false,\n type: 'string',\n },\n 'profile-create-if-missing': {\n describe: 'Create the profile directory if it does not already exist',\n demandOption: false,\n type: 'boolean',\n },\n 'keep-profile-changes': {\n describe:\n 'Run Firefox directly in custom profile. Any changes to ' +\n 'the profile will be saved.',\n demandOption: false,\n type: 'boolean',\n },\n reload: {\n describe:\n 'Reload the extension when source files change.' +\n 'Disable with --no-reload.',\n demandOption: false,\n default: true,\n type: 'boolean',\n },\n 'watch-file': {\n alias: ['watch-files'],\n describe:\n 'Reload the extension only when the contents of this' +\n ' file changes. This is useful if you use a custom' +\n ' build process for your extension',\n demandOption: false,\n type: 'array',\n },\n 'watch-ignored': {\n describe:\n 'Paths and globs patterns that should not be ' +\n 'watched for changes. This is useful if you want ' +\n 'to explicitly prevent web-ext from watching part ' +\n 'of the extension directory tree, ' +\n 'e.g. the node_modules folder.',\n demandOption: false,\n type: 'array',\n },\n 'pre-install': {\n describe:\n 'Pre-install the extension into the profile before ' +\n 'startup. This is only needed to support older versions ' +\n 'of Firefox.',\n demandOption: false,\n type: 'boolean',\n },\n pref: {\n describe:\n 'Launch firefox with a custom preference ' +\n '(example: --pref=general.useragent.locale=fr-FR). ' +\n 'You can repeat this option to set more than one ' +\n 'preference.',\n demandOption: false,\n requiresArg: true,\n type: 'array',\n coerce: (arg) =>\n arg != null ? coerceCLICustomPreference(arg) : undefined,\n },\n 'start-url': {\n alias: ['u', 'url'],\n describe: 'Launch firefox at specified page',\n demandOption: false,\n type: 'array',\n },\n devtools: {\n describe:\n 'Open the DevTools for the installed add-on ' +\n '(Firefox 106 and later)',\n demandOption: false,\n type: 'boolean',\n },\n 'browser-console': {\n alias: ['bc'],\n describe: 'Open the DevTools Browser Console.',\n demandOption: false,\n type: 'boolean',\n },\n args: {\n alias: ['arg'],\n describe: 'Additional CLI options passed to the Browser binary',\n demandOption: false,\n type: 'array',\n },\n 'firefox-preview': firefoxPreviewOption,\n // Firefox for Android CLI options.\n 'adb-bin': {\n describe: 'Specify a custom path to the adb binary',\n demandOption: false,\n type: 'string',\n requiresArg: true,\n },\n 'adb-host': {\n describe: 'Connect to adb on the specified host',\n demandOption: false,\n type: 'string',\n requiresArg: true,\n },\n 'adb-port': {\n describe: 'Connect to adb on the specified port',\n demandOption: false,\n type: 'string',\n requiresArg: true,\n },\n 'adb-device': {\n alias: ['android-device'],\n describe: 'Connect to the specified adb device name',\n demandOption: false,\n type: 'string',\n requiresArg: true,\n },\n 'adb-discovery-timeout': {\n describe: 'Number of milliseconds to wait before giving up',\n demandOption: false,\n type: 'number',\n requiresArg: true,\n },\n 'adb-remove-old-artifacts': {\n describe: 'Remove old artifacts directories from the adb device',\n demandOption: false,\n type: 'boolean',\n },\n 'firefox-apk': {\n describe:\n 'Run a specific Firefox for Android APK. ' +\n 'Example: org.mozilla.fennec_aurora',\n demandOption: false,\n type: 'string',\n requiresArg: true,\n },\n 'firefox-apk-component': {\n describe:\n 'Run a specific Android Component (defaults to <firefox-apk>/.App)',\n demandOption: false,\n type: 'string',\n requiresArg: true,\n },\n })\n .command('lint', 'Validate the extension source', commands.lint, {\n output: {\n alias: 'o',\n describe: 'The type of output to generate',\n type: 'string',\n default: 'text',\n choices: ['json', 'text'],\n },\n metadata: {\n describe: 'Output only metadata as JSON',\n type: 'boolean',\n default: false,\n },\n 'warnings-as-errors': {\n describe: 'Treat warnings as errors by exiting non-zero for warnings',\n alias: 'w',\n type: 'boolean',\n default: false,\n },\n pretty: {\n describe: 'Prettify JSON output',\n type: 'boolean',\n default: false,\n },\n privileged: {\n describe: 'Treat your extension as a privileged extension',\n type: 'boolean',\n default: false,\n },\n 'self-hosted': {\n describe:\n 'Your extension will be self-hosted. This disables messages ' +\n 'related to hosting on addons.mozilla.org.',\n type: 'boolean',\n default: false,\n },\n boring: {\n describe: 'Disables colorful shell output',\n type: 'boolean',\n default: false,\n },\n 'firefox-preview': firefoxPreviewOption,\n })\n .command(\n 'docs',\n 'Open the web-ext documentation in a browser',\n commands.docs,\n {}\n );\n\n return program.execute({ getVersion, ...runOptions });\n}\n"],"mappings":"AACA,OAAOA,EAAE,MAAM,IAAI;AACnB,OAAOC,IAAI,MAAM,MAAM;AACvB,SAASC,YAAY,QAAQ,IAAI;AAEjC,OAAOC,SAAS,MAAM,WAAW;AACjC,OAAOC,UAAU,MAAM,YAAY;AACnC,OAAOC,KAAK,MAAM,OAAO;AACzB,SAASC,MAAM,IAAIC,WAAW,QAAQ,eAAe;AAErD,OAAOC,eAAe,MAAM,gBAAgB;AAC5C,SAASC,UAAU,QAAQ,aAAa;AACxC,SACEC,YAAY,EACZC,aAAa,IAAIC,gBAAgB,QAC5B,kBAAkB;AACzB,SAASC,yBAAyB,QAAQ,0BAA0B;AACpE,SAASC,eAAe,IAAIC,oBAAoB,QAAQ,mBAAmB;AAC3E,SACEC,mBAAmB,IAAIC,sBAAsB,EAC7CC,gBAAgB,IAAIC,uBAAuB,EAC3CC,iBAAiB,IAAIC,wBAAwB,QACxC,aAAa;AAEpB,MAAMC,GAAG,GAAGZ,YAAY,CAACa,MAAM,CAACC,IAAI,CAACC,GAAG,CAAC;AACzC,MAAMC,SAAS,GAAG,SAAS;AAC3B;AACA;AACA,MAAMC,gBAAgB,GAAG,gBAAgC,aAAa;AAsBtE,OAAO,MAAMC,YAAY,GAAG,oCAAoC;;AAEhE;AACA;AACA;AACA,OAAO,MAAMC,OAAO,CAAC;EAUnBC,WAAWA,CACTC,IAAoB,EACpB;IAAEC,kBAAkB,GAAGC,OAAO,CAACC,GAAG;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B,KAAK,EAAE,GAAG;MACVJ,QAAQ,EAAE,gCAAgC;MAC1CC,IAAI,EAAE,QAAQ;MACdK,OAAO,EAAE,MAAM;MACfc,OAAO,EAAE,CAAC,MAAM,EAAE,MAAM;IAC1B,CAAC;IACDM,QAAQ,EAAE;MACR1B,QAAQ,EAAE,8BAA8B;MACxCC,IAAI,EAAE,SAAS;MACfK,OAAO,EAAE;IACX,CAAC;IACD,oBAAoB,EAAE;MACpBN,QAAQ,EAAE,2DAA2D;MACrEI,KAAK,EAAE,GAAG;MACVH,IAAI,EAAE,SAAS;MACfK,OAAO,EAAE;IACX,CAAC;IACDqB,MAAM,EAAE;MACN3B,QAAQ,EAAE,sBAAsB;MAChCC,IAAI,EAAE,SAAS;MACfK,OAAO,EAAE;IACX,CAAC;IACDsB,UAAU,EAAE;MACV5B,QAAQ,EAAE,gDAAgD;MAC1DC,IAAI,EAAE,SAAS;MACfK,OAAO,EAAE;IACX,CAAC;IACD,aAAa,EAAE;MACbN,QAAQ,EACN,6DAA6D,GAC7D,2CAA2C;MAC7CC,IAAI,EAAE,SAAS;MACfK,OAAO,EAAE;IACX,CAAC;IACDuB,MAAM,EAAE;MACN7B,QAAQ,EAAE,gCAAgC;MAC1CC,IAAI,EAAE,SAAS;MACfK,OAAO,EAAE;IACX,CAAC;IACD,iBAAiB,EAAEP;EACrB,CAAC,CAAC,CACDjG,OAAO,CACN,MAAM,EACN,6CAA6C,EAC7CF,QAAQ,CAACkI,IAAI,EACb,CAAC,CAAC,CACH;EAEH,OAAOhC,OAAO,CAACpC,OAAO,CAAC;IAAEC,UAAU;IAAE,GAAGkC;EAAW,CAAC,CAAC;AACvD"}
|
package/lib/util/adb.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"adb.js","names":["ADBKit","isErrorWithCode","UsageError","WebExtError","createLogger","packageIdentifiers","defaultApkComponents","DEVICE_DIR_BASE","ARTIFACTS_DIR_PREFIX","defaultADB","default","log","import","meta","url","wrapADBCall","asyncFn","error","message","includes","ADBUtils","constructor","params","adb","adbBin","adbHost","adbPort","adbClient","createClient","bin","host","port","artifactsDirMap","Map","userAbortDiscovery","runShellCommand","deviceId","cmd","debug","JSON","stringify","getDevice","shell","then","util","readAll","res","toString","discoverDevices","devices","listDevices","map","dev","id","discoverInstalledFirefoxAPKs","firefoxApk","pmList","split","line","replace","trim","filter","browser","startsWith","getAndroidVersionNumber","androidVersion","androidVersionNumber","parseInt","isNaN","ensureRequiredAPKRuntimePermissions","apk","permissions","permissionsMap","perm","pmDumpLogs","amForceStopAPK","getOrCreateArtifactsDir","artifactsDir","get","Date","now","testDirOut","set","detectOrRemoveOldArtifacts","removeArtifactDirs","files","readdir","found","file","isDirectory","name","clearArtifactsDir","delete","pushFile","localPath","devicePath","push","transfer","Promise","resolve","on","startFirefoxAPK","apkComponent","deviceProfileDir","extras","key","value","component","startActivity","wait","action","setUserAbortDiscovery","discoverRDPUnixSocket","maxDiscoveryTime","retryInterval","rdpUnixSockets","discoveryStartedAt","msg","length","info","endsWith","setTimeout","pop","setupForward","remote","local","forward","listADBDevices","adbUtils","listADBFirefoxAPKs"],"sources":["../../src/util/adb.js"],"sourcesContent":["/* @flow */\nimport ADBKit from '@devicefarmer/adbkit';\n\nimport { isErrorWithCode, UsageError, WebExtError } from '../errors.js';\nimport { createLogger } from '../util/logger.js';\nimport packageIdentifiers, {\n defaultApkComponents,\n} from '../firefox/package-identifiers.js';\n\nexport const DEVICE_DIR_BASE = '/data/local/tmp/';\nexport const ARTIFACTS_DIR_PREFIX = 'web-ext-artifacts-';\n\nconst defaultADB = ADBKit.default;\n\nconst log = createLogger(import.meta.url);\n\nexport type ADBUtilsParams = {|\n adb?: typeof defaultADB,\n // ADB configs.\n adbBin?: string,\n adbHost?: string,\n adbPort?: string,\n adbDevice?: string,\n|};\n\nexport type DiscoveryParams = {\n maxDiscoveryTime: number,\n retryInterval: number,\n};\n\n// Helper function used to raise an UsageError when the adb binary has not been found.\nasync function wrapADBCall(asyncFn: (...any) => Promise<any>): Promise<any> {\n try {\n return await asyncFn();\n } catch (error) {\n if (\n isErrorWithCode('ENOENT', error) &&\n error.message.includes('spawn adb')\n ) {\n throw new UsageError(\n 'No adb executable has been found. ' +\n 'You can Use --adb-bin, --adb-host/--adb-port ' +\n 'to configure it manually if needed.'\n );\n }\n\n throw error;\n }\n}\n\nexport default class ADBUtils {\n params: ADBUtilsParams;\n adb: typeof defaultADB;\n adbClient: any; // TODO: better flow typing here.\n\n // Map<deviceId -> artifactsDir>\n artifactsDirMap: Map<string, string>;\n // Toggled when the user wants to abort the RDP Unix Socket discovery loop\n // while it is still executing.\n userAbortDiscovery: boolean;\n\n constructor(params: ADBUtilsParams) {\n this.params = params;\n\n const { adb, adbBin, adbHost, adbPort } = params;\n\n this.adb = adb || defaultADB;\n\n this.adbClient = this.adb.createClient({\n bin: adbBin,\n host: adbHost,\n port: adbPort,\n });\n\n this.artifactsDirMap = new Map();\n\n this.userAbortDiscovery = false;\n }\n\n runShellCommand(\n deviceId: string,\n cmd: string | Array<string>\n ): Promise<string> {\n const { adb, adbClient } = this;\n\n log.debug(`Run adb shell command on ${deviceId}: ${JSON.stringify(cmd)}`);\n\n return wrapADBCall(async () => {\n return await adbClient\n .getDevice(deviceId)\n .shell(cmd)\n .then(adb.util.readAll);\n }).then((res) => res.toString());\n }\n\n async discoverDevices(): Promise<Array<string>> {\n const { adbClient } = this;\n\n let devices = [];\n\n log.debug('Listing android devices');\n devices = await wrapADBCall(async () => adbClient.listDevices());\n\n return devices.map((dev) => dev.id);\n }\n\n async discoverInstalledFirefoxAPKs(\n deviceId: string,\n firefoxApk?: string\n ): Promise<Array<string>> {\n log.debug(`Listing installed Firefox APKs on ${deviceId}`);\n\n const pmList = await this.runShellCommand(deviceId, [\n 'pm',\n 'list',\n 'packages',\n ]);\n\n return pmList\n .split('\\n')\n .map((line) => line.replace('package:', '').trim())\n .filter((line) => {\n // Look for an exact match if firefoxApk is defined.\n if (firefoxApk) {\n return line === firefoxApk;\n }\n // Match any package name that starts with the package name of a Firefox for Android browser.\n for (const browser of packageIdentifiers) {\n if (line.startsWith(browser)) {\n return true;\n }\n }\n\n return false;\n });\n }\n\n async getAndroidVersionNumber(deviceId: string): Promise<number> {\n const androidVersion = (\n await this.runShellCommand(deviceId, ['getprop', 'ro.build.version.sdk'])\n ).trim();\n\n const androidVersionNumber = parseInt(androidVersion);\n\n // No need to check the granted runtime permissions on Android versions < Lollypop.\n if (isNaN(androidVersionNumber)) {\n throw new WebExtError(\n 'Unable to discovery android version on ' +\n `${deviceId}: ${androidVersion}`\n );\n }\n\n return androidVersionNumber;\n }\n\n // Raise an UsageError when the given APK does not have the required runtime permissions.\n async ensureRequiredAPKRuntimePermissions(\n deviceId: string,\n apk: string,\n permissions: Array<string>\n ): Promise<void> {\n const permissionsMap = {};\n\n // Initialize every permission to false in the permissions map.\n for (const perm of permissions) {\n permissionsMap[perm] = false;\n }\n\n // Retrieve the permissions information for the given apk.\n const pmDumpLogs = (\n await this.runShellCommand(deviceId, ['pm', 'dump', apk])\n ).split('\\n');\n\n // Set to true the required permissions that have been granted.\n for (const line of pmDumpLogs) {\n for (const perm of permissions) {\n if (\n line.includes(`${perm}: granted=true`) ||\n line.includes(`${perm}, granted=true`)\n ) {\n permissionsMap[perm] = true;\n }\n }\n }\n\n for (const perm of permissions) {\n if (!permissionsMap[perm]) {\n throw new UsageError(\n `Required ${perm} has not be granted for ${apk}. ` +\n 'Please grant them using the Android Settings ' +\n 'or using the following adb command:\\n' +\n `\\t adb shell pm grant ${apk} ${perm}\\n`\n );\n }\n }\n }\n\n async amForceStopAPK(deviceId: string, apk: string): Promise<void> {\n await this.runShellCommand(deviceId, ['am', 'force-stop', apk]);\n }\n\n async getOrCreateArtifactsDir(deviceId: string): Promise<string> {\n let artifactsDir = this.artifactsDirMap.get(deviceId);\n\n if (artifactsDir) {\n return artifactsDir;\n }\n\n artifactsDir = `${DEVICE_DIR_BASE}${ARTIFACTS_DIR_PREFIX}${Date.now()}`;\n\n const testDirOut = (\n await this.runShellCommand(deviceId, `test -d ${artifactsDir} ; echo $?`)\n ).trim();\n\n if (testDirOut !== '1') {\n throw new WebExtError(\n `Cannot create artifacts directory ${artifactsDir} ` +\n `because it exists on ${deviceId}.`\n );\n }\n\n await this.runShellCommand(deviceId, ['mkdir', '-p', artifactsDir]);\n\n this.artifactsDirMap.set(deviceId, artifactsDir);\n\n return artifactsDir;\n }\n\n async detectOrRemoveOldArtifacts(\n deviceId: string,\n removeArtifactDirs?: boolean = false\n ): Promise<boolean> {\n const { adbClient } = this;\n\n log.debug('Checking adb device for existing web-ext artifacts dirs');\n\n return wrapADBCall(async () => {\n const files = await adbClient\n .getDevice(deviceId)\n .readdir(DEVICE_DIR_BASE);\n let found = false;\n\n for (const file of files) {\n if (\n !file.isDirectory() ||\n !file.name.startsWith(ARTIFACTS_DIR_PREFIX)\n ) {\n continue;\n }\n\n // Return earlier if we only need to warn the user that some\n // existing artifacts dirs have been found on the adb device.\n if (!removeArtifactDirs) {\n return true;\n }\n\n found = true;\n\n const artifactsDir = `${DEVICE_DIR_BASE}${file.name}`;\n\n log.debug(\n `Removing artifacts directory ${artifactsDir} from device ${deviceId}`\n );\n\n await this.runShellCommand(deviceId, ['rm', '-rf', artifactsDir]);\n }\n\n return found;\n });\n }\n\n async clearArtifactsDir(deviceId: string): Promise<void> {\n const artifactsDir = this.artifactsDirMap.get(deviceId);\n\n if (!artifactsDir) {\n // nothing to do here.\n return;\n }\n\n this.artifactsDirMap.delete(deviceId);\n\n log.debug(\n `Removing ${artifactsDir} artifacts directory on ${deviceId} device`\n );\n\n await this.runShellCommand(deviceId, ['rm', '-rf', artifactsDir]);\n }\n\n async pushFile(\n deviceId: string,\n localPath: string,\n devicePath: string\n ): Promise<void> {\n const { adbClient } = this;\n\n log.debug(`Pushing ${localPath} to ${devicePath} on ${deviceId}`);\n\n await wrapADBCall(async () => {\n await adbClient\n .getDevice(deviceId)\n .push(localPath, devicePath)\n .then(function (transfer) {\n return new Promise((resolve) => {\n transfer.on('end', resolve);\n });\n });\n });\n }\n\n async startFirefoxAPK(\n deviceId: string,\n apk: string,\n apkComponent: ?string,\n deviceProfileDir: string\n ): Promise<void> {\n const { adbClient } = this;\n\n log.debug(`Starting ${apk} on ${deviceId}`);\n\n // Fenix does ignore the -profile parameter, on the contrary Fennec\n // would run using the given path as the profile to be used during\n // this execution.\n const extras = [\n {\n key: 'args',\n value: `-profile ${deviceProfileDir}`,\n },\n ];\n\n if (!apkComponent) {\n apkComponent = '.App';\n if (defaultApkComponents[apk]) {\n apkComponent = defaultApkComponents[apk];\n }\n } else if (!apkComponent.includes('.')) {\n apkComponent = `.${apkComponent}`;\n }\n\n // if `apk` is a browser package or the `apk` has a\n // browser package prefix: prepend the package identifier\n // before `apkComponent`\n if (apkComponent.startsWith('.')) {\n for (const browser of packageIdentifiers) {\n if (apk === browser || apk.startsWith(`${browser}.`)) {\n apkComponent = browser + apkComponent;\n }\n }\n }\n\n // if `apkComponent` starts with a '.', then adb will expand\n // the following to: `${apk}/${apk}.${apkComponent}`\n const component = `${apk}/${apkComponent}`;\n\n await wrapADBCall(async () => {\n await adbClient.getDevice(deviceId).startActivity({\n wait: true,\n action: 'android.activity.MAIN',\n component,\n extras,\n });\n });\n }\n\n setUserAbortDiscovery(value: boolean) {\n this.userAbortDiscovery = value;\n }\n\n async discoverRDPUnixSocket(\n deviceId: string,\n apk: string,\n { maxDiscoveryTime, retryInterval }: DiscoveryParams = {}\n ): Promise<string> {\n let rdpUnixSockets = [];\n\n const discoveryStartedAt = Date.now();\n const msg =\n `Waiting for ${apk} Remote Debugging Server...` +\n '\\nMake sure to enable \"Remote Debugging via USB\" ' +\n 'from Settings -> Developer Tools if it is not yet enabled.';\n\n while (rdpUnixSockets.length === 0) {\n log.info(msg);\n if (this.userAbortDiscovery) {\n throw new UsageError(\n 'Exiting Firefox Remote Debugging socket discovery on user request'\n );\n }\n\n if (Date.now() - discoveryStartedAt > maxDiscoveryTime) {\n throw new WebExtError(\n 'Timeout while waiting for the Android Firefox Debugger Socket'\n );\n }\n\n rdpUnixSockets = (\n await this.runShellCommand(deviceId, ['cat', '/proc/net/unix'])\n )\n .split('\\n')\n .filter((line) => {\n // The RDP unix socket is expected to be a path in the form:\n // /data/data/org.mozilla.fennec_rpl/firefox-debugger-socket\n return line.trim().endsWith(`${apk}/firefox-debugger-socket`);\n });\n\n if (rdpUnixSockets.length === 0) {\n await new Promise((resolve) => setTimeout(resolve, retryInterval));\n }\n }\n\n // Convert into an array of unix socket filenames.\n rdpUnixSockets = rdpUnixSockets.map((line) => {\n return line.trim().split(/\\s/).pop();\n });\n\n if (rdpUnixSockets.length > 1) {\n throw new WebExtError(\n 'Unexpected multiple RDP sockets: ' +\n `${JSON.stringify(rdpUnixSockets)}`\n );\n }\n\n return rdpUnixSockets[0];\n }\n\n async setupForward(deviceId: string, remote: string, local: string) {\n const { adbClient } = this;\n\n // TODO(rpl): we should use adb.listForwards and reuse the existing one if any (especially\n // because adbkit doesn't seem to support `adb forward --remote` yet).\n log.debug(`Configuring ADB forward for ${deviceId}: ${remote} -> ${local}`);\n\n await wrapADBCall(async () => {\n await adbClient.getDevice(deviceId).forward(local, remote);\n });\n }\n}\n\nexport async function listADBDevices(adbBin?: string): Promise<Array<string>> {\n const adbUtils = new ADBUtils({ adbBin });\n return adbUtils.discoverDevices();\n}\n\nexport async function listADBFirefoxAPKs(\n deviceId: string,\n adbBin?: string\n): Promise<Array<string>> {\n const adbUtils = new ADBUtils({ adbBin });\n return adbUtils.discoverInstalledFirefoxAPKs(deviceId);\n}\n"],"mappings":"AACA,OAAOA,MAAM,MAAM,sBAAsB;AAEzC,SAASC,eAAe,EAAEC,UAAU,EAAEC,WAAW,QAAQ,cAAc;AACvE,SAASC,YAAY,QAAQ,mBAAmB;AAChD,OAAOC,kBAAkB,IACvBC,oBAAoB,QACf,mCAAmC;AAE1C,OAAO,MAAMC,eAAe,GAAG,kBAAkB;AACjD,OAAO,MAAMC,oBAAo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xB,MAAMwG,QAAQ,GAAG,IAAI5G,QAAQ,CAAC;IAAEI;EAAO,CAAC,CAAC;EACzC,OAAOwG,QAAQ,CAAC1E,4BAA4B,CAAClB,QAAQ,CAAC;AACxD"}
|
|
1
|
+
{"version":3,"file":"adb.js","names":["ADBKit","isErrorWithCode","UsageError","WebExtError","createLogger","packageIdentifiers","defaultApkComponents","DEVICE_DIR_BASE","ARTIFACTS_DIR_PREFIX","defaultADB","default","log","import","meta","url","wrapADBCall","asyncFn","error","message","includes","ADBUtils","constructor","params","adb","adbBin","adbHost","adbPort","adbClient","createClient","bin","host","port","artifactsDirMap","Map","userAbortDiscovery","runShellCommand","deviceId","cmd","debug","JSON","stringify","getDevice","shell","then","util","readAll","res","toString","discoverDevices","devices","listDevices","map","dev","id","discoverInstalledFirefoxAPKs","firefoxApk","pmList","split","line","replace","trim","filter","browser","startsWith","getAndroidVersionNumber","androidVersion","androidVersionNumber","parseInt","isNaN","ensureRequiredAPKRuntimePermissions","apk","permissions","permissionsMap","perm","pmDumpLogs","amForceStopAPK","getOrCreateArtifactsDir","artifactsDir","get","Date","now","testDirOut","set","detectOrRemoveOldArtifacts","removeArtifactDirs","files","readdir","found","file","isDirectory","name","clearArtifactsDir","delete","pushFile","localPath","devicePath","push","transfer","Promise","resolve","on","startFirefoxAPK","apkComponent","deviceProfileDir","extras","key","value","component","startActivity","wait","action","setUserAbortDiscovery","discoverRDPUnixSocket","maxDiscoveryTime","retryInterval","rdpUnixSockets","discoveryStartedAt","msg","length","info","endsWith","setTimeout","pop","setupForward","remote","local","forward","listADBDevices","adbUtils","listADBFirefoxAPKs"],"sources":["../../src/util/adb.js"],"sourcesContent":["/* @flow */\nimport ADBKit from '@devicefarmer/adbkit';\n\nimport { isErrorWithCode, UsageError, WebExtError } from '../errors.js';\nimport { createLogger } from '../util/logger.js';\nimport packageIdentifiers, {\n defaultApkComponents,\n} from '../firefox/package-identifiers.js';\n\nexport const DEVICE_DIR_BASE = '/data/local/tmp/';\nexport const ARTIFACTS_DIR_PREFIX = 'web-ext-artifacts-';\n\nconst defaultADB = ADBKit.default;\n\nconst log = createLogger(import.meta.url);\n\nexport type ADBUtilsParams = {|\n adb?: typeof defaultADB,\n // ADB configs.\n adbBin?: string,\n adbHost?: string,\n adbPort?: string,\n adbDevice?: string,\n|};\n\nexport type DiscoveryParams = {\n maxDiscoveryTime: number,\n retryInterval: number,\n};\n\n// Helper function used to raise an UsageError when the adb binary has not been found.\nasync function wrapADBCall(asyncFn: (...any) => Promise<any>): Promise<any> {\n try {\n return await asyncFn();\n } catch (error) {\n if (\n isErrorWithCode('ENOENT', error) &&\n error.message.includes('spawn adb')\n ) {\n throw new UsageError(\n 'No adb executable has been found. ' +\n 'You can Use --adb-bin, --adb-host/--adb-port ' +\n 'to configure it manually if needed.'\n );\n }\n\n throw error;\n }\n}\n\nexport default class ADBUtils {\n params: ADBUtilsParams;\n adb: typeof defaultADB;\n adbClient: any; // TODO: better flow typing here.\n\n // Map<deviceId -> artifactsDir>\n artifactsDirMap: Map<string, string>;\n // Toggled when the user wants to abort the RDP Unix Socket discovery loop\n // while it is still executing.\n userAbortDiscovery: boolean;\n\n constructor(params: ADBUtilsParams) {\n this.params = params;\n\n const { adb, adbBin, adbHost, adbPort } = params;\n\n this.adb = adb || defaultADB;\n\n this.adbClient = this.adb.createClient({\n bin: adbBin,\n host: adbHost,\n port: adbPort,\n });\n\n this.artifactsDirMap = new Map();\n\n this.userAbortDiscovery = false;\n }\n\n runShellCommand(\n deviceId: string,\n cmd: string | Array<string>\n ): Promise<string> {\n const { adb, adbClient } = this;\n\n log.debug(`Run adb shell command on ${deviceId}: ${JSON.stringify(cmd)}`);\n\n return wrapADBCall(async () => {\n return await adbClient\n .getDevice(deviceId)\n .shell(cmd)\n .then(adb.util.readAll);\n }).then((res) => res.toString());\n }\n\n async discoverDevices(): Promise<Array<string>> {\n const { adbClient } = this;\n\n let devices = [];\n\n log.debug('Listing android devices');\n devices = await wrapADBCall(async () => adbClient.listDevices());\n\n return devices.map((dev) => dev.id);\n }\n\n async discoverInstalledFirefoxAPKs(\n deviceId: string,\n firefoxApk?: string\n ): Promise<Array<string>> {\n log.debug(`Listing installed Firefox APKs on ${deviceId}`);\n\n const pmList = await this.runShellCommand(deviceId, [\n 'pm',\n 'list',\n 'packages',\n ]);\n\n return pmList\n .split('\\n')\n .map((line) => line.replace('package:', '').trim())\n .filter((line) => {\n // Look for an exact match if firefoxApk is defined.\n if (firefoxApk) {\n return line === firefoxApk;\n }\n // Match any package name that starts with the package name of a Firefox for Android browser.\n for (const browser of packageIdentifiers) {\n if (line.startsWith(browser)) {\n return true;\n }\n }\n\n return false;\n });\n }\n\n async getAndroidVersionNumber(deviceId: string): Promise<number> {\n const androidVersion = (\n await this.runShellCommand(deviceId, ['getprop', 'ro.build.version.sdk'])\n ).trim();\n\n const androidVersionNumber = parseInt(androidVersion);\n\n // No need to check the granted runtime permissions on Android versions < Lollypop.\n if (isNaN(androidVersionNumber)) {\n throw new WebExtError(\n 'Unable to discovery android version on ' +\n `${deviceId}: ${androidVersion}`\n );\n }\n\n return androidVersionNumber;\n }\n\n // Raise an UsageError when the given APK does not have the required runtime permissions.\n async ensureRequiredAPKRuntimePermissions(\n deviceId: string,\n apk: string,\n permissions: Array<string>\n ): Promise<void> {\n const permissionsMap = {};\n\n // Initialize every permission to false in the permissions map.\n for (const perm of permissions) {\n permissionsMap[perm] = false;\n }\n\n // Retrieve the permissions information for the given apk.\n const pmDumpLogs = (\n await this.runShellCommand(deviceId, ['pm', 'dump', apk])\n ).split('\\n');\n\n // Set to true the required permissions that have been granted.\n for (const line of pmDumpLogs) {\n for (const perm of permissions) {\n if (\n line.includes(`${perm}: granted=true`) ||\n line.includes(`${perm}, granted=true`)\n ) {\n permissionsMap[perm] = true;\n }\n }\n }\n\n for (const perm of permissions) {\n if (!permissionsMap[perm]) {\n throw new UsageError(\n `Required ${perm} has not be granted for ${apk}. ` +\n 'Please grant them using the Android Settings ' +\n 'or using the following adb command:\\n' +\n `\\t adb shell pm grant ${apk} ${perm}\\n`\n );\n }\n }\n }\n\n async amForceStopAPK(deviceId: string, apk: string): Promise<void> {\n await this.runShellCommand(deviceId, ['am', 'force-stop', apk]);\n }\n\n async getOrCreateArtifactsDir(deviceId: string): Promise<string> {\n let artifactsDir = this.artifactsDirMap.get(deviceId);\n\n if (artifactsDir) {\n return artifactsDir;\n }\n\n artifactsDir = `${DEVICE_DIR_BASE}${ARTIFACTS_DIR_PREFIX}${Date.now()}`;\n\n const testDirOut = (\n await this.runShellCommand(deviceId, `test -d ${artifactsDir} ; echo $?`)\n ).trim();\n\n if (testDirOut !== '1') {\n throw new WebExtError(\n `Cannot create artifacts directory ${artifactsDir} ` +\n `because it exists on ${deviceId}.`\n );\n }\n\n await this.runShellCommand(deviceId, ['mkdir', '-p', artifactsDir]);\n\n this.artifactsDirMap.set(deviceId, artifactsDir);\n\n return artifactsDir;\n }\n\n async detectOrRemoveOldArtifacts(\n deviceId: string,\n removeArtifactDirs?: boolean = false\n ): Promise<boolean> {\n const { adbClient } = this;\n\n log.debug('Checking adb device for existing web-ext artifacts dirs');\n\n return wrapADBCall(async () => {\n const files = await adbClient\n .getDevice(deviceId)\n .readdir(DEVICE_DIR_BASE);\n let found = false;\n\n for (const file of files) {\n if (\n !file.isDirectory() ||\n !file.name.startsWith(ARTIFACTS_DIR_PREFIX)\n ) {\n continue;\n }\n\n // Return earlier if we only need to warn the user that some\n // existing artifacts dirs have been found on the adb device.\n if (!removeArtifactDirs) {\n return true;\n }\n\n found = true;\n\n const artifactsDir = `${DEVICE_DIR_BASE}${file.name}`;\n\n log.debug(\n `Removing artifacts directory ${artifactsDir} from device ${deviceId}`\n );\n\n await this.runShellCommand(deviceId, ['rm', '-rf', artifactsDir]);\n }\n\n return found;\n });\n }\n\n async clearArtifactsDir(deviceId: string): Promise<void> {\n const artifactsDir = this.artifactsDirMap.get(deviceId);\n\n if (!artifactsDir) {\n // nothing to do here.\n return;\n }\n\n this.artifactsDirMap.delete(deviceId);\n\n log.debug(\n `Removing ${artifactsDir} artifacts directory on ${deviceId} device`\n );\n\n await this.runShellCommand(deviceId, ['rm', '-rf', artifactsDir]);\n }\n\n async pushFile(\n deviceId: string,\n localPath: string,\n devicePath: string\n ): Promise<void> {\n const { adbClient } = this;\n\n log.debug(`Pushing ${localPath} to ${devicePath} on ${deviceId}`);\n\n await wrapADBCall(async () => {\n await adbClient\n .getDevice(deviceId)\n .push(localPath, devicePath)\n .then(function (transfer) {\n return new Promise((resolve) => {\n transfer.on('end', resolve);\n });\n });\n });\n }\n\n async startFirefoxAPK(\n deviceId: string,\n apk: string,\n apkComponent: ?string,\n deviceProfileDir: string\n ): Promise<void> {\n const { adbClient } = this;\n\n log.debug(`Starting ${apk} on ${deviceId}`);\n\n // Fenix does ignore the -profile parameter, on the contrary Fennec\n // would run using the given path as the profile to be used during\n // this execution.\n const extras = [\n {\n key: 'args',\n value: `-profile ${deviceProfileDir}`,\n },\n ];\n\n if (!apkComponent) {\n apkComponent = '.App';\n if (defaultApkComponents[apk]) {\n apkComponent = defaultApkComponents[apk];\n }\n } else if (!apkComponent.includes('.')) {\n apkComponent = `.${apkComponent}`;\n }\n\n // if `apk` is a browser package or the `apk` has a\n // browser package prefix: prepend the package identifier\n // before `apkComponent`\n if (apkComponent.startsWith('.')) {\n for (const browser of packageIdentifiers) {\n if (apk === browser || apk.startsWith(`${browser}.`)) {\n apkComponent = browser + apkComponent;\n }\n }\n }\n\n // if `apkComponent` starts with a '.', then adb will expand\n // the following to: `${apk}/${apk}.${apkComponent}`\n const component = `${apk}/${apkComponent}`;\n\n await wrapADBCall(async () => {\n await adbClient.getDevice(deviceId).startActivity({\n wait: true,\n action: 'android.activity.MAIN',\n component,\n extras,\n });\n });\n }\n\n setUserAbortDiscovery(value: boolean) {\n this.userAbortDiscovery = value;\n }\n\n async discoverRDPUnixSocket(\n deviceId: string,\n apk: string,\n { maxDiscoveryTime, retryInterval }: DiscoveryParams = {}\n ): Promise<string> {\n let rdpUnixSockets = [];\n\n const discoveryStartedAt = Date.now();\n const msg =\n `Waiting for ${apk} Remote Debugging Server...` +\n '\\nMake sure to enable \"Remote Debugging via USB\" ' +\n 'from Settings -> Developer Tools if it is not yet enabled.';\n\n while (rdpUnixSockets.length === 0) {\n log.info(msg);\n if (this.userAbortDiscovery) {\n throw new UsageError(\n 'Exiting Firefox Remote Debugging socket discovery on user request'\n );\n }\n\n if (Date.now() - discoveryStartedAt > maxDiscoveryTime) {\n throw new WebExtError(\n 'Timeout while waiting for the Android Firefox Debugger Socket'\n );\n }\n\n rdpUnixSockets = (\n await this.runShellCommand(deviceId, ['cat', '/proc/net/unix'])\n )\n .split('\\n')\n .filter((line) => {\n // The RDP unix socket is expected to be a path in the form:\n // /data/data/org.mozilla.fennec_rpl/firefox-debugger-socket\n return line.trim().endsWith(`${apk}/firefox-debugger-socket`);\n });\n\n if (rdpUnixSockets.length === 0) {\n await new Promise((resolve) => setTimeout(resolve, retryInterval));\n }\n }\n\n // Convert into an array of unix socket filenames.\n rdpUnixSockets = rdpUnixSockets.map((line) => {\n return line.trim().split(/\\s/).pop();\n });\n\n if (rdpUnixSockets.length > 1) {\n throw new WebExtError(\n 'Unexpected multiple RDP sockets: ' +\n `${JSON.stringify(rdpUnixSockets)}`\n );\n }\n\n return rdpUnixSockets[0];\n }\n\n async setupForward(deviceId: string, remote: string, local: string) {\n const { adbClient } = this;\n\n // TODO(rpl): we should use adb.listForwards and reuse the existing one if any (especially\n // because adbkit doesn't seem to support `adb forward --remote` yet).\n log.debug(`Configuring ADB forward for ${deviceId}: ${remote} -> ${local}`);\n\n await wrapADBCall(async () => {\n await adbClient.getDevice(deviceId).forward(local, remote);\n });\n }\n}\n\nexport async function listADBDevices(adbBin?: string): Promise<Array<string>> {\n const adbUtils = new ADBUtils({ adbBin });\n return adbUtils.discoverDevices();\n}\n\nexport async function listADBFirefoxAPKs(\n deviceId: string,\n adbBin?: string\n): Promise<Array<string>> {\n const adbUtils = new ADBUtils({ adbB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AAQ,CAAC,CAAC0F,OAAO,CAACD,KAAK,EAAED,MAAM,CAAC;IAC5D,CAAC,CAAC;EACJ;AACF;AAEA,OAAO,eAAeG,cAAcA,CAACvG,MAAe,EAA0B;EAC5E,MAAMwG,QAAQ,GAAG,IAAI5G,QAAQ,CAAC;IAAEI;EAAO,CAAC,CAAC;EACzC,OAAOwG,QAAQ,CAAChF,eAAe,EAAE;AACnC;AAEA,OAAO,eAAeiF,kBAAkBA,CACtC7F,QAAgB,EAChBZ,MAAe,EACS;EACxB,MAAMwG,QAAQ,GAAG,IAAI5G,QAAQ,CAAC;IAAEI;EAAO,CAAC,CAAC;EACzC,OAAOwG,QAAQ,CAAC1E,4BAA4B,CAAClB,QAAQ,CAAC;AACxD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"artifacts.js","names":["fs","defaultAsyncMkdirp","UsageError","isErrorWithCode","createLogger","log","import","meta","url","defaultAsyncFsAccess","access","bind","prepareArtifactsDir","artifactsDir","asyncMkdirp","asyncFsAccess","stats","stat","isDirectory","W_OK","accessErr","error","debug","mkdirErr"],"sources":["../../src/util/artifacts.js"],"sourcesContent":["/* @flow */\nimport { fs } from 'mz';\nimport defaultAsyncMkdirp from 'mkdirp';\n\nimport { UsageError, isErrorWithCode } from '../errors.js';\nimport { createLogger } from './logger.js';\n\nconst log = createLogger(import.meta.url);\n\nconst defaultAsyncFsAccess: typeof fs.access = fs.access.bind(fs);\n\ntype PrepareArtifactsDirOptions = {\n asyncMkdirp?: typeof defaultAsyncMkdirp,\n asyncFsAccess?: typeof defaultAsyncFsAccess,\n};\n\nexport async function prepareArtifactsDir(\n artifactsDir: string,\n {\n asyncMkdirp = defaultAsyncMkdirp,\n asyncFsAccess = defaultAsyncFsAccess,\n }: PrepareArtifactsDirOptions = {}\n): Promise<string> {\n try {\n const stats = await fs.stat(artifactsDir);\n if (!stats.isDirectory()) {\n throw new UsageError(\n `--artifacts-dir=\"${artifactsDir}\" exists but it is not a directory.`\n );\n }\n // If the artifactsDir already exists, check that we have the write permissions on it.\n try {\n await asyncFsAccess(artifactsDir, fs.W_OK);\n } catch (accessErr) {\n if (isErrorWithCode('EACCES', accessErr)) {\n throw new UsageError(\n `--artifacts-dir=\"${artifactsDir}\" exists but the user lacks ` +\n 'permissions on it.'\n );\n } else {\n throw accessErr;\n }\n }\n } catch (error) {\n if (isErrorWithCode('EACCES', error)) {\n // Handle errors when the artifactsDir cannot be accessed.\n throw new UsageError(\n `Cannot access --artifacts-dir=\"${artifactsDir}\" because the user ` +\n `lacks permissions: ${error}`\n );\n } else if (isErrorWithCode('ENOENT', error)) {\n // Create the artifact dir if it doesn't exist yet.\n try {\n log.debug(`Creating artifacts directory: ${artifactsDir}`);\n await asyncMkdirp(artifactsDir);\n } catch (mkdirErr) {\n if (isErrorWithCode('EACCES', mkdirErr)) {\n // Handle errors when the artifactsDir cannot be created for lack of permissions.\n throw new UsageError(\n `Cannot create --artifacts-dir=\"${artifactsDir}\" because the ` +\n `user lacks permissions: ${mkdirErr}`\n );\n } else {\n throw mkdirErr;\n }\n }\n } else {\n throw error;\n }\n }\n\n return artifactsDir;\n}\n"],"mappings":"AACA,SAASA,EAAE,QAAQ,IAAI;AACvB,OAAOC,kBAAkB,MAAM,QAAQ;AAEvC,SAASC,UAAU,EAAEC,eAAe,QAAQ,cAAc;AAC1D,SAASC,YAAY,QAAQ,aAAa;AAE1C,MAAMC,GAAG,GAAGD,YAAY,CAACE,MAAM,CAACC,IAAI,CAACC,GAAG,CAAC;AAEzC,MAAMC,oBAAsC,GAAGT,EAAE,CAACU,MAAM,CAACC,IAAI,CAACX,EAAE,CAAC;AAOjE,OAAO,eAAeY,
|
|
1
|
+
{"version":3,"file":"artifacts.js","names":["fs","defaultAsyncMkdirp","UsageError","isErrorWithCode","createLogger","log","import","meta","url","defaultAsyncFsAccess","access","bind","prepareArtifactsDir","artifactsDir","asyncMkdirp","asyncFsAccess","stats","stat","isDirectory","W_OK","accessErr","error","debug","mkdirErr"],"sources":["../../src/util/artifacts.js"],"sourcesContent":["/* @flow */\nimport { fs } from 'mz';\nimport defaultAsyncMkdirp from 'mkdirp';\n\nimport { UsageError, isErrorWithCode } from '../errors.js';\nimport { createLogger } from './logger.js';\n\nconst log = createLogger(import.meta.url);\n\nconst defaultAsyncFsAccess: typeof fs.access = fs.access.bind(fs);\n\ntype PrepareArtifactsDirOptions = {\n asyncMkdirp?: typeof defaultAsyncMkdirp,\n asyncFsAccess?: typeof defaultAsyncFsAccess,\n};\n\nexport async function prepareArtifactsDir(\n artifactsDir: string,\n {\n asyncMkdirp = defaultAsyncMkdirp,\n asyncFsAccess = defaultAsyncFsAccess,\n }: PrepareArtifactsDirOptions = {}\n): Promise<string> {\n try {\n const stats = await fs.stat(artifactsDir);\n if (!stats.isDirectory()) {\n throw new UsageError(\n `--artifacts-dir=\"${artifactsDir}\" exists but it is not a directory.`\n );\n }\n // If the artifactsDir already exists, check that we have the write permissions on it.\n try {\n await asyncFsAccess(artifactsDir, fs.W_OK);\n } catch (accessErr) {\n if (isErrorWithCode('EACCES', accessErr)) {\n throw new UsageError(\n `--artifacts-dir=\"${artifactsDir}\" exists but the user lacks ` +\n 'permissions on it.'\n );\n } else {\n throw accessErr;\n }\n }\n } catch (error) {\n if (isErrorWithCode('EACCES', error)) {\n // Handle errors when the artifactsDir cannot be accessed.\n throw new UsageError(\n `Cannot access --artifacts-dir=\"${artifactsDir}\" because the user ` +\n `lacks permissions: ${error}`\n );\n } else if (isErrorWithCode('ENOENT', error)) {\n // Create the artifact dir if it doesn't exist yet.\n try {\n log.debug(`Creating artifacts directory: ${artifactsDir}`);\n await asyncMkdirp(artifactsDir);\n } catch (mkdirErr) {\n if (isErrorWithCode('EACCES', mkdirErr)) {\n // Handle errors when the artifactsDir cannot be created for lack of permissions.\n throw new UsageError(\n `Cannot create --artifacts-dir=\"${artifactsDir}\" because the ` +\n `user lacks permissions: ${mkdirErr}`\n );\n } else {\n throw mkdirErr;\n }\n }\n } else {\n throw error;\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