1
0
mirror of https://gitcode.com/github-mirrors/react-native-update-cli.git synced 2025-10-30 22:33:11 +08:00
Code Issues Packages Projects Releases Wiki Activity GitHub Gitee

cli modular refactor (#16)

* add logic to support SENTRY_PROPERTIES parameter

* remove update.json and meta.json files in ppk

* udpapte

* refactor modles

* update

* add package-module file

* update

* update readme file

* modifu cli.json file

* fix command issues

* improve version workflow logic

* udpate

* update

* update

* update

* udpate

* udpate

* add example

* update readme file

* udpate version

* change logic to use pushy command uniformly
This commit is contained in:
波仔糕
2025-07-24 11:46:20 +08:00
committed by GitHub
parent 4cb5f7fa4e
commit e98bcf504f
53 changed files with 10853 additions and 855 deletions

View File

@@ -1,64 +1,74 @@
const Zip = require('./zip')
const { mapInfoResource, findApkIconPath, getBase64FromBuffer } = require('./utils')
const ManifestName = /^androidmanifest\.xml$/
const ResourceName = /^resources\.arsc$/
const Zip = require('./zip');
const {
mapInfoResource,
findApkIconPath,
getBase64FromBuffer,
} = require('./utils');
const ManifestName = /^androidmanifest\.xml$/;
const ResourceName = /^resources\.arsc$/;
const ManifestXmlParser = require('./xml-parser/manifest')
const ResourceFinder = require('./resource-finder')
const ManifestXmlParser = require('./xml-parser/manifest');
const ResourceFinder = require('./resource-finder');
class ApkParser extends Zip {
/**
* parser for parsing .apk file
* @param {String | File | Blob} file // file's path in Node, instance of File or Blob in Browser
*/
constructor (file) {
super(file)
constructor(file) {
super(file);
if (!(this instanceof ApkParser)) {
return new ApkParser(file)
return new ApkParser(file);
}
}
parse () {
parse() {
return new Promise((resolve, reject) => {
this.getEntries([ManifestName, ResourceName]).then(buffers => {
if (!buffers[ManifestName]) {
throw new Error('AndroidManifest.xml can\'t be found.')
}
let apkInfo = this._parseManifest(buffers[ManifestName])
let resourceMap
if (!buffers[ResourceName]) {
resolve(apkInfo)
} else {
// parse resourceMap
resourceMap = this._parseResourceMap(buffers[ResourceName])
// update apkInfo with resourceMap
apkInfo = mapInfoResource(apkInfo, resourceMap)
// find icon path and parse icon
const iconPath = findApkIconPath(apkInfo)
if (iconPath) {
this.getEntry(iconPath).then(iconBuffer => {
apkInfo.icon = iconBuffer ? getBase64FromBuffer(iconBuffer) : null
resolve(apkInfo)
}).catch(e => {
apkInfo.icon = null
resolve(apkInfo)
console.warn('[Warning] failed to parse icon: ', e)
})
} else {
apkInfo.icon = null
resolve(apkInfo)
this.getEntries([ManifestName, ResourceName])
.then((buffers) => {
if (!buffers[ManifestName]) {
throw new Error("AndroidManifest.xml can't be found.");
}
}
}).catch(e => {
reject(e)
})
})
let apkInfo = this._parseManifest(buffers[ManifestName]);
let resourceMap;
if (!buffers[ResourceName]) {
resolve(apkInfo);
} else {
// parse resourceMap
resourceMap = this._parseResourceMap(buffers[ResourceName]);
// update apkInfo with resourceMap
apkInfo = mapInfoResource(apkInfo, resourceMap);
// find icon path and parse icon
const iconPath = findApkIconPath(apkInfo);
if (iconPath) {
this.getEntry(iconPath)
.then((iconBuffer) => {
apkInfo.icon = iconBuffer
? getBase64FromBuffer(iconBuffer)
: null;
resolve(apkInfo);
})
.catch((e) => {
apkInfo.icon = null;
resolve(apkInfo);
console.warn('[Warning] failed to parse icon: ', e);
});
} else {
apkInfo.icon = null;
resolve(apkInfo);
}
}
})
.catch((e) => {
reject(e);
});
});
}
/**
* Parse manifest
* @param {Buffer} buffer // manifest file's buffer
*/
_parseManifest (buffer) {
_parseManifest(buffer) {
try {
const parser = new ManifestXmlParser(buffer, {
ignore: [
@@ -66,25 +76,25 @@ class ApkParser extends Zip {
'application.service',
'application.receiver',
'application.provider',
'permission-group'
]
})
return parser.parse()
'permission-group',
],
});
return parser.parse();
} catch (e) {
throw new Error('Parse AndroidManifest.xml error: ', e)
throw new Error('Parse AndroidManifest.xml error: ', e);
}
}
/**
* Parse resourceMap
* @param {Buffer} buffer // resourceMap file's buffer
*/
_parseResourceMap (buffer) {
_parseResourceMap(buffer) {
try {
return new ResourceFinder().processResourceTable(buffer)
return new ResourceFinder().processResourceTable(buffer);
} catch (e) {
throw new Error('Parser resources.arsc error: ' + e)
throw new Error('Parser resources.arsc error: ' + e);
}
}
}
module.exports = ApkParser
module.exports = ApkParser;

View File

@@ -1,16 +1,16 @@
const Zip = require('./zip')
const Zip = require('./zip');
class AppParser extends Zip {
/**
* parser for parsing .apk file
* @param {String | File | Blob} file // file's path in Node, instance of File or Blob in Browser
*/
constructor (file) {
super(file)
constructor(file) {
super(file);
if (!(this instanceof AppParser)) {
return new AppParser(file)
return new AppParser(file);
}
}
}
module.exports = AppParser
module.exports = AppParser;

View File

@@ -1,92 +1,104 @@
const parsePlist = require('plist').parse
const parseBplist = require('bplist-parser').parseBuffer
const cgbiToPng = require('cgbi-to-png')
const parsePlist = require('plist').parse;
const parseBplist = require('bplist-parser').parseBuffer;
const cgbiToPng = require('cgbi-to-png');
const Zip = require('./zip')
const { findIpaIconPath, getBase64FromBuffer, isBrowser } = require('./utils')
const Zip = require('./zip');
const { findIpaIconPath, getBase64FromBuffer, isBrowser } = require('./utils');
const PlistName = new RegExp('payload/[^/]+?.app/info.plist$', 'i')
const ProvisionName = /payload\/.+?\.app\/embedded.mobileprovision/
const PlistName = /payload\/[^\/]+?.app\/info.plist$/i;
const ProvisionName = /payload\/.+?\.app\/embedded.mobileprovision/;
class IpaParser extends Zip {
/**
* parser for parsing .ipa file
* @param {String | File | Blob} file // file's path in Node, instance of File or Blob in Browser
*/
constructor (file) {
super(file)
constructor(file) {
super(file);
if (!(this instanceof IpaParser)) {
return new IpaParser(file)
return new IpaParser(file);
}
}
parse () {
parse() {
return new Promise((resolve, reject) => {
this.getEntries([PlistName, ProvisionName]).then(buffers => {
if (!buffers[PlistName]) {
throw new Error('Info.plist can\'t be found.')
}
const plistInfo = this._parsePlist(buffers[PlistName])
// parse mobile provision
const provisionInfo = this._parseProvision(buffers[ProvisionName])
plistInfo.mobileProvision = provisionInfo
// find icon path and parse icon
const iconRegex = new RegExp(findIpaIconPath(plistInfo).toLowerCase())
this.getEntry(iconRegex).then(iconBuffer => {
try {
// In general, the ipa file's icon has been specially processed, should be converted
plistInfo.icon = iconBuffer ? getBase64FromBuffer(cgbiToPng.revert(iconBuffer)) : null
} catch (err) {
if (isBrowser()) {
// Normal conversion in other cases
plistInfo.icon = iconBuffer ? getBase64FromBuffer(window.btoa(String.fromCharCode(...iconBuffer))) : null
} else {
plistInfo.icon = null
console.warn('[Warning] failed to parse icon: ', err)
}
this.getEntries([PlistName, ProvisionName])
.then((buffers) => {
if (!buffers[PlistName]) {
throw new Error("Info.plist can't be found.");
}
resolve(plistInfo)
}).catch(e => {
reject(e)
const plistInfo = this._parsePlist(buffers[PlistName]);
// parse mobile provision
const provisionInfo = this._parseProvision(buffers[ProvisionName]);
plistInfo.mobileProvision = provisionInfo;
// find icon path and parse icon
const iconRegex = new RegExp(
findIpaIconPath(plistInfo).toLowerCase(),
);
this.getEntry(iconRegex)
.then((iconBuffer) => {
try {
// In general, the ipa file's icon has been specially processed, should be converted
plistInfo.icon = iconBuffer
? getBase64FromBuffer(cgbiToPng.revert(iconBuffer))
: null;
} catch (err) {
if (isBrowser()) {
// Normal conversion in other cases
plistInfo.icon = iconBuffer
? getBase64FromBuffer(
window.btoa(String.fromCharCode(...iconBuffer)),
)
: null;
} else {
plistInfo.icon = null;
console.warn('[Warning] failed to parse icon: ', err);
}
}
resolve(plistInfo);
})
.catch((e) => {
reject(e);
});
})
}).catch(e => {
reject(e)
})
})
.catch((e) => {
reject(e);
});
});
}
/**
* Parse plist
* @param {Buffer} buffer // plist file's buffer
*/
_parsePlist (buffer) {
let result
const bufferType = buffer[0]
_parsePlist(buffer) {
let result;
const bufferType = buffer[0];
if (bufferType === 60 || bufferType === '<' || bufferType === 239) {
result = parsePlist(buffer.toString())
result = parsePlist(buffer.toString());
} else if (bufferType === 98) {
result = parseBplist(buffer)[0]
result = parseBplist(buffer)[0];
} else {
throw new Error('Unknown plist buffer type.')
throw new Error('Unknown plist buffer type.');
}
return result
return result;
}
/**
* parse provision
* @param {Buffer} buffer // provision file's buffer
*/
_parseProvision (buffer) {
let info = {}
_parseProvision(buffer) {
let info = {};
if (buffer) {
let content = buffer.toString('utf-8')
const firstIndex = content.indexOf('<?xml')
const endIndex = content.indexOf('</plist>')
content = content.slice(firstIndex, endIndex + 8)
let content = buffer.toString('utf-8');
const firstIndex = content.indexOf('<?xml');
const endIndex = content.indexOf('</plist>');
content = content.slice(firstIndex, endIndex + 8);
if (content) {
info = parsePlist(content)
info = parsePlist(content);
}
}
return info
return info;
}
}
module.exports = IpaParser
module.exports = IpaParser;

View File

@@ -4,7 +4,7 @@
* Decode binary file `resources.arsc` from a .apk file to a JavaScript Object.
*/
var ByteBuffer = require("bytebuffer");
var ByteBuffer = require('bytebuffer');
var DEBUG = false;
@@ -39,13 +39,13 @@ function ResourceFinder() {
* @param len length
* @returns {Buffer}
*/
ResourceFinder.readBytes = function(bb, len) {
ResourceFinder.readBytes = (bb, len) => {
var uint8Array = new Uint8Array(len);
for (var i = 0; i < len; i++) {
uint8Array[i] = bb.readUint8();
}
return ByteBuffer.wrap(uint8Array, "binary", true);
return ByteBuffer.wrap(uint8Array, 'binary', true);
};
//
@@ -54,8 +54,8 @@ ResourceFinder.readBytes = function(bb, len) {
* @param {ByteBuffer} bb
* @return {Map<String, Set<String>>}
*/
ResourceFinder.prototype.processResourceTable = function(resourceBuffer) {
const bb = ByteBuffer.wrap(resourceBuffer, "binary", true);
ResourceFinder.prototype.processResourceTable = function (resourceBuffer) {
const bb = ByteBuffer.wrap(resourceBuffer, 'binary', true);
// Resource table structure
var type = bb.readShort(),
@@ -65,10 +65,10 @@ ResourceFinder.prototype.processResourceTable = function(resourceBuffer) {
buffer,
bb2;
if (type != RES_TABLE_TYPE) {
throw new Error("No RES_TABLE_TYPE found!");
throw new Error('No RES_TABLE_TYPE found!');
}
if (size != bb.limit) {
throw new Error("The buffer size not matches to the resource table size.");
throw new Error('The buffer size not matches to the resource table size.');
}
bb.offset = headerSize;
@@ -90,14 +90,14 @@ ResourceFinder.prototype.processResourceTable = function(resourceBuffer) {
if (realStringPoolCount == 0) {
// Only the first string pool is processed.
if (DEBUG) {
console.log("Processing the string pool ...");
console.log('Processing the string pool ...');
}
buffer = new ByteBuffer(s);
bb.offset = pos;
bb.prependTo(buffer);
bb2 = ByteBuffer.wrap(buffer, "binary", true);
bb2 = ByteBuffer.wrap(buffer, 'binary', true);
bb2.LE();
this.valueStringPool = this.processStringPool(bb2);
@@ -106,30 +106,30 @@ ResourceFinder.prototype.processResourceTable = function(resourceBuffer) {
} else if (t == RES_TABLE_PACKAGE_TYPE) {
// Process the package
if (DEBUG) {
console.log("Processing the package " + realPackageCount + " ...");
console.log('Processing the package ' + realPackageCount + ' ...');
}
buffer = new ByteBuffer(s);
bb.offset = pos;
bb.prependTo(buffer);
bb2 = ByteBuffer.wrap(buffer, "binary", true);
bb2 = ByteBuffer.wrap(buffer, 'binary', true);
bb2.LE();
this.processPackage(bb2);
realPackageCount++;
} else {
throw new Error("Unsupported type");
throw new Error('Unsupported type');
}
bb.offset = pos + s;
if (!bb.remaining()) break;
}
if (realStringPoolCount != 1) {
throw new Error("More than 1 string pool found!");
throw new Error('More than 1 string pool found!');
}
if (realPackageCount != packageCount) {
throw new Error("Real package count not equals the declared count.");
throw new Error('Real package count not equals the declared count.');
}
return this.responseMap;
@@ -139,7 +139,7 @@ ResourceFinder.prototype.processResourceTable = function(resourceBuffer) {
*
* @param {ByteBuffer} bb
*/
ResourceFinder.prototype.processPackage = function(bb) {
ResourceFinder.prototype.processPackage = function (bb) {
// Package structure
var type = bb.readShort(),
headerSize = bb.readShort(),
@@ -159,12 +159,12 @@ ResourceFinder.prototype.processPackage = function(bb) {
if (typeStrings != headerSize) {
throw new Error(
"TypeStrings must immediately following the package structure header."
'TypeStrings must immediately following the package structure header.',
);
}
if (DEBUG) {
console.log("Type strings:");
console.log('Type strings:');
}
var lastPosition = bb.offset;
@@ -175,7 +175,7 @@ ResourceFinder.prototype.processPackage = function(bb) {
// Key strings
if (DEBUG) {
console.log("Key strings:");
console.log('Key strings:');
}
bb.offset = keyStrings;
@@ -237,7 +237,7 @@ ResourceFinder.prototype.processPackage = function(bb) {
*
* @param {ByteBuffer} bb
*/
ResourceFinder.prototype.processType = function(bb) {
ResourceFinder.prototype.processType = function (bb) {
var type = bb.readShort(),
headerSize = bb.readShort(),
size = bb.readInt(),
@@ -255,7 +255,7 @@ ResourceFinder.prototype.processType = function(bb) {
bb.offset = headerSize;
if (headerSize + entryCount * 4 != entriesStart) {
throw new Error("HeaderSize, entryCount and entriesStart are not valid.");
throw new Error('HeaderSize, entryCount and entriesStart are not valid.');
}
// Start to get entry indices
@@ -279,11 +279,11 @@ ResourceFinder.prototype.processType = function(bb) {
value_dataType,
value_data;
try {
entry_size = bb.readShort()
entry_flag = bb.readShort()
entry_key = bb.readInt()
entry_size = bb.readShort();
entry_flag = bb.readShort();
entry_key = bb.readInt();
} catch (e) {
break
break;
}
// Get the value (simple) or map (complex)
@@ -303,11 +303,11 @@ ResourceFinder.prototype.processType = function(bb) {
if (DEBUG) {
console.log(
"Entry 0x" + idStr + ", key: " + keyStr + ", simple value type: "
'Entry 0x' + idStr + ', key: ' + keyStr + ', simple value type: ',
);
}
var key = parseInt(idStr, 16);
var key = Number.parseInt(idStr, 16);
var entryArr = this.entryMap[key];
if (entryArr == null) {
@@ -321,20 +321,20 @@ ResourceFinder.prototype.processType = function(bb) {
data = this.valueStringPool[value_data];
if (DEBUG) {
console.log(", data: " + this.valueStringPool[value_data] + "");
console.log(', data: ' + this.valueStringPool[value_data] + '');
}
} else if (value_dataType == TYPE_REFERENCE) {
var hexIndex = Number(value_data).toString(16);
refKeys[idStr] = value_data;
} else {
data = "" + value_data;
data = '' + value_data;
if (DEBUG) {
console.log(", data: " + value_data + "");
console.log(', data: ' + value_data + '');
}
}
this.putIntoMap("@" + idStr, data);
this.putIntoMap('@' + idStr, data);
} else {
// Complex case
var entry_parent = bb.readInt();
@@ -350,26 +350,22 @@ ResourceFinder.prototype.processType = function(bb) {
if (DEBUG) {
console.log(
"Entry 0x" +
'Entry 0x' +
Number(resource_id).toString(16) +
", key: " +
', key: ' +
this.keyStringPool[entry_key] +
", complex value, not printed."
', complex value, not printed.',
);
}
}
}
for (var refK in refKeys) {
var values = this.responseMap[
"@" +
Number(refKeys[refK])
.toString(16)
.toUpperCase()
];
var values =
this.responseMap['@' + Number(refKeys[refK]).toString(16).toUpperCase()];
if (values != null && Object.keys(values).length < 1000) {
for (var value in values) {
this.putIntoMap("@" + refK, values[value]);
this.putIntoMap('@' + refK, values[value]);
}
}
}
@@ -380,7 +376,7 @@ ResourceFinder.prototype.processType = function(bb) {
* @param {ByteBuffer} bb
* @return {Array}
*/
ResourceFinder.prototype.processStringPool = function(bb) {
ResourceFinder.prototype.processStringPool = (bb) => {
// String pool structure
//
var type = bb.readShort(),
@@ -407,7 +403,7 @@ ResourceFinder.prototype.processStringPool = function(bb) {
var pos = stringsStart + offsets[i];
bb.offset = pos;
strings[i] = "";
strings[i] = '';
if (isUTF_8) {
u16len = bb.readUint8();
@@ -424,15 +420,15 @@ ResourceFinder.prototype.processStringPool = function(bb) {
if (u8len > 0) {
buffer = ResourceFinder.readBytes(bb, u8len);
try {
strings[i] = ByteBuffer.wrap(buffer, "utf8", true).toString("utf8");
strings[i] = ByteBuffer.wrap(buffer, 'utf8', true).toString('utf8');
} catch (e) {
if (DEBUG) {
console.error(e);
console.log("Error when turning buffer to utf-8 string.");
console.log('Error when turning buffer to utf-8 string.');
}
}
} else {
strings[i] = "";
strings[i] = '';
}
} else {
u16len = bb.readUint16();
@@ -445,18 +441,18 @@ ResourceFinder.prototype.processStringPool = function(bb) {
var len = u16len * 2;
buffer = ResourceFinder.readBytes(bb, len);
try {
strings[i] = ByteBuffer.wrap(buffer, "utf8", true).toString("utf8");
strings[i] = ByteBuffer.wrap(buffer, 'utf8', true).toString('utf8');
} catch (e) {
if (DEBUG) {
console.error(e);
console.log("Error when turning buffer to utf-8 string.");
console.log('Error when turning buffer to utf-8 string.');
}
}
}
}
if (DEBUG) {
console.log("Parsed value: {0}", strings[i]);
console.log('Parsed value: {0}', strings[i]);
}
}
@@ -467,7 +463,7 @@ ResourceFinder.prototype.processStringPool = function(bb) {
*
* @param {ByteBuffer} bb
*/
ResourceFinder.prototype.processTypeSpec = function(bb) {
ResourceFinder.prototype.processTypeSpec = function (bb) {
var type = bb.readShort(),
headerSize = bb.readShort(),
size = bb.readInt(),
@@ -477,7 +473,7 @@ ResourceFinder.prototype.processTypeSpec = function(bb) {
entryCount = bb.readInt();
if (DEBUG) {
console.log("Processing type spec " + this.typeStringPool[id - 1] + "...");
console.log('Processing type spec ' + this.typeStringPool[id - 1] + '...');
}
var flags = new Array(entryCount);
@@ -487,12 +483,12 @@ ResourceFinder.prototype.processTypeSpec = function(bb) {
}
};
ResourceFinder.prototype.putIntoMap = function(resId, value) {
ResourceFinder.prototype.putIntoMap = function (resId, value) {
if (this.responseMap[resId.toUpperCase()] == null) {
this.responseMap[resId.toUpperCase()] = []
this.responseMap[resId.toUpperCase()] = [];
}
if(value){
this.responseMap[resId.toUpperCase()].push(value)
if (value) {
this.responseMap[resId.toUpperCase()].push(value);
}
};

View File

@@ -1,24 +1,27 @@
function objectType (o) {
return Object.prototype.toString.call(o).slice(8, -1).toLowerCase()
function objectType(o) {
return Object.prototype.toString.call(o).slice(8, -1).toLowerCase();
}
function isArray (o) {
return objectType(o) === 'array'
function isArray(o) {
return objectType(o) === 'array';
}
function isObject (o) {
return objectType(o) === 'object'
function isObject(o) {
return objectType(o) === 'object';
}
function isPrimitive (o) {
return o === null || ['boolean', 'number', 'string', 'undefined'].includes(objectType(o))
function isPrimitive(o) {
return (
o === null ||
['boolean', 'number', 'string', 'undefined'].includes(objectType(o))
);
}
function isBrowser () {
function isBrowser() {
return (
typeof process === 'undefined' ||
Object.prototype.toString.call(process) !== '[object process]'
)
);
}
/**
@@ -26,48 +29,48 @@ function isBrowser () {
* @param {Object} apkInfo // json info parsed from .apk file
* @param {Object} resourceMap // resourceMap
*/
function mapInfoResource (apkInfo, resourceMap) {
iteratorObj(apkInfo)
return apkInfo
function iteratorObj (obj) {
function mapInfoResource(apkInfo, resourceMap) {
iteratorObj(apkInfo);
return apkInfo;
function iteratorObj(obj) {
for (const i in obj) {
if (isArray(obj[i])) {
iteratorArray(obj[i])
iteratorArray(obj[i]);
} else if (isObject(obj[i])) {
iteratorObj(obj[i])
iteratorObj(obj[i]);
} else if (isPrimitive(obj[i])) {
if (isResources(obj[i])) {
obj[i] = resourceMap[transKeyToMatchResourceMap(obj[i])]
obj[i] = resourceMap[transKeyToMatchResourceMap(obj[i])];
}
}
}
}
function iteratorArray (array) {
const l = array.length
function iteratorArray(array) {
const l = array.length;
for (let i = 0; i < l; i++) {
if (isArray(array[i])) {
iteratorArray(array[i])
iteratorArray(array[i]);
} else if (isObject(array[i])) {
iteratorObj(array[i])
iteratorObj(array[i]);
} else if (isPrimitive(array[i])) {
if (isResources(array[i])) {
array[i] = resourceMap[transKeyToMatchResourceMap(array[i])]
array[i] = resourceMap[transKeyToMatchResourceMap(array[i])];
}
}
}
}
function isResources (attrValue) {
if (!attrValue) return false
function isResources(attrValue) {
if (!attrValue) return false;
if (typeof attrValue !== 'string') {
attrValue = attrValue.toString()
attrValue = attrValue.toString();
}
return attrValue.indexOf('resourceId:') === 0
return attrValue.indexOf('resourceId:') === 0;
}
function transKeyToMatchResourceMap (resourceId) {
return '@' + resourceId.replace('resourceId:0x', '').toUpperCase()
function transKeyToMatchResourceMap(resourceId) {
return '@' + resourceId.replace('resourceId:0x', '').toUpperCase();
}
}
@@ -75,62 +78,64 @@ function mapInfoResource (apkInfo, resourceMap) {
* find .apk file's icon path from json info
* @param info // json info parsed from .apk file
*/
function findApkIconPath (info) {
function findApkIconPath(info) {
if (!info.application.icon || !info.application.icon.splice) {
return ''
return '';
}
const rulesMap = {
mdpi: 48,
hdpi: 72,
xhdpi: 96,
xxdpi: 144,
xxxhdpi: 192
}
const resultMap = {}
const maxDpiIcon = { dpi: 120, icon: '' }
xxxhdpi: 192,
};
const resultMap = {};
const maxDpiIcon = { dpi: 120, icon: '' };
for (const i in rulesMap) {
info.application.icon.some((icon) => {
if (icon && icon.indexOf(i) !== -1) {
resultMap['application-icon-' + rulesMap[i]] = icon
return true
resultMap['application-icon-' + rulesMap[i]] = icon;
return true;
}
})
});
// get the maximal size icon
if (
resultMap['application-icon-' + rulesMap[i]] &&
rulesMap[i] >= maxDpiIcon.dpi
) {
maxDpiIcon.dpi = rulesMap[i]
maxDpiIcon.icon = resultMap['application-icon-' + rulesMap[i]]
maxDpiIcon.dpi = rulesMap[i];
maxDpiIcon.icon = resultMap['application-icon-' + rulesMap[i]];
}
}
if (Object.keys(resultMap).length === 0 || !maxDpiIcon.icon) {
maxDpiIcon.dpi = 120
maxDpiIcon.icon = info.application.icon[0] || ''
resultMap['applicataion-icon-120'] = maxDpiIcon.icon
maxDpiIcon.dpi = 120;
maxDpiIcon.icon = info.application.icon[0] || '';
resultMap['applicataion-icon-120'] = maxDpiIcon.icon;
}
return maxDpiIcon.icon
return maxDpiIcon.icon;
}
/**
* find .ipa file's icon path from json info
* @param info // json info parsed from .ipa file
*/
function findIpaIconPath (info) {
function findIpaIconPath(info) {
if (
info.CFBundleIcons &&
info.CFBundleIcons.CFBundlePrimaryIcon &&
info.CFBundleIcons.CFBundlePrimaryIcon.CFBundleIconFiles &&
info.CFBundleIcons.CFBundlePrimaryIcon.CFBundleIconFiles.length
) {
return info.CFBundleIcons.CFBundlePrimaryIcon.CFBundleIconFiles[info.CFBundleIcons.CFBundlePrimaryIcon.CFBundleIconFiles.length - 1]
return info.CFBundleIcons.CFBundlePrimaryIcon.CFBundleIconFiles[
info.CFBundleIcons.CFBundlePrimaryIcon.CFBundleIconFiles.length - 1
];
} else if (info.CFBundleIconFiles && info.CFBundleIconFiles.length) {
return info.CFBundleIconFiles[info.CFBundleIconFiles.length - 1]
return info.CFBundleIconFiles[info.CFBundleIconFiles.length - 1];
} else {
return '.app/Icon.png'
return '.app/Icon.png';
}
}
@@ -138,20 +143,20 @@ function findIpaIconPath (info) {
* transform buffer to base64
* @param {Buffer} buffer
*/
function getBase64FromBuffer (buffer) {
return 'data:image/png;base64,' + buffer.toString('base64')
function getBase64FromBuffer(buffer) {
return 'data:image/png;base64,' + buffer.toString('base64');
}
/**
* 去除unicode空字符
* @param {String} str
*/
function decodeNullUnicode (str) {
function decodeNullUnicode(str) {
if (typeof str === 'string') {
// eslint-disable-next-line
str = str.replace(/\u0000/g, '')
str = str.replace(/\u0000/g, '');
}
return str
return str;
}
module.exports = {
@@ -163,5 +168,5 @@ module.exports = {
findApkIconPath,
findIpaIconPath,
getBase64FromBuffer,
decodeNullUnicode
}
decodeNullUnicode,
};

View File

@@ -2,8 +2,8 @@
const NodeType = {
ELEMENT_NODE: 1,
ATTRIBUTE_NODE: 2,
CDATA_SECTION_NODE: 4
}
CDATA_SECTION_NODE: 4,
};
const ChunkType = {
NULL: 0x0000,
@@ -20,13 +20,13 @@ const ChunkType = {
XML_RESOURCE_MAP: 0x0180,
TABLE_PACKAGE: 0x0200,
TABLE_TYPE: 0x0201,
TABLE_TYPE_SPEC: 0x0202
}
TABLE_TYPE_SPEC: 0x0202,
};
const StringFlags = {
SORTED: 1 << 0,
UTF8: 1 << 8
}
UTF8: 1 << 8,
};
// Taken from android.util.TypedValue
const TypedValue = {
@@ -67,381 +67,390 @@ const TypedValue = {
TYPE_LAST_INT: 0x0000001f,
TYPE_NULL: 0x00000000,
TYPE_REFERENCE: 0x00000001,
TYPE_STRING: 0x00000003
}
TYPE_STRING: 0x00000003,
};
class BinaryXmlParser {
constructor (buffer, options = {}) {
this.buffer = buffer
this.cursor = 0
this.strings = []
this.resources = []
this.document = null
this.parent = null
this.stack = []
this.debug = options.debug || false
constructor(buffer, options = {}) {
this.buffer = buffer;
this.cursor = 0;
this.strings = [];
this.resources = [];
this.document = null;
this.parent = null;
this.stack = [];
this.debug = options.debug || false;
}
readU8 () {
this.debug && console.group('readU8')
this.debug && console.debug('cursor:', this.cursor)
const val = this.buffer[this.cursor]
this.debug && console.debug('value:', val)
this.cursor += 1
this.debug && console.groupEnd()
return val
readU8() {
this.debug && console.group('readU8');
this.debug && console.debug('cursor:', this.cursor);
const val = this.buffer[this.cursor];
this.debug && console.debug('value:', val);
this.cursor += 1;
this.debug && console.groupEnd();
return val;
}
readU16 () {
this.debug && console.group('readU16')
this.debug && console.debug('cursor:', this.cursor)
const val = this.buffer.readUInt16LE(this.cursor)
this.debug && console.debug('value:', val)
this.cursor += 2
this.debug && console.groupEnd()
return val
readU16() {
this.debug && console.group('readU16');
this.debug && console.debug('cursor:', this.cursor);
const val = this.buffer.readUInt16LE(this.cursor);
this.debug && console.debug('value:', val);
this.cursor += 2;
this.debug && console.groupEnd();
return val;
}
readS32 () {
this.debug && console.group('readS32')
this.debug && console.debug('cursor:', this.cursor)
const val = this.buffer.readInt32LE(this.cursor)
this.debug && console.debug('value:', val)
this.cursor += 4
this.debug && console.groupEnd()
return val
readS32() {
this.debug && console.group('readS32');
this.debug && console.debug('cursor:', this.cursor);
const val = this.buffer.readInt32LE(this.cursor);
this.debug && console.debug('value:', val);
this.cursor += 4;
this.debug && console.groupEnd();
return val;
}
readU32 () {
this.debug && console.group('readU32')
this.debug && console.debug('cursor:', this.cursor)
const val = this.buffer.readUInt32LE(this.cursor)
this.debug && console.debug('value:', val)
this.cursor += 4
this.debug && console.groupEnd()
return val
readU32() {
this.debug && console.group('readU32');
this.debug && console.debug('cursor:', this.cursor);
const val = this.buffer.readUInt32LE(this.cursor);
this.debug && console.debug('value:', val);
this.cursor += 4;
this.debug && console.groupEnd();
return val;
}
readLength8 () {
this.debug && console.group('readLength8')
let len = this.readU8()
readLength8() {
this.debug && console.group('readLength8');
let len = this.readU8();
if (len & 0x80) {
len = (len & 0x7f) << 8
len += this.readU8()
len = (len & 0x7f) << 8;
len += this.readU8();
}
this.debug && console.debug('length:', len)
this.debug && console.groupEnd()
return len
this.debug && console.debug('length:', len);
this.debug && console.groupEnd();
return len;
}
readLength16 () {
this.debug && console.group('readLength16')
let len = this.readU16()
readLength16() {
this.debug && console.group('readLength16');
let len = this.readU16();
if (len & 0x8000) {
len = (len & 0x7fff) << 16
len += this.readU16()
len = (len & 0x7fff) << 16;
len += this.readU16();
}
this.debug && console.debug('length:', len)
this.debug && console.groupEnd()
return len
this.debug && console.debug('length:', len);
this.debug && console.groupEnd();
return len;
}
readDimension () {
this.debug && console.group('readDimension')
readDimension() {
this.debug && console.group('readDimension');
const dimension = {
value: null,
unit: null,
rawUnit: null
}
rawUnit: null,
};
const value = this.readU32()
const unit = dimension.value & 0xff
const value = this.readU32();
const unit = dimension.value & 0xff;
dimension.value = value >> 8
dimension.rawUnit = unit
dimension.value = value >> 8;
dimension.rawUnit = unit;
switch (unit) {
case TypedValue.COMPLEX_UNIT_MM:
dimension.unit = 'mm'
break
dimension.unit = 'mm';
break;
case TypedValue.COMPLEX_UNIT_PX:
dimension.unit = 'px'
break
dimension.unit = 'px';
break;
case TypedValue.COMPLEX_UNIT_DIP:
dimension.unit = 'dp'
break
dimension.unit = 'dp';
break;
case TypedValue.COMPLEX_UNIT_SP:
dimension.unit = 'sp'
break
dimension.unit = 'sp';
break;
case TypedValue.COMPLEX_UNIT_PT:
dimension.unit = 'pt'
break
dimension.unit = 'pt';
break;
case TypedValue.COMPLEX_UNIT_IN:
dimension.unit = 'in'
break
dimension.unit = 'in';
break;
}
this.debug && console.groupEnd()
this.debug && console.groupEnd();
return dimension
return dimension;
}
readFraction () {
this.debug && console.group('readFraction')
readFraction() {
this.debug && console.group('readFraction');
const fraction = {
value: null,
type: null,
rawType: null
}
rawType: null,
};
const value = this.readU32()
const type = value & 0xf
const value = this.readU32();
const type = value & 0xf;
fraction.value = this.convertIntToFloat(value >> 4)
fraction.rawType = type
fraction.value = this.convertIntToFloat(value >> 4);
fraction.rawType = type;
switch (type) {
case TypedValue.COMPLEX_UNIT_FRACTION:
fraction.type = '%'
break
fraction.type = '%';
break;
case TypedValue.COMPLEX_UNIT_FRACTION_PARENT:
fraction.type = '%p'
break
fraction.type = '%p';
break;
}
this.debug && console.groupEnd()
this.debug && console.groupEnd();
return fraction
return fraction;
}
readHex24 () {
this.debug && console.group('readHex24')
var val = (this.readU32() & 0xffffff).toString(16)
this.debug && console.groupEnd()
return val
readHex24() {
this.debug && console.group('readHex24');
var val = (this.readU32() & 0xffffff).toString(16);
this.debug && console.groupEnd();
return val;
}
readHex32 () {
this.debug && console.group('readHex32')
var val = this.readU32().toString(16)
this.debug && console.groupEnd()
return val
readHex32() {
this.debug && console.group('readHex32');
var val = this.readU32().toString(16);
this.debug && console.groupEnd();
return val;
}
readTypedValue () {
this.debug && console.group('readTypedValue')
readTypedValue() {
this.debug && console.group('readTypedValue');
const typedValue = {
value: null,
type: null,
rawType: null
}
rawType: null,
};
const start = this.cursor
const start = this.cursor;
let size = this.readU16()
/* const zero = */ this.readU8()
const dataType = this.readU8()
let size = this.readU16();
/* const zero = */ this.readU8();
const dataType = this.readU8();
// Yes, there has been a real world APK where the size is malformed.
if (size === 0) {
size = 8
size = 8;
}
typedValue.rawType = dataType
typedValue.rawType = dataType;
switch (dataType) {
case TypedValue.TYPE_INT_DEC:
typedValue.value = this.readS32()
typedValue.type = 'int_dec'
break
typedValue.value = this.readS32();
typedValue.type = 'int_dec';
break;
case TypedValue.TYPE_INT_HEX:
typedValue.value = this.readS32()
typedValue.type = 'int_hex'
break
typedValue.value = this.readS32();
typedValue.type = 'int_hex';
break;
case TypedValue.TYPE_STRING:
var ref = this.readS32()
typedValue.value = ref > 0 ? this.strings[ref] : ''
typedValue.type = 'string'
break
var ref = this.readS32();
typedValue.value = ref > 0 ? this.strings[ref] : '';
typedValue.type = 'string';
break;
case TypedValue.TYPE_REFERENCE:
var id = this.readU32()
typedValue.value = `resourceId:0x${id.toString(16)}`
typedValue.type = 'reference'
break
var id = this.readU32();
typedValue.value = `resourceId:0x${id.toString(16)}`;
typedValue.type = 'reference';
break;
case TypedValue.TYPE_INT_BOOLEAN:
typedValue.value = this.readS32() !== 0
typedValue.type = 'boolean'
break
typedValue.value = this.readS32() !== 0;
typedValue.type = 'boolean';
break;
case TypedValue.TYPE_NULL:
this.readU32()
typedValue.value = null
typedValue.type = 'null'
break
this.readU32();
typedValue.value = null;
typedValue.type = 'null';
break;
case TypedValue.TYPE_INT_COLOR_RGB8:
typedValue.value = this.readHex24()
typedValue.type = 'rgb8'
break
typedValue.value = this.readHex24();
typedValue.type = 'rgb8';
break;
case TypedValue.TYPE_INT_COLOR_RGB4:
typedValue.value = this.readHex24()
typedValue.type = 'rgb4'
break
typedValue.value = this.readHex24();
typedValue.type = 'rgb4';
break;
case TypedValue.TYPE_INT_COLOR_ARGB8:
typedValue.value = this.readHex32()
typedValue.type = 'argb8'
break
typedValue.value = this.readHex32();
typedValue.type = 'argb8';
break;
case TypedValue.TYPE_INT_COLOR_ARGB4:
typedValue.value = this.readHex32()
typedValue.type = 'argb4'
break
typedValue.value = this.readHex32();
typedValue.type = 'argb4';
break;
case TypedValue.TYPE_DIMENSION:
typedValue.value = this.readDimension()
typedValue.type = 'dimension'
break
typedValue.value = this.readDimension();
typedValue.type = 'dimension';
break;
case TypedValue.TYPE_FRACTION:
typedValue.value = this.readFraction()
typedValue.type = 'fraction'
break
typedValue.value = this.readFraction();
typedValue.type = 'fraction';
break;
default: {
const type = dataType.toString(16)
console.debug(`Not sure what to do with typed value of type 0x${type}, falling back to reading an uint32.`)
typedValue.value = this.readU32()
typedValue.type = 'unknown'
const type = dataType.toString(16);
console.debug(
`Not sure what to do with typed value of type 0x${type}, falling back to reading an uint32.`,
);
typedValue.value = this.readU32();
typedValue.type = 'unknown';
}
}
// Ensure we consume the whole value
const end = start + size
const end = start + size;
if (this.cursor !== end) {
const type = dataType.toString(16)
const diff = end - this.cursor
const type = dataType.toString(16);
const diff = end - this.cursor;
console.debug(`Cursor is off by ${diff} bytes at ${this.cursor} at supposed end \
of typed value of type 0x${type}. The typed value started at offset ${start} \
and is supposed to end at offset ${end}. Ignoring the rest of the value.`)
this.cursor = end
and is supposed to end at offset ${end}. Ignoring the rest of the value.`);
this.cursor = end;
}
this.debug && console.groupEnd()
this.debug && console.groupEnd();
return typedValue
return typedValue;
}
// https://twitter.com/kawasima/status/427730289201139712
convertIntToFloat (int) {
const buf = new ArrayBuffer(4)
;(new Int32Array(buf))[0] = int
return (new Float32Array(buf))[0]
convertIntToFloat(int) {
const buf = new ArrayBuffer(4);
new Int32Array(buf)[0] = int;
return new Float32Array(buf)[0];
}
readString (encoding) {
this.debug && console.group('readString', encoding)
readString(encoding) {
this.debug && console.group('readString', encoding);
switch (encoding) {
case 'utf-8':
var stringLength = this.readLength8(encoding)
this.debug && console.debug('stringLength:', stringLength)
var byteLength = this.readLength8(encoding)
this.debug && console.debug('byteLength:', byteLength)
var value = this.buffer.toString(encoding, this.cursor, (this.cursor += byteLength))
this.debug && console.debug('value:', value)
this.debug && console.groupEnd()
return value
var stringLength = this.readLength8(encoding);
this.debug && console.debug('stringLength:', stringLength);
var byteLength = this.readLength8(encoding);
this.debug && console.debug('byteLength:', byteLength);
var value = this.buffer.toString(
encoding,
this.cursor,
(this.cursor += byteLength),
);
this.debug && console.debug('value:', value);
this.debug && console.groupEnd();
return value;
case 'ucs2':
stringLength = this.readLength16(encoding)
this.debug && console.debug('stringLength:', stringLength)
byteLength = stringLength * 2
this.debug && console.debug('byteLength:', byteLength)
value = this.buffer.toString(encoding, this.cursor, (this.cursor += byteLength))
this.debug && console.debug('value:', value)
this.debug && console.groupEnd()
return value
stringLength = this.readLength16(encoding);
this.debug && console.debug('stringLength:', stringLength);
byteLength = stringLength * 2;
this.debug && console.debug('byteLength:', byteLength);
value = this.buffer.toString(
encoding,
this.cursor,
(this.cursor += byteLength),
);
this.debug && console.debug('value:', value);
this.debug && console.groupEnd();
return value;
default:
throw new Error(`Unsupported encoding '${encoding}'`)
throw new Error(`Unsupported encoding '${encoding}'`);
}
}
readChunkHeader () {
this.debug && console.group('readChunkHeader')
readChunkHeader() {
this.debug && console.group('readChunkHeader');
var header = {
startOffset: this.cursor,
chunkType: this.readU16(),
headerSize: this.readU16(),
chunkSize: this.readU32()
}
this.debug && console.debug('startOffset:', header.startOffset)
this.debug && console.debug('chunkType:', header.chunkType)
this.debug && console.debug('headerSize:', header.headerSize)
this.debug && console.debug('chunkSize:', header.chunkSize)
this.debug && console.groupEnd()
return header
chunkSize: this.readU32(),
};
this.debug && console.debug('startOffset:', header.startOffset);
this.debug && console.debug('chunkType:', header.chunkType);
this.debug && console.debug('headerSize:', header.headerSize);
this.debug && console.debug('chunkSize:', header.chunkSize);
this.debug && console.groupEnd();
return header;
}
readStringPool (header) {
this.debug && console.group('readStringPool')
readStringPool(header) {
this.debug && console.group('readStringPool');
header.stringCount = this.readU32()
this.debug && console.debug('stringCount:', header.stringCount)
header.styleCount = this.readU32()
this.debug && console.debug('styleCount:', header.styleCount)
header.flags = this.readU32()
this.debug && console.debug('flags:', header.flags)
header.stringsStart = this.readU32()
this.debug && console.debug('stringsStart:', header.stringsStart)
header.stylesStart = this.readU32()
this.debug && console.debug('stylesStart:', header.stylesStart)
header.stringCount = this.readU32();
this.debug && console.debug('stringCount:', header.stringCount);
header.styleCount = this.readU32();
this.debug && console.debug('styleCount:', header.styleCount);
header.flags = this.readU32();
this.debug && console.debug('flags:', header.flags);
header.stringsStart = this.readU32();
this.debug && console.debug('stringsStart:', header.stringsStart);
header.stylesStart = this.readU32();
this.debug && console.debug('stylesStart:', header.stylesStart);
if (header.chunkType !== ChunkType.STRING_POOL) {
throw new Error('Invalid string pool header')
throw new Error('Invalid string pool header');
}
const offsets = []
const offsets = [];
for (let i = 0, l = header.stringCount; i < l; ++i) {
this.debug && console.debug('offset:', i)
offsets.push(this.readU32())
this.debug && console.debug('offset:', i);
offsets.push(this.readU32());
}
const sorted = (header.flags & StringFlags.SORTED) === StringFlags.SORTED
this.debug && console.debug('sorted:', sorted)
const encoding = (header.flags & StringFlags.UTF8) === StringFlags.UTF8
? 'utf-8'
: 'ucs2'
this.debug && console.debug('encoding:', encoding)
const sorted = (header.flags & StringFlags.SORTED) === StringFlags.SORTED;
this.debug && console.debug('sorted:', sorted);
const encoding =
(header.flags & StringFlags.UTF8) === StringFlags.UTF8 ? 'utf-8' : 'ucs2';
this.debug && console.debug('encoding:', encoding);
const stringsStart = header.startOffset + header.stringsStart
this.cursor = stringsStart
const stringsStart = header.startOffset + header.stringsStart;
this.cursor = stringsStart;
for (let i = 0, l = header.stringCount; i < l; ++i) {
this.debug && console.debug('string:', i)
this.debug && console.debug('offset:', offsets[i])
this.cursor = stringsStart + offsets[i]
this.strings.push(this.readString(encoding))
this.debug && console.debug('string:', i);
this.debug && console.debug('offset:', offsets[i]);
this.cursor = stringsStart + offsets[i];
this.strings.push(this.readString(encoding));
}
// Skip styles
this.cursor = header.startOffset + header.chunkSize
this.cursor = header.startOffset + header.chunkSize;
this.debug && console.groupEnd()
this.debug && console.groupEnd();
return null
return null;
}
readResourceMap (header) {
this.debug && console.group('readResourceMap')
const count = Math.floor((header.chunkSize - header.headerSize) / 4)
readResourceMap(header) {
this.debug && console.group('readResourceMap');
const count = Math.floor((header.chunkSize - header.headerSize) / 4);
for (let i = 0; i < count; ++i) {
this.resources.push(this.readU32())
this.resources.push(this.readU32());
}
this.debug && console.groupEnd()
return null
this.debug && console.groupEnd();
return null;
}
readXmlNamespaceStart (/* header */) {
this.debug && console.group('readXmlNamespaceStart')
readXmlNamespaceStart(/* header */) {
this.debug && console.group('readXmlNamespaceStart');
/* const line = */ this.readU32()
/* const commentRef = */ this.readU32()
/* const prefixRef = */ this.readS32()
/* const uriRef = */ this.readS32()
/* const line = */ this.readU32();
/* const commentRef = */ this.readU32();
/* const prefixRef = */ this.readS32();
/* const uriRef = */ this.readS32();
// We don't currently care about the values, but they could
// be accessed like so:
@@ -449,18 +458,18 @@ and is supposed to end at offset ${end}. Ignoring the rest of the value.`)
// namespaceURI.prefix = this.strings[prefixRef] // if prefixRef > 0
// namespaceURI.uri = this.strings[uriRef] // if uriRef > 0
this.debug && console.groupEnd()
this.debug && console.groupEnd();
return null
return null;
}
readXmlNamespaceEnd (/* header */) {
this.debug && console.group('readXmlNamespaceEnd')
readXmlNamespaceEnd(/* header */) {
this.debug && console.group('readXmlNamespaceEnd');
/* const line = */ this.readU32()
/* const commentRef = */ this.readU32()
/* const prefixRef = */ this.readS32()
/* const uriRef = */ this.readS32()
/* const line = */ this.readU32();
/* const commentRef = */ this.readU32();
/* const prefixRef = */ this.readS32();
/* const uriRef = */ this.readS32();
// We don't currently care about the values, but they could
// be accessed like so:
@@ -468,60 +477,60 @@ and is supposed to end at offset ${end}. Ignoring the rest of the value.`)
// namespaceURI.prefix = this.strings[prefixRef] // if prefixRef > 0
// namespaceURI.uri = this.strings[uriRef] // if uriRef > 0
this.debug && console.groupEnd()
this.debug && console.groupEnd();
return null
return null;
}
readXmlElementStart (/* header */) {
this.debug && console.group('readXmlElementStart')
readXmlElementStart(/* header */) {
this.debug && console.group('readXmlElementStart');
const node = {
namespaceURI: null,
nodeType: NodeType.ELEMENT_NODE,
nodeName: null,
attributes: [],
childNodes: []
}
childNodes: [],
};
/* const line = */ this.readU32()
/* const commentRef = */ this.readU32()
const nsRef = this.readS32()
const nameRef = this.readS32()
/* const line = */ this.readU32();
/* const commentRef = */ this.readU32();
const nsRef = this.readS32();
const nameRef = this.readS32();
if (nsRef > 0) {
node.namespaceURI = this.strings[nsRef]
node.namespaceURI = this.strings[nsRef];
}
node.nodeName = this.strings[nameRef]
node.nodeName = this.strings[nameRef];
/* const attrStart = */ this.readU16()
/* const attrSize = */ this.readU16()
const attrCount = this.readU16()
/* const idIndex = */ this.readU16()
/* const classIndex = */ this.readU16()
/* const styleIndex = */ this.readU16()
/* const attrStart = */ this.readU16();
/* const attrSize = */ this.readU16();
const attrCount = this.readU16();
/* const idIndex = */ this.readU16();
/* const classIndex = */ this.readU16();
/* const styleIndex = */ this.readU16();
for (let i = 0; i < attrCount; ++i) {
node.attributes.push(this.readXmlAttribute())
node.attributes.push(this.readXmlAttribute());
}
if (this.document) {
this.parent.childNodes.push(node)
this.parent = node
this.parent.childNodes.push(node);
this.parent = node;
} else {
this.document = (this.parent = node)
this.document = this.parent = node;
}
this.stack.push(node)
this.stack.push(node);
this.debug && console.groupEnd()
this.debug && console.groupEnd();
return node
return node;
}
readXmlAttribute () {
this.debug && console.group('readXmlAttribute')
readXmlAttribute() {
this.debug && console.group('readXmlAttribute');
const attr = {
namespaceURI: null,
@@ -529,146 +538,149 @@ and is supposed to end at offset ${end}. Ignoring the rest of the value.`)
nodeName: null,
name: null,
value: null,
typedValue: null
}
typedValue: null,
};
const nsRef = this.readS32()
const nameRef = this.readS32()
const valueRef = this.readS32()
const nsRef = this.readS32();
const nameRef = this.readS32();
const valueRef = this.readS32();
if (nsRef > 0) {
attr.namespaceURI = this.strings[nsRef]
attr.namespaceURI = this.strings[nsRef];
}
attr.nodeName = attr.name = this.strings[nameRef]
attr.nodeName = attr.name = this.strings[nameRef];
if (valueRef > 0) {
// some apk have versionName with special characters
if (attr.name === 'versionName') {
// only keep printable characters
// https://www.ascii-code.com/characters/printable-characters
this.strings[valueRef] = this.strings[valueRef].replace(/[^\x21-\x7E]/g, '')
this.strings[valueRef] = this.strings[valueRef].replace(
/[^\x21-\x7E]/g,
'',
);
}
attr.value = this.strings[valueRef]
attr.value = this.strings[valueRef];
}
attr.typedValue = this.readTypedValue()
attr.typedValue = this.readTypedValue();
this.debug && console.groupEnd()
this.debug && console.groupEnd();
return attr
return attr;
}
readXmlElementEnd (/* header */) {
this.debug && console.group('readXmlCData')
readXmlElementEnd(/* header */) {
this.debug && console.group('readXmlCData');
/* const line = */ this.readU32()
/* const commentRef = */ this.readU32()
/* const nsRef = */ this.readS32()
/* const nameRef = */ this.readS32()
/* const line = */ this.readU32();
/* const commentRef = */ this.readU32();
/* const nsRef = */ this.readS32();
/* const nameRef = */ this.readS32();
this.stack.pop()
this.parent = this.stack[this.stack.length - 1]
this.stack.pop();
this.parent = this.stack[this.stack.length - 1];
this.debug && console.groupEnd()
this.debug && console.groupEnd();
return null
return null;
}
readXmlCData (/* header */) {
this.debug && console.group('readXmlCData')
readXmlCData(/* header */) {
this.debug && console.group('readXmlCData');
const cdata = {
namespaceURI: null,
nodeType: NodeType.CDATA_SECTION_NODE,
nodeName: '#cdata',
data: null,
typedValue: null
}
typedValue: null,
};
/* const line = */ this.readU32()
/* const commentRef = */ this.readU32()
const dataRef = this.readS32()
/* const line = */ this.readU32();
/* const commentRef = */ this.readU32();
const dataRef = this.readS32();
if (dataRef > 0) {
cdata.data = this.strings[dataRef]
cdata.data = this.strings[dataRef];
}
cdata.typedValue = this.readTypedValue()
cdata.typedValue = this.readTypedValue();
this.parent.childNodes.push(cdata)
this.parent.childNodes.push(cdata);
this.debug && console.groupEnd()
this.debug && console.groupEnd();
return cdata
return cdata;
}
readNull (header) {
this.debug && console.group('readNull')
this.cursor += header.chunkSize - header.headerSize
this.debug && console.groupEnd()
return null
readNull(header) {
this.debug && console.group('readNull');
this.cursor += header.chunkSize - header.headerSize;
this.debug && console.groupEnd();
return null;
}
parse () {
this.debug && console.group('BinaryXmlParser.parse')
parse() {
this.debug && console.group('BinaryXmlParser.parse');
const xmlHeader = this.readChunkHeader()
const xmlHeader = this.readChunkHeader();
if (xmlHeader.chunkType !== ChunkType.XML) {
throw new Error('Invalid XML header')
throw new Error('Invalid XML header');
}
while (this.cursor < this.buffer.length) {
this.debug && console.group('chunk')
const start = this.cursor
const header = this.readChunkHeader()
this.debug && console.group('chunk');
const start = this.cursor;
const header = this.readChunkHeader();
switch (header.chunkType) {
case ChunkType.STRING_POOL:
this.readStringPool(header)
break
this.readStringPool(header);
break;
case ChunkType.XML_RESOURCE_MAP:
this.readResourceMap(header)
break
this.readResourceMap(header);
break;
case ChunkType.XML_START_NAMESPACE:
this.readXmlNamespaceStart(header)
break
this.readXmlNamespaceStart(header);
break;
case ChunkType.XML_END_NAMESPACE:
this.readXmlNamespaceEnd(header)
break
this.readXmlNamespaceEnd(header);
break;
case ChunkType.XML_START_ELEMENT:
this.readXmlElementStart(header)
break
this.readXmlElementStart(header);
break;
case ChunkType.XML_END_ELEMENT:
this.readXmlElementEnd(header)
break
this.readXmlElementEnd(header);
break;
case ChunkType.XML_CDATA:
this.readXmlCData(header)
break
this.readXmlCData(header);
break;
case ChunkType.NULL:
this.readNull(header)
break
this.readNull(header);
break;
default:
throw new Error(`Unsupported chunk type '${header.chunkType}'`)
throw new Error(`Unsupported chunk type '${header.chunkType}'`);
}
// Ensure we consume the whole chunk
const end = start + header.chunkSize
const end = start + header.chunkSize;
if (this.cursor !== end) {
const diff = end - this.cursor
const type = header.chunkType.toString(16)
const diff = end - this.cursor;
const type = header.chunkType.toString(16);
console.debug(`Cursor is off by ${diff} bytes at ${this.cursor} at supposed \
end of chunk of type 0x${type}. The chunk started at offset ${start} and is \
supposed to end at offset ${end}. Ignoring the rest of the chunk.`)
this.cursor = end
supposed to end at offset ${end}. Ignoring the rest of the chunk.`);
this.cursor = end;
}
this.debug && console.groupEnd()
this.debug && console.groupEnd();
}
this.debug && console.groupEnd()
this.debug && console.groupEnd();
return this.document
return this.document;
}
}
module.exports = BinaryXmlParser
module.exports = BinaryXmlParser;

View File

@@ -1,216 +1,224 @@
// From https://github.com/openstf/adbkit-apkreader
const BinaryXmlParser = require('./binary')
const BinaryXmlParser = require('./binary');
const INTENT_MAIN = 'android.intent.action.MAIN'
const CATEGORY_LAUNCHER = 'android.intent.category.LAUNCHER'
const INTENT_MAIN = 'android.intent.action.MAIN';
const CATEGORY_LAUNCHER = 'android.intent.category.LAUNCHER';
class ManifestParser {
constructor (buffer, options = {}) {
this.buffer = buffer
this.xmlParser = new BinaryXmlParser(this.buffer, options)
constructor(buffer, options = {}) {
this.buffer = buffer;
this.xmlParser = new BinaryXmlParser(this.buffer, options);
}
collapseAttributes (element) {
const collapsed = Object.create(null)
for (let attr of Array.from(element.attributes)) {
collapsed[attr.name] = attr.typedValue.value
collapseAttributes(element) {
const collapsed = Object.create(null);
for (const attr of Array.from(element.attributes)) {
collapsed[attr.name] = attr.typedValue.value;
}
return collapsed
return collapsed;
}
parseIntents (element, target) {
target.intentFilters = []
target.metaData = []
parseIntents(element, target) {
target.intentFilters = [];
target.metaData = [];
return element.childNodes.forEach(element => {
return element.childNodes.forEach((element) => {
switch (element.nodeName) {
case 'intent-filter': {
const intentFilter = this.collapseAttributes(element)
const intentFilter = this.collapseAttributes(element);
intentFilter.actions = []
intentFilter.categories = []
intentFilter.data = []
intentFilter.actions = [];
intentFilter.categories = [];
intentFilter.data = [];
element.childNodes.forEach(element => {
element.childNodes.forEach((element) => {
switch (element.nodeName) {
case 'action':
intentFilter.actions.push(this.collapseAttributes(element))
break
intentFilter.actions.push(this.collapseAttributes(element));
break;
case 'category':
intentFilter.categories.push(this.collapseAttributes(element))
break
intentFilter.categories.push(this.collapseAttributes(element));
break;
case 'data':
intentFilter.data.push(this.collapseAttributes(element))
break
intentFilter.data.push(this.collapseAttributes(element));
break;
}
})
});
target.intentFilters.push(intentFilter)
break
target.intentFilters.push(intentFilter);
break;
}
case 'meta-data':
target.metaData.push(this.collapseAttributes(element))
break
target.metaData.push(this.collapseAttributes(element));
break;
}
})
});
}
parseApplication (element) {
const app = this.collapseAttributes(element)
parseApplication(element) {
const app = this.collapseAttributes(element);
app.activities = []
app.activityAliases = []
app.launcherActivities = []
app.services = []
app.receivers = []
app.providers = []
app.usesLibraries = []
app.metaData = []
app.activities = [];
app.activityAliases = [];
app.launcherActivities = [];
app.services = [];
app.receivers = [];
app.providers = [];
app.usesLibraries = [];
app.metaData = [];
element.childNodes.forEach(element => {
element.childNodes.forEach((element) => {
switch (element.nodeName) {
case 'activity': {
const activity = this.collapseAttributes(element)
this.parseIntents(element, activity)
app.activities.push(activity)
const activity = this.collapseAttributes(element);
this.parseIntents(element, activity);
app.activities.push(activity);
if (this.isLauncherActivity(activity)) {
app.launcherActivities.push(activity)
app.launcherActivities.push(activity);
}
break
break;
}
case 'activity-alias': {
const activityAlias = this.collapseAttributes(element)
this.parseIntents(element, activityAlias)
app.activityAliases.push(activityAlias)
const activityAlias = this.collapseAttributes(element);
this.parseIntents(element, activityAlias);
app.activityAliases.push(activityAlias);
if (this.isLauncherActivity(activityAlias)) {
app.launcherActivities.push(activityAlias)
app.launcherActivities.push(activityAlias);
}
break
break;
}
case 'service': {
const service = this.collapseAttributes(element)
this.parseIntents(element, service)
app.services.push(service)
break
const service = this.collapseAttributes(element);
this.parseIntents(element, service);
app.services.push(service);
break;
}
case 'receiver': {
const receiver = this.collapseAttributes(element)
this.parseIntents(element, receiver)
app.receivers.push(receiver)
break
const receiver = this.collapseAttributes(element);
this.parseIntents(element, receiver);
app.receivers.push(receiver);
break;
}
case 'provider': {
const provider = this.collapseAttributes(element)
const provider = this.collapseAttributes(element);
provider.grantUriPermissions = []
provider.metaData = []
provider.pathPermissions = []
provider.grantUriPermissions = [];
provider.metaData = [];
provider.pathPermissions = [];
element.childNodes.forEach(element => {
element.childNodes.forEach((element) => {
switch (element.nodeName) {
case 'grant-uri-permission':
provider.grantUriPermissions.push(this.collapseAttributes(element))
break
provider.grantUriPermissions.push(
this.collapseAttributes(element),
);
break;
case 'meta-data':
provider.metaData.push(this.collapseAttributes(element))
break
provider.metaData.push(this.collapseAttributes(element));
break;
case 'path-permission':
provider.pathPermissions.push(this.collapseAttributes(element))
break
provider.pathPermissions.push(this.collapseAttributes(element));
break;
}
})
});
app.providers.push(provider)
break
app.providers.push(provider);
break;
}
case 'uses-library':
app.usesLibraries.push(this.collapseAttributes(element))
break
app.usesLibraries.push(this.collapseAttributes(element));
break;
case 'meta-data':
app.metaData.push(this.collapseAttributes(element))
break
app.metaData.push(this.collapseAttributes(element));
break;
}
})
});
return app
return app;
}
isLauncherActivity (activity) {
return activity.intentFilters.some(function (filter) {
const hasMain = filter.actions.some(action => action.name === INTENT_MAIN)
isLauncherActivity(activity) {
return activity.intentFilters.some((filter) => {
const hasMain = filter.actions.some(
(action) => action.name === INTENT_MAIN,
);
if (!hasMain) {
return false
return false;
}
return filter.categories.some(category => category.name === CATEGORY_LAUNCHER)
})
return filter.categories.some(
(category) => category.name === CATEGORY_LAUNCHER,
);
});
}
parse () {
const document = this.xmlParser.parse()
const manifest = this.collapseAttributes(document)
parse() {
const document = this.xmlParser.parse();
const manifest = this.collapseAttributes(document);
manifest.usesPermissions = []
manifest.usesPermissionsSDK23 = []
manifest.permissions = []
manifest.permissionTrees = []
manifest.permissionGroups = []
manifest.instrumentation = null
manifest.usesSdk = null
manifest.usesConfiguration = null
manifest.usesFeatures = []
manifest.supportsScreens = null
manifest.compatibleScreens = []
manifest.supportsGlTextures = []
manifest.application = Object.create(null)
manifest.usesPermissions = [];
manifest.usesPermissionsSDK23 = [];
manifest.permissions = [];
manifest.permissionTrees = [];
manifest.permissionGroups = [];
manifest.instrumentation = null;
manifest.usesSdk = null;
manifest.usesConfiguration = null;
manifest.usesFeatures = [];
manifest.supportsScreens = null;
manifest.compatibleScreens = [];
manifest.supportsGlTextures = [];
manifest.application = Object.create(null);
document.childNodes.forEach(element => {
document.childNodes.forEach((element) => {
switch (element.nodeName) {
case 'uses-permission':
manifest.usesPermissions.push(this.collapseAttributes(element))
break
manifest.usesPermissions.push(this.collapseAttributes(element));
break;
case 'uses-permission-sdk-23':
manifest.usesPermissionsSDK23.push(this.collapseAttributes(element))
break
manifest.usesPermissionsSDK23.push(this.collapseAttributes(element));
break;
case 'permission':
manifest.permissions.push(this.collapseAttributes(element))
break
manifest.permissions.push(this.collapseAttributes(element));
break;
case 'permission-tree':
manifest.permissionTrees.push(this.collapseAttributes(element))
break
manifest.permissionTrees.push(this.collapseAttributes(element));
break;
case 'permission-group':
manifest.permissionGroups.push(this.collapseAttributes(element))
break
manifest.permissionGroups.push(this.collapseAttributes(element));
break;
case 'instrumentation':
manifest.instrumentation = this.collapseAttributes(element)
break
manifest.instrumentation = this.collapseAttributes(element);
break;
case 'uses-sdk':
manifest.usesSdk = this.collapseAttributes(element)
break
manifest.usesSdk = this.collapseAttributes(element);
break;
case 'uses-configuration':
manifest.usesConfiguration = this.collapseAttributes(element)
break
manifest.usesConfiguration = this.collapseAttributes(element);
break;
case 'uses-feature':
manifest.usesFeatures.push(this.collapseAttributes(element))
break
manifest.usesFeatures.push(this.collapseAttributes(element));
break;
case 'supports-screens':
manifest.supportsScreens = this.collapseAttributes(element)
break
manifest.supportsScreens = this.collapseAttributes(element);
break;
case 'compatible-screens':
element.childNodes.forEach(screen => {
return manifest.compatibleScreens.push(this.collapseAttributes(screen))
})
break
element.childNodes.forEach((screen) => {
return manifest.compatibleScreens.push(
this.collapseAttributes(screen),
);
});
break;
case 'supports-gl-texture':
manifest.supportsGlTextures.push(this.collapseAttributes(element))
break
manifest.supportsGlTextures.push(this.collapseAttributes(element));
break;
case 'application':
manifest.application = this.parseApplication(element)
break
manifest.application = this.parseApplication(element);
break;
}
})
});
return manifest
return manifest;
}
}
module.exports = ManifestParser
module.exports = ManifestParser;

View File

@@ -1,6 +1,6 @@
const Unzip = require('isomorphic-unzip');
const { isBrowser, decodeNullUnicode } = require('./utils');
import { enumZipEntries, readEntry } from '../../bundle';
const { enumZipEntries, readEntry } = require('../../bundle');
class Zip {
constructor(file) {

View File

@@ -1,5 +1,5 @@
import { plugins } from './plugin-config';
import { t } from './i18n';
import { plugins } from './plugin-config';
interface BundleParams {
sentry: boolean;
@@ -21,7 +21,9 @@ export async function checkPlugins(): Promise<BundleParams> {
console.log(t('pluginDetected', { name: plugin.name }));
}
} catch (err) {
console.warn(t('pluginDetectionError', { name: plugin.name, error: err }));
console.warn(
t('pluginDetectionError', { name: plugin.name, error: err }),
);
}
}

View File

@@ -3,8 +3,12 @@ const currentPackage = require(`${process.cwd()}/package.json`);
const _depVersions: Record<string, string> = {};
if (currentPackage) {
const depKeys = currentPackage.dependencies ? Object.keys(currentPackage.dependencies) : [];
const devDepKeys = currentPackage.devDependencies ? Object.keys(currentPackage.devDependencies) : [];
const depKeys = currentPackage.dependencies
? Object.keys(currentPackage.dependencies)
: [];
const devDepKeys = currentPackage.devDependencies
? Object.keys(currentPackage.devDependencies)
: [];
const dedupedDeps = [...new Set([...depKeys, ...devDepKeys])];
for (const dep of dedupedDeps) {
@@ -20,9 +24,12 @@ if (currentPackage) {
export const depVersions = Object.keys(_depVersions)
.sort() // Sort the keys alphabetically
.reduce((obj, key) => {
obj[key] = _depVersions[key]; // Rebuild the object with sorted keys
return obj;
}, {} as Record<string, string>);
.reduce(
(obj, key) => {
obj[key] = _depVersions[key]; // Rebuild the object with sorted keys
return obj;
},
{} as Record<string, string>,
);
// console.log({ depVersions });

View File

@@ -1,6 +1,6 @@
import git from 'isomorphic-git';
import fs from 'fs';
import path from 'path';
import git from 'isomorphic-git';
export interface CommitInfo {
hash: string;

View File

@@ -34,4 +34,6 @@ declare module 'i18next' {
}
}
export const t = i18next.t;
export function t(key: string, options?: any): string {
return i18next.t(key as any, options);
}

View File

@@ -1,11 +1,11 @@
import fs from 'fs-extra';
import os from 'os';
import path from 'path';
import pkg from '../../package.json';
import AppInfoParser from './app-info-parser';
import { satisfies } from 'compare-versions';
import chalk from 'chalk';
import { satisfies } from 'compare-versions';
import fs from 'fs-extra';
import pkg from '../../package.json';
import latestVersion from '../utils/latest-version';
import AppInfoParser from './app-info-parser';
import { checkPlugins } from './check-plugin';
import { read } from 'read';
@@ -88,16 +88,14 @@ export async function getAppInfo(fn: string) {
}),
);
}
const updateJsonFile = await appInfoParser.parser.getEntryFromHarmonyApp(
/rawfile\/update.json/,
);
const updateJsonFile =
await appInfoParser.parser.getEntryFromHarmonyApp(/rawfile\/update.json/);
let appCredential = {};
if (updateJsonFile) {
appCredential = JSON.parse(updateJsonFile.toString()).harmony;
}
const metaJsonFile = await appInfoParser.parser.getEntryFromHarmonyApp(
/rawfile\/meta.json/,
);
const metaJsonFile =
await appInfoParser.parser.getEntryFromHarmonyApp(/rawfile\/meta.json/);
let metaData: Record<string, any> = {};
if (metaJsonFile) {
metaData = JSON.parse(metaJsonFile.toString());

View File

@@ -1,3 +1,5 @@
import { existsSync, readFileSync } from 'fs';
import { dirname } from 'path';
import {
blue,
bold,
@@ -12,16 +14,14 @@ import {
underline,
yellow,
} from '@colors/colors/safe';
import { existsSync, readFileSync } from 'fs';
import { dirname } from 'path';
import semverDiff from 'semver/functions/diff';
import semverMajor from 'semver/functions/major';
import latestVersion, {
type Package,
type PackageJson,
type LatestVersionPackage,
type LatestVersionOptions,
} from '.';
import semverMajor from 'semver/functions/major';
import semverDiff from 'semver/functions/diff';
interface TableColumn {
label: string;

View File

@@ -1,19 +1,19 @@
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
import type {
RequestOptions as HttpRequestOptions,
Agent,
RequestOptions as HttpRequestOptions,
IncomingMessage,
} from 'http';
import type { RequestOptions as HttpsRequestOptions } from 'https';
import { join, dirname, resolve as pathResolve, parse } from 'path';
import { npm, yarn } from 'global-dirs';
import { homedir } from 'os';
import { dirname, join, parse, resolve as pathResolve } from 'path';
import { URL } from 'url';
import { npm, yarn } from 'global-dirs';
import getRegistryUrl from 'registry-auth-token/registry-url';
import registryAuthToken from 'registry-auth-token';
import maxSatisfying from 'semver/ranges/max-satisfying';
import getRegistryUrl from 'registry-auth-token/registry-url';
import gt from 'semver/functions/gt';
import maxSatisfying from 'semver/ranges/max-satisfying';
interface RegistryVersions {
/**
@@ -132,9 +132,10 @@ interface LatestVersion {
* If `registryUrl` is not supplied, the default from `.npmrc` is used or a fallback to the `npm registry url` instead.
* @returns {Promise<LatestVersionPackage[]>}
*/
(item: PackageJson, options?: LatestVersionOptions): Promise<
LatestVersionPackage[]
>;
(
item: PackageJson,
options?: LatestVersionOptions,
): Promise<LatestVersionPackage[]>;
/**
* Get latest version of a single package.
@@ -161,9 +162,10 @@ interface LatestVersion {
* If `registryUrl` is not supplied, the default from `.npmrc` is used or a fallback to the npm registry url instead.
* @returns {Promise<LatestVersionPackage[]>}
*/
(items: Package[], options?: LatestVersionOptions): Promise<
LatestVersionPackage[]
>; // eslint-disable-line @typescript-eslint/unified-signatures
(
items: Package[],
options?: LatestVersionOptions,
): Promise<LatestVersionPackage[]>; // eslint-disable-line @typescript-eslint/unified-signatures
}
type PackageRange = `${'@' | ''}${string}@${string}`;
type Package = PackageRange | string; // eslint-disable-line @typescript-eslint/no-redundant-type-constituents
@@ -225,7 +227,7 @@ const downloadMetadata = (
};
const authInfo = registryAuthToken(pkgUrl.toString(), { recursive: true });
if (authInfo && requestOptions.headers) {
requestOptions.headers.authorization = `${authInfo.type} ${authInfo.token}`;
(requestOptions.headers as any).authorization = `${authInfo.type} ${authInfo.token}`;
}
if (options?.requestOptions) {
requestOptions = { ...requestOptions, ...options.requestOptions };
@@ -362,11 +364,9 @@ const getInstalledVersion = (
?.version as string;
} else if (location === 'globalYarn') {
// Make sure package is globally installed by Yarn
const yarnGlobalPkg = require(pathResolve(
yarn.packages,
'..',
'package.json',
));
const yarnGlobalPkg = require(
pathResolve(yarn.packages, '..', 'package.json'),
);
if (!yarnGlobalPkg?.dependencies?.[pkgName]) {
return undefined;
}

View File

@@ -27,6 +27,6 @@ export const plugins: PluginConfig[] = [
return false;
}
}
}
}
];
},
},
];