Skip to content

Commit

Permalink
🎨 Optimize the use of CLI.
Browse files Browse the repository at this point in the history
  • Loading branch information
tw93 committed Jun 22, 2023
1 parent 57c1bc5 commit db37728
Show file tree
Hide file tree
Showing 9 changed files with 79 additions and 49 deletions.
3 changes: 3 additions & 0 deletions bin/builders/BaseBuilder.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import ora from "ora";
import path from 'path';
import fsExtra from "fs-extra";
import prompts from 'prompts';
Expand Down Expand Up @@ -39,6 +40,8 @@ export default abstract class BaseBuilder {
}

protected async runBuildCommand(directory: string, command: string) {
const spinner = ora('Building...').start();
setTimeout(() => spinner.succeed(), 5000);
const isChina = await isChinaDomain("www.npmjs.com");
if (isChina) {
logger.info("Located in China, using npm/Rust CN mirror.");
Expand Down
21 changes: 11 additions & 10 deletions bin/builders/BuilderProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,20 @@ import MacBuilder from './MacBuilder';
import WinBuilder from './WinBuilder';
import LinuxBuilder from './LinuxBuilder';

import { IS_MAC, IS_WIN, IS_LINUX } from '@/utils/platform';
const { platform } = process;

const buildersMap: Record<string, new () => BaseBuilder> = {
darwin: MacBuilder,
win32: WinBuilder,
linux: LinuxBuilder,
};

export default class BuilderProvider {
static create(): BaseBuilder {
if (IS_MAC) {
return new MacBuilder();
}
if (IS_WIN) {
return new WinBuilder();
}
if (IS_LINUX) {
return new LinuxBuilder();
const Builder = buildersMap[platform];
if (!Builder) {
throw new Error('The current system is not supported!');
}
throw new Error('The current system is not supported!');
return new Builder();
}
}
4 changes: 3 additions & 1 deletion bin/cli.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import ora from "ora";
import log from 'loglevel';
import { program } from 'commander';

Expand Down Expand Up @@ -46,10 +47,11 @@ program
log.setLevel('debug');
}

const spinner = ora('Preparing...').start();
const builder = BuilderProvider.create();
await builder.prepare();

const appOptions = await handleInputOptions(options, url);
spinner.succeed();

log.debug('PakeAppOptions', appOptions);

Expand Down
6 changes: 3 additions & 3 deletions bin/helpers/merge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,19 +127,19 @@ export async function mergeConfig(
const platformIconMap: PlatformMap = {
win32: {
fileExt: '.ico',
path: `png/${name.toLowerCase()}_32.ico`,
path: `png/${name.toLowerCase()}_256.ico`,
defaultIcon: 'png/icon_256.ico',
message: 'Windows icon must be .ico and 256x256px.',
},
linux: {
fileExt: '.png',
path: `png/${name.toLowerCase()}_32.png`,
path: `png/${name.toLowerCase()}_512.png`,
defaultIcon: 'png/icon_512.png',
message: 'Linux icon must be .png and 512x512px.',
},
darwin: {
fileExt: '.icns',
path: `icons/${name.toLowerCase()}_32.icns`,
path: `icons/${name.toLowerCase()}.icns`,
defaultIcon: 'icons/icon.icns',
message: 'MacOS icon must be .icns type.',
},
Expand Down
6 changes: 3 additions & 3 deletions bin/options/icon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,10 @@ export async function handleIcon(options: PakeAppOptions) {

export async function downloadIcon(iconUrl: string) {
try {
const iconResponse = await axios.get(iconUrl, {
responseType: 'arraybuffer',
});
const iconResponse = await axios.get(iconUrl, { responseType: 'arraybuffer' });

const iconData = await iconResponse.data;

if (!iconData) {
return null;
}
Expand All @@ -42,6 +41,7 @@ export async function downloadIcon(iconUrl: string) {
const { path: tempPath } = await dir();
const iconPath = `${tempPath}/icon.${fileDetails.ext}`;
await fsExtra.outputFile(iconPath, iconData);

return iconPath;
} catch (error) {
if (error.response && error.response.status === 404) {
Expand Down
18 changes: 14 additions & 4 deletions bin/utils/ip.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ const ping = async (host: string) => {
const ip = await lookup(host);
const start = new Date();

return new Promise<number>((resolve, reject) => {
// Prevent timeouts from affecting user experience.
const requestPromise = new Promise<number>((resolve, reject) => {
const req = http.get(`http://${ip.address}`, (res) => {
const delay = new Date().getTime() - start.getTime();
res.resume();
Expand All @@ -21,25 +22,34 @@ const ping = async (host: string) => {
reject(err);
});
});

const timeoutPromise = new Promise<number>((_, reject) => {
setTimeout(() => {
reject(new Error('Request timed out after 3 seconds'));
}, 3000);
});

return Promise.race([requestPromise, timeoutPromise]);
};


async function isChinaDomain(domain: string): Promise<boolean> {
try {
const [ip] = await resolve(domain);
return await isChinaIP(ip, domain);
} catch (error) {
logger.info(`${domain} can't be parse!`);
logger.debug(`${domain} can't be parse!`);
return false;
}
}

async function isChinaIP(ip: string, domain: string): Promise<boolean> {
try {
const delay = await ping(ip);
logger.info(`${domain} latency is ${delay} ms`);
logger.debug(`${domain} latency is ${delay} ms`);
return delay > 500;
} catch (error) {
logger.info(`ping ${domain} failed!`);
logger.debug(`ping ${domain} failed!`);
return false;
}
}
Expand Down
64 changes: 37 additions & 27 deletions dist/cli.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import ora from 'ora';
import log from 'loglevel';
import { InvalidArgumentError, program } from 'commander';
import fsExtra from 'fs-extra';
Expand All @@ -15,7 +16,6 @@ import shelljs from 'shelljs';
import dns from 'dns';
import http from 'http';
import { promisify } from 'util';
import ora from 'ora';
import updateNotifier from 'update-notifier';
import fs from 'fs';

Expand All @@ -42,10 +42,10 @@ const currentModulePath = fileURLToPath(import.meta.url);
// Resolve the parent directory of the current module
const npmDirectory = path.join(path.dirname(currentModulePath), '..');

const { platform: platform$1 } = process;
const IS_MAC = platform$1 === 'darwin';
const IS_WIN = platform$1 === 'win32';
const IS_LINUX = platform$1 === 'linux';
const { platform: platform$2 } = process;
const IS_MAC = platform$2 === 'darwin';
const IS_WIN = platform$2 === 'win32';
const IS_LINUX = platform$2 === 'linux';

async function handleIcon(options) {
if (options.icon) {
Expand All @@ -64,9 +64,7 @@ async function handleIcon(options) {
}
async function downloadIcon(iconUrl) {
try {
const iconResponse = await axios.get(iconUrl, {
responseType: 'arraybuffer',
});
const iconResponse = await axios.get(iconUrl, { responseType: 'arraybuffer' });
const iconData = await iconResponse.data;
if (!iconData) {
return null;
Expand Down Expand Up @@ -347,9 +345,9 @@ const platformConfigs = {
darwin: MacConf,
linux: LinuxConf
};
const { platform } = process;
const { platform: platform$1 } = process;
// @ts-ignore
const platformConfig = platformConfigs[platform];
const platformConfig = platformConfigs[platform$1];
let tauriConfig = {
tauri: {
...CommonConf.tauri,
Expand Down Expand Up @@ -378,7 +376,8 @@ const ping = async (host) => {
const lookup = promisify(dns.lookup);
const ip = await lookup(host);
const start = new Date();
return new Promise((resolve, reject) => {
// Prevent timeouts from affecting user experience.
const requestPromise = new Promise((resolve, reject) => {
const req = http.get(`http://${ip.address}`, (res) => {
const delay = new Date().getTime() - start.getTime();
res.resume();
Expand All @@ -388,25 +387,31 @@ const ping = async (host) => {
reject(err);
});
});
const timeoutPromise = new Promise((_, reject) => {
setTimeout(() => {
reject(new Error('Request timed out after 3 seconds'));
}, 3000);
});
return Promise.race([requestPromise, timeoutPromise]);
};
async function isChinaDomain(domain) {
try {
const [ip] = await resolve(domain);
return await isChinaIP(ip, domain);
}
catch (error) {
logger.info(`${domain} can't be parse!`);
logger.debug(`${domain} can't be parse!`);
return false;
}
}
async function isChinaIP(ip, domain) {
try {
const delay = await ping(ip);
logger.info(`${domain} latency is ${delay} ms`);
logger.debug(`${domain} latency is ${delay} ms`);
return delay > 500;
}
catch (error) {
logger.info(`ping ${domain} failed!`);
logger.debug(`ping ${domain} failed!`);
return false;
}
}
Expand Down Expand Up @@ -457,6 +462,8 @@ class BaseBuilder {
}
}
async runBuildCommand(directory, command) {
const spinner = ora('Building...').start();
setTimeout(() => spinner.succeed(), 5000);
const isChina = await isChinaDomain("www.npmjs.com");
if (isChina) {
logger.info("Located in China, using npm/Rust CN mirror.");
Expand Down Expand Up @@ -557,19 +564,19 @@ async function mergeConfig(url, options, tauriConf) {
const platformIconMap = {
win32: {
fileExt: '.ico',
path: `png/${name.toLowerCase()}_32.ico`,
path: `png/${name.toLowerCase()}_256.ico`,
defaultIcon: 'png/icon_256.ico',
message: 'Windows icon must be .ico and 256x256px.',
},
linux: {
fileExt: '.png',
path: `png/${name.toLowerCase()}_32.png`,
path: `png/${name.toLowerCase()}_512.png`,
defaultIcon: 'png/icon_512.png',
message: 'Linux icon must be .png and 512x512px.',
},
darwin: {
fileExt: '.icns',
path: `icons/${name.toLowerCase()}_32.icns`,
path: `icons/${name.toLowerCase()}.icns`,
defaultIcon: 'icons/icon.icns',
message: 'MacOS icon must be .icns type.',
},
Expand Down Expand Up @@ -718,23 +725,24 @@ class LinuxBuilder extends BaseBuilder {
}
}

const { platform } = process;
const buildersMap = {
darwin: MacBuilder,
win32: WinBuilder,
linux: LinuxBuilder,
};
class BuilderProvider {
static create() {
if (IS_MAC) {
return new MacBuilder();
}
if (IS_WIN) {
return new WinBuilder();
}
if (IS_LINUX) {
return new LinuxBuilder();
const Builder = buildersMap[platform];
if (!Builder) {
throw new Error('The current system is not supported!');
}
throw new Error('The current system is not supported!');
return new Builder();
}
}

var name = "pake-cli";
var version = "2.1.0";
var version = "2.1.1";
var description = "🤱🏻 Turn any webpage into a desktop app with Rust. 🤱🏻 很简单的用 Rust 打包网页生成很小的桌面 App。";
var engines = {
node: ">=16.0.0"
Expand Down Expand Up @@ -907,9 +915,11 @@ program
if (options.debug) {
log.setLevel('debug');
}
const spinner = ora('Preparing...').start();
const builder = BuilderProvider.create();
await builder.prepare();
const appOptions = await handleOptions(options, url);
spinner.succeed();
log.debug('PakeAppOptions', appOptions);
await builder.build(url, appOptions);
});
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "pake-cli",
"version": "2.1.0",
"version": "2.1.1",
"description": "🤱🏻 Turn any webpage into a desktop app with Rust. 🤱🏻 很简单的用 Rust 打包网页生成很小的桌面 App。",
"engines": {
"node": ">=16.0.0"
Expand Down
4 changes: 4 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
"types": [
"node"
],
"lib": [
"es2020",
"dom"
],
"esModuleInterop": true,
"resolveJsonModule": true,
"allowSyntheticDefaultImports": true,
Expand Down

0 comments on commit db37728

Please sign in to comment.