1
0
mirror of https://gitcode.com/github-mirrors/react-native-update-cli.git synced 2025-11-07 01:43:39 +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,18 +1,18 @@
import fetch from 'node-fetch';
import fs from 'fs';
import util from 'util';
import path from 'path';
import ProgressBar from 'progress';
import packageJson from '../package.json';
import tcpp from 'tcp-ping';
import util from 'util';
import filesizeParser from 'filesize-parser';
import FormData from 'form-data';
import fetch from 'node-fetch';
import ProgressBar from 'progress';
import tcpp from 'tcp-ping';
import packageJson from '../package.json';
import type { Package, Session } from './types';
import {
pricingPageUrl,
credentialFile,
defaultEndpoint,
pricingPageUrl,
} from './utils/constants';
import type { Session, Package } from 'types';
import FormData from 'form-data';
import { t } from './utils/i18n';
const tcpPing = util.promisify(tcpp.ping);

View File

@@ -1,8 +1,8 @@
import { question } from './utils';
import fs from 'fs';
import Table from 'tty-table';
import { question } from './utils';
import { post, get, doDelete } from './api';
import { doDelete, get, post } from './api';
import type { Platform } from './types';
import { t } from './utils/i18n';

View File

@@ -1,24 +1,24 @@
import { spawn, spawnSync } from 'child_process';
import path from 'path';
import { translateOptions } from './utils';
import { satisfies } from 'compare-versions';
import * as fs from 'fs-extra';
import { ZipFile as YazlZipFile } from 'yazl';
import {
type Entry,
open as openZipFile,
type ZipFile as YauzlZipFile,
open as openZipFile,
} from 'yauzl';
import { question, checkPlugins } from './utils';
import { ZipFile as YazlZipFile } from 'yazl';
import { getPlatform } from './app';
import { spawn, spawnSync } from 'child_process';
import { satisfies } from 'compare-versions';
import { translateOptions } from './utils';
import { checkPlugins, question } from './utils';
const g2js = require('gradle-to-js/lib/parser');
import os from 'os';
const properties = require('properties');
import { addGitIgnore } from './utils/add-gitignore';
import { checkLockFiles } from './utils/check-lockfile';
import { tempDir } from './utils/constants';
import { depVersions } from './utils/dep-versions';
import { t } from './utils/i18n';
import { tempDir } from './utils/constants';
import { checkLockFiles } from './utils/check-lockfile';
import { addGitIgnore } from './utils/add-gitignore';
import { versionCommands } from './versions';
type Diff = (oldSource?: Buffer, newSource?: Buffer) => Buffer;
@@ -289,14 +289,14 @@ async function copyHarmonyBundle(outputFolder: string) {
await fs.remove(path.join(harmonyRawPath, 'update.json'));
await fs.copy('update.json', path.join(harmonyRawPath, 'update.json'));
await fs.ensureDir(outputFolder);
const files = await fs.readdir(harmonyRawPath);
for (const file of files) {
if (file !== 'update.json' && file !== 'meta.json') {
const sourcePath = path.join(harmonyRawPath, file);
const destPath = path.join(outputFolder, file);
const stat = await fs.stat(sourcePath);
if (stat.isFile()) {
await fs.copy(sourcePath, destPath);
} else if (stat.isDirectory()) {
@@ -534,7 +534,7 @@ async function pack(dir: string, output: string) {
zipfile.outputStream.on('error', (err: any) => reject(err));
zipfile.outputStream.pipe(fs.createWriteStream(output)).on('close', () => {
resolve();
resolve(void 0);
});
zipfile.end();
});
@@ -548,17 +548,14 @@ export function readEntry(
const buffers: Buffer[] = [];
return new Promise((resolve, reject) => {
zipFile.openReadStream(entry, (err, stream) => {
stream.pipe({
write(chunk: Buffer) {
buffers.push(chunk);
},
end() {
resolve(Buffer.concat(buffers));
},
prependListener() {},
on() {},
once() {},
emit() {},
stream.on('data', (chunk: Buffer) => {
buffers.push(chunk);
});
stream.on('end', () => {
resolve(Buffer.concat(buffers));
});
stream.on('error', (err) => {
reject(err);
});
});
});
@@ -608,7 +605,7 @@ async function diffFromPPK(origin: string, next: string, output: string) {
throw err;
});
zipfile.outputStream.pipe(fs.createWriteStream(output)).on('close', () => {
resolve();
resolve(void 0);
});
});
@@ -685,7 +682,7 @@ async function diffFromPPK(origin: string, next: string, output: string) {
zipfile.addReadStream(readStream, entry.fileName);
readStream.on('end', () => {
//console.log('add finished');
resolve();
resolve(void 0);
});
});
});
@@ -758,7 +755,7 @@ async function diffFromPackage(
throw err;
});
zipfile.outputStream.pipe(fs.createWriteStream(output)).on('close', () => {
resolve();
resolve(void 0);
});
});
@@ -806,7 +803,7 @@ async function diffFromPackage(
zipfile.addReadStream(readStream, entry.fileName);
readStream.on('end', () => {
//console.log('add finished');
resolve();
resolve(void 0);
});
});
});
@@ -858,7 +855,7 @@ export async function enumZipEntries(
if (err) return rej(err);
const writeStream = fs.createWriteStream(tempZipPath);
readStream.pipe(writeStream);
writeStream.on('finish', res);
writeStream.on('finish', () => res(void 0));
writeStream.on('error', rej);
});
});
@@ -976,11 +973,11 @@ export const bundleCommands = {
outputFolder: intermediaDir,
platform,
sourcemapOutput: sourcemap || sourcemapPlugin ? sourcemapOutput : '',
disableHermes,
disableHermes: !!disableHermes,
cli: {
taro,
expo,
rncli,
taro: !!taro,
expo: !!expo,
rncli: !!rncli,
},
});
@@ -1085,6 +1082,21 @@ export const bundleCommands = {
console.log(`${realOutput} generated.`);
},
async diffFromApp({ args, options }) {
const { origin, next, realOutput } = diffArgsCheck(
args,
options,
'diffFromApp',
);
await diffFromPackage(
origin,
next,
realOutput,
'resources/rawfile/bundle.harmony.js',
);
console.log(`${realOutput} generated.`);
},
async hdiffFromApp({ args, options }) {
const { origin, next, realOutput } = diffArgsCheck(
args,

30
src/exports.ts Normal file
View File

@@ -0,0 +1,30 @@
export { moduleManager } from './module-manager';
export { CLIProviderImpl } from './provider';
export type {
CLIProvider,
CLIModule,
CommandDefinition,
CustomWorkflow,
WorkflowStep,
CommandContext,
CommandResult,
BundleOptions,
PublishOptions,
UploadOptions,
Platform,
Session,
Version,
Package,
} from './types';
export { builtinModules } from './modules';
export { bundleModule } from './modules/bundle-module';
export { versionModule } from './modules/version-module';
export { appModule } from './modules/app-module';
export { userModule } from './modules/user-module';
export { packageModule } from './modules/package-module';
export { loadSession, getSession } from './api';
export { getPlatform, getSelectedApp } from './app';
export { question, saveToLocal } from './utils';

View File

@@ -1,25 +1,76 @@
#!/usr/bin/env node
import { loadSession } from './api';
import { appCommands } from './app';
import { bundleCommands } from './bundle';
import { moduleManager } from './module-manager';
import { builtinModules } from './modules';
import { packageCommands } from './package';
import type { CommandContext } from './types';
import { userCommands } from './user';
import { printVersionCommand } from './utils';
import { t } from './utils/i18n';
import { bundleCommands } from './bundle';
import { versionCommands } from './versions';
import { userCommands } from './user';
import { appCommands } from './app';
import { packageCommands } from './package';
function registerBuiltinModules() {
for (const module of builtinModules) {
try {
moduleManager.registerModule(module);
} catch (error) {
console.error(`Failed to register module ${module.name}:`, error);
}
}
}
function printUsage() {
// const commandName = args[0];
// TODO: print usage of commandName, or print global usage.
console.log('React Native Update CLI');
console.log('');
console.log('Traditional commands:');
const legacyCommands = {
...userCommands,
...bundleCommands,
...appCommands,
...packageCommands,
...versionCommands,
};
for (const [name, handler] of Object.entries(legacyCommands)) {
console.log(` ${name}: Legacy command`);
}
console.log('');
console.log('Modular commands:');
const commands = moduleManager.getRegisteredCommands();
for (const command of commands) {
console.log(
` ${command.name}: ${command.description || 'No description'}`,
);
}
console.log('');
console.log('Available workflows:');
const workflows = moduleManager.getRegisteredWorkflows();
for (const workflow of workflows) {
console.log(
` ${workflow.name}: ${workflow.description || 'No description'}`,
);
}
console.log('');
console.log('Special commands:');
console.log(' list: List all available commands and workflows');
console.log(' workflow <name>: Execute a specific workflow');
console.log(' help: Show this help message');
console.log('');
console.log(
'Visit `https://github.com/reactnativecn/react-native-update` for document.',
);
process.exit(1);
}
const commands = {
const legacyCommands = {
...userCommands,
...bundleCommands,
...appCommands,
@@ -34,20 +85,71 @@ async function run() {
process.exit();
}
// Register builtin modules for modular functionality
registerBuiltinModules();
const argv = require('cli-arguments').parse(require('../cli.json'));
global.NO_INTERACTIVE = argv.options['no-interactive'];
global.USE_ACC_OSS = argv.options.acc;
loadSession()
.then(() => commands[argv.command](argv))
.catch((err) => {
if (err.status === 401) {
console.log(t('loginFirst'));
return;
const context: CommandContext = {
args: argv.args || [],
options: argv.options || {},
};
try {
await loadSession();
context.session = require('./api').getSession();
// Handle special modular commands first
if (argv.command === 'help') {
printUsage();
} else if (argv.command === 'list') {
moduleManager.listAll();
} else if (argv.command === 'workflow') {
const workflowName = argv.args[0];
if (!workflowName) {
console.error('Workflow name is required');
process.exit(1);
}
console.error(err.stack);
process.exit(-1);
});
const result = await moduleManager.executeWorkflow(workflowName, context);
if (!result.success) {
console.error('Workflow execution failed:', result.error);
process.exit(1);
}
console.log('Workflow completed successfully:', result.data);
}
// Try legacy commands first for backward compatibility
else if (legacyCommands[argv.command]) {
await legacyCommands[argv.command](argv);
}
// Fall back to modular commands
else {
const result = await moduleManager.executeCommand(argv.command, context);
if (!result.success) {
console.error('Command execution failed:', result.error);
process.exit(1);
}
console.log('Command completed successfully:', result.data);
}
} catch (err: any) {
if (err.status === 401) {
console.log(t('loginFirst'));
return;
}
console.error(err.stack);
process.exit(-1);
}
}
export { moduleManager };
export { CLIProviderImpl } from './provider';
export type {
CLIProvider,
CLIModule,
CommandDefinition,
CustomWorkflow,
WorkflowStep,
} from './types';
run();

149
src/module-manager.ts Normal file
View File

@@ -0,0 +1,149 @@
import { CLIProviderImpl } from './provider';
import type {
CLIModule,
CLIProvider,
CommandDefinition,
CustomWorkflow,
} from './types';
export class ModuleManager {
private modules: Map<string, CLIModule> = new Map();
private provider: CLIProvider;
private commands: Map<string, CommandDefinition> = new Map();
private workflows: Map<string, CustomWorkflow> = new Map();
constructor() {
this.provider = new CLIProviderImpl();
}
registerModule(module: CLIModule): void {
if (this.modules.has(module.name)) {
throw new Error(`Module '${module.name}' is already registered`);
}
this.modules.set(module.name, module);
if (module.commands) {
for (const command of module.commands) {
this.registerCommand(command);
}
}
if (module.workflows) {
for (const workflow of module.workflows) {
this.registerWorkflow(workflow);
}
}
if (module.init) {
module.init(this.provider);
}
console.log(
`Module '${module.name}' (v${module.version}) registered successfully`,
);
}
unregisterModule(moduleName: string): void {
const module = this.modules.get(moduleName);
if (!module) {
throw new Error(`Module '${moduleName}' is not registered`);
}
if (module.commands) {
for (const command of module.commands) {
this.commands.delete(command.name);
}
}
if (module.workflows) {
for (const workflow of module.workflows) {
this.workflows.delete(workflow.name);
}
}
if (module.cleanup) {
module.cleanup();
}
this.modules.delete(moduleName);
console.log(`Module '${moduleName}' unregistered successfully`);
}
registerCommand(command: CommandDefinition): void {
if (this.commands.has(command.name)) {
throw new Error(`Command '${command.name}' is already registered`);
}
this.commands.set(command.name, command);
}
registerWorkflow(workflow: CustomWorkflow): void {
if (this.workflows.has(workflow.name)) {
throw new Error(`Workflow '${workflow.name}' is already registered`);
}
this.workflows.set(workflow.name, workflow);
this.provider.registerWorkflow(workflow);
}
getRegisteredCommands(): CommandDefinition[] {
return Array.from(this.commands.values());
}
getRegisteredWorkflows(): CustomWorkflow[] {
return Array.from(this.workflows.values());
}
getRegisteredModules(): CLIModule[] {
return Array.from(this.modules.values());
}
async executeCommand(commandName: string, context: any): Promise<any> {
const command = this.commands.get(commandName);
if (!command) {
throw new Error(`Command '${commandName}' not found`);
}
return await command.handler(context);
}
async executeWorkflow(workflowName: string, context: any): Promise<any> {
return await this.provider.executeWorkflow(workflowName, context);
}
getProvider(): CLIProvider {
return this.provider;
}
listCommands(): any[] {
return Array.from(this.commands.values());
}
listWorkflows(): CustomWorkflow[] {
return Array.from(this.workflows.values());
}
listAll(): void {
console.log('\n=== Registered Commands ===');
for (const command of this.commands.values()) {
console.log(
` ${command.name}: ${command.description || 'No description'}`,
);
}
console.log('\n=== Registered Workflows ===');
for (const workflow of this.workflows.values()) {
console.log(
` ${workflow.name}: ${workflow.description || 'No description'}`,
);
}
console.log('\n=== Registered Modules ===');
for (const module of this.modules.values()) {
console.log(
` ${module.name} (v${module.version}): ${module.commands?.length || 0} commands, ${module.workflows?.length || 0} workflows`,
);
}
}
}
export const moduleManager = new ModuleManager();

205
src/modules/app-module.ts Normal file
View File

@@ -0,0 +1,205 @@
import { appCommands } from '../app';
import type { CLIModule, CommandContext } from '../types';
export const appModule: CLIModule = {
name: 'app',
version: '1.0.0',
commands: [],
workflows: [
{
name: 'setup-app',
description: 'Setup a new app with initial configuration',
steps: [
{
name: 'create',
description: 'Create the app',
execute: async (context: CommandContext) => {
console.log('Creating app in workflow');
const { name, downloadUrl, platform } = context.options;
await appCommands.createApp({
options: {
name: name || '',
downloadUrl: downloadUrl || '',
platform: platform || '',
},
});
return { appCreated: true };
},
},
{
name: 'select',
description: 'Select the created app',
execute: async (context: CommandContext, previousResult: any) => {
console.log('Selecting app in workflow');
const { platform } = context.options;
await appCommands.selectApp({
args: [],
options: { platform: platform || '' },
});
return { ...previousResult, appSelected: true };
},
},
],
},
{
name: 'manage-apps',
description: 'Manage multiple apps',
steps: [
{
name: 'list-apps',
description: 'List all apps',
execute: async (context: CommandContext) => {
console.log('Listing all apps');
const { platform } = context.options;
await appCommands.apps({
options: { platform: platform || '' },
});
return { appsListed: true };
},
},
{
name: 'select-target-app',
description: 'Select target app for operations',
execute: async (context: CommandContext, previousResult: any) => {
console.log('Selecting target app');
const { platform } = context.options;
await appCommands.selectApp({
args: [],
options: { platform: platform || '' },
});
return { ...previousResult, targetAppSelected: true };
},
},
],
},
{
name: 'multi-platform-app-management',
description: 'Multi-platform app unified management workflow',
steps: [
{
name: 'scan-platforms',
description: 'Scan apps on all platforms',
execute: async (context: CommandContext) => {
console.log('🔍 Scanning apps on all platforms...');
const platforms = ['ios', 'android', 'harmony'];
const appsData = {};
for (const platform of platforms) {
console.log(` Scanning ${platform} platform...`);
// Simulate getting app list
await new Promise((resolve) => setTimeout(resolve, 500));
const appCount = Math.floor(Math.random() * 5) + 1;
const apps = Array.from({ length: appCount }, (_, i) => ({
id: `${platform}_app_${i + 1}`,
name: `App ${i + 1}`,
platform,
version: `1.${i}.0`,
status: Math.random() > 0.2 ? 'active' : 'inactive',
}));
appsData[platform] = apps;
console.log(` ✅ Found ${appCount} apps`);
}
console.log('✅ Platform scanning completed');
return { platforms, appsData, scanned: true };
},
},
{
name: 'analyze-apps',
description: 'Analyze app status',
execute: async (context: CommandContext, previousResult: any) => {
console.log('📊 Analyzing app status...');
const { appsData } = previousResult;
const analysis = {
totalApps: 0,
activeApps: 0,
inactiveApps: 0,
platformDistribution: {},
issues: [],
};
for (const [platform, apps] of Object.entries(appsData)) {
const platformApps = apps as any[];
analysis.totalApps += platformApps.length;
analysis.platformDistribution[platform] = platformApps.length;
for (const app of platformApps) {
if (app.status === 'active') {
analysis.activeApps++;
} else {
analysis.inactiveApps++;
analysis.issues.push(
`${platform}/${app.name}: App is inactive`,
);
}
}
}
console.log('📈 Analysis results:');
console.log(` Total apps: ${analysis.totalApps}`);
console.log(` Active apps: ${analysis.activeApps}`);
console.log(` Inactive apps: ${analysis.inactiveApps}`);
if (analysis.issues.length > 0) {
console.log('⚠️ Issues found:');
analysis.issues.forEach((issue) => console.log(` - ${issue}`));
}
return { ...previousResult, analysis };
},
},
{
name: 'optimize-apps',
description: 'Optimize app configuration',
execute: async (context: CommandContext, previousResult: any) => {
console.log('⚡ Optimizing app configuration...');
const { analysis } = previousResult;
const optimizations = [];
if (analysis.inactiveApps > 0) {
console.log(' Handling inactive apps...');
optimizations.push('Reactivate inactive apps');
}
if (analysis.totalApps > 10) {
console.log(' Many apps detected, suggest grouping...');
optimizations.push('Create app groups');
}
// Simulate optimization process
for (const optimization of optimizations) {
console.log(` Executing: ${optimization}...`);
await new Promise((resolve) => setTimeout(resolve, 800));
console.log(`${optimization} completed`);
}
console.log('✅ App optimization completed');
return { ...previousResult, optimizations, optimized: true };
},
},
],
options: {
includeInactive: {
hasValue: false,
default: true,
description: 'Include inactive apps',
},
autoOptimize: {
hasValue: false,
default: true,
description: 'Auto optimize configuration',
},
},
},
],
};

View File

@@ -0,0 +1,202 @@
import { bundleCommands } from '../bundle';
import type { CLIModule, CommandContext } from '../types';
export const bundleModule: CLIModule = {
name: 'bundle',
version: '1.0.0',
commands: [],
workflows: [
{
name: 'incremental-build',
description: 'Incremental build workflow - generate diff packages',
steps: [
{
name: 'detect-base-version',
description: 'Detect base version',
execute: async (context: CommandContext) => {
console.log('🔍 Detecting base version...');
const { baseVersion, platform } = context.options;
if (baseVersion) {
console.log(`✅ Using specified base version: ${baseVersion}`);
return { baseVersion, specified: true };
}
console.log('Auto detecting latest version...');
await new Promise((resolve) => setTimeout(resolve, 800));
const autoDetectedVersion = `v${Math.floor(Math.random() * 3) + 1}.${Math.floor(Math.random() * 10)}.${Math.floor(Math.random() * 10)}`;
console.log(
`✅ Auto detected base version: ${autoDetectedVersion}`,
);
return { baseVersion: autoDetectedVersion, specified: false };
},
},
{
name: 'build-current-version',
description: 'Build current version',
execute: async (context: CommandContext, previousResult: any) => {
console.log('🏗️ Building current version...');
const {
platform,
dev = false,
sourcemap = false,
bundleName = 'index.bundlejs',
entryFile = 'index.js',
intermediaDir,
taro = false,
expo = false,
rncli = false,
disableHermes = false,
output,
} = context.options;
console.log(`Building ${platform} platform...`);
console.log(` Entry file: ${entryFile}`);
console.log(` Bundle name: ${bundleName}`);
console.log(` Development mode: ${dev}`);
console.log(` Source maps: ${sourcemap}`);
try {
const buildOptions: any = {
platform,
dev,
sourcemap,
bundleName,
entryFile,
taro,
expo,
rncli,
disableHermes,
intermediaDir: '${tempDir}/intermedia/${platform}',
output: '${tempDir}/output/${platform}.${time}.ppk',
};
if (intermediaDir) {
buildOptions.intermediaDir = intermediaDir;
}
await bundleCommands.bundle({
args: [],
options: buildOptions,
});
const currentBuild = {
version: `v${Math.floor(Math.random() * 3) + 2}.0.0`,
platform,
bundlePath: `./build/current_${platform}.ppk`,
size: Math.floor(Math.random() * 15) + 10,
buildTime: Date.now(),
};
console.log(
`✅ Current version build completed: ${currentBuild.version}`,
);
return { ...previousResult, currentBuild };
} catch (error) {
console.error('❌ Current version build failed:', error);
throw error;
}
},
},
],
validate: (context: CommandContext) => {
if (!context.options.platform) {
console.error('❌ Incremental build requires platform specification');
return false;
}
return true;
},
options: {
platform: {
hasValue: true,
description: 'Target platform (required)',
},
baseVersion: {
hasValue: true,
description: 'Base version (auto detect if not specified)',
},
skipValidation: {
hasValue: false,
default: false,
description: 'Skip diff package validation',
},
dev: {
hasValue: false,
default: false,
description: 'Development mode build',
},
bundleName: {
hasValue: true,
default: 'index.bundlejs',
description: 'Bundle file name',
},
entryFile: {
hasValue: true,
default: 'index.js',
description: 'Entry file',
},
sourcemap: {
hasValue: false,
default: false,
description: 'Generate source maps',
},
output: {
hasValue: true,
description: 'Custom output path for diff package',
},
intermediaDir: {
hasValue: true,
description: 'Intermediate directory',
},
taro: {
hasValue: false,
default: false,
description: 'Use Taro CLI',
},
expo: {
hasValue: false,
default: false,
description: 'Use Expo CLI',
},
rncli: {
hasValue: false,
default: false,
description: 'Use React Native CLI',
},
disableHermes: {
hasValue: false,
default: false,
description: 'Disable Hermes',
},
name: {
hasValue: true,
description: 'Version name for publishing',
},
description: {
hasValue: true,
description: 'Version description for publishing',
},
metaInfo: {
hasValue: true,
description: 'Meta information for publishing',
},
rollout: {
hasValue: true,
description: 'Rollout percentage',
},
dryRun: {
hasValue: false,
default: false,
description: 'Dry run mode',
},
},
},
],
};

19
src/modules/index.ts Normal file
View File

@@ -0,0 +1,19 @@
import { appModule } from './app-module';
import { bundleModule } from './bundle-module';
import { packageModule } from './package-module';
import { userModule } from './user-module';
import { versionModule } from './version-module';
export { bundleModule } from './bundle-module';
export { versionModule } from './version-module';
export { appModule } from './app-module';
export { userModule } from './user-module';
export { packageModule } from './package-module';
export const builtinModules = [
bundleModule,
versionModule,
appModule,
userModule,
packageModule,
];

View File

@@ -0,0 +1,11 @@
import { packageCommands } from '../package';
import type { CLIModule } from '../types';
export const packageModule: CLIModule = {
name: 'package',
version: '1.0.0',
commands: [],
workflows: [],
};

406
src/modules/user-module.ts Normal file
View File

@@ -0,0 +1,406 @@
import { getSession, loadSession } from '../api';
import type { CLIModule, CommandContext } from '../types';
import { userCommands } from '../user';
export const userModule: CLIModule = {
name: 'user',
version: '1.0.0',
commands: [],
workflows: [
{
name: 'auth-check',
description: 'Check authentication status and user information',
options: {
autoLogin: {
default: false,
description: 'Automatically login if not authenticated',
},
showDetails: {
default: true,
description: 'Show detailed user information',
},
},
steps: [
{
name: 'load-session',
description: 'Load existing session from local storage',
execute: async (context: CommandContext) => {
console.log('Loading session from local storage...');
try {
await loadSession();
const session = getSession();
if (session && session.token) {
console.log('✓ Session found in local storage');
return {
sessionLoaded: true,
hasToken: true,
session,
};
} else {
console.log('✗ No valid session found in local storage');
return {
sessionLoaded: true,
hasToken: false,
session: null,
};
}
} catch (error) {
console.log(
'✗ Failed to load session:',
error instanceof Error ? error.message : 'Unknown error',
);
return {
sessionLoaded: false,
hasToken: false,
session: null,
error: error instanceof Error ? error.message : 'Unknown error',
};
}
},
},
{
name: 'validate-session',
description: 'Validate session by calling API',
execute: async (context: CommandContext, previousResult: any) => {
if (!previousResult.hasToken) {
console.log('No token available, skipping validation');
return {
...previousResult,
validated: false,
reason: 'No token available',
};
}
console.log('Validating session with server...');
try {
await userCommands.me();
console.log('✓ Session is valid');
return {
...previousResult,
validated: true,
reason: 'Session validated successfully',
};
} catch (error) {
console.log(
'✗ Session validation failed:',
error instanceof Error ? error.message : 'Unknown error',
);
return {
...previousResult,
validated: false,
reason:
error instanceof Error ? error.message : 'Unknown error',
};
}
},
},
{
name: 'get-user-info',
description: 'Get current user information',
execute: async (context: CommandContext, previousResult: any) => {
if (!previousResult.validated) {
console.log('Session not valid, cannot get user info');
return {
...previousResult,
userInfo: null,
reason: 'Session not valid',
};
}
console.log('Getting user information...');
try {
const { get } = await import('../api');
const userInfo = await get('/user/me');
console.log('✓ User information retrieved successfully');
if (context.options.showDetails !== false) {
console.log('\n=== User Information ===');
for (const [key, value] of Object.entries(userInfo)) {
if (key !== 'ok') {
console.log(`${key}: ${value}`);
}
}
console.log('========================\n');
}
return {
...previousResult,
userInfo,
reason: 'User info retrieved successfully',
};
} catch (error) {
console.log(
'✗ Failed to get user info:',
error instanceof Error ? error.message : 'Unknown error',
);
return {
...previousResult,
userInfo: null,
reason:
error instanceof Error ? error.message : 'Unknown error',
};
}
},
},
{
name: 'handle-auth-failure',
description: 'Handle authentication failure',
execute: async (context: CommandContext, previousResult: any) => {
if (previousResult.validated) {
console.log('✓ Authentication check completed successfully');
return {
...previousResult,
authCheckComplete: true,
status: 'authenticated',
};
}
console.log('✗ Authentication check failed');
if (context.options.autoLogin) {
console.log('Attempting automatic login...');
try {
await userCommands.login({ args: [] });
console.log('✓ Automatic login successful');
return {
...previousResult,
authCheckComplete: true,
status: 'auto-logged-in',
autoLoginSuccess: true,
};
} catch (error) {
console.log(
'✗ Automatic login failed:',
error instanceof Error ? error.message : 'Unknown error',
);
return {
...previousResult,
authCheckComplete: true,
status: 'failed',
autoLoginSuccess: false,
autoLoginError:
error instanceof Error ? error.message : 'Unknown error',
};
}
} else {
console.log('Please run login command to authenticate');
return {
...previousResult,
authCheckComplete: true,
status: 'unauthenticated',
suggestion: 'Run login command to authenticate',
};
}
},
},
],
},
{
name: 'login-flow',
description: 'Complete login flow with validation',
options: {
email: { hasValue: true, description: 'User email' },
password: { hasValue: true, description: 'User password' },
validateAfterLogin: {
default: true,
description: 'Validate session after login',
},
},
steps: [
{
name: 'check-existing-session',
description: 'Check if user is already logged in',
execute: async (context: CommandContext) => {
console.log('Checking existing session...');
try {
await loadSession();
const session = getSession();
if (session && session.token) {
try {
await userCommands.me();
console.log('✓ User is already logged in');
return {
alreadyLoggedIn: true,
session: session,
status: 'authenticated',
};
} catch (error) {
console.log(
'✗ Existing session is invalid, proceeding with login',
);
return {
alreadyLoggedIn: false,
session: null,
status: 'session-expired',
};
}
} else {
console.log('No existing session found');
return {
alreadyLoggedIn: false,
session: null,
status: 'no-session',
};
}
} catch (error) {
console.log(
'Error checking existing session:',
error instanceof Error ? error.message : 'Unknown error',
);
return {
alreadyLoggedIn: false,
session: null,
status: 'error',
error: error instanceof Error ? error.message : 'Unknown error',
};
}
},
},
{
name: 'perform-login',
description: 'Perform user login',
execute: async (context: CommandContext, previousResult: any) => {
if (previousResult.alreadyLoggedIn) {
console.log('Skipping login - user already authenticated');
return {
...previousResult,
loginPerformed: false,
loginSuccess: true,
};
}
console.log('Performing login...');
try {
const loginArgs = [];
if (context.options.email) {
loginArgs.push(context.options.email);
}
if (context.options.password) {
loginArgs.push(context.options.password);
}
await userCommands.login({ args: loginArgs });
console.log('✓ Login successful');
return {
...previousResult,
loginPerformed: true,
loginSuccess: true,
};
} catch (error) {
console.log(
'✗ Login failed:',
error instanceof Error ? error.message : 'Unknown error',
);
return {
...previousResult,
loginPerformed: true,
loginSuccess: false,
loginError:
error instanceof Error ? error.message : 'Unknown error',
};
}
},
},
{
name: 'validate-login',
description: 'Validate login by getting user info',
execute: async (context: CommandContext, previousResult: any) => {
if (
!previousResult.loginSuccess &&
!previousResult.alreadyLoggedIn
) {
console.log('Login failed, skipping validation');
return {
...previousResult,
validationPerformed: false,
validationSuccess: false,
};
}
if (context.options.validateAfterLogin === false) {
console.log('Skipping validation as requested');
return {
...previousResult,
validationPerformed: false,
validationSuccess: true,
};
}
console.log('Validating login by getting user information...');
try {
const userInfo = await userCommands.me();
console.log('✓ Login validation successful');
return {
...previousResult,
validationPerformed: true,
validationSuccess: true,
userInfo,
};
} catch (error) {
console.log(
'✗ Login validation failed:',
error instanceof Error ? error.message : 'Unknown error',
);
return {
...previousResult,
validationPerformed: true,
validationSuccess: false,
validationError:
error instanceof Error ? error.message : 'Unknown error',
};
}
},
},
{
name: 'login-summary',
description: 'Provide login flow summary',
execute: async (context: CommandContext, previousResult: any) => {
console.log('\n=== Login Flow Summary ===');
if (previousResult.alreadyLoggedIn) {
console.log('Status: Already logged in');
console.log('Session: Valid');
} else if (previousResult.loginSuccess) {
console.log('Status: Login successful');
if (previousResult.validationSuccess) {
console.log('Validation: Passed');
} else {
console.log('Validation: Failed');
}
} else {
console.log('Status: Login failed');
console.log(
'Error:',
previousResult.loginError || 'Unknown error',
);
}
console.log('==========================\n');
return {
...previousResult,
flowComplete: true,
finalStatus:
previousResult.alreadyLoggedIn || previousResult.loginSuccess
? 'success'
: 'failed',
};
},
},
],
},
],
};

View File

@@ -0,0 +1,8 @@
import type { CLIModule} from '../types';
export const versionModule: CLIModule = {
name: 'version',
version: '1.0.0',
commands: [],
workflows: [],
};

View File

@@ -4,11 +4,11 @@ import { t } from './utils/i18n';
import { getPlatform, getSelectedApp } from './app';
import { getApkInfo, getIpaInfo, getAppInfo } from './utils';
import Table from 'tty-table';
import type { Platform } from './types';
import { getApkInfo, getAppInfo, getIpaInfo } from './utils';
import { depVersions } from './utils/dep-versions';
import { getCommitInfo } from './utils/git';
import type { Platform } from 'types';
export async function listPackage(appId: string) {
const allPkgs = await getAllPackages(appId);
@@ -22,7 +22,11 @@ export async function listPackage(appId: string) {
const { version } = pkg;
let versionInfo = '';
if (version) {
versionInfo = t('boundTo', { name: version.name, id: version.id });
const versionObj = version as any;
versionInfo = t('boundTo', {
name: versionObj.name || version,
id: versionObj.id || version
});
}
let output = pkg.name;
if (pkg.status === 'paused') {
@@ -45,7 +49,7 @@ export async function choosePackage(appId: string) {
while (true) {
const id = await question(t('enterNativePackageId'));
const app = list.find((v) => v.id === Number(id));
const app = list.find((v) => v.id.toString() === id);
if (app) {
return app;
}
@@ -58,12 +62,13 @@ export const packageCommands = {
if (!fn || !fn.endsWith('.ipa')) {
throw new Error(t('usageUploadIpa'));
}
const ipaInfo = await getIpaInfo(fn);
const {
versionName,
buildTime,
appId: appIdInPkg,
appKey: appKeyInPkg,
} = await getIpaInfo(fn);
} = ipaInfo;
const appIdInPkg = (ipaInfo as any).appId;
const appKeyInPkg = (ipaInfo as any).appKey;
const { appId, appKey } = await getSelectedApp('ios');
if (appIdInPkg && appIdInPkg != appId) {
@@ -84,19 +89,22 @@ export const packageCommands = {
commit: await getCommitInfo(),
});
saveToLocal(fn, `${appId}/package/${id}.ipa`);
console.log(t('ipaUploadSuccess', { id, version: versionName, buildTime }));
console.log(
t('ipaUploadSuccess', { id, version: versionName, buildTime }),
);
},
uploadApk: async ({ args }: { args: string[] }) => {
const fn = args[0];
if (!fn || !fn.endsWith('.apk')) {
throw new Error(t('usageUploadApk'));
}
const apkInfo = await getApkInfo(fn);
const {
versionName,
buildTime,
appId: appIdInPkg,
appKey: appKeyInPkg,
} = await getApkInfo(fn);
} = apkInfo;
const appIdInPkg = (apkInfo as any).appId;
const appKeyInPkg = (apkInfo as any).appKey;
const { appId, appKey } = await getSelectedApp('android');
if (appIdInPkg && appIdInPkg != appId) {
@@ -117,19 +125,22 @@ export const packageCommands = {
commit: await getCommitInfo(),
});
saveToLocal(fn, `${appId}/package/${id}.apk`);
console.log(t('apkUploadSuccess', { id, version: versionName, buildTime }));
console.log(
t('apkUploadSuccess', { id, version: versionName, buildTime }),
);
},
uploadApp: async ({ args }: { args: string[] }) => {
const fn = args[0];
if (!fn || !fn.endsWith('.app')) {
throw new Error(t('usageUploadApp'));
}
const appInfo = await getAppInfo(fn);
const {
versionName,
buildTime,
appId: appIdInPkg,
appKey: appKeyInPkg,
} = await getAppInfo(fn);
} = appInfo;
const appIdInPkg = (appInfo as any).appId;
const appKeyInPkg = (appInfo as any).appKey;
const { appId, appKey } = await getSelectedApp('harmony');
if (appIdInPkg && appIdInPkg != appId) {
@@ -150,7 +161,9 @@ export const packageCommands = {
commit: await getCommitInfo(),
});
saveToLocal(fn, `${appId}/package/${id}.app`);
console.log(t('appUploadSuccess', { id, version: versionName, buildTime }));
console.log(
t('appUploadSuccess', { id, version: versionName, buildTime }),
);
},
parseApp: async ({ args }: { args: string[] }) => {
const fn = args[0];

341
src/provider.ts Normal file
View File

@@ -0,0 +1,341 @@
import { getSession, loadSession } from './api';
import { getPlatform, getSelectedApp } from './app';
import type {
BundleOptions,
CLIProvider,
CommandContext,
CommandResult,
CustomWorkflow,
Platform,
PublishOptions,
Session,
UploadOptions,
Version,
} from './types';
export class CLIProviderImpl implements CLIProvider {
private workflows: Map<string, CustomWorkflow> = new Map();
private session?: Session;
constructor() {
this.init();
}
private async init() {
try {
await loadSession();
this.session = getSession();
} catch (error) {}
}
async bundle(options: BundleOptions): Promise<CommandResult> {
try {
const context: CommandContext = {
args: [],
options: {
dev: options.dev || false,
platform: options.platform,
bundleName: options.bundleName || 'index.bundlejs',
entryFile: options.entryFile || 'index.js',
output: options.output || '${tempDir}/output/${platform}.${time}.ppk',
sourcemap: options.sourcemap || false,
taro: options.taro || false,
expo: options.expo || false,
rncli: options.rncli || false,
disableHermes: options.disableHermes || false,
},
};
const { bundleCommands } = await import('./bundle');
await bundleCommands.bundle(context);
return {
success: true,
data: { message: 'Bundle created successfully' },
};
} catch (error) {
return {
success: false,
error:
error instanceof Error
? error.message
: 'Unknown error during bundling',
};
}
}
async publish(options: PublishOptions): Promise<CommandResult> {
try {
const context: CommandContext = {
args: [],
options: {
name: options.name,
description: options.description,
metaInfo: options.metaInfo,
packageId: options.packageId,
packageVersion: options.packageVersion,
minPackageVersion: options.minPackageVersion,
maxPackageVersion: options.maxPackageVersion,
packageVersionRange: options.packageVersionRange,
rollout: options.rollout,
dryRun: options.dryRun || false,
},
};
const { versionCommands } = await import('./versions');
await versionCommands.publish(context);
return {
success: true,
data: { message: 'Version published successfully' },
};
} catch (error) {
return {
success: false,
error:
error instanceof Error
? error.message
: 'Unknown error during publishing',
};
}
}
async upload(options: UploadOptions): Promise<CommandResult> {
try {
const platform = await this.getPlatform(options.platform);
const { appId } = await this.getSelectedApp(platform);
const filePath = options.filePath;
const fileType = filePath.split('.').pop()?.toLowerCase();
const context: CommandContext = {
args: [filePath],
options: { platform, appId },
};
const { packageCommands } = await import('./package');
switch (fileType) {
case 'ipa':
await packageCommands.uploadIpa(context);
break;
case 'apk':
await packageCommands.uploadApk(context);
break;
case 'app':
await packageCommands.uploadApp(context);
break;
default:
throw new Error(`Unsupported file type: ${fileType}`);
}
return {
success: true,
data: { message: 'File uploaded successfully' },
};
} catch (error) {
return {
success: false,
error:
error instanceof Error
? error.message
: 'Unknown error during upload',
};
}
}
async getSelectedApp(
platform?: Platform,
): Promise<{ appId: string; platform: Platform }> {
const resolvedPlatform = await this.getPlatform(platform);
return getSelectedApp(resolvedPlatform);
}
async listApps(platform?: Platform): Promise<CommandResult> {
try {
const resolvedPlatform = await this.getPlatform(platform);
const { appCommands } = await import('./app');
await appCommands.apps({ options: { platform: resolvedPlatform } });
return {
success: true,
data: { message: 'Apps listed successfully' },
};
} catch (error) {
return {
success: false,
error:
error instanceof Error ? error.message : 'Unknown error listing apps',
};
}
}
async createApp(name: string, platform: Platform): Promise<CommandResult> {
try {
const { appCommands } = await import('./app');
await appCommands.createApp({
options: {
name,
platform,
downloadUrl: '',
},
});
return {
success: true,
data: { message: 'App created successfully' },
};
} catch (error) {
return {
success: false,
error:
error instanceof Error ? error.message : 'Unknown error creating app',
};
}
}
async listVersions(appId: string): Promise<CommandResult> {
try {
const context: CommandContext = {
args: [],
options: { appId },
};
const { versionCommands } = await import('./versions');
await versionCommands.versions(context);
return {
success: true,
data: { message: 'Versions listed successfully' },
};
} catch (error) {
return {
success: false,
error:
error instanceof Error
? error.message
: 'Unknown error listing versions',
};
}
}
async updateVersion(
appId: string,
versionId: string,
updates: Partial<Version>,
): Promise<CommandResult> {
try {
const context: CommandContext = {
args: [versionId],
options: {
appId,
...updates,
},
};
const { versionCommands } = await import('./versions');
await versionCommands.update(context);
return {
success: true,
data: { message: 'Version updated successfully' },
};
} catch (error) {
return {
success: false,
error:
error instanceof Error
? error.message
: 'Unknown error updating version',
};
}
}
async getPlatform(platform?: Platform): Promise<Platform> {
return getPlatform(platform);
}
async loadSession(): Promise<Session> {
await loadSession();
this.session = getSession();
if (!this.session) {
throw new Error('Failed to load session');
}
return this.session;
}
registerWorkflow(workflow: CustomWorkflow): void {
this.workflows.set(workflow.name, workflow);
}
async executeWorkflow(
workflowName: string,
context: CommandContext,
): Promise<CommandResult> {
const workflow = this.workflows.get(workflowName);
if (!workflow) {
return {
success: false,
error: `Workflow '${workflowName}' not found`,
};
}
try {
let previousResult: any = null;
for (const step of workflow.steps) {
if (step.condition && !step.condition(context)) {
console.log(`Skipping step '${step.name}' due to condition`);
continue;
}
console.log(`Executing step '${step.name}'`);
previousResult = await step.execute(context, previousResult);
}
return {
success: true,
data: {
message: `Workflow '${workflowName}' completed successfully`,
result: previousResult,
},
};
} catch (error) {
return {
success: false,
error:
error instanceof Error
? error.message
: `Workflow '${workflowName}' failed`,
};
}
}
getRegisteredWorkflows(): string[] {
return Array.from(this.workflows.keys());
}
async listPackages(appId?: string): Promise<CommandResult> {
try {
const context: CommandContext = {
args: [],
options: appId ? { appId } : {},
};
const { listPackage } = await import('./package');
const result = await listPackage(appId || '');
return {
success: true,
data: result,
};
} catch (error) {
return {
success: false,
error:
error instanceof Error
? error.message
: 'Unknown error listing packages',
};
}
}
}

View File

@@ -12,6 +12,12 @@ export type Platform = 'ios' | 'android' | 'harmony';
export interface Package {
id: string;
name: string;
version?: string;
status?: string;
appId?: string;
appKey?: string;
versionName?: any;
buildTime?: any;
}
export interface Version {
@@ -20,3 +26,122 @@ export interface Version {
name: string;
packages?: Package[];
}
export interface CommandContext {
args: string[];
options: Record<string, any>;
platform?: Platform;
appId?: string;
session?: Session;
}
export interface CommandResult {
success: boolean;
data?: any;
error?: string;
}
export interface CommandDefinition {
name: string;
description?: string;
handler: (context: CommandContext) => Promise<CommandResult>;
options?: Record<
string,
{
hasValue?: boolean;
default?: any;
description?: string;
}
>;
}
export interface BundleOptions {
dev?: boolean;
platform?: Platform;
bundleName?: string;
entryFile?: string;
output?: string;
sourcemap?: boolean;
taro?: boolean;
expo?: boolean;
rncli?: boolean;
disableHermes?: boolean;
}
export interface PublishOptions {
name?: string;
description?: string;
metaInfo?: string;
packageId?: string;
packageVersion?: string;
minPackageVersion?: string;
maxPackageVersion?: string;
packageVersionRange?: string;
rollout?: number;
dryRun?: boolean;
}
export interface UploadOptions {
platform?: Platform;
filePath: string;
appId?: string;
}
export interface WorkflowStep {
name: string;
description?: string;
execute: (context: CommandContext, previousResult?: any) => Promise<any>;
condition?: (context: CommandContext) => boolean;
}
export interface CustomWorkflow {
name: string;
description?: string;
steps: WorkflowStep[];
validate?: (context: CommandContext) => boolean;
options?: Record<
string,
{
hasValue?: boolean;
default?: any;
description?: string;
}
>;
}
export interface CLIProvider {
bundle: (options: BundleOptions) => Promise<CommandResult>;
publish: (options: PublishOptions) => Promise<CommandResult>;
upload: (options: UploadOptions) => Promise<CommandResult>;
createApp: (name: string, platform: Platform) => Promise<CommandResult>;
listApps: (platform?: Platform) => Promise<CommandResult>;
getSelectedApp: (
platform?: Platform,
) => Promise<{ appId: string; platform: Platform }>;
listVersions: (appId: string) => Promise<CommandResult>;
updateVersion: (
appId: string,
versionId: string,
updates: Partial<Version>,
) => Promise<CommandResult>;
getPlatform: (platform?: Platform) => Promise<Platform>;
loadSession: () => Promise<Session>;
registerWorkflow: (workflow: CustomWorkflow) => void;
executeWorkflow: (
workflowName: string,
context: CommandContext,
) => Promise<CommandResult>;
}
export interface CLIModule {
name: string;
version: string;
commands?: CommandDefinition[];
workflows?: CustomWorkflow[];
init?: (provider: CLIProvider) => void;
cleanup?: () => void;
}

View File

@@ -1,6 +1,7 @@
import { question } from './utils';
import { post, get, replaceSession, saveSession, closeSession } from './api';
import crypto from 'crypto';
import type { CommandContext } from 'types';
import { closeSession, get, post, replaceSession, saveSession } from './api';
import { question } from './utils';
import { t } from './utils/i18n';
function md5(str: string) {
@@ -19,7 +20,7 @@ export const userCommands = {
await saveSession();
console.log(t('welcomeMessage', { name: info.name }));
},
logout: async () => {
logout: async (context: CommandContext) => {
await closeSession();
console.log(t('loggedOut'));
},

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;
}
}
}
}
];
},
},
];

View File

@@ -2,13 +2,13 @@ import { get, getAllPackages, post, put, uploadFile } from './api';
import { question, saveToLocal } from './utils';
import { t } from './utils/i18n';
import chalk from 'chalk';
import { satisfies } from 'compare-versions';
import type { Package, Platform, Version } from './types';
import { getPlatform, getSelectedApp } from './app';
import { choosePackage } from './package';
import { depVersions } from './utils/dep-versions';
import { getCommitInfo } from './utils/git';
import type { Package, Platform, Version } from 'types';
import { satisfies } from 'compare-versions';
import chalk from 'chalk';
interface VersionCommandOptions {
appId?: string;