Fix gitignore
This commit is contained in:
parent
cca8b02fea
commit
a3f9280a1e
2902 changed files with 86686 additions and 2 deletions
3
.gitignore
vendored
3
.gitignore
vendored
|
|
@ -1,7 +1,6 @@
|
|||
.idea/
|
||||
|
||||
electron/build
|
||||
android/build
|
||||
android/app/build
|
||||
|
||||
build/
|
||||
build/miarven*
|
||||
61
electron/build/src/index.js
Normal file
61
electron/build/src/index.js
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
"use strict";
|
||||
var _a, _b;
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const tslib_1 = require("tslib");
|
||||
const electron_1 = require("@capacitor-community/electron");
|
||||
const electron_2 = require("electron");
|
||||
const electron_is_dev_1 = tslib_1.__importDefault(require("electron-is-dev"));
|
||||
const electron_unhandled_1 = tslib_1.__importDefault(require("electron-unhandled"));
|
||||
const electron_updater_1 = require("electron-updater");
|
||||
const setup_1 = require("./setup");
|
||||
// Graceful handling of unhandled errors.
|
||||
(0, electron_unhandled_1.default)();
|
||||
// Define our menu templates (these are optional)
|
||||
const trayMenuTemplate = [new electron_2.MenuItem({ label: 'Quit App', role: 'quit' })];
|
||||
const appMenuBarMenuTemplate = [
|
||||
{ role: process.platform === 'darwin' ? 'appMenu' : 'fileMenu' },
|
||||
{ role: 'viewMenu' },
|
||||
];
|
||||
// Get Config options from capacitor.config
|
||||
const capacitorFileConfig = (0, electron_1.getCapacitorElectronConfig)();
|
||||
// Initialize our app. You can pass menu templates into the app here.
|
||||
// const myCapacitorApp = new ElectronCapacitorApp(capacitorFileConfig);
|
||||
const myCapacitorApp = new setup_1.ElectronCapacitorApp(capacitorFileConfig, trayMenuTemplate, appMenuBarMenuTemplate);
|
||||
// If deeplinking is enabled then we will set it up here.
|
||||
if ((_a = capacitorFileConfig.electron) === null || _a === void 0 ? void 0 : _a.deepLinkingEnabled) {
|
||||
(0, electron_1.setupElectronDeepLinking)(myCapacitorApp, {
|
||||
customProtocol: (_b = capacitorFileConfig.electron.deepLinkingCustomProtocol) !== null && _b !== void 0 ? _b : 'mycapacitorapp',
|
||||
});
|
||||
}
|
||||
// If we are in Dev mode, use the file watcher components.
|
||||
if (electron_is_dev_1.default) {
|
||||
(0, setup_1.setupReloadWatcher)(myCapacitorApp);
|
||||
}
|
||||
// Run Application
|
||||
(async () => {
|
||||
// Wait for electron app to be ready.
|
||||
await electron_2.app.whenReady();
|
||||
// Security - Set Content-Security-Policy based on whether or not we are in dev mode.
|
||||
(0, setup_1.setupContentSecurityPolicy)(myCapacitorApp.getCustomURLScheme());
|
||||
// Initialize our app, build windows, and load content.
|
||||
await myCapacitorApp.init();
|
||||
// Check for updates if we are in a packaged app.
|
||||
electron_updater_1.autoUpdater.checkForUpdatesAndNotify();
|
||||
})();
|
||||
// Handle when all of our windows are close (platforms have their own expectations).
|
||||
electron_2.app.on('window-all-closed', function () {
|
||||
// On OS X it is common for applications and their menu bar
|
||||
// to stay active until the user quits explicitly with Cmd + Q
|
||||
if (process.platform !== 'darwin') {
|
||||
electron_2.app.quit();
|
||||
}
|
||||
});
|
||||
// When the dock icon is clicked.
|
||||
electron_2.app.on('activate', async function () {
|
||||
// On OS X it's common to re-create a window in the app when the
|
||||
// dock icon is clicked and there are no other windows open.
|
||||
if (myCapacitorApp.getMainWindow().isDestroyed()) {
|
||||
await myCapacitorApp.init();
|
||||
}
|
||||
});
|
||||
// Place all ipc or other electron api calls and custom functionality under this line
|
||||
4
electron/build/src/preload.js
Normal file
4
electron/build/src/preload.js
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
require('./rt/electron-rt');
|
||||
//////////////////////////////
|
||||
// User Defined Preload scripts below
|
||||
console.log('User Preload!');
|
||||
2
electron/build/src/rt/electron-plugins.js
Normal file
2
electron/build/src/rt/electron-plugins.js
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
module.exports = {};
|
||||
68
electron/build/src/rt/electron-rt.js
Normal file
68
electron/build/src/rt/electron-rt.js
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const crypto_1 = require("crypto");
|
||||
const electron_1 = require("electron");
|
||||
const events_1 = require("events");
|
||||
////////////////////////////////////////////////////////
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
const plugins = require('./electron-plugins');
|
||||
const randomId = (length = 5) => (0, crypto_1.randomBytes)(length).toString('hex');
|
||||
const contextApi = {};
|
||||
Object.keys(plugins).forEach((pluginKey) => {
|
||||
Object.keys(plugins[pluginKey])
|
||||
.filter((className) => className !== 'default')
|
||||
.forEach((classKey) => {
|
||||
const functionList = Object.getOwnPropertyNames(plugins[pluginKey][classKey].prototype).filter((v) => v !== 'constructor');
|
||||
if (!contextApi[classKey]) {
|
||||
contextApi[classKey] = {};
|
||||
}
|
||||
functionList.forEach((functionName) => {
|
||||
if (!contextApi[classKey][functionName]) {
|
||||
contextApi[classKey][functionName] = (...args) => electron_1.ipcRenderer.invoke(`${classKey}-${functionName}`, ...args);
|
||||
}
|
||||
});
|
||||
// Events
|
||||
if (plugins[pluginKey][classKey].prototype instanceof events_1.EventEmitter) {
|
||||
const listeners = {};
|
||||
const listenersOfTypeExist = (type) => !!Object.values(listeners).find((listenerObj) => listenerObj.type === type);
|
||||
Object.assign(contextApi[classKey], {
|
||||
addListener(type, callback) {
|
||||
const id = randomId();
|
||||
// Deduplicate events
|
||||
if (!listenersOfTypeExist(type)) {
|
||||
electron_1.ipcRenderer.send(`event-add-${classKey}`, type);
|
||||
}
|
||||
const eventHandler = (_, ...args) => callback(...args);
|
||||
electron_1.ipcRenderer.addListener(`event-${classKey}-${type}`, eventHandler);
|
||||
listeners[id] = { type, listener: eventHandler };
|
||||
return id;
|
||||
},
|
||||
removeListener(id) {
|
||||
if (!listeners[id]) {
|
||||
throw new Error('Invalid id');
|
||||
}
|
||||
const { type, listener } = listeners[id];
|
||||
electron_1.ipcRenderer.removeListener(`event-${classKey}-${type}`, listener);
|
||||
delete listeners[id];
|
||||
if (!listenersOfTypeExist(type)) {
|
||||
electron_1.ipcRenderer.send(`event-remove-${classKey}-${type}`);
|
||||
}
|
||||
},
|
||||
removeAllListeners(type) {
|
||||
Object.entries(listeners).forEach(([id, listenerObj]) => {
|
||||
if (!type || listenerObj.type === type) {
|
||||
electron_1.ipcRenderer.removeListener(`event-${classKey}-${listenerObj.type}`, listenerObj.listener);
|
||||
electron_1.ipcRenderer.send(`event-remove-${classKey}-${listenerObj.type}`);
|
||||
delete listeners[id];
|
||||
}
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
electron_1.contextBridge.exposeInMainWorld('CapacitorCustomPlatform', {
|
||||
name: 'electron',
|
||||
plugins: contextApi,
|
||||
});
|
||||
////////////////////////////////////////////////////////
|
||||
195
electron/build/src/setup.js
Normal file
195
electron/build/src/setup.js
Normal file
|
|
@ -0,0 +1,195 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ElectronCapacitorApp = void 0;
|
||||
exports.setupReloadWatcher = setupReloadWatcher;
|
||||
exports.setupContentSecurityPolicy = setupContentSecurityPolicy;
|
||||
const tslib_1 = require("tslib");
|
||||
const electron_1 = require("@capacitor-community/electron");
|
||||
const chokidar_1 = tslib_1.__importDefault(require("chokidar"));
|
||||
const electron_2 = require("electron");
|
||||
//import electronIsDev from 'electron-is-dev';
|
||||
var electronIsDev = false;
|
||||
const electron_serve_1 = tslib_1.__importDefault(require("electron-serve"));
|
||||
const electron_window_state_1 = tslib_1.__importDefault(require("electron-window-state"));
|
||||
const path_1 = require("path");
|
||||
// Define components for a watcher to detect when the webapp is changed so we can reload in Dev mode.
|
||||
const reloadWatcher = {
|
||||
debouncer: null,
|
||||
ready: false,
|
||||
watcher: null,
|
||||
};
|
||||
function setupReloadWatcher(electronCapacitorApp) {
|
||||
reloadWatcher.watcher = chokidar_1.default
|
||||
.watch((0, path_1.join)(electron_2.app.getAppPath(), 'app'), {
|
||||
ignored: /[/\\]\./,
|
||||
persistent: true,
|
||||
})
|
||||
.on('ready', () => {
|
||||
reloadWatcher.ready = true;
|
||||
})
|
||||
.on('all', (_event, _path) => {
|
||||
if (reloadWatcher.ready) {
|
||||
clearTimeout(reloadWatcher.debouncer);
|
||||
reloadWatcher.debouncer = setTimeout(async () => {
|
||||
electronCapacitorApp.getMainWindow().webContents.reload();
|
||||
reloadWatcher.ready = false;
|
||||
clearTimeout(reloadWatcher.debouncer);
|
||||
reloadWatcher.debouncer = null;
|
||||
reloadWatcher.watcher = null;
|
||||
setupReloadWatcher(electronCapacitorApp);
|
||||
}, 1500);
|
||||
}
|
||||
});
|
||||
}
|
||||
// Define our class to manage our app.
|
||||
class ElectronCapacitorApp {
|
||||
constructor(capacitorFileConfig, trayMenuTemplate, appMenuBarMenuTemplate) {
|
||||
var _a, _b;
|
||||
this.MainWindow = null;
|
||||
this.SplashScreen = null;
|
||||
this.TrayIcon = null;
|
||||
this.TrayMenuTemplate = [
|
||||
new electron_2.MenuItem({ label: 'Quit App', role: 'quit' }),
|
||||
];
|
||||
this.AppMenuBarMenuTemplate = [
|
||||
{ role: process.platform === 'darwin' ? 'appMenu' : 'fileMenu' },
|
||||
{ role: 'viewMenu' },
|
||||
];
|
||||
this.CapacitorFileConfig = capacitorFileConfig;
|
||||
this.customScheme = (_b = (_a = this.CapacitorFileConfig.electron) === null || _a === void 0 ? void 0 : _a.customUrlScheme) !== null && _b !== void 0 ? _b : 'capacitor-electron';
|
||||
if (trayMenuTemplate) {
|
||||
this.TrayMenuTemplate = trayMenuTemplate;
|
||||
}
|
||||
if (appMenuBarMenuTemplate) {
|
||||
this.AppMenuBarMenuTemplate = appMenuBarMenuTemplate;
|
||||
}
|
||||
// Setup our web app loader, this lets us load apps like react, vue, and angular without changing their build chains.
|
||||
this.loadWebApp = (0, electron_serve_1.default)({
|
||||
directory: (0, path_1.join)(electron_2.app.getAppPath(), 'app'),
|
||||
scheme: this.customScheme,
|
||||
});
|
||||
}
|
||||
// Helper function to load in the app.
|
||||
async loadMainWindow(thisRef) {
|
||||
await thisRef.loadWebApp(thisRef.MainWindow);
|
||||
}
|
||||
// Expose the mainWindow ref for use outside of the class.
|
||||
getMainWindow() {
|
||||
return this.MainWindow;
|
||||
}
|
||||
getCustomURLScheme() {
|
||||
return this.customScheme;
|
||||
}
|
||||
async init() {
|
||||
var _a;
|
||||
const icon = electron_2.nativeImage.createFromPath((0, path_1.join)(electron_2.app.getAppPath(), 'assets', process.platform === 'win32' ? 'icon.ico' : 'icon.png'));
|
||||
const appName = "miarven";
|
||||
electron_2.app.setName(appName);
|
||||
electron_2.app.setAppUserModelId(appName);
|
||||
this.mainWindowState = (0, electron_window_state_1.default)({
|
||||
defaultWidth: 1000,
|
||||
defaultHeight: 800,
|
||||
});
|
||||
// Setup preload script path and construct our main window.
|
||||
const preloadPath = (0, path_1.join)(electron_2.app.getAppPath(), 'build', 'src', 'preload.js');
|
||||
this.MainWindow = new electron_2.BrowserWindow({
|
||||
icon,
|
||||
show: false,
|
||||
x: this.mainWindowState.x,
|
||||
y: this.mainWindowState.y,
|
||||
width: this.mainWindowState.width,
|
||||
height: this.mainWindowState.height,
|
||||
autoHideMenuBar: true,
|
||||
webPreferences: {
|
||||
nodeIntegration: true,
|
||||
contextIsolation: true,
|
||||
// Use preload to inject the electron varriant overrides for capacitor plugins.
|
||||
// preload: join(app.getAppPath(), "node_modules", "@capacitor-community", "electron", "dist", "runtime", "electron-rt.js"),
|
||||
preload: preloadPath,
|
||||
},
|
||||
});
|
||||
this.mainWindowState.manage(this.MainWindow);
|
||||
if (this.CapacitorFileConfig.backgroundColor) {
|
||||
this.MainWindow.setBackgroundColor(this.CapacitorFileConfig.electron.backgroundColor);
|
||||
}
|
||||
// If we close the main window with the splashscreen enabled we need to destory the ref.
|
||||
this.MainWindow.on('closed', () => {
|
||||
var _a;
|
||||
if (((_a = this.SplashScreen) === null || _a === void 0 ? void 0 : _a.getSplashWindow()) && !this.SplashScreen.getSplashWindow().isDestroyed()) {
|
||||
this.SplashScreen.getSplashWindow().close();
|
||||
}
|
||||
});
|
||||
// When the tray icon is enabled, setup the options.
|
||||
if ((_a = this.CapacitorFileConfig.electron) === null || _a === void 0 ? void 0 : _a.trayIconAndMenuEnabled) {
|
||||
this.TrayIcon = new electron_2.Tray(icon);
|
||||
this.TrayIcon.on('double-click', () => {
|
||||
if (this.MainWindow) {
|
||||
if (this.MainWindow.isVisible()) {
|
||||
this.MainWindow.hide();
|
||||
}
|
||||
else {
|
||||
this.MainWindow.show();
|
||||
this.MainWindow.focus();
|
||||
}
|
||||
}
|
||||
});
|
||||
this.TrayIcon.on('click', () => {
|
||||
if (this.MainWindow) {
|
||||
if (this.MainWindow.isVisible()) {
|
||||
this.MainWindow.hide();
|
||||
}
|
||||
else {
|
||||
this.MainWindow.show();
|
||||
this.MainWindow.focus();
|
||||
}
|
||||
}
|
||||
});
|
||||
this.TrayIcon.setToolTip(electron_2.app.getName());
|
||||
this.TrayIcon.setContextMenu(electron_2.Menu.buildFromTemplate(this.TrayMenuTemplate));
|
||||
}
|
||||
// Setup the main manu bar at the top of our window.
|
||||
//Menu.setApplicationMenu(Menu.buildFromTemplate(this.AppMenuBarMenuTemplate));
|
||||
electron_2.Menu.setApplicationMenu(null);
|
||||
this.loadMainWindow(this);
|
||||
// Security
|
||||
this.MainWindow.webContents.setWindowOpenHandler((details) => {
|
||||
return { action: 'allow' };
|
||||
});
|
||||
this.MainWindow.webContents.on('will-navigate', (event, _newURL) => {
|
||||
if (!this.MainWindow.webContents.getURL().includes(this.customScheme)) {
|
||||
event.preventDefault();
|
||||
}
|
||||
});
|
||||
// Link electron plugins into the system.
|
||||
(0, electron_1.setupCapacitorElectronPlugins)();
|
||||
// When the web app is loaded we hide the splashscreen if needed and show the mainwindow.
|
||||
this.MainWindow.webContents.on('dom-ready', () => {
|
||||
var _a, _b;
|
||||
if ((_a = this.CapacitorFileConfig.electron) === null || _a === void 0 ? void 0 : _a.splashScreenEnabled) {
|
||||
this.SplashScreen.getSplashWindow().hide();
|
||||
}
|
||||
if (!((_b = this.CapacitorFileConfig.electron) === null || _b === void 0 ? void 0 : _b.hideMainWindowOnLaunch)) {
|
||||
this.MainWindow.show();
|
||||
}
|
||||
setTimeout(() => {
|
||||
electron_1.CapElectronEventEmitter.emit('CAPELECTRON_DeeplinkListenerInitialized', '');
|
||||
}, 400);
|
||||
});
|
||||
this.MainWindow.setMenu(null);
|
||||
this.MainWindow.setAutoHideMenuBar(true);
|
||||
this.MainWindow.removeMenu();
|
||||
}
|
||||
}
|
||||
exports.ElectronCapacitorApp = ElectronCapacitorApp;
|
||||
// Set a CSP up for our application based on the custom scheme
|
||||
function setupContentSecurityPolicy(customScheme) {
|
||||
electron_2.session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
|
||||
callback({
|
||||
responseHeaders: Object.assign(Object.assign({}, details.responseHeaders), { 'Content-Security-Policy': [
|
||||
electronIsDev
|
||||
? `default-src ${customScheme}://* 'unsafe-inline' devtools://* 'unsafe-eval' data:`
|
||||
: `default-src ${customScheme}://* 'unsafe-inline' data:`,
|
||||
] }),
|
||||
});
|
||||
});
|
||||
}
|
||||
2
electron/node_modules/boolean/build/lib/boolean.d.ts
generated
vendored
Normal file
2
electron/node_modules/boolean/build/lib/boolean.d.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
declare const boolean: (value: any) => boolean;
|
||||
export { boolean };
|
||||
16
electron/node_modules/boolean/build/lib/boolean.js
generated
vendored
Normal file
16
electron/node_modules/boolean/build/lib/boolean.js
generated
vendored
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.boolean = void 0;
|
||||
const boolean = function (value) {
|
||||
switch (Object.prototype.toString.call(value)) {
|
||||
case '[object String]':
|
||||
return ['true', 't', 'yes', 'y', 'on', '1'].includes(value.trim().toLowerCase());
|
||||
case '[object Number]':
|
||||
return value.valueOf() === 1;
|
||||
case '[object Boolean]':
|
||||
return value.valueOf();
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
};
|
||||
exports.boolean = boolean;
|
||||
3
electron/node_modules/boolean/build/lib/index.d.ts
generated
vendored
Normal file
3
electron/node_modules/boolean/build/lib/index.d.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
import { boolean } from './boolean';
|
||||
import { isBooleanable } from './isBooleanable';
|
||||
export { boolean, isBooleanable };
|
||||
7
electron/node_modules/boolean/build/lib/index.js
generated
vendored
Normal file
7
electron/node_modules/boolean/build/lib/index.js
generated
vendored
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.isBooleanable = exports.boolean = void 0;
|
||||
const boolean_1 = require("./boolean");
|
||||
Object.defineProperty(exports, "boolean", { enumerable: true, get: function () { return boolean_1.boolean; } });
|
||||
const isBooleanable_1 = require("./isBooleanable");
|
||||
Object.defineProperty(exports, "isBooleanable", { enumerable: true, get: function () { return isBooleanable_1.isBooleanable; } });
|
||||
2
electron/node_modules/boolean/build/lib/isBooleanable.d.ts
generated
vendored
Normal file
2
electron/node_modules/boolean/build/lib/isBooleanable.d.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
declare const isBooleanable: (value: any) => boolean;
|
||||
export { isBooleanable };
|
||||
19
electron/node_modules/boolean/build/lib/isBooleanable.js
generated
vendored
Normal file
19
electron/node_modules/boolean/build/lib/isBooleanable.js
generated
vendored
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.isBooleanable = void 0;
|
||||
const isBooleanable = function (value) {
|
||||
switch (Object.prototype.toString.call(value)) {
|
||||
case '[object String]':
|
||||
return [
|
||||
'true', 't', 'yes', 'y', 'on', '1',
|
||||
'false', 'f', 'no', 'n', 'off', '0'
|
||||
].includes(value.trim().toLowerCase());
|
||||
case '[object Number]':
|
||||
return [0, 1].includes(value.valueOf());
|
||||
case '[object Boolean]':
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
};
|
||||
exports.isBooleanable = isBooleanable;
|
||||
302
electron/node_modules/cliui/build/index.cjs
generated
vendored
Normal file
302
electron/node_modules/cliui/build/index.cjs
generated
vendored
Normal file
|
|
@ -0,0 +1,302 @@
|
|||
'use strict';
|
||||
|
||||
const align = {
|
||||
right: alignRight,
|
||||
center: alignCenter
|
||||
};
|
||||
const top = 0;
|
||||
const right = 1;
|
||||
const bottom = 2;
|
||||
const left = 3;
|
||||
class UI {
|
||||
constructor(opts) {
|
||||
var _a;
|
||||
this.width = opts.width;
|
||||
this.wrap = (_a = opts.wrap) !== null && _a !== void 0 ? _a : true;
|
||||
this.rows = [];
|
||||
}
|
||||
span(...args) {
|
||||
const cols = this.div(...args);
|
||||
cols.span = true;
|
||||
}
|
||||
resetOutput() {
|
||||
this.rows = [];
|
||||
}
|
||||
div(...args) {
|
||||
if (args.length === 0) {
|
||||
this.div('');
|
||||
}
|
||||
if (this.wrap && this.shouldApplyLayoutDSL(...args) && typeof args[0] === 'string') {
|
||||
return this.applyLayoutDSL(args[0]);
|
||||
}
|
||||
const cols = args.map(arg => {
|
||||
if (typeof arg === 'string') {
|
||||
return this.colFromString(arg);
|
||||
}
|
||||
return arg;
|
||||
});
|
||||
this.rows.push(cols);
|
||||
return cols;
|
||||
}
|
||||
shouldApplyLayoutDSL(...args) {
|
||||
return args.length === 1 && typeof args[0] === 'string' &&
|
||||
/[\t\n]/.test(args[0]);
|
||||
}
|
||||
applyLayoutDSL(str) {
|
||||
const rows = str.split('\n').map(row => row.split('\t'));
|
||||
let leftColumnWidth = 0;
|
||||
// simple heuristic for layout, make sure the
|
||||
// second column lines up along the left-hand.
|
||||
// don't allow the first column to take up more
|
||||
// than 50% of the screen.
|
||||
rows.forEach(columns => {
|
||||
if (columns.length > 1 && mixin.stringWidth(columns[0]) > leftColumnWidth) {
|
||||
leftColumnWidth = Math.min(Math.floor(this.width * 0.5), mixin.stringWidth(columns[0]));
|
||||
}
|
||||
});
|
||||
// generate a table:
|
||||
// replacing ' ' with padding calculations.
|
||||
// using the algorithmically generated width.
|
||||
rows.forEach(columns => {
|
||||
this.div(...columns.map((r, i) => {
|
||||
return {
|
||||
text: r.trim(),
|
||||
padding: this.measurePadding(r),
|
||||
width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined
|
||||
};
|
||||
}));
|
||||
});
|
||||
return this.rows[this.rows.length - 1];
|
||||
}
|
||||
colFromString(text) {
|
||||
return {
|
||||
text,
|
||||
padding: this.measurePadding(text)
|
||||
};
|
||||
}
|
||||
measurePadding(str) {
|
||||
// measure padding without ansi escape codes
|
||||
const noAnsi = mixin.stripAnsi(str);
|
||||
return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length];
|
||||
}
|
||||
toString() {
|
||||
const lines = [];
|
||||
this.rows.forEach(row => {
|
||||
this.rowToString(row, lines);
|
||||
});
|
||||
// don't display any lines with the
|
||||
// hidden flag set.
|
||||
return lines
|
||||
.filter(line => !line.hidden)
|
||||
.map(line => line.text)
|
||||
.join('\n');
|
||||
}
|
||||
rowToString(row, lines) {
|
||||
this.rasterize(row).forEach((rrow, r) => {
|
||||
let str = '';
|
||||
rrow.forEach((col, c) => {
|
||||
const { width } = row[c]; // the width with padding.
|
||||
const wrapWidth = this.negatePadding(row[c]); // the width without padding.
|
||||
let ts = col; // temporary string used during alignment/padding.
|
||||
if (wrapWidth > mixin.stringWidth(col)) {
|
||||
ts += ' '.repeat(wrapWidth - mixin.stringWidth(col));
|
||||
}
|
||||
// align the string within its column.
|
||||
if (row[c].align && row[c].align !== 'left' && this.wrap) {
|
||||
const fn = align[row[c].align];
|
||||
ts = fn(ts, wrapWidth);
|
||||
if (mixin.stringWidth(ts) < wrapWidth) {
|
||||
ts += ' '.repeat((width || 0) - mixin.stringWidth(ts) - 1);
|
||||
}
|
||||
}
|
||||
// apply border and padding to string.
|
||||
const padding = row[c].padding || [0, 0, 0, 0];
|
||||
if (padding[left]) {
|
||||
str += ' '.repeat(padding[left]);
|
||||
}
|
||||
str += addBorder(row[c], ts, '| ');
|
||||
str += ts;
|
||||
str += addBorder(row[c], ts, ' |');
|
||||
if (padding[right]) {
|
||||
str += ' '.repeat(padding[right]);
|
||||
}
|
||||
// if prior row is span, try to render the
|
||||
// current row on the prior line.
|
||||
if (r === 0 && lines.length > 0) {
|
||||
str = this.renderInline(str, lines[lines.length - 1]);
|
||||
}
|
||||
});
|
||||
// remove trailing whitespace.
|
||||
lines.push({
|
||||
text: str.replace(/ +$/, ''),
|
||||
span: row.span
|
||||
});
|
||||
});
|
||||
return lines;
|
||||
}
|
||||
// if the full 'source' can render in
|
||||
// the target line, do so.
|
||||
renderInline(source, previousLine) {
|
||||
const match = source.match(/^ */);
|
||||
const leadingWhitespace = match ? match[0].length : 0;
|
||||
const target = previousLine.text;
|
||||
const targetTextWidth = mixin.stringWidth(target.trimRight());
|
||||
if (!previousLine.span) {
|
||||
return source;
|
||||
}
|
||||
// if we're not applying wrapping logic,
|
||||
// just always append to the span.
|
||||
if (!this.wrap) {
|
||||
previousLine.hidden = true;
|
||||
return target + source;
|
||||
}
|
||||
if (leadingWhitespace < targetTextWidth) {
|
||||
return source;
|
||||
}
|
||||
previousLine.hidden = true;
|
||||
return target.trimRight() + ' '.repeat(leadingWhitespace - targetTextWidth) + source.trimLeft();
|
||||
}
|
||||
rasterize(row) {
|
||||
const rrows = [];
|
||||
const widths = this.columnWidths(row);
|
||||
let wrapped;
|
||||
// word wrap all columns, and create
|
||||
// a data-structure that is easy to rasterize.
|
||||
row.forEach((col, c) => {
|
||||
// leave room for left and right padding.
|
||||
col.width = widths[c];
|
||||
if (this.wrap) {
|
||||
wrapped = mixin.wrap(col.text, this.negatePadding(col), { hard: true }).split('\n');
|
||||
}
|
||||
else {
|
||||
wrapped = col.text.split('\n');
|
||||
}
|
||||
if (col.border) {
|
||||
wrapped.unshift('.' + '-'.repeat(this.negatePadding(col) + 2) + '.');
|
||||
wrapped.push("'" + '-'.repeat(this.negatePadding(col) + 2) + "'");
|
||||
}
|
||||
// add top and bottom padding.
|
||||
if (col.padding) {
|
||||
wrapped.unshift(...new Array(col.padding[top] || 0).fill(''));
|
||||
wrapped.push(...new Array(col.padding[bottom] || 0).fill(''));
|
||||
}
|
||||
wrapped.forEach((str, r) => {
|
||||
if (!rrows[r]) {
|
||||
rrows.push([]);
|
||||
}
|
||||
const rrow = rrows[r];
|
||||
for (let i = 0; i < c; i++) {
|
||||
if (rrow[i] === undefined) {
|
||||
rrow.push('');
|
||||
}
|
||||
}
|
||||
rrow.push(str);
|
||||
});
|
||||
});
|
||||
return rrows;
|
||||
}
|
||||
negatePadding(col) {
|
||||
let wrapWidth = col.width || 0;
|
||||
if (col.padding) {
|
||||
wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0);
|
||||
}
|
||||
if (col.border) {
|
||||
wrapWidth -= 4;
|
||||
}
|
||||
return wrapWidth;
|
||||
}
|
||||
columnWidths(row) {
|
||||
if (!this.wrap) {
|
||||
return row.map(col => {
|
||||
return col.width || mixin.stringWidth(col.text);
|
||||
});
|
||||
}
|
||||
let unset = row.length;
|
||||
let remainingWidth = this.width;
|
||||
// column widths can be set in config.
|
||||
const widths = row.map(col => {
|
||||
if (col.width) {
|
||||
unset--;
|
||||
remainingWidth -= col.width;
|
||||
return col.width;
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
// any unset widths should be calculated.
|
||||
const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0;
|
||||
return widths.map((w, i) => {
|
||||
if (w === undefined) {
|
||||
return Math.max(unsetWidth, _minWidth(row[i]));
|
||||
}
|
||||
return w;
|
||||
});
|
||||
}
|
||||
}
|
||||
function addBorder(col, ts, style) {
|
||||
if (col.border) {
|
||||
if (/[.']-+[.']/.test(ts)) {
|
||||
return '';
|
||||
}
|
||||
if (ts.trim().length !== 0) {
|
||||
return style;
|
||||
}
|
||||
return ' ';
|
||||
}
|
||||
return '';
|
||||
}
|
||||
// calculates the minimum width of
|
||||
// a column, based on padding preferences.
|
||||
function _minWidth(col) {
|
||||
const padding = col.padding || [];
|
||||
const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0);
|
||||
if (col.border) {
|
||||
return minWidth + 4;
|
||||
}
|
||||
return minWidth;
|
||||
}
|
||||
function getWindowWidth() {
|
||||
/* istanbul ignore next: depends on terminal */
|
||||
if (typeof process === 'object' && process.stdout && process.stdout.columns) {
|
||||
return process.stdout.columns;
|
||||
}
|
||||
return 80;
|
||||
}
|
||||
function alignRight(str, width) {
|
||||
str = str.trim();
|
||||
const strWidth = mixin.stringWidth(str);
|
||||
if (strWidth < width) {
|
||||
return ' '.repeat(width - strWidth) + str;
|
||||
}
|
||||
return str;
|
||||
}
|
||||
function alignCenter(str, width) {
|
||||
str = str.trim();
|
||||
const strWidth = mixin.stringWidth(str);
|
||||
/* istanbul ignore next */
|
||||
if (strWidth >= width) {
|
||||
return str;
|
||||
}
|
||||
return ' '.repeat((width - strWidth) >> 1) + str;
|
||||
}
|
||||
let mixin;
|
||||
function cliui(opts, _mixin) {
|
||||
mixin = _mixin;
|
||||
return new UI({
|
||||
width: (opts === null || opts === void 0 ? void 0 : opts.width) || getWindowWidth(),
|
||||
wrap: opts === null || opts === void 0 ? void 0 : opts.wrap
|
||||
});
|
||||
}
|
||||
|
||||
// Bootstrap cliui with CommonJS dependencies:
|
||||
const stringWidth = require('string-width');
|
||||
const stripAnsi = require('strip-ansi');
|
||||
const wrap = require('wrap-ansi');
|
||||
function ui(opts) {
|
||||
return cliui(opts, {
|
||||
stringWidth,
|
||||
stripAnsi,
|
||||
wrap
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = ui;
|
||||
43
electron/node_modules/cliui/build/index.d.cts
generated
vendored
Normal file
43
electron/node_modules/cliui/build/index.d.cts
generated
vendored
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
interface UIOptions {
|
||||
width: number;
|
||||
wrap?: boolean;
|
||||
rows?: string[];
|
||||
}
|
||||
interface Column {
|
||||
text: string;
|
||||
width?: number;
|
||||
align?: "right" | "left" | "center";
|
||||
padding: number[];
|
||||
border?: boolean;
|
||||
}
|
||||
interface ColumnArray extends Array<Column> {
|
||||
span: boolean;
|
||||
}
|
||||
interface Line {
|
||||
hidden?: boolean;
|
||||
text: string;
|
||||
span?: boolean;
|
||||
}
|
||||
declare class UI {
|
||||
width: number;
|
||||
wrap: boolean;
|
||||
rows: ColumnArray[];
|
||||
constructor(opts: UIOptions);
|
||||
span(...args: ColumnArray): void;
|
||||
resetOutput(): void;
|
||||
div(...args: (Column | string)[]): ColumnArray;
|
||||
private shouldApplyLayoutDSL;
|
||||
private applyLayoutDSL;
|
||||
private colFromString;
|
||||
private measurePadding;
|
||||
toString(): string;
|
||||
rowToString(row: ColumnArray, lines: Line[]): Line[];
|
||||
// if the full 'source' can render in
|
||||
// the target line, do so.
|
||||
private renderInline;
|
||||
private rasterize;
|
||||
private negatePadding;
|
||||
private columnWidths;
|
||||
}
|
||||
declare function ui(opts: UIOptions): UI;
|
||||
export { ui as default };
|
||||
287
electron/node_modules/cliui/build/lib/index.js
generated
vendored
Normal file
287
electron/node_modules/cliui/build/lib/index.js
generated
vendored
Normal file
|
|
@ -0,0 +1,287 @@
|
|||
'use strict';
|
||||
const align = {
|
||||
right: alignRight,
|
||||
center: alignCenter
|
||||
};
|
||||
const top = 0;
|
||||
const right = 1;
|
||||
const bottom = 2;
|
||||
const left = 3;
|
||||
export class UI {
|
||||
constructor(opts) {
|
||||
var _a;
|
||||
this.width = opts.width;
|
||||
this.wrap = (_a = opts.wrap) !== null && _a !== void 0 ? _a : true;
|
||||
this.rows = [];
|
||||
}
|
||||
span(...args) {
|
||||
const cols = this.div(...args);
|
||||
cols.span = true;
|
||||
}
|
||||
resetOutput() {
|
||||
this.rows = [];
|
||||
}
|
||||
div(...args) {
|
||||
if (args.length === 0) {
|
||||
this.div('');
|
||||
}
|
||||
if (this.wrap && this.shouldApplyLayoutDSL(...args) && typeof args[0] === 'string') {
|
||||
return this.applyLayoutDSL(args[0]);
|
||||
}
|
||||
const cols = args.map(arg => {
|
||||
if (typeof arg === 'string') {
|
||||
return this.colFromString(arg);
|
||||
}
|
||||
return arg;
|
||||
});
|
||||
this.rows.push(cols);
|
||||
return cols;
|
||||
}
|
||||
shouldApplyLayoutDSL(...args) {
|
||||
return args.length === 1 && typeof args[0] === 'string' &&
|
||||
/[\t\n]/.test(args[0]);
|
||||
}
|
||||
applyLayoutDSL(str) {
|
||||
const rows = str.split('\n').map(row => row.split('\t'));
|
||||
let leftColumnWidth = 0;
|
||||
// simple heuristic for layout, make sure the
|
||||
// second column lines up along the left-hand.
|
||||
// don't allow the first column to take up more
|
||||
// than 50% of the screen.
|
||||
rows.forEach(columns => {
|
||||
if (columns.length > 1 && mixin.stringWidth(columns[0]) > leftColumnWidth) {
|
||||
leftColumnWidth = Math.min(Math.floor(this.width * 0.5), mixin.stringWidth(columns[0]));
|
||||
}
|
||||
});
|
||||
// generate a table:
|
||||
// replacing ' ' with padding calculations.
|
||||
// using the algorithmically generated width.
|
||||
rows.forEach(columns => {
|
||||
this.div(...columns.map((r, i) => {
|
||||
return {
|
||||
text: r.trim(),
|
||||
padding: this.measurePadding(r),
|
||||
width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined
|
||||
};
|
||||
}));
|
||||
});
|
||||
return this.rows[this.rows.length - 1];
|
||||
}
|
||||
colFromString(text) {
|
||||
return {
|
||||
text,
|
||||
padding: this.measurePadding(text)
|
||||
};
|
||||
}
|
||||
measurePadding(str) {
|
||||
// measure padding without ansi escape codes
|
||||
const noAnsi = mixin.stripAnsi(str);
|
||||
return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length];
|
||||
}
|
||||
toString() {
|
||||
const lines = [];
|
||||
this.rows.forEach(row => {
|
||||
this.rowToString(row, lines);
|
||||
});
|
||||
// don't display any lines with the
|
||||
// hidden flag set.
|
||||
return lines
|
||||
.filter(line => !line.hidden)
|
||||
.map(line => line.text)
|
||||
.join('\n');
|
||||
}
|
||||
rowToString(row, lines) {
|
||||
this.rasterize(row).forEach((rrow, r) => {
|
||||
let str = '';
|
||||
rrow.forEach((col, c) => {
|
||||
const { width } = row[c]; // the width with padding.
|
||||
const wrapWidth = this.negatePadding(row[c]); // the width without padding.
|
||||
let ts = col; // temporary string used during alignment/padding.
|
||||
if (wrapWidth > mixin.stringWidth(col)) {
|
||||
ts += ' '.repeat(wrapWidth - mixin.stringWidth(col));
|
||||
}
|
||||
// align the string within its column.
|
||||
if (row[c].align && row[c].align !== 'left' && this.wrap) {
|
||||
const fn = align[row[c].align];
|
||||
ts = fn(ts, wrapWidth);
|
||||
if (mixin.stringWidth(ts) < wrapWidth) {
|
||||
ts += ' '.repeat((width || 0) - mixin.stringWidth(ts) - 1);
|
||||
}
|
||||
}
|
||||
// apply border and padding to string.
|
||||
const padding = row[c].padding || [0, 0, 0, 0];
|
||||
if (padding[left]) {
|
||||
str += ' '.repeat(padding[left]);
|
||||
}
|
||||
str += addBorder(row[c], ts, '| ');
|
||||
str += ts;
|
||||
str += addBorder(row[c], ts, ' |');
|
||||
if (padding[right]) {
|
||||
str += ' '.repeat(padding[right]);
|
||||
}
|
||||
// if prior row is span, try to render the
|
||||
// current row on the prior line.
|
||||
if (r === 0 && lines.length > 0) {
|
||||
str = this.renderInline(str, lines[lines.length - 1]);
|
||||
}
|
||||
});
|
||||
// remove trailing whitespace.
|
||||
lines.push({
|
||||
text: str.replace(/ +$/, ''),
|
||||
span: row.span
|
||||
});
|
||||
});
|
||||
return lines;
|
||||
}
|
||||
// if the full 'source' can render in
|
||||
// the target line, do so.
|
||||
renderInline(source, previousLine) {
|
||||
const match = source.match(/^ */);
|
||||
const leadingWhitespace = match ? match[0].length : 0;
|
||||
const target = previousLine.text;
|
||||
const targetTextWidth = mixin.stringWidth(target.trimRight());
|
||||
if (!previousLine.span) {
|
||||
return source;
|
||||
}
|
||||
// if we're not applying wrapping logic,
|
||||
// just always append to the span.
|
||||
if (!this.wrap) {
|
||||
previousLine.hidden = true;
|
||||
return target + source;
|
||||
}
|
||||
if (leadingWhitespace < targetTextWidth) {
|
||||
return source;
|
||||
}
|
||||
previousLine.hidden = true;
|
||||
return target.trimRight() + ' '.repeat(leadingWhitespace - targetTextWidth) + source.trimLeft();
|
||||
}
|
||||
rasterize(row) {
|
||||
const rrows = [];
|
||||
const widths = this.columnWidths(row);
|
||||
let wrapped;
|
||||
// word wrap all columns, and create
|
||||
// a data-structure that is easy to rasterize.
|
||||
row.forEach((col, c) => {
|
||||
// leave room for left and right padding.
|
||||
col.width = widths[c];
|
||||
if (this.wrap) {
|
||||
wrapped = mixin.wrap(col.text, this.negatePadding(col), { hard: true }).split('\n');
|
||||
}
|
||||
else {
|
||||
wrapped = col.text.split('\n');
|
||||
}
|
||||
if (col.border) {
|
||||
wrapped.unshift('.' + '-'.repeat(this.negatePadding(col) + 2) + '.');
|
||||
wrapped.push("'" + '-'.repeat(this.negatePadding(col) + 2) + "'");
|
||||
}
|
||||
// add top and bottom padding.
|
||||
if (col.padding) {
|
||||
wrapped.unshift(...new Array(col.padding[top] || 0).fill(''));
|
||||
wrapped.push(...new Array(col.padding[bottom] || 0).fill(''));
|
||||
}
|
||||
wrapped.forEach((str, r) => {
|
||||
if (!rrows[r]) {
|
||||
rrows.push([]);
|
||||
}
|
||||
const rrow = rrows[r];
|
||||
for (let i = 0; i < c; i++) {
|
||||
if (rrow[i] === undefined) {
|
||||
rrow.push('');
|
||||
}
|
||||
}
|
||||
rrow.push(str);
|
||||
});
|
||||
});
|
||||
return rrows;
|
||||
}
|
||||
negatePadding(col) {
|
||||
let wrapWidth = col.width || 0;
|
||||
if (col.padding) {
|
||||
wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0);
|
||||
}
|
||||
if (col.border) {
|
||||
wrapWidth -= 4;
|
||||
}
|
||||
return wrapWidth;
|
||||
}
|
||||
columnWidths(row) {
|
||||
if (!this.wrap) {
|
||||
return row.map(col => {
|
||||
return col.width || mixin.stringWidth(col.text);
|
||||
});
|
||||
}
|
||||
let unset = row.length;
|
||||
let remainingWidth = this.width;
|
||||
// column widths can be set in config.
|
||||
const widths = row.map(col => {
|
||||
if (col.width) {
|
||||
unset--;
|
||||
remainingWidth -= col.width;
|
||||
return col.width;
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
// any unset widths should be calculated.
|
||||
const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0;
|
||||
return widths.map((w, i) => {
|
||||
if (w === undefined) {
|
||||
return Math.max(unsetWidth, _minWidth(row[i]));
|
||||
}
|
||||
return w;
|
||||
});
|
||||
}
|
||||
}
|
||||
function addBorder(col, ts, style) {
|
||||
if (col.border) {
|
||||
if (/[.']-+[.']/.test(ts)) {
|
||||
return '';
|
||||
}
|
||||
if (ts.trim().length !== 0) {
|
||||
return style;
|
||||
}
|
||||
return ' ';
|
||||
}
|
||||
return '';
|
||||
}
|
||||
// calculates the minimum width of
|
||||
// a column, based on padding preferences.
|
||||
function _minWidth(col) {
|
||||
const padding = col.padding || [];
|
||||
const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0);
|
||||
if (col.border) {
|
||||
return minWidth + 4;
|
||||
}
|
||||
return minWidth;
|
||||
}
|
||||
function getWindowWidth() {
|
||||
/* istanbul ignore next: depends on terminal */
|
||||
if (typeof process === 'object' && process.stdout && process.stdout.columns) {
|
||||
return process.stdout.columns;
|
||||
}
|
||||
return 80;
|
||||
}
|
||||
function alignRight(str, width) {
|
||||
str = str.trim();
|
||||
const strWidth = mixin.stringWidth(str);
|
||||
if (strWidth < width) {
|
||||
return ' '.repeat(width - strWidth) + str;
|
||||
}
|
||||
return str;
|
||||
}
|
||||
function alignCenter(str, width) {
|
||||
str = str.trim();
|
||||
const strWidth = mixin.stringWidth(str);
|
||||
/* istanbul ignore next */
|
||||
if (strWidth >= width) {
|
||||
return str;
|
||||
}
|
||||
return ' '.repeat((width - strWidth) >> 1) + str;
|
||||
}
|
||||
let mixin;
|
||||
export function cliui(opts, _mixin) {
|
||||
mixin = _mixin;
|
||||
return new UI({
|
||||
width: (opts === null || opts === void 0 ? void 0 : opts.width) || getWindowWidth(),
|
||||
wrap: opts === null || opts === void 0 ? void 0 : opts.wrap
|
||||
});
|
||||
}
|
||||
27
electron/node_modules/cliui/build/lib/string-utils.js
generated
vendored
Normal file
27
electron/node_modules/cliui/build/lib/string-utils.js
generated
vendored
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
// Minimal replacement for ansi string helpers "wrap-ansi" and "strip-ansi".
|
||||
// to facilitate ESM and Deno modules.
|
||||
// TODO: look at porting https://www.npmjs.com/package/wrap-ansi to ESM.
|
||||
// The npm application
|
||||
// Copyright (c) npm, Inc. and Contributors
|
||||
// Licensed on the terms of The Artistic License 2.0
|
||||
// See: https://github.com/npm/cli/blob/4c65cd952bc8627811735bea76b9b110cc4fc80e/lib/utils/ansi-trim.js
|
||||
const ansi = new RegExp('\x1b(?:\\[(?:\\d+[ABCDEFGJKSTm]|\\d+;\\d+[Hfm]|' +
|
||||
'\\d+;\\d+;\\d+m|6n|s|u|\\?25[lh])|\\w)', 'g');
|
||||
export function stripAnsi(str) {
|
||||
return str.replace(ansi, '');
|
||||
}
|
||||
export function wrap(str, width) {
|
||||
const [start, end] = str.match(ansi) || ['', ''];
|
||||
str = stripAnsi(str);
|
||||
let wrapped = '';
|
||||
for (let i = 0; i < str.length; i++) {
|
||||
if (i !== 0 && (i % width) === 0) {
|
||||
wrapped += '\n';
|
||||
}
|
||||
wrapped += str.charAt(i);
|
||||
}
|
||||
if (start && end) {
|
||||
wrapped = `${start}${wrapped}${end}`;
|
||||
}
|
||||
return wrapped;
|
||||
}
|
||||
13
electron/node_modules/simple-update-notifier/build/index.d.ts
generated
vendored
Normal file
13
electron/node_modules/simple-update-notifier/build/index.d.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
interface IUpdate {
|
||||
pkg: {
|
||||
name: string;
|
||||
version: string;
|
||||
};
|
||||
updateCheckInterval?: number;
|
||||
shouldNotifyInNpmScript?: boolean;
|
||||
distTag?: string;
|
||||
alwaysRun?: boolean;
|
||||
debug?: boolean;
|
||||
}
|
||||
declare const simpleUpdateNotifier: (args: IUpdate) => Promise<void>;
|
||||
export { simpleUpdateNotifier as default };
|
||||
217
electron/node_modules/simple-update-notifier/build/index.js
generated
vendored
Normal file
217
electron/node_modules/simple-update-notifier/build/index.js
generated
vendored
Normal file
|
|
@ -0,0 +1,217 @@
|
|||
'use strict';
|
||||
|
||||
var process$1 = require('process');
|
||||
var semver = require('semver');
|
||||
var os = require('os');
|
||||
var path = require('path');
|
||||
var fs = require('fs');
|
||||
var https = require('https');
|
||||
|
||||
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
|
||||
|
||||
var process__default = /*#__PURE__*/_interopDefaultLegacy(process$1);
|
||||
var semver__default = /*#__PURE__*/_interopDefaultLegacy(semver);
|
||||
var os__default = /*#__PURE__*/_interopDefaultLegacy(os);
|
||||
var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
|
||||
var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
|
||||
var https__default = /*#__PURE__*/_interopDefaultLegacy(https);
|
||||
|
||||
/******************************************************************************
|
||||
Copyright (c) Microsoft Corporation.
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||
PERFORMANCE OF THIS SOFTWARE.
|
||||
***************************************************************************** */
|
||||
|
||||
function __awaiter(thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
}
|
||||
|
||||
function __generator(thisArg, body) {
|
||||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
|
||||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
|
||||
function verb(n) { return function (v) { return step([n, v]); }; }
|
||||
function step(op) {
|
||||
if (f) throw new TypeError("Generator is already executing.");
|
||||
while (_) try {
|
||||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
|
||||
if (y = 0, t) op = [op[0] & 2, t.value];
|
||||
switch (op[0]) {
|
||||
case 0: case 1: t = op; break;
|
||||
case 4: _.label++; return { value: op[1], done: false };
|
||||
case 5: _.label++; y = op[1]; op = [0]; continue;
|
||||
case 7: op = _.ops.pop(); _.trys.pop(); continue;
|
||||
default:
|
||||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
|
||||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
|
||||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
|
||||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
|
||||
if (t[2]) _.ops.pop();
|
||||
_.trys.pop(); continue;
|
||||
}
|
||||
op = body.call(thisArg, _);
|
||||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
|
||||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
|
||||
}
|
||||
}
|
||||
|
||||
var packageJson = process__default["default"].env.npm_package_json;
|
||||
var userAgent = process__default["default"].env.npm_config_user_agent;
|
||||
var isNpm6 = Boolean(userAgent && userAgent.startsWith('npm'));
|
||||
var isNpm7 = Boolean(packageJson && packageJson.endsWith('package.json'));
|
||||
var isNpm = isNpm6 || isNpm7;
|
||||
var isYarn = Boolean(userAgent && userAgent.startsWith('yarn'));
|
||||
var isNpmOrYarn = isNpm || isYarn;
|
||||
|
||||
var homeDirectory = os__default["default"].homedir();
|
||||
var configDir = process.env.XDG_CONFIG_HOME ||
|
||||
path__default["default"].join(homeDirectory, '.config', 'simple-update-notifier');
|
||||
var getConfigFile = function (packageName) {
|
||||
return path__default["default"].join(configDir, "".concat(packageName.replace('@', '').replace('/', '__'), ".json"));
|
||||
};
|
||||
var createConfigDir = function () {
|
||||
if (!fs__default["default"].existsSync(configDir)) {
|
||||
fs__default["default"].mkdirSync(configDir, { recursive: true });
|
||||
}
|
||||
};
|
||||
var getLastUpdate = function (packageName) {
|
||||
var configFile = getConfigFile(packageName);
|
||||
try {
|
||||
if (!fs__default["default"].existsSync(configFile)) {
|
||||
return undefined;
|
||||
}
|
||||
var file = JSON.parse(fs__default["default"].readFileSync(configFile, 'utf8'));
|
||||
return file.lastUpdateCheck;
|
||||
}
|
||||
catch (_a) {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
var saveLastUpdate = function (packageName) {
|
||||
var configFile = getConfigFile(packageName);
|
||||
fs__default["default"].writeFileSync(configFile, JSON.stringify({ lastUpdateCheck: new Date().getTime() }));
|
||||
};
|
||||
|
||||
var getDistVersion = function (packageName, distTag) { return __awaiter(void 0, void 0, void 0, function () {
|
||||
var url;
|
||||
return __generator(this, function (_a) {
|
||||
url = "https://registry.npmjs.org/-/package/".concat(packageName, "/dist-tags");
|
||||
return [2 /*return*/, new Promise(function (resolve, reject) {
|
||||
https__default["default"]
|
||||
.get(url, function (res) {
|
||||
var body = '';
|
||||
res.on('data', function (chunk) { return (body += chunk); });
|
||||
res.on('end', function () {
|
||||
try {
|
||||
var json = JSON.parse(body);
|
||||
var version = json[distTag];
|
||||
if (!version) {
|
||||
reject(new Error('Error getting version'));
|
||||
}
|
||||
resolve(version);
|
||||
}
|
||||
catch (_a) {
|
||||
reject(new Error('Could not parse version response'));
|
||||
}
|
||||
});
|
||||
})
|
||||
.on('error', function (err) { return reject(err); });
|
||||
})];
|
||||
});
|
||||
}); };
|
||||
|
||||
var hasNewVersion = function (_a) {
|
||||
var pkg = _a.pkg, _b = _a.updateCheckInterval, updateCheckInterval = _b === void 0 ? 1000 * 60 * 60 * 24 : _b, _c = _a.distTag, distTag = _c === void 0 ? 'latest' : _c, alwaysRun = _a.alwaysRun, debug = _a.debug;
|
||||
return __awaiter(void 0, void 0, void 0, function () {
|
||||
var lastUpdateCheck, latestVersion;
|
||||
return __generator(this, function (_d) {
|
||||
switch (_d.label) {
|
||||
case 0:
|
||||
createConfigDir();
|
||||
lastUpdateCheck = getLastUpdate(pkg.name);
|
||||
if (!(alwaysRun ||
|
||||
!lastUpdateCheck ||
|
||||
lastUpdateCheck < new Date().getTime() - updateCheckInterval)) return [3 /*break*/, 2];
|
||||
return [4 /*yield*/, getDistVersion(pkg.name, distTag)];
|
||||
case 1:
|
||||
latestVersion = _d.sent();
|
||||
saveLastUpdate(pkg.name);
|
||||
if (semver__default["default"].gt(latestVersion, pkg.version)) {
|
||||
return [2 /*return*/, latestVersion];
|
||||
}
|
||||
else if (debug) {
|
||||
console.error("Latest version (".concat(latestVersion, ") not newer than current version (").concat(pkg.version, ")"));
|
||||
}
|
||||
return [3 /*break*/, 3];
|
||||
case 2:
|
||||
if (debug) {
|
||||
console.error("Too recent to check for a new update. simpleUpdateNotifier() interval set to ".concat(updateCheckInterval, "ms but only ").concat(new Date().getTime() - lastUpdateCheck, "ms since last check."));
|
||||
}
|
||||
_d.label = 3;
|
||||
case 3: return [2 /*return*/, false];
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
var borderedText = function (text) {
|
||||
var lines = text.split('\n');
|
||||
var width = Math.max.apply(Math, lines.map(function (l) { return l.length; }));
|
||||
var res = ["\u250C".concat('─'.repeat(width + 2), "\u2510")];
|
||||
for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) {
|
||||
var line = lines_1[_i];
|
||||
res.push("\u2502 ".concat(line.padEnd(width), " \u2502"));
|
||||
}
|
||||
res.push("\u2514".concat('─'.repeat(width + 2), "\u2518"));
|
||||
return res.join('\n');
|
||||
};
|
||||
|
||||
var simpleUpdateNotifier = function (args) { return __awaiter(void 0, void 0, void 0, function () {
|
||||
var latestVersion, err_1;
|
||||
return __generator(this, function (_a) {
|
||||
switch (_a.label) {
|
||||
case 0:
|
||||
if (!args.alwaysRun &&
|
||||
(!process.stdout.isTTY || (isNpmOrYarn && !args.shouldNotifyInNpmScript))) {
|
||||
if (args.debug) {
|
||||
console.error('Opting out of running simpleUpdateNotifier()');
|
||||
}
|
||||
return [2 /*return*/];
|
||||
}
|
||||
_a.label = 1;
|
||||
case 1:
|
||||
_a.trys.push([1, 3, , 4]);
|
||||
return [4 /*yield*/, hasNewVersion(args)];
|
||||
case 2:
|
||||
latestVersion = _a.sent();
|
||||
if (latestVersion) {
|
||||
console.error(borderedText("New version of ".concat(args.pkg.name, " available!\nCurrent Version: ").concat(args.pkg.version, "\nLatest Version: ").concat(latestVersion)));
|
||||
}
|
||||
return [3 /*break*/, 4];
|
||||
case 3:
|
||||
err_1 = _a.sent();
|
||||
// Catch any network errors or cache writing errors so module doesn't cause a crash
|
||||
if (args.debug && err_1 instanceof Error) {
|
||||
console.error('Unexpected error in simpleUpdateNotifier():', err_1);
|
||||
}
|
||||
return [3 /*break*/, 4];
|
||||
case 4: return [2 /*return*/];
|
||||
}
|
||||
});
|
||||
}); };
|
||||
|
||||
module.exports = simpleUpdateNotifier;
|
||||
1233
electron/node_modules/smart-buffer/build/smartbuffer.js
generated
vendored
Normal file
1233
electron/node_modules/smart-buffer/build/smartbuffer.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load diff
1
electron/node_modules/smart-buffer/build/smartbuffer.js.map
generated
vendored
Normal file
1
electron/node_modules/smart-buffer/build/smartbuffer.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
108
electron/node_modules/smart-buffer/build/utils.js
generated
vendored
Normal file
108
electron/node_modules/smart-buffer/build/utils.js
generated
vendored
Normal file
|
|
@ -0,0 +1,108 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const buffer_1 = require("buffer");
|
||||
/**
|
||||
* Error strings
|
||||
*/
|
||||
const ERRORS = {
|
||||
INVALID_ENCODING: 'Invalid encoding provided. Please specify a valid encoding the internal Node.js Buffer supports.',
|
||||
INVALID_SMARTBUFFER_SIZE: 'Invalid size provided. Size must be a valid integer greater than zero.',
|
||||
INVALID_SMARTBUFFER_BUFFER: 'Invalid Buffer provided in SmartBufferOptions.',
|
||||
INVALID_SMARTBUFFER_OBJECT: 'Invalid SmartBufferOptions object supplied to SmartBuffer constructor or factory methods.',
|
||||
INVALID_OFFSET: 'An invalid offset value was provided.',
|
||||
INVALID_OFFSET_NON_NUMBER: 'An invalid offset value was provided. A numeric value is required.',
|
||||
INVALID_LENGTH: 'An invalid length value was provided.',
|
||||
INVALID_LENGTH_NON_NUMBER: 'An invalid length value was provived. A numeric value is required.',
|
||||
INVALID_TARGET_OFFSET: 'Target offset is beyond the bounds of the internal SmartBuffer data.',
|
||||
INVALID_TARGET_LENGTH: 'Specified length value moves cursor beyong the bounds of the internal SmartBuffer data.',
|
||||
INVALID_READ_BEYOND_BOUNDS: 'Attempted to read beyond the bounds of the managed data.',
|
||||
INVALID_WRITE_BEYOND_BOUNDS: 'Attempted to write beyond the bounds of the managed data.'
|
||||
};
|
||||
exports.ERRORS = ERRORS;
|
||||
/**
|
||||
* Checks if a given encoding is a valid Buffer encoding. (Throws an exception if check fails)
|
||||
*
|
||||
* @param { String } encoding The encoding string to check.
|
||||
*/
|
||||
function checkEncoding(encoding) {
|
||||
if (!buffer_1.Buffer.isEncoding(encoding)) {
|
||||
throw new Error(ERRORS.INVALID_ENCODING);
|
||||
}
|
||||
}
|
||||
exports.checkEncoding = checkEncoding;
|
||||
/**
|
||||
* Checks if a given number is a finite integer. (Throws an exception if check fails)
|
||||
*
|
||||
* @param { Number } value The number value to check.
|
||||
*/
|
||||
function isFiniteInteger(value) {
|
||||
return typeof value === 'number' && isFinite(value) && isInteger(value);
|
||||
}
|
||||
exports.isFiniteInteger = isFiniteInteger;
|
||||
/**
|
||||
* Checks if an offset/length value is valid. (Throws an exception if check fails)
|
||||
*
|
||||
* @param value The value to check.
|
||||
* @param offset True if checking an offset, false if checking a length.
|
||||
*/
|
||||
function checkOffsetOrLengthValue(value, offset) {
|
||||
if (typeof value === 'number') {
|
||||
// Check for non finite/non integers
|
||||
if (!isFiniteInteger(value) || value < 0) {
|
||||
throw new Error(offset ? ERRORS.INVALID_OFFSET : ERRORS.INVALID_LENGTH);
|
||||
}
|
||||
}
|
||||
else {
|
||||
throw new Error(offset ? ERRORS.INVALID_OFFSET_NON_NUMBER : ERRORS.INVALID_LENGTH_NON_NUMBER);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Checks if a length value is valid. (Throws an exception if check fails)
|
||||
*
|
||||
* @param { Number } length The value to check.
|
||||
*/
|
||||
function checkLengthValue(length) {
|
||||
checkOffsetOrLengthValue(length, false);
|
||||
}
|
||||
exports.checkLengthValue = checkLengthValue;
|
||||
/**
|
||||
* Checks if a offset value is valid. (Throws an exception if check fails)
|
||||
*
|
||||
* @param { Number } offset The value to check.
|
||||
*/
|
||||
function checkOffsetValue(offset) {
|
||||
checkOffsetOrLengthValue(offset, true);
|
||||
}
|
||||
exports.checkOffsetValue = checkOffsetValue;
|
||||
/**
|
||||
* Checks if a target offset value is out of bounds. (Throws an exception if check fails)
|
||||
*
|
||||
* @param { Number } offset The offset value to check.
|
||||
* @param { SmartBuffer } buff The SmartBuffer instance to check against.
|
||||
*/
|
||||
function checkTargetOffset(offset, buff) {
|
||||
if (offset < 0 || offset > buff.length) {
|
||||
throw new Error(ERRORS.INVALID_TARGET_OFFSET);
|
||||
}
|
||||
}
|
||||
exports.checkTargetOffset = checkTargetOffset;
|
||||
/**
|
||||
* Determines whether a given number is a integer.
|
||||
* @param value The number to check.
|
||||
*/
|
||||
function isInteger(value) {
|
||||
return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;
|
||||
}
|
||||
/**
|
||||
* Throws if Node.js version is too low to support bigint
|
||||
*/
|
||||
function bigIntAndBufferInt64Check(bufferMethod) {
|
||||
if (typeof BigInt === 'undefined') {
|
||||
throw new Error('Platform does not support JS BigInt type.');
|
||||
}
|
||||
if (typeof buffer_1.Buffer.prototype[bufferMethod] === 'undefined') {
|
||||
throw new Error(`Platform does not support Buffer.prototype.${bufferMethod}.`);
|
||||
}
|
||||
}
|
||||
exports.bigIntAndBufferInt64Check = bigIntAndBufferInt64Check;
|
||||
//# sourceMappingURL=utils.js.map
|
||||
1
electron/node_modules/smart-buffer/build/utils.js.map
generated
vendored
Normal file
1
electron/node_modules/smart-buffer/build/utils.js.map
generated
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";;AACA,mCAAgC;AAEhC;;GAEG;AACH,MAAM,MAAM,GAAG;IACb,gBAAgB,EAAE,kGAAkG;IACpH,wBAAwB,EAAE,wEAAwE;IAClG,0BAA0B,EAAE,gDAAgD;IAC5E,0BAA0B,EAAE,2FAA2F;IACvH,cAAc,EAAE,uCAAuC;IACvD,yBAAyB,EAAE,oEAAoE;IAC/F,cAAc,EAAE,uCAAuC;IACvD,yBAAyB,EAAE,oEAAoE;IAC/F,qBAAqB,EAAE,sEAAsE;IAC7F,qBAAqB,EAAE,yFAAyF;IAChH,0BAA0B,EAAE,0DAA0D;IACtF,2BAA2B,EAAE,2DAA2D;CACzF,CAAC;AAuGA,wBAAM;AArGR;;;;GAIG;AACH,SAAS,aAAa,CAAC,QAAwB;IAC7C,IAAI,CAAC,eAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE;QAChC,MAAM,IAAI,KAAK,CAAC,MAAM,CAAC,gBAAgB,CAAC,CAAC;KAC1C;AACH,CAAC;AA4F0B,sCAAa;AA1FxC;;;;GAIG;AACH,SAAS,eAAe,CAAC,KAAa;IACpC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,QAAQ,CAAC,KAAK,CAAC,IAAI,SAAS,CAAC,KAAK,CAAC,CAAC;AAC1E,CAAC;AAmFS,0CAAe;AAjFzB;;;;;GAKG;AACH,SAAS,wBAAwB,CAAC,KAAU,EAAE,MAAe;IAC3D,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;QAC7B,oCAAoC;QACpC,IAAI,CAAC,eAAe,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC,EAAE;YACxC,MAAM,IAAI,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC;SACzE;KACF;SAAM;QACL,MAAM,IAAI,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,yBAAyB,CAAC,CAAC,CAAC,MAAM,CAAC,yBAAyB,CAAC,CAAC;KAC/F;AACH,CAAC;AAED;;;;GAIG;AACH,SAAS,gBAAgB,CAAC,MAAW;IACnC,wBAAwB,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;AAC1C,CAAC;AA0DC,4CAAgB;AAxDlB;;;;GAIG;AACH,SAAS,gBAAgB,CAAC,MAAW;IACnC,wBAAwB,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;AACzC,CAAC;AAgDyC,4CAAgB;AA9C1D;;;;;GAKG;AACH,SAAS,iBAAiB,CAAC,MAAc,EAAE,IAAiB;IAC1D,IAAI,MAAM,GAAG,CAAC,IAAI,MAAM,GAAG,IAAI,CAAC,MAAM,EAAE;QACtC,MAAM,IAAI,KAAK,CAAC,MAAM,CAAC,qBAAqB,CAAC,CAAC;KAC/C;AACH,CAAC;AAqCmB,8CAAiB;AAnCrC;;;GAGG;AACH,SAAS,SAAS,CAAC,KAAa;IAC9B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,QAAQ,CAAC,KAAK,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,KAAK,CAAC;AACrF,CAAC;AAcD;;GAEG;AACH,SAAS,yBAAyB,CAAC,YAA0B;IAC3D,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;QACjC,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;KAC9D;IAED,IAAI,OAAO,eAAM,CAAC,SAAS,CAAC,YAAY,CAAC,KAAK,WAAW,EAAE;QACzD,MAAM,IAAI,KAAK,CAAC,8CAA8C,YAAY,GAAG,CAAC,CAAC;KAChF;AACH,CAAC;AAIsC,8DAAyB"}
|
||||
793
electron/node_modules/socks/build/client/socksclient.js
generated
vendored
Normal file
793
electron/node_modules/socks/build/client/socksclient.js
generated
vendored
Normal file
|
|
@ -0,0 +1,793 @@
|
|||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.SocksClientError = exports.SocksClient = void 0;
|
||||
const events_1 = require("events");
|
||||
const net = require("net");
|
||||
const smart_buffer_1 = require("smart-buffer");
|
||||
const constants_1 = require("../common/constants");
|
||||
const helpers_1 = require("../common/helpers");
|
||||
const receivebuffer_1 = require("../common/receivebuffer");
|
||||
const util_1 = require("../common/util");
|
||||
Object.defineProperty(exports, "SocksClientError", { enumerable: true, get: function () { return util_1.SocksClientError; } });
|
||||
const ip_address_1 = require("ip-address");
|
||||
class SocksClient extends events_1.EventEmitter {
|
||||
constructor(options) {
|
||||
super();
|
||||
this.options = Object.assign({}, options);
|
||||
// Validate SocksClientOptions
|
||||
(0, helpers_1.validateSocksClientOptions)(options);
|
||||
// Default state
|
||||
this.setState(constants_1.SocksClientState.Created);
|
||||
}
|
||||
/**
|
||||
* Creates a new SOCKS connection.
|
||||
*
|
||||
* Note: Supports callbacks and promises. Only supports the connect command.
|
||||
* @param options { SocksClientOptions } Options.
|
||||
* @param callback { Function } An optional callback function.
|
||||
* @returns { Promise }
|
||||
*/
|
||||
static createConnection(options, callback) {
|
||||
return new Promise((resolve, reject) => {
|
||||
// Validate SocksClientOptions
|
||||
try {
|
||||
(0, helpers_1.validateSocksClientOptions)(options, ['connect']);
|
||||
}
|
||||
catch (err) {
|
||||
if (typeof callback === 'function') {
|
||||
callback(err);
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
return resolve(err); // Resolves pending promise (prevents memory leaks).
|
||||
}
|
||||
else {
|
||||
return reject(err);
|
||||
}
|
||||
}
|
||||
const client = new SocksClient(options);
|
||||
client.connect(options.existing_socket);
|
||||
client.once('established', (info) => {
|
||||
client.removeAllListeners();
|
||||
if (typeof callback === 'function') {
|
||||
callback(null, info);
|
||||
resolve(info); // Resolves pending promise (prevents memory leaks).
|
||||
}
|
||||
else {
|
||||
resolve(info);
|
||||
}
|
||||
});
|
||||
// Error occurred, failed to establish connection.
|
||||
client.once('error', (err) => {
|
||||
client.removeAllListeners();
|
||||
if (typeof callback === 'function') {
|
||||
callback(err);
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
resolve(err); // Resolves pending promise (prevents memory leaks).
|
||||
}
|
||||
else {
|
||||
reject(err);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Creates a new SOCKS connection chain to a destination host through 2 or more SOCKS proxies.
|
||||
*
|
||||
* Note: Supports callbacks and promises. Only supports the connect method.
|
||||
* Note: Implemented via createConnection() factory function.
|
||||
* @param options { SocksClientChainOptions } Options
|
||||
* @param callback { Function } An optional callback function.
|
||||
* @returns { Promise }
|
||||
*/
|
||||
static createConnectionChain(options, callback) {
|
||||
// eslint-disable-next-line no-async-promise-executor
|
||||
return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
|
||||
// Validate SocksClientChainOptions
|
||||
try {
|
||||
(0, helpers_1.validateSocksClientChainOptions)(options);
|
||||
}
|
||||
catch (err) {
|
||||
if (typeof callback === 'function') {
|
||||
callback(err);
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
return resolve(err); // Resolves pending promise (prevents memory leaks).
|
||||
}
|
||||
else {
|
||||
return reject(err);
|
||||
}
|
||||
}
|
||||
// Shuffle proxies
|
||||
if (options.randomizeChain) {
|
||||
(0, util_1.shuffleArray)(options.proxies);
|
||||
}
|
||||
try {
|
||||
let sock;
|
||||
for (let i = 0; i < options.proxies.length; i++) {
|
||||
const nextProxy = options.proxies[i];
|
||||
// If we've reached the last proxy in the chain, the destination is the actual destination, otherwise it's the next proxy.
|
||||
const nextDestination = i === options.proxies.length - 1
|
||||
? options.destination
|
||||
: {
|
||||
host: options.proxies[i + 1].host ||
|
||||
options.proxies[i + 1].ipaddress,
|
||||
port: options.proxies[i + 1].port,
|
||||
};
|
||||
// Creates the next connection in the chain.
|
||||
const result = yield SocksClient.createConnection({
|
||||
command: 'connect',
|
||||
proxy: nextProxy,
|
||||
destination: nextDestination,
|
||||
existing_socket: sock,
|
||||
});
|
||||
// If sock is undefined, assign it here.
|
||||
sock = sock || result.socket;
|
||||
}
|
||||
if (typeof callback === 'function') {
|
||||
callback(null, { socket: sock });
|
||||
resolve({ socket: sock }); // Resolves pending promise (prevents memory leaks).
|
||||
}
|
||||
else {
|
||||
resolve({ socket: sock });
|
||||
}
|
||||
}
|
||||
catch (err) {
|
||||
if (typeof callback === 'function') {
|
||||
callback(err);
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
resolve(err); // Resolves pending promise (prevents memory leaks).
|
||||
}
|
||||
else {
|
||||
reject(err);
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
/**
|
||||
* Creates a SOCKS UDP Frame.
|
||||
* @param options
|
||||
*/
|
||||
static createUDPFrame(options) {
|
||||
const buff = new smart_buffer_1.SmartBuffer();
|
||||
buff.writeUInt16BE(0);
|
||||
buff.writeUInt8(options.frameNumber || 0);
|
||||
// IPv4/IPv6/Hostname
|
||||
if (net.isIPv4(options.remoteHost.host)) {
|
||||
buff.writeUInt8(constants_1.Socks5HostType.IPv4);
|
||||
buff.writeUInt32BE((0, helpers_1.ipv4ToInt32)(options.remoteHost.host));
|
||||
}
|
||||
else if (net.isIPv6(options.remoteHost.host)) {
|
||||
buff.writeUInt8(constants_1.Socks5HostType.IPv6);
|
||||
buff.writeBuffer((0, helpers_1.ipToBuffer)(options.remoteHost.host));
|
||||
}
|
||||
else {
|
||||
buff.writeUInt8(constants_1.Socks5HostType.Hostname);
|
||||
buff.writeUInt8(Buffer.byteLength(options.remoteHost.host));
|
||||
buff.writeString(options.remoteHost.host);
|
||||
}
|
||||
// Port
|
||||
buff.writeUInt16BE(options.remoteHost.port);
|
||||
// Data
|
||||
buff.writeBuffer(options.data);
|
||||
return buff.toBuffer();
|
||||
}
|
||||
/**
|
||||
* Parses a SOCKS UDP frame.
|
||||
* @param data
|
||||
*/
|
||||
static parseUDPFrame(data) {
|
||||
const buff = smart_buffer_1.SmartBuffer.fromBuffer(data);
|
||||
buff.readOffset = 2;
|
||||
const frameNumber = buff.readUInt8();
|
||||
const hostType = buff.readUInt8();
|
||||
let remoteHost;
|
||||
if (hostType === constants_1.Socks5HostType.IPv4) {
|
||||
remoteHost = (0, helpers_1.int32ToIpv4)(buff.readUInt32BE());
|
||||
}
|
||||
else if (hostType === constants_1.Socks5HostType.IPv6) {
|
||||
remoteHost = ip_address_1.Address6.fromByteArray(Array.from(buff.readBuffer(16))).canonicalForm();
|
||||
}
|
||||
else {
|
||||
remoteHost = buff.readString(buff.readUInt8());
|
||||
}
|
||||
const remotePort = buff.readUInt16BE();
|
||||
return {
|
||||
frameNumber,
|
||||
remoteHost: {
|
||||
host: remoteHost,
|
||||
port: remotePort,
|
||||
},
|
||||
data: buff.readBuffer(),
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Internal state setter. If the SocksClient is in an error state, it cannot be changed to a non error state.
|
||||
*/
|
||||
setState(newState) {
|
||||
if (this.state !== constants_1.SocksClientState.Error) {
|
||||
this.state = newState;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Starts the connection establishment to the proxy and destination.
|
||||
* @param existingSocket Connected socket to use instead of creating a new one (internal use).
|
||||
*/
|
||||
connect(existingSocket) {
|
||||
this.onDataReceived = (data) => this.onDataReceivedHandler(data);
|
||||
this.onClose = () => this.onCloseHandler();
|
||||
this.onError = (err) => this.onErrorHandler(err);
|
||||
this.onConnect = () => this.onConnectHandler();
|
||||
// Start timeout timer (defaults to 30 seconds)
|
||||
const timer = setTimeout(() => this.onEstablishedTimeout(), this.options.timeout || constants_1.DEFAULT_TIMEOUT);
|
||||
// check whether unref is available as it differs from browser to NodeJS (#33)
|
||||
if (timer.unref && typeof timer.unref === 'function') {
|
||||
timer.unref();
|
||||
}
|
||||
// If an existing socket is provided, use it to negotiate SOCKS handshake. Otherwise create a new Socket.
|
||||
if (existingSocket) {
|
||||
this.socket = existingSocket;
|
||||
}
|
||||
else {
|
||||
this.socket = new net.Socket();
|
||||
}
|
||||
// Attach Socket error handlers.
|
||||
this.socket.once('close', this.onClose);
|
||||
this.socket.once('error', this.onError);
|
||||
this.socket.once('connect', this.onConnect);
|
||||
this.socket.on('data', this.onDataReceived);
|
||||
this.setState(constants_1.SocksClientState.Connecting);
|
||||
this.receiveBuffer = new receivebuffer_1.ReceiveBuffer();
|
||||
if (existingSocket) {
|
||||
this.socket.emit('connect');
|
||||
}
|
||||
else {
|
||||
this.socket.connect(this.getSocketOptions());
|
||||
if (this.options.set_tcp_nodelay !== undefined &&
|
||||
this.options.set_tcp_nodelay !== null) {
|
||||
this.socket.setNoDelay(!!this.options.set_tcp_nodelay);
|
||||
}
|
||||
}
|
||||
// Listen for established event so we can re-emit any excess data received during handshakes.
|
||||
this.prependOnceListener('established', (info) => {
|
||||
setImmediate(() => {
|
||||
if (this.receiveBuffer.length > 0) {
|
||||
const excessData = this.receiveBuffer.get(this.receiveBuffer.length);
|
||||
info.socket.emit('data', excessData);
|
||||
}
|
||||
info.socket.resume();
|
||||
});
|
||||
});
|
||||
}
|
||||
// Socket options (defaults host/port to options.proxy.host/options.proxy.port)
|
||||
getSocketOptions() {
|
||||
return Object.assign(Object.assign({}, this.options.socket_options), { host: this.options.proxy.host || this.options.proxy.ipaddress, port: this.options.proxy.port });
|
||||
}
|
||||
/**
|
||||
* Handles internal Socks timeout callback.
|
||||
* Note: If the Socks client is not BoundWaitingForConnection or Established, the connection will be closed.
|
||||
*/
|
||||
onEstablishedTimeout() {
|
||||
if (this.state !== constants_1.SocksClientState.Established &&
|
||||
this.state !== constants_1.SocksClientState.BoundWaitingForConnection) {
|
||||
this.closeSocket(constants_1.ERRORS.ProxyConnectionTimedOut);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Handles Socket connect event.
|
||||
*/
|
||||
onConnectHandler() {
|
||||
this.setState(constants_1.SocksClientState.Connected);
|
||||
// Send initial handshake.
|
||||
if (this.options.proxy.type === 4) {
|
||||
this.sendSocks4InitialHandshake();
|
||||
}
|
||||
else {
|
||||
this.sendSocks5InitialHandshake();
|
||||
}
|
||||
this.setState(constants_1.SocksClientState.SentInitialHandshake);
|
||||
}
|
||||
/**
|
||||
* Handles Socket data event.
|
||||
* @param data
|
||||
*/
|
||||
onDataReceivedHandler(data) {
|
||||
/*
|
||||
All received data is appended to a ReceiveBuffer.
|
||||
This makes sure that all the data we need is received before we attempt to process it.
|
||||
*/
|
||||
this.receiveBuffer.append(data);
|
||||
// Process data that we have.
|
||||
this.processData();
|
||||
}
|
||||
/**
|
||||
* Handles processing of the data we have received.
|
||||
*/
|
||||
processData() {
|
||||
// If we have enough data to process the next step in the SOCKS handshake, proceed.
|
||||
while (this.state !== constants_1.SocksClientState.Established &&
|
||||
this.state !== constants_1.SocksClientState.Error &&
|
||||
this.receiveBuffer.length >= this.nextRequiredPacketBufferSize) {
|
||||
// Sent initial handshake, waiting for response.
|
||||
if (this.state === constants_1.SocksClientState.SentInitialHandshake) {
|
||||
if (this.options.proxy.type === 4) {
|
||||
// Socks v4 only has one handshake response.
|
||||
this.handleSocks4FinalHandshakeResponse();
|
||||
}
|
||||
else {
|
||||
// Socks v5 has two handshakes, handle initial one here.
|
||||
this.handleInitialSocks5HandshakeResponse();
|
||||
}
|
||||
// Sent auth request for Socks v5, waiting for response.
|
||||
}
|
||||
else if (this.state === constants_1.SocksClientState.SentAuthentication) {
|
||||
this.handleInitialSocks5AuthenticationHandshakeResponse();
|
||||
// Sent final Socks v5 handshake, waiting for final response.
|
||||
}
|
||||
else if (this.state === constants_1.SocksClientState.SentFinalHandshake) {
|
||||
this.handleSocks5FinalHandshakeResponse();
|
||||
// Socks BIND established. Waiting for remote connection via proxy.
|
||||
}
|
||||
else if (this.state === constants_1.SocksClientState.BoundWaitingForConnection) {
|
||||
if (this.options.proxy.type === 4) {
|
||||
this.handleSocks4IncomingConnectionResponse();
|
||||
}
|
||||
else {
|
||||
this.handleSocks5IncomingConnectionResponse();
|
||||
}
|
||||
}
|
||||
else {
|
||||
this.closeSocket(constants_1.ERRORS.InternalError);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Handles Socket close event.
|
||||
* @param had_error
|
||||
*/
|
||||
onCloseHandler() {
|
||||
this.closeSocket(constants_1.ERRORS.SocketClosed);
|
||||
}
|
||||
/**
|
||||
* Handles Socket error event.
|
||||
* @param err
|
||||
*/
|
||||
onErrorHandler(err) {
|
||||
this.closeSocket(err.message);
|
||||
}
|
||||
/**
|
||||
* Removes internal event listeners on the underlying Socket.
|
||||
*/
|
||||
removeInternalSocketHandlers() {
|
||||
// Pauses data flow of the socket (this is internally resumed after 'established' is emitted)
|
||||
this.socket.pause();
|
||||
this.socket.removeListener('data', this.onDataReceived);
|
||||
this.socket.removeListener('close', this.onClose);
|
||||
this.socket.removeListener('error', this.onError);
|
||||
this.socket.removeListener('connect', this.onConnect);
|
||||
}
|
||||
/**
|
||||
* Closes and destroys the underlying Socket. Emits an error event.
|
||||
* @param err { String } An error string to include in error event.
|
||||
*/
|
||||
closeSocket(err) {
|
||||
// Make sure only one 'error' event is fired for the lifetime of this SocksClient instance.
|
||||
if (this.state !== constants_1.SocksClientState.Error) {
|
||||
// Set internal state to Error.
|
||||
this.setState(constants_1.SocksClientState.Error);
|
||||
// Destroy Socket
|
||||
this.socket.destroy();
|
||||
// Remove internal listeners
|
||||
this.removeInternalSocketHandlers();
|
||||
// Fire 'error' event.
|
||||
this.emit('error', new util_1.SocksClientError(err, this.options));
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Sends initial Socks v4 handshake request.
|
||||
*/
|
||||
sendSocks4InitialHandshake() {
|
||||
const userId = this.options.proxy.userId || '';
|
||||
const buff = new smart_buffer_1.SmartBuffer();
|
||||
buff.writeUInt8(0x04);
|
||||
buff.writeUInt8(constants_1.SocksCommand[this.options.command]);
|
||||
buff.writeUInt16BE(this.options.destination.port);
|
||||
// Socks 4 (IPv4)
|
||||
if (net.isIPv4(this.options.destination.host)) {
|
||||
buff.writeBuffer((0, helpers_1.ipToBuffer)(this.options.destination.host));
|
||||
buff.writeStringNT(userId);
|
||||
// Socks 4a (hostname)
|
||||
}
|
||||
else {
|
||||
buff.writeUInt8(0x00);
|
||||
buff.writeUInt8(0x00);
|
||||
buff.writeUInt8(0x00);
|
||||
buff.writeUInt8(0x01);
|
||||
buff.writeStringNT(userId);
|
||||
buff.writeStringNT(this.options.destination.host);
|
||||
}
|
||||
this.nextRequiredPacketBufferSize =
|
||||
constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks4Response;
|
||||
this.socket.write(buff.toBuffer());
|
||||
}
|
||||
/**
|
||||
* Handles Socks v4 handshake response.
|
||||
* @param data
|
||||
*/
|
||||
handleSocks4FinalHandshakeResponse() {
|
||||
const data = this.receiveBuffer.get(8);
|
||||
if (data[1] !== constants_1.Socks4Response.Granted) {
|
||||
this.closeSocket(`${constants_1.ERRORS.Socks4ProxyRejectedConnection} - (${constants_1.Socks4Response[data[1]]})`);
|
||||
}
|
||||
else {
|
||||
// Bind response
|
||||
if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.bind) {
|
||||
const buff = smart_buffer_1.SmartBuffer.fromBuffer(data);
|
||||
buff.readOffset = 2;
|
||||
const remoteHost = {
|
||||
port: buff.readUInt16BE(),
|
||||
host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE()),
|
||||
};
|
||||
// If host is 0.0.0.0, set to proxy host.
|
||||
if (remoteHost.host === '0.0.0.0') {
|
||||
remoteHost.host = this.options.proxy.ipaddress;
|
||||
}
|
||||
this.setState(constants_1.SocksClientState.BoundWaitingForConnection);
|
||||
this.emit('bound', { remoteHost, socket: this.socket });
|
||||
// Connect response
|
||||
}
|
||||
else {
|
||||
this.setState(constants_1.SocksClientState.Established);
|
||||
this.removeInternalSocketHandlers();
|
||||
this.emit('established', { socket: this.socket });
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Handles Socks v4 incoming connection request (BIND)
|
||||
* @param data
|
||||
*/
|
||||
handleSocks4IncomingConnectionResponse() {
|
||||
const data = this.receiveBuffer.get(8);
|
||||
if (data[1] !== constants_1.Socks4Response.Granted) {
|
||||
this.closeSocket(`${constants_1.ERRORS.Socks4ProxyRejectedIncomingBoundConnection} - (${constants_1.Socks4Response[data[1]]})`);
|
||||
}
|
||||
else {
|
||||
const buff = smart_buffer_1.SmartBuffer.fromBuffer(data);
|
||||
buff.readOffset = 2;
|
||||
const remoteHost = {
|
||||
port: buff.readUInt16BE(),
|
||||
host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE()),
|
||||
};
|
||||
this.setState(constants_1.SocksClientState.Established);
|
||||
this.removeInternalSocketHandlers();
|
||||
this.emit('established', { remoteHost, socket: this.socket });
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Sends initial Socks v5 handshake request.
|
||||
*/
|
||||
sendSocks5InitialHandshake() {
|
||||
const buff = new smart_buffer_1.SmartBuffer();
|
||||
// By default we always support no auth.
|
||||
const supportedAuthMethods = [constants_1.Socks5Auth.NoAuth];
|
||||
// We should only tell the proxy we support user/pass auth if auth info is actually provided.
|
||||
// Note: As of Tor v0.3.5.7+, if user/pass auth is an option from the client, by default it will always take priority.
|
||||
if (this.options.proxy.userId || this.options.proxy.password) {
|
||||
supportedAuthMethods.push(constants_1.Socks5Auth.UserPass);
|
||||
}
|
||||
// Custom auth method?
|
||||
if (this.options.proxy.custom_auth_method !== undefined) {
|
||||
supportedAuthMethods.push(this.options.proxy.custom_auth_method);
|
||||
}
|
||||
// Build handshake packet
|
||||
buff.writeUInt8(0x05);
|
||||
buff.writeUInt8(supportedAuthMethods.length);
|
||||
for (const authMethod of supportedAuthMethods) {
|
||||
buff.writeUInt8(authMethod);
|
||||
}
|
||||
this.nextRequiredPacketBufferSize =
|
||||
constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5InitialHandshakeResponse;
|
||||
this.socket.write(buff.toBuffer());
|
||||
this.setState(constants_1.SocksClientState.SentInitialHandshake);
|
||||
}
|
||||
/**
|
||||
* Handles initial Socks v5 handshake response.
|
||||
* @param data
|
||||
*/
|
||||
handleInitialSocks5HandshakeResponse() {
|
||||
const data = this.receiveBuffer.get(2);
|
||||
if (data[0] !== 0x05) {
|
||||
this.closeSocket(constants_1.ERRORS.InvalidSocks5IntiailHandshakeSocksVersion);
|
||||
}
|
||||
else if (data[1] === constants_1.SOCKS5_NO_ACCEPTABLE_AUTH) {
|
||||
this.closeSocket(constants_1.ERRORS.InvalidSocks5InitialHandshakeNoAcceptedAuthType);
|
||||
}
|
||||
else {
|
||||
// If selected Socks v5 auth method is no auth, send final handshake request.
|
||||
if (data[1] === constants_1.Socks5Auth.NoAuth) {
|
||||
this.socks5ChosenAuthType = constants_1.Socks5Auth.NoAuth;
|
||||
this.sendSocks5CommandRequest();
|
||||
// If selected Socks v5 auth method is user/password, send auth handshake.
|
||||
}
|
||||
else if (data[1] === constants_1.Socks5Auth.UserPass) {
|
||||
this.socks5ChosenAuthType = constants_1.Socks5Auth.UserPass;
|
||||
this.sendSocks5UserPassAuthentication();
|
||||
// If selected Socks v5 auth method is the custom_auth_method, send custom handshake.
|
||||
}
|
||||
else if (data[1] === this.options.proxy.custom_auth_method) {
|
||||
this.socks5ChosenAuthType = this.options.proxy.custom_auth_method;
|
||||
this.sendSocks5CustomAuthentication();
|
||||
}
|
||||
else {
|
||||
this.closeSocket(constants_1.ERRORS.InvalidSocks5InitialHandshakeUnknownAuthType);
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Sends Socks v5 user & password auth handshake.
|
||||
*
|
||||
* Note: No auth and user/pass are currently supported.
|
||||
*/
|
||||
sendSocks5UserPassAuthentication() {
|
||||
const userId = this.options.proxy.userId || '';
|
||||
const password = this.options.proxy.password || '';
|
||||
const buff = new smart_buffer_1.SmartBuffer();
|
||||
buff.writeUInt8(0x01);
|
||||
buff.writeUInt8(Buffer.byteLength(userId));
|
||||
buff.writeString(userId);
|
||||
buff.writeUInt8(Buffer.byteLength(password));
|
||||
buff.writeString(password);
|
||||
this.nextRequiredPacketBufferSize =
|
||||
constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5UserPassAuthenticationResponse;
|
||||
this.socket.write(buff.toBuffer());
|
||||
this.setState(constants_1.SocksClientState.SentAuthentication);
|
||||
}
|
||||
sendSocks5CustomAuthentication() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
this.nextRequiredPacketBufferSize =
|
||||
this.options.proxy.custom_auth_response_size;
|
||||
this.socket.write(yield this.options.proxy.custom_auth_request_handler());
|
||||
this.setState(constants_1.SocksClientState.SentAuthentication);
|
||||
});
|
||||
}
|
||||
handleSocks5CustomAuthHandshakeResponse(data) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
return yield this.options.proxy.custom_auth_response_handler(data);
|
||||
});
|
||||
}
|
||||
handleSocks5AuthenticationNoAuthHandshakeResponse(data) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
return data[1] === 0x00;
|
||||
});
|
||||
}
|
||||
handleSocks5AuthenticationUserPassHandshakeResponse(data) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
return data[1] === 0x00;
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Handles Socks v5 auth handshake response.
|
||||
* @param data
|
||||
*/
|
||||
handleInitialSocks5AuthenticationHandshakeResponse() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
this.setState(constants_1.SocksClientState.ReceivedAuthenticationResponse);
|
||||
let authResult = false;
|
||||
if (this.socks5ChosenAuthType === constants_1.Socks5Auth.NoAuth) {
|
||||
authResult = yield this.handleSocks5AuthenticationNoAuthHandshakeResponse(this.receiveBuffer.get(2));
|
||||
}
|
||||
else if (this.socks5ChosenAuthType === constants_1.Socks5Auth.UserPass) {
|
||||
authResult =
|
||||
yield this.handleSocks5AuthenticationUserPassHandshakeResponse(this.receiveBuffer.get(2));
|
||||
}
|
||||
else if (this.socks5ChosenAuthType === this.options.proxy.custom_auth_method) {
|
||||
authResult = yield this.handleSocks5CustomAuthHandshakeResponse(this.receiveBuffer.get(this.options.proxy.custom_auth_response_size));
|
||||
}
|
||||
if (!authResult) {
|
||||
this.closeSocket(constants_1.ERRORS.Socks5AuthenticationFailed);
|
||||
}
|
||||
else {
|
||||
this.sendSocks5CommandRequest();
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Sends Socks v5 final handshake request.
|
||||
*/
|
||||
sendSocks5CommandRequest() {
|
||||
const buff = new smart_buffer_1.SmartBuffer();
|
||||
buff.writeUInt8(0x05);
|
||||
buff.writeUInt8(constants_1.SocksCommand[this.options.command]);
|
||||
buff.writeUInt8(0x00);
|
||||
// ipv4, ipv6, domain?
|
||||
if (net.isIPv4(this.options.destination.host)) {
|
||||
buff.writeUInt8(constants_1.Socks5HostType.IPv4);
|
||||
buff.writeBuffer((0, helpers_1.ipToBuffer)(this.options.destination.host));
|
||||
}
|
||||
else if (net.isIPv6(this.options.destination.host)) {
|
||||
buff.writeUInt8(constants_1.Socks5HostType.IPv6);
|
||||
buff.writeBuffer((0, helpers_1.ipToBuffer)(this.options.destination.host));
|
||||
}
|
||||
else {
|
||||
buff.writeUInt8(constants_1.Socks5HostType.Hostname);
|
||||
buff.writeUInt8(this.options.destination.host.length);
|
||||
buff.writeString(this.options.destination.host);
|
||||
}
|
||||
buff.writeUInt16BE(this.options.destination.port);
|
||||
this.nextRequiredPacketBufferSize =
|
||||
constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader;
|
||||
this.socket.write(buff.toBuffer());
|
||||
this.setState(constants_1.SocksClientState.SentFinalHandshake);
|
||||
}
|
||||
/**
|
||||
* Handles Socks v5 final handshake response.
|
||||
* @param data
|
||||
*/
|
||||
handleSocks5FinalHandshakeResponse() {
|
||||
// Peek at available data (we need at least 5 bytes to get the hostname length)
|
||||
const header = this.receiveBuffer.peek(5);
|
||||
if (header[0] !== 0x05 || header[1] !== constants_1.Socks5Response.Granted) {
|
||||
this.closeSocket(`${constants_1.ERRORS.InvalidSocks5FinalHandshakeRejected} - ${constants_1.Socks5Response[header[1]]}`);
|
||||
}
|
||||
else {
|
||||
// Read address type
|
||||
const addressType = header[3];
|
||||
let remoteHost;
|
||||
let buff;
|
||||
// IPv4
|
||||
if (addressType === constants_1.Socks5HostType.IPv4) {
|
||||
// Check if data is available.
|
||||
const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;
|
||||
if (this.receiveBuffer.length < dataNeeded) {
|
||||
this.nextRequiredPacketBufferSize = dataNeeded;
|
||||
return;
|
||||
}
|
||||
buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4));
|
||||
remoteHost = {
|
||||
host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE()),
|
||||
port: buff.readUInt16BE(),
|
||||
};
|
||||
// If given host is 0.0.0.0, assume remote proxy ip instead.
|
||||
if (remoteHost.host === '0.0.0.0') {
|
||||
remoteHost.host = this.options.proxy.ipaddress;
|
||||
}
|
||||
// Hostname
|
||||
}
|
||||
else if (addressType === constants_1.Socks5HostType.Hostname) {
|
||||
const hostLength = header[4];
|
||||
const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(hostLength); // header + host length + host + port
|
||||
// Check if data is available.
|
||||
if (this.receiveBuffer.length < dataNeeded) {
|
||||
this.nextRequiredPacketBufferSize = dataNeeded;
|
||||
return;
|
||||
}
|
||||
buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(5));
|
||||
remoteHost = {
|
||||
host: buff.readString(hostLength),
|
||||
port: buff.readUInt16BE(),
|
||||
};
|
||||
// IPv6
|
||||
}
|
||||
else if (addressType === constants_1.Socks5HostType.IPv6) {
|
||||
// Check if data is available.
|
||||
const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;
|
||||
if (this.receiveBuffer.length < dataNeeded) {
|
||||
this.nextRequiredPacketBufferSize = dataNeeded;
|
||||
return;
|
||||
}
|
||||
buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4));
|
||||
remoteHost = {
|
||||
host: ip_address_1.Address6.fromByteArray(Array.from(buff.readBuffer(16))).canonicalForm(),
|
||||
port: buff.readUInt16BE(),
|
||||
};
|
||||
}
|
||||
// We have everything we need
|
||||
this.setState(constants_1.SocksClientState.ReceivedFinalResponse);
|
||||
// If using CONNECT, the client is now in the established state.
|
||||
if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.connect) {
|
||||
this.setState(constants_1.SocksClientState.Established);
|
||||
this.removeInternalSocketHandlers();
|
||||
this.emit('established', { remoteHost, socket: this.socket });
|
||||
}
|
||||
else if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.bind) {
|
||||
/* If using BIND, the Socks client is now in BoundWaitingForConnection state.
|
||||
This means that the remote proxy server is waiting for a remote connection to the bound port. */
|
||||
this.setState(constants_1.SocksClientState.BoundWaitingForConnection);
|
||||
this.nextRequiredPacketBufferSize =
|
||||
constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader;
|
||||
this.emit('bound', { remoteHost, socket: this.socket });
|
||||
/*
|
||||
If using Associate, the Socks client is now Established. And the proxy server is now accepting UDP packets at the
|
||||
given bound port. This initial Socks TCP connection must remain open for the UDP relay to continue to work.
|
||||
*/
|
||||
}
|
||||
else if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.associate) {
|
||||
this.setState(constants_1.SocksClientState.Established);
|
||||
this.removeInternalSocketHandlers();
|
||||
this.emit('established', {
|
||||
remoteHost,
|
||||
socket: this.socket,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Handles Socks v5 incoming connection request (BIND).
|
||||
*/
|
||||
handleSocks5IncomingConnectionResponse() {
|
||||
// Peek at available data (we need at least 5 bytes to get the hostname length)
|
||||
const header = this.receiveBuffer.peek(5);
|
||||
if (header[0] !== 0x05 || header[1] !== constants_1.Socks5Response.Granted) {
|
||||
this.closeSocket(`${constants_1.ERRORS.Socks5ProxyRejectedIncomingBoundConnection} - ${constants_1.Socks5Response[header[1]]}`);
|
||||
}
|
||||
else {
|
||||
// Read address type
|
||||
const addressType = header[3];
|
||||
let remoteHost;
|
||||
let buff;
|
||||
// IPv4
|
||||
if (addressType === constants_1.Socks5HostType.IPv4) {
|
||||
// Check if data is available.
|
||||
const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;
|
||||
if (this.receiveBuffer.length < dataNeeded) {
|
||||
this.nextRequiredPacketBufferSize = dataNeeded;
|
||||
return;
|
||||
}
|
||||
buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4));
|
||||
remoteHost = {
|
||||
host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE()),
|
||||
port: buff.readUInt16BE(),
|
||||
};
|
||||
// If given host is 0.0.0.0, assume remote proxy ip instead.
|
||||
if (remoteHost.host === '0.0.0.0') {
|
||||
remoteHost.host = this.options.proxy.ipaddress;
|
||||
}
|
||||
// Hostname
|
||||
}
|
||||
else if (addressType === constants_1.Socks5HostType.Hostname) {
|
||||
const hostLength = header[4];
|
||||
const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(hostLength); // header + host length + port
|
||||
// Check if data is available.
|
||||
if (this.receiveBuffer.length < dataNeeded) {
|
||||
this.nextRequiredPacketBufferSize = dataNeeded;
|
||||
return;
|
||||
}
|
||||
buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(5));
|
||||
remoteHost = {
|
||||
host: buff.readString(hostLength),
|
||||
port: buff.readUInt16BE(),
|
||||
};
|
||||
// IPv6
|
||||
}
|
||||
else if (addressType === constants_1.Socks5HostType.IPv6) {
|
||||
// Check if data is available.
|
||||
const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;
|
||||
if (this.receiveBuffer.length < dataNeeded) {
|
||||
this.nextRequiredPacketBufferSize = dataNeeded;
|
||||
return;
|
||||
}
|
||||
buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4));
|
||||
remoteHost = {
|
||||
host: ip_address_1.Address6.fromByteArray(Array.from(buff.readBuffer(16))).canonicalForm(),
|
||||
port: buff.readUInt16BE(),
|
||||
};
|
||||
}
|
||||
this.setState(constants_1.SocksClientState.Established);
|
||||
this.removeInternalSocketHandlers();
|
||||
this.emit('established', { remoteHost, socket: this.socket });
|
||||
}
|
||||
}
|
||||
get socksClientOptions() {
|
||||
return Object.assign({}, this.options);
|
||||
}
|
||||
}
|
||||
exports.SocksClient = SocksClient;
|
||||
//# sourceMappingURL=socksclient.js.map
|
||||
1
electron/node_modules/socks/build/client/socksclient.js.map
generated
vendored
Normal file
1
electron/node_modules/socks/build/client/socksclient.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
108
electron/node_modules/socks/build/common/constants.js
generated
vendored
Normal file
108
electron/node_modules/socks/build/common/constants.js
generated
vendored
Normal file
|
|
@ -0,0 +1,108 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.SOCKS5_NO_ACCEPTABLE_AUTH = exports.SOCKS5_CUSTOM_AUTH_END = exports.SOCKS5_CUSTOM_AUTH_START = exports.SOCKS_INCOMING_PACKET_SIZES = exports.SocksClientState = exports.Socks5Response = exports.Socks5HostType = exports.Socks5Auth = exports.Socks4Response = exports.SocksCommand = exports.ERRORS = exports.DEFAULT_TIMEOUT = void 0;
|
||||
const DEFAULT_TIMEOUT = 30000;
|
||||
exports.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT;
|
||||
// prettier-ignore
|
||||
const ERRORS = {
|
||||
InvalidSocksCommand: 'An invalid SOCKS command was provided. Valid options are connect, bind, and associate.',
|
||||
InvalidSocksCommandForOperation: 'An invalid SOCKS command was provided. Only a subset of commands are supported for this operation.',
|
||||
InvalidSocksCommandChain: 'An invalid SOCKS command was provided. Chaining currently only supports the connect command.',
|
||||
InvalidSocksClientOptionsDestination: 'An invalid destination host was provided.',
|
||||
InvalidSocksClientOptionsExistingSocket: 'An invalid existing socket was provided. This should be an instance of stream.Duplex.',
|
||||
InvalidSocksClientOptionsProxy: 'Invalid SOCKS proxy details were provided.',
|
||||
InvalidSocksClientOptionsTimeout: 'An invalid timeout value was provided. Please enter a value above 0 (in ms).',
|
||||
InvalidSocksClientOptionsProxiesLength: 'At least two socks proxies must be provided for chaining.',
|
||||
InvalidSocksClientOptionsCustomAuthRange: 'Custom auth must be a value between 0x80 and 0xFE.',
|
||||
InvalidSocksClientOptionsCustomAuthOptions: 'When a custom_auth_method is provided, custom_auth_request_handler, custom_auth_response_size, and custom_auth_response_handler must also be provided and valid.',
|
||||
NegotiationError: 'Negotiation error',
|
||||
SocketClosed: 'Socket closed',
|
||||
ProxyConnectionTimedOut: 'Proxy connection timed out',
|
||||
InternalError: 'SocksClient internal error (this should not happen)',
|
||||
InvalidSocks4HandshakeResponse: 'Received invalid Socks4 handshake response',
|
||||
Socks4ProxyRejectedConnection: 'Socks4 Proxy rejected connection',
|
||||
InvalidSocks4IncomingConnectionResponse: 'Socks4 invalid incoming connection response',
|
||||
Socks4ProxyRejectedIncomingBoundConnection: 'Socks4 Proxy rejected incoming bound connection',
|
||||
InvalidSocks5InitialHandshakeResponse: 'Received invalid Socks5 initial handshake response',
|
||||
InvalidSocks5IntiailHandshakeSocksVersion: 'Received invalid Socks5 initial handshake (invalid socks version)',
|
||||
InvalidSocks5InitialHandshakeNoAcceptedAuthType: 'Received invalid Socks5 initial handshake (no accepted authentication type)',
|
||||
InvalidSocks5InitialHandshakeUnknownAuthType: 'Received invalid Socks5 initial handshake (unknown authentication type)',
|
||||
Socks5AuthenticationFailed: 'Socks5 Authentication failed',
|
||||
InvalidSocks5FinalHandshake: 'Received invalid Socks5 final handshake response',
|
||||
InvalidSocks5FinalHandshakeRejected: 'Socks5 proxy rejected connection',
|
||||
InvalidSocks5IncomingConnectionResponse: 'Received invalid Socks5 incoming connection response',
|
||||
Socks5ProxyRejectedIncomingBoundConnection: 'Socks5 Proxy rejected incoming bound connection',
|
||||
};
|
||||
exports.ERRORS = ERRORS;
|
||||
const SOCKS_INCOMING_PACKET_SIZES = {
|
||||
Socks5InitialHandshakeResponse: 2,
|
||||
Socks5UserPassAuthenticationResponse: 2,
|
||||
// Command response + incoming connection (bind)
|
||||
Socks5ResponseHeader: 5, // We need at least 5 to read the hostname length, then we wait for the address+port information.
|
||||
Socks5ResponseIPv4: 10, // 4 header + 4 ip + 2 port
|
||||
Socks5ResponseIPv6: 22, // 4 header + 16 ip + 2 port
|
||||
Socks5ResponseHostname: (hostNameLength) => hostNameLength + 7, // 4 header + 1 host length + host + 2 port
|
||||
// Command response + incoming connection (bind)
|
||||
Socks4Response: 8, // 2 header + 2 port + 4 ip
|
||||
};
|
||||
exports.SOCKS_INCOMING_PACKET_SIZES = SOCKS_INCOMING_PACKET_SIZES;
|
||||
var SocksCommand;
|
||||
(function (SocksCommand) {
|
||||
SocksCommand[SocksCommand["connect"] = 1] = "connect";
|
||||
SocksCommand[SocksCommand["bind"] = 2] = "bind";
|
||||
SocksCommand[SocksCommand["associate"] = 3] = "associate";
|
||||
})(SocksCommand || (exports.SocksCommand = SocksCommand = {}));
|
||||
var Socks4Response;
|
||||
(function (Socks4Response) {
|
||||
Socks4Response[Socks4Response["Granted"] = 90] = "Granted";
|
||||
Socks4Response[Socks4Response["Failed"] = 91] = "Failed";
|
||||
Socks4Response[Socks4Response["Rejected"] = 92] = "Rejected";
|
||||
Socks4Response[Socks4Response["RejectedIdent"] = 93] = "RejectedIdent";
|
||||
})(Socks4Response || (exports.Socks4Response = Socks4Response = {}));
|
||||
var Socks5Auth;
|
||||
(function (Socks5Auth) {
|
||||
Socks5Auth[Socks5Auth["NoAuth"] = 0] = "NoAuth";
|
||||
Socks5Auth[Socks5Auth["GSSApi"] = 1] = "GSSApi";
|
||||
Socks5Auth[Socks5Auth["UserPass"] = 2] = "UserPass";
|
||||
})(Socks5Auth || (exports.Socks5Auth = Socks5Auth = {}));
|
||||
const SOCKS5_CUSTOM_AUTH_START = 0x80;
|
||||
exports.SOCKS5_CUSTOM_AUTH_START = SOCKS5_CUSTOM_AUTH_START;
|
||||
const SOCKS5_CUSTOM_AUTH_END = 0xfe;
|
||||
exports.SOCKS5_CUSTOM_AUTH_END = SOCKS5_CUSTOM_AUTH_END;
|
||||
const SOCKS5_NO_ACCEPTABLE_AUTH = 0xff;
|
||||
exports.SOCKS5_NO_ACCEPTABLE_AUTH = SOCKS5_NO_ACCEPTABLE_AUTH;
|
||||
var Socks5Response;
|
||||
(function (Socks5Response) {
|
||||
Socks5Response[Socks5Response["Granted"] = 0] = "Granted";
|
||||
Socks5Response[Socks5Response["Failure"] = 1] = "Failure";
|
||||
Socks5Response[Socks5Response["NotAllowed"] = 2] = "NotAllowed";
|
||||
Socks5Response[Socks5Response["NetworkUnreachable"] = 3] = "NetworkUnreachable";
|
||||
Socks5Response[Socks5Response["HostUnreachable"] = 4] = "HostUnreachable";
|
||||
Socks5Response[Socks5Response["ConnectionRefused"] = 5] = "ConnectionRefused";
|
||||
Socks5Response[Socks5Response["TTLExpired"] = 6] = "TTLExpired";
|
||||
Socks5Response[Socks5Response["CommandNotSupported"] = 7] = "CommandNotSupported";
|
||||
Socks5Response[Socks5Response["AddressNotSupported"] = 8] = "AddressNotSupported";
|
||||
})(Socks5Response || (exports.Socks5Response = Socks5Response = {}));
|
||||
var Socks5HostType;
|
||||
(function (Socks5HostType) {
|
||||
Socks5HostType[Socks5HostType["IPv4"] = 1] = "IPv4";
|
||||
Socks5HostType[Socks5HostType["Hostname"] = 3] = "Hostname";
|
||||
Socks5HostType[Socks5HostType["IPv6"] = 4] = "IPv6";
|
||||
})(Socks5HostType || (exports.Socks5HostType = Socks5HostType = {}));
|
||||
var SocksClientState;
|
||||
(function (SocksClientState) {
|
||||
SocksClientState[SocksClientState["Created"] = 0] = "Created";
|
||||
SocksClientState[SocksClientState["Connecting"] = 1] = "Connecting";
|
||||
SocksClientState[SocksClientState["Connected"] = 2] = "Connected";
|
||||
SocksClientState[SocksClientState["SentInitialHandshake"] = 3] = "SentInitialHandshake";
|
||||
SocksClientState[SocksClientState["ReceivedInitialHandshakeResponse"] = 4] = "ReceivedInitialHandshakeResponse";
|
||||
SocksClientState[SocksClientState["SentAuthentication"] = 5] = "SentAuthentication";
|
||||
SocksClientState[SocksClientState["ReceivedAuthenticationResponse"] = 6] = "ReceivedAuthenticationResponse";
|
||||
SocksClientState[SocksClientState["SentFinalHandshake"] = 7] = "SentFinalHandshake";
|
||||
SocksClientState[SocksClientState["ReceivedFinalResponse"] = 8] = "ReceivedFinalResponse";
|
||||
SocksClientState[SocksClientState["BoundWaitingForConnection"] = 9] = "BoundWaitingForConnection";
|
||||
SocksClientState[SocksClientState["Established"] = 10] = "Established";
|
||||
SocksClientState[SocksClientState["Disconnected"] = 11] = "Disconnected";
|
||||
SocksClientState[SocksClientState["Error"] = 99] = "Error";
|
||||
})(SocksClientState || (exports.SocksClientState = SocksClientState = {}));
|
||||
//# sourceMappingURL=constants.js.map
|
||||
1
electron/node_modules/socks/build/common/constants.js.map
generated
vendored
Normal file
1
electron/node_modules/socks/build/common/constants.js.map
generated
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/common/constants.ts"],"names":[],"mappings":";;;AAGA,MAAM,eAAe,GAAG,KAAK,CAAC;AAyM5B,0CAAe;AArMjB,kBAAkB;AAClB,MAAM,MAAM,GAAG;IACb,mBAAmB,EAAE,wFAAwF;IAC7G,+BAA+B,EAAE,oGAAoG;IACrI,wBAAwB,EAAE,8FAA8F;IACxH,oCAAoC,EAAE,2CAA2C;IACjF,uCAAuC,EAAE,uFAAuF;IAChI,8BAA8B,EAAE,4CAA4C;IAC5E,gCAAgC,EAAE,8EAA8E;IAChH,sCAAsC,EAAE,2DAA2D;IACnG,wCAAwC,EAAE,oDAAoD;IAC9F,0CAA0C,EAAE,kKAAkK;IAC9M,gBAAgB,EAAE,mBAAmB;IACrC,YAAY,EAAE,eAAe;IAC7B,uBAAuB,EAAE,4BAA4B;IACrD,aAAa,EAAE,qDAAqD;IACpE,8BAA8B,EAAE,4CAA4C;IAC5E,6BAA6B,EAAE,kCAAkC;IACjE,uCAAuC,EAAE,6CAA6C;IACtF,0CAA0C,EAAE,iDAAiD;IAC7F,qCAAqC,EAAE,oDAAoD;IAC3F,yCAAyC,EAAE,mEAAmE;IAC9G,+CAA+C,EAAE,6EAA6E;IAC9H,4CAA4C,EAAE,yEAAyE;IACvH,0BAA0B,EAAE,8BAA8B;IAC1D,2BAA2B,EAAE,kDAAkD;IAC/E,mCAAmC,EAAE,kCAAkC;IACvE,uCAAuC,EAAE,sDAAsD;IAC/F,0CAA0C,EAAE,iDAAiD;CAC9F,CAAC;AAyKA,wBAAM;AAvKR,MAAM,2BAA2B,GAAG;IAClC,8BAA8B,EAAE,CAAC;IACjC,oCAAoC,EAAE,CAAC;IACvC,gDAAgD;IAChD,oBAAoB,EAAE,CAAC,EAAE,iGAAiG;IAC1H,kBAAkB,EAAE,EAAE,EAAE,2BAA2B;IACnD,kBAAkB,EAAE,EAAE,EAAE,4BAA4B;IACpD,sBAAsB,EAAE,CAAC,cAAsB,EAAE,EAAE,CAAC,cAAc,GAAG,CAAC,EAAE,2CAA2C;IACnH,gDAAgD;IAChD,cAAc,EAAE,CAAC,EAAE,2BAA2B;CAC/C,CAAC;AA6KA,kEAA2B;AAzK7B,IAAK,YAIJ;AAJD,WAAK,YAAY;IACf,qDAAc,CAAA;IACd,+CAAW,CAAA;IACX,yDAAgB,CAAA;AAClB,CAAC,EAJI,YAAY,4BAAZ,YAAY,QAIhB;AAED,IAAK,cAKJ;AALD,WAAK,cAAc;IACjB,0DAAc,CAAA;IACd,wDAAa,CAAA;IACb,4DAAe,CAAA;IACf,sEAAoB,CAAA;AACtB,CAAC,EALI,cAAc,8BAAd,cAAc,QAKlB;AAED,IAAK,UAIJ;AAJD,WAAK,UAAU;IACb,+CAAa,CAAA;IACb,+CAAa,CAAA;IACb,mDAAe,CAAA;AACjB,CAAC,EAJI,UAAU,0BAAV,UAAU,QAId;AAED,MAAM,wBAAwB,GAAG,IAAI,CAAC;AAuJpC,4DAAwB;AAtJ1B,MAAM,sBAAsB,GAAG,IAAI,CAAC;AAuJlC,wDAAsB;AArJxB,MAAM,yBAAyB,GAAG,IAAI,CAAC;AAsJrC,8DAAyB;AApJ3B,IAAK,cAUJ;AAVD,WAAK,cAAc;IACjB,yDAAc,CAAA;IACd,yDAAc,CAAA;IACd,+DAAiB,CAAA;IACjB,+EAAyB,CAAA;IACzB,yEAAsB,CAAA;IACtB,6EAAwB,CAAA;IACxB,+DAAiB,CAAA;IACjB,iFAA0B,CAAA;IAC1B,iFAA0B,CAAA;AAC5B,CAAC,EAVI,cAAc,8BAAd,cAAc,QAUlB;AAED,IAAK,cAIJ;AAJD,WAAK,cAAc;IACjB,mDAAW,CAAA;IACX,2DAAe,CAAA;IACf,mDAAW,CAAA;AACb,CAAC,EAJI,cAAc,8BAAd,cAAc,QAIlB;AAED,IAAK,gBAcJ;AAdD,WAAK,gBAAgB;IACnB,6DAAW,CAAA;IACX,mEAAc,CAAA;IACd,iEAAa,CAAA;IACb,uFAAwB,CAAA;IACxB,+GAAoC,CAAA;IACpC,mFAAsB,CAAA;IACtB,2GAAkC,CAAA;IAClC,mFAAsB,CAAA;IACtB,yFAAyB,CAAA;IACzB,iGAA6B,CAAA;IAC7B,sEAAgB,CAAA;IAChB,wEAAiB,CAAA;IACjB,0DAAU,CAAA;AACZ,CAAC,EAdI,gBAAgB,gCAAhB,gBAAgB,QAcpB"}
|
||||
167
electron/node_modules/socks/build/common/helpers.js
generated
vendored
Normal file
167
electron/node_modules/socks/build/common/helpers.js
generated
vendored
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ipToBuffer = exports.int32ToIpv4 = exports.ipv4ToInt32 = exports.validateSocksClientChainOptions = exports.validateSocksClientOptions = void 0;
|
||||
const util_1 = require("./util");
|
||||
const constants_1 = require("./constants");
|
||||
const stream = require("stream");
|
||||
const ip_address_1 = require("ip-address");
|
||||
const net = require("net");
|
||||
/**
|
||||
* Validates the provided SocksClientOptions
|
||||
* @param options { SocksClientOptions }
|
||||
* @param acceptedCommands { string[] } A list of accepted SocksProxy commands.
|
||||
*/
|
||||
function validateSocksClientOptions(options, acceptedCommands = ['connect', 'bind', 'associate']) {
|
||||
// Check SOCKs command option.
|
||||
if (!constants_1.SocksCommand[options.command]) {
|
||||
throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommand, options);
|
||||
}
|
||||
// Check SocksCommand for acceptable command.
|
||||
if (acceptedCommands.indexOf(options.command) === -1) {
|
||||
throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommandForOperation, options);
|
||||
}
|
||||
// Check destination
|
||||
if (!isValidSocksRemoteHost(options.destination)) {
|
||||
throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsDestination, options);
|
||||
}
|
||||
// Check SOCKS proxy to use
|
||||
if (!isValidSocksProxy(options.proxy)) {
|
||||
throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxy, options);
|
||||
}
|
||||
// Validate custom auth (if set)
|
||||
validateCustomProxyAuth(options.proxy, options);
|
||||
// Check timeout
|
||||
if (options.timeout && !isValidTimeoutValue(options.timeout)) {
|
||||
throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsTimeout, options);
|
||||
}
|
||||
// Check existing_socket (if provided)
|
||||
if (options.existing_socket &&
|
||||
!(options.existing_socket instanceof stream.Duplex)) {
|
||||
throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsExistingSocket, options);
|
||||
}
|
||||
}
|
||||
exports.validateSocksClientOptions = validateSocksClientOptions;
|
||||
/**
|
||||
* Validates the SocksClientChainOptions
|
||||
* @param options { SocksClientChainOptions }
|
||||
*/
|
||||
function validateSocksClientChainOptions(options) {
|
||||
// Only connect is supported when chaining.
|
||||
if (options.command !== 'connect') {
|
||||
throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommandChain, options);
|
||||
}
|
||||
// Check destination
|
||||
if (!isValidSocksRemoteHost(options.destination)) {
|
||||
throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsDestination, options);
|
||||
}
|
||||
// Validate proxies (length)
|
||||
if (!(options.proxies &&
|
||||
Array.isArray(options.proxies) &&
|
||||
options.proxies.length >= 2)) {
|
||||
throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxiesLength, options);
|
||||
}
|
||||
// Validate proxies
|
||||
options.proxies.forEach((proxy) => {
|
||||
if (!isValidSocksProxy(proxy)) {
|
||||
throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxy, options);
|
||||
}
|
||||
// Validate custom auth (if set)
|
||||
validateCustomProxyAuth(proxy, options);
|
||||
});
|
||||
// Check timeout
|
||||
if (options.timeout && !isValidTimeoutValue(options.timeout)) {
|
||||
throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsTimeout, options);
|
||||
}
|
||||
}
|
||||
exports.validateSocksClientChainOptions = validateSocksClientChainOptions;
|
||||
function validateCustomProxyAuth(proxy, options) {
|
||||
if (proxy.custom_auth_method !== undefined) {
|
||||
// Invalid auth method range
|
||||
if (proxy.custom_auth_method < constants_1.SOCKS5_CUSTOM_AUTH_START ||
|
||||
proxy.custom_auth_method > constants_1.SOCKS5_CUSTOM_AUTH_END) {
|
||||
throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthRange, options);
|
||||
}
|
||||
// Missing custom_auth_request_handler
|
||||
if (proxy.custom_auth_request_handler === undefined ||
|
||||
typeof proxy.custom_auth_request_handler !== 'function') {
|
||||
throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthOptions, options);
|
||||
}
|
||||
// Missing custom_auth_response_size
|
||||
if (proxy.custom_auth_response_size === undefined) {
|
||||
throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthOptions, options);
|
||||
}
|
||||
// Missing/invalid custom_auth_response_handler
|
||||
if (proxy.custom_auth_response_handler === undefined ||
|
||||
typeof proxy.custom_auth_response_handler !== 'function') {
|
||||
throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthOptions, options);
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Validates a SocksRemoteHost
|
||||
* @param remoteHost { SocksRemoteHost }
|
||||
*/
|
||||
function isValidSocksRemoteHost(remoteHost) {
|
||||
return (remoteHost &&
|
||||
typeof remoteHost.host === 'string' &&
|
||||
Buffer.byteLength(remoteHost.host) < 256 &&
|
||||
typeof remoteHost.port === 'number' &&
|
||||
remoteHost.port >= 0 &&
|
||||
remoteHost.port <= 65535);
|
||||
}
|
||||
/**
|
||||
* Validates a SocksProxy
|
||||
* @param proxy { SocksProxy }
|
||||
*/
|
||||
function isValidSocksProxy(proxy) {
|
||||
return (proxy &&
|
||||
(typeof proxy.host === 'string' || typeof proxy.ipaddress === 'string') &&
|
||||
typeof proxy.port === 'number' &&
|
||||
proxy.port >= 0 &&
|
||||
proxy.port <= 65535 &&
|
||||
(proxy.type === 4 || proxy.type === 5));
|
||||
}
|
||||
/**
|
||||
* Validates a timeout value.
|
||||
* @param value { Number }
|
||||
*/
|
||||
function isValidTimeoutValue(value) {
|
||||
return typeof value === 'number' && value > 0;
|
||||
}
|
||||
function ipv4ToInt32(ip) {
|
||||
const address = new ip_address_1.Address4(ip);
|
||||
// Convert the IPv4 address parts to an integer
|
||||
return address.toArray().reduce((acc, part) => (acc << 8) + part, 0) >>> 0;
|
||||
}
|
||||
exports.ipv4ToInt32 = ipv4ToInt32;
|
||||
function int32ToIpv4(int32) {
|
||||
// Extract each byte (octet) from the 32-bit integer
|
||||
const octet1 = (int32 >>> 24) & 0xff;
|
||||
const octet2 = (int32 >>> 16) & 0xff;
|
||||
const octet3 = (int32 >>> 8) & 0xff;
|
||||
const octet4 = int32 & 0xff;
|
||||
// Combine the octets into a string in IPv4 format
|
||||
return [octet1, octet2, octet3, octet4].join('.');
|
||||
}
|
||||
exports.int32ToIpv4 = int32ToIpv4;
|
||||
function ipToBuffer(ip) {
|
||||
if (net.isIPv4(ip)) {
|
||||
// Handle IPv4 addresses
|
||||
const address = new ip_address_1.Address4(ip);
|
||||
return Buffer.from(address.toArray());
|
||||
}
|
||||
else if (net.isIPv6(ip)) {
|
||||
// Handle IPv6 addresses
|
||||
const address = new ip_address_1.Address6(ip);
|
||||
return Buffer.from(address
|
||||
.canonicalForm()
|
||||
.split(':')
|
||||
.map((segment) => segment.padStart(4, '0'))
|
||||
.join(''), 'hex');
|
||||
}
|
||||
else {
|
||||
throw new Error('Invalid IP address format');
|
||||
}
|
||||
}
|
||||
exports.ipToBuffer = ipToBuffer;
|
||||
//# sourceMappingURL=helpers.js.map
|
||||
1
electron/node_modules/socks/build/common/helpers.js.map
generated
vendored
Normal file
1
electron/node_modules/socks/build/common/helpers.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
43
electron/node_modules/socks/build/common/receivebuffer.js
generated
vendored
Normal file
43
electron/node_modules/socks/build/common/receivebuffer.js
generated
vendored
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ReceiveBuffer = void 0;
|
||||
class ReceiveBuffer {
|
||||
constructor(size = 4096) {
|
||||
this.buffer = Buffer.allocUnsafe(size);
|
||||
this.offset = 0;
|
||||
this.originalSize = size;
|
||||
}
|
||||
get length() {
|
||||
return this.offset;
|
||||
}
|
||||
append(data) {
|
||||
if (!Buffer.isBuffer(data)) {
|
||||
throw new Error('Attempted to append a non-buffer instance to ReceiveBuffer.');
|
||||
}
|
||||
if (this.offset + data.length >= this.buffer.length) {
|
||||
const tmp = this.buffer;
|
||||
this.buffer = Buffer.allocUnsafe(Math.max(this.buffer.length + this.originalSize, this.buffer.length + data.length));
|
||||
tmp.copy(this.buffer);
|
||||
}
|
||||
data.copy(this.buffer, this.offset);
|
||||
return (this.offset += data.length);
|
||||
}
|
||||
peek(length) {
|
||||
if (length > this.offset) {
|
||||
throw new Error('Attempted to read beyond the bounds of the managed internal data.');
|
||||
}
|
||||
return this.buffer.slice(0, length);
|
||||
}
|
||||
get(length) {
|
||||
if (length > this.offset) {
|
||||
throw new Error('Attempted to read beyond the bounds of the managed internal data.');
|
||||
}
|
||||
const value = Buffer.allocUnsafe(length);
|
||||
this.buffer.slice(0, length).copy(value);
|
||||
this.buffer.copyWithin(0, length, length + this.offset - length);
|
||||
this.offset -= length;
|
||||
return value;
|
||||
}
|
||||
}
|
||||
exports.ReceiveBuffer = ReceiveBuffer;
|
||||
//# sourceMappingURL=receivebuffer.js.map
|
||||
1
electron/node_modules/socks/build/common/receivebuffer.js.map
generated
vendored
Normal file
1
electron/node_modules/socks/build/common/receivebuffer.js.map
generated
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"file":"receivebuffer.js","sourceRoot":"","sources":["../../src/common/receivebuffer.ts"],"names":[],"mappings":";;;AAAA,MAAM,aAAa;IAKjB,YAAY,IAAI,GAAG,IAAI;QACrB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;QACvC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC;QAChB,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC;IAC3B,CAAC;IAED,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;IAED,MAAM,CAAC,IAAY;QACjB,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;YAC3B,MAAM,IAAI,KAAK,CACb,6DAA6D,CAC9D,CAAC;QACJ,CAAC;QAED,IAAI,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC;YACpD,MAAM,GAAG,GAAG,IAAI,CAAC,MAAM,CAAC;YACxB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,WAAW,CAC9B,IAAI,CAAC,GAAG,CACN,IAAI,CAAC,MAAM,CAAC,MAAM,GAAG,IAAI,CAAC,YAAY,EACtC,IAAI,CAAC,MAAM,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CACjC,CACF,CAAC;YACF,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACxB,CAAC;QAED,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;QACpC,OAAO,CAAC,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,MAAM,CAAC,CAAC;IACtC,CAAC;IAED,IAAI,CAAC,MAAc;QACjB,IAAI,MAAM,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC;YACzB,MAAM,IAAI,KAAK,CACb,mEAAmE,CACpE,CAAC;QACJ,CAAC;QACD,OAAO,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;IACtC,CAAC;IAED,GAAG,CAAC,MAAc;QAChB,IAAI,MAAM,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC;YACzB,MAAM,IAAI,KAAK,CACb,mEAAmE,CACpE,CAAC;QACJ,CAAC;QAED,MAAM,KAAK,GAAG,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;QACzC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACzC,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,CAAC;QACjE,IAAI,CAAC,MAAM,IAAI,MAAM,CAAC;QAEtB,OAAO,KAAK,CAAC;IACf,CAAC;CACF;AAEO,sCAAa"}
|
||||
25
electron/node_modules/socks/build/common/util.js
generated
vendored
Normal file
25
electron/node_modules/socks/build/common/util.js
generated
vendored
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.shuffleArray = exports.SocksClientError = void 0;
|
||||
/**
|
||||
* Error wrapper for SocksClient
|
||||
*/
|
||||
class SocksClientError extends Error {
|
||||
constructor(message, options) {
|
||||
super(message);
|
||||
this.options = options;
|
||||
}
|
||||
}
|
||||
exports.SocksClientError = SocksClientError;
|
||||
/**
|
||||
* Shuffles a given array.
|
||||
* @param array The array to shuffle.
|
||||
*/
|
||||
function shuffleArray(array) {
|
||||
for (let i = array.length - 1; i > 0; i--) {
|
||||
const j = Math.floor(Math.random() * (i + 1));
|
||||
[array[i], array[j]] = [array[j], array[i]];
|
||||
}
|
||||
}
|
||||
exports.shuffleArray = shuffleArray;
|
||||
//# sourceMappingURL=util.js.map
|
||||
1
electron/node_modules/socks/build/common/util.js.map
generated
vendored
Normal file
1
electron/node_modules/socks/build/common/util.js.map
generated
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"file":"util.js","sourceRoot":"","sources":["../../src/common/util.ts"],"names":[],"mappings":";;;AAEA;;GAEG;AACH,MAAM,gBAAiB,SAAQ,KAAK;IAClC,YACE,OAAe,EACR,OAAqD;QAE5D,KAAK,CAAC,OAAO,CAAC,CAAC;QAFR,YAAO,GAAP,OAAO,CAA8C;IAG9D,CAAC;CACF;AAaO,4CAAgB;AAXxB;;;GAGG;AACH,SAAS,YAAY,CAAC,KAAgB;IACpC,KAAK,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC;QAC1C,MAAM,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;QAC9C,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IAC9C,CAAC;AACH,CAAC;AAEyB,oCAAY"}
|
||||
18
electron/node_modules/socks/build/index.js
generated
vendored
Normal file
18
electron/node_modules/socks/build/index.js
generated
vendored
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
||||
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
__exportStar(require("./client/socksclient"), exports);
|
||||
//# sourceMappingURL=index.js.map
|
||||
1
electron/node_modules/socks/build/index.js.map
generated
vendored
Normal file
1
electron/node_modules/socks/build/index.js.map
generated
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,uDAAqC"}
|
||||
203
electron/node_modules/y18n/build/index.cjs
generated
vendored
Normal file
203
electron/node_modules/y18n/build/index.cjs
generated
vendored
Normal file
|
|
@ -0,0 +1,203 @@
|
|||
'use strict';
|
||||
|
||||
var fs = require('fs');
|
||||
var util = require('util');
|
||||
var path = require('path');
|
||||
|
||||
let shim;
|
||||
class Y18N {
|
||||
constructor(opts) {
|
||||
// configurable options.
|
||||
opts = opts || {};
|
||||
this.directory = opts.directory || './locales';
|
||||
this.updateFiles = typeof opts.updateFiles === 'boolean' ? opts.updateFiles : true;
|
||||
this.locale = opts.locale || 'en';
|
||||
this.fallbackToLanguage = typeof opts.fallbackToLanguage === 'boolean' ? opts.fallbackToLanguage : true;
|
||||
// internal stuff.
|
||||
this.cache = Object.create(null);
|
||||
this.writeQueue = [];
|
||||
}
|
||||
__(...args) {
|
||||
if (typeof arguments[0] !== 'string') {
|
||||
return this._taggedLiteral(arguments[0], ...arguments);
|
||||
}
|
||||
const str = args.shift();
|
||||
let cb = function () { }; // start with noop.
|
||||
if (typeof args[args.length - 1] === 'function')
|
||||
cb = args.pop();
|
||||
cb = cb || function () { }; // noop.
|
||||
if (!this.cache[this.locale])
|
||||
this._readLocaleFile();
|
||||
// we've observed a new string, update the language file.
|
||||
if (!this.cache[this.locale][str] && this.updateFiles) {
|
||||
this.cache[this.locale][str] = str;
|
||||
// include the current directory and locale,
|
||||
// since these values could change before the
|
||||
// write is performed.
|
||||
this._enqueueWrite({
|
||||
directory: this.directory,
|
||||
locale: this.locale,
|
||||
cb
|
||||
});
|
||||
}
|
||||
else {
|
||||
cb();
|
||||
}
|
||||
return shim.format.apply(shim.format, [this.cache[this.locale][str] || str].concat(args));
|
||||
}
|
||||
__n() {
|
||||
const args = Array.prototype.slice.call(arguments);
|
||||
const singular = args.shift();
|
||||
const plural = args.shift();
|
||||
const quantity = args.shift();
|
||||
let cb = function () { }; // start with noop.
|
||||
if (typeof args[args.length - 1] === 'function')
|
||||
cb = args.pop();
|
||||
if (!this.cache[this.locale])
|
||||
this._readLocaleFile();
|
||||
let str = quantity === 1 ? singular : plural;
|
||||
if (this.cache[this.locale][singular]) {
|
||||
const entry = this.cache[this.locale][singular];
|
||||
str = entry[quantity === 1 ? 'one' : 'other'];
|
||||
}
|
||||
// we've observed a new string, update the language file.
|
||||
if (!this.cache[this.locale][singular] && this.updateFiles) {
|
||||
this.cache[this.locale][singular] = {
|
||||
one: singular,
|
||||
other: plural
|
||||
};
|
||||
// include the current directory and locale,
|
||||
// since these values could change before the
|
||||
// write is performed.
|
||||
this._enqueueWrite({
|
||||
directory: this.directory,
|
||||
locale: this.locale,
|
||||
cb
|
||||
});
|
||||
}
|
||||
else {
|
||||
cb();
|
||||
}
|
||||
// if a %d placeholder is provided, add quantity
|
||||
// to the arguments expanded by util.format.
|
||||
const values = [str];
|
||||
if (~str.indexOf('%d'))
|
||||
values.push(quantity);
|
||||
return shim.format.apply(shim.format, values.concat(args));
|
||||
}
|
||||
setLocale(locale) {
|
||||
this.locale = locale;
|
||||
}
|
||||
getLocale() {
|
||||
return this.locale;
|
||||
}
|
||||
updateLocale(obj) {
|
||||
if (!this.cache[this.locale])
|
||||
this._readLocaleFile();
|
||||
for (const key in obj) {
|
||||
if (Object.prototype.hasOwnProperty.call(obj, key)) {
|
||||
this.cache[this.locale][key] = obj[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
_taggedLiteral(parts, ...args) {
|
||||
let str = '';
|
||||
parts.forEach(function (part, i) {
|
||||
const arg = args[i + 1];
|
||||
str += part;
|
||||
if (typeof arg !== 'undefined') {
|
||||
str += '%s';
|
||||
}
|
||||
});
|
||||
return this.__.apply(this, [str].concat([].slice.call(args, 1)));
|
||||
}
|
||||
_enqueueWrite(work) {
|
||||
this.writeQueue.push(work);
|
||||
if (this.writeQueue.length === 1)
|
||||
this._processWriteQueue();
|
||||
}
|
||||
_processWriteQueue() {
|
||||
const _this = this;
|
||||
const work = this.writeQueue[0];
|
||||
// destructure the enqueued work.
|
||||
const directory = work.directory;
|
||||
const locale = work.locale;
|
||||
const cb = work.cb;
|
||||
const languageFile = this._resolveLocaleFile(directory, locale);
|
||||
const serializedLocale = JSON.stringify(this.cache[locale], null, 2);
|
||||
shim.fs.writeFile(languageFile, serializedLocale, 'utf-8', function (err) {
|
||||
_this.writeQueue.shift();
|
||||
if (_this.writeQueue.length > 0)
|
||||
_this._processWriteQueue();
|
||||
cb(err);
|
||||
});
|
||||
}
|
||||
_readLocaleFile() {
|
||||
let localeLookup = {};
|
||||
const languageFile = this._resolveLocaleFile(this.directory, this.locale);
|
||||
try {
|
||||
// When using a bundler such as webpack, readFileSync may not be defined:
|
||||
if (shim.fs.readFileSync) {
|
||||
localeLookup = JSON.parse(shim.fs.readFileSync(languageFile, 'utf-8'));
|
||||
}
|
||||
}
|
||||
catch (err) {
|
||||
if (err instanceof SyntaxError) {
|
||||
err.message = 'syntax error in ' + languageFile;
|
||||
}
|
||||
if (err.code === 'ENOENT')
|
||||
localeLookup = {};
|
||||
else
|
||||
throw err;
|
||||
}
|
||||
this.cache[this.locale] = localeLookup;
|
||||
}
|
||||
_resolveLocaleFile(directory, locale) {
|
||||
let file = shim.resolve(directory, './', locale + '.json');
|
||||
if (this.fallbackToLanguage && !this._fileExistsSync(file) && ~locale.lastIndexOf('_')) {
|
||||
// attempt fallback to language only
|
||||
const languageFile = shim.resolve(directory, './', locale.split('_')[0] + '.json');
|
||||
if (this._fileExistsSync(languageFile))
|
||||
file = languageFile;
|
||||
}
|
||||
return file;
|
||||
}
|
||||
_fileExistsSync(file) {
|
||||
return shim.exists(file);
|
||||
}
|
||||
}
|
||||
function y18n$1(opts, _shim) {
|
||||
shim = _shim;
|
||||
const y18n = new Y18N(opts);
|
||||
return {
|
||||
__: y18n.__.bind(y18n),
|
||||
__n: y18n.__n.bind(y18n),
|
||||
setLocale: y18n.setLocale.bind(y18n),
|
||||
getLocale: y18n.getLocale.bind(y18n),
|
||||
updateLocale: y18n.updateLocale.bind(y18n),
|
||||
locale: y18n.locale
|
||||
};
|
||||
}
|
||||
|
||||
var nodePlatformShim = {
|
||||
fs: {
|
||||
readFileSync: fs.readFileSync,
|
||||
writeFile: fs.writeFile
|
||||
},
|
||||
format: util.format,
|
||||
resolve: path.resolve,
|
||||
exists: (file) => {
|
||||
try {
|
||||
return fs.statSync(file).isFile();
|
||||
}
|
||||
catch (err) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const y18n = (opts) => {
|
||||
return y18n$1(opts, nodePlatformShim);
|
||||
};
|
||||
|
||||
module.exports = y18n;
|
||||
6
electron/node_modules/y18n/build/lib/cjs.js
generated
vendored
Normal file
6
electron/node_modules/y18n/build/lib/cjs.js
generated
vendored
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
import { y18n as _y18n } from './index.js';
|
||||
import nodePlatformShim from './platform-shims/node.js';
|
||||
const y18n = (opts) => {
|
||||
return _y18n(opts, nodePlatformShim);
|
||||
};
|
||||
export default y18n;
|
||||
174
electron/node_modules/y18n/build/lib/index.js
generated
vendored
Normal file
174
electron/node_modules/y18n/build/lib/index.js
generated
vendored
Normal file
|
|
@ -0,0 +1,174 @@
|
|||
let shim;
|
||||
class Y18N {
|
||||
constructor(opts) {
|
||||
// configurable options.
|
||||
opts = opts || {};
|
||||
this.directory = opts.directory || './locales';
|
||||
this.updateFiles = typeof opts.updateFiles === 'boolean' ? opts.updateFiles : true;
|
||||
this.locale = opts.locale || 'en';
|
||||
this.fallbackToLanguage = typeof opts.fallbackToLanguage === 'boolean' ? opts.fallbackToLanguage : true;
|
||||
// internal stuff.
|
||||
this.cache = Object.create(null);
|
||||
this.writeQueue = [];
|
||||
}
|
||||
__(...args) {
|
||||
if (typeof arguments[0] !== 'string') {
|
||||
return this._taggedLiteral(arguments[0], ...arguments);
|
||||
}
|
||||
const str = args.shift();
|
||||
let cb = function () { }; // start with noop.
|
||||
if (typeof args[args.length - 1] === 'function')
|
||||
cb = args.pop();
|
||||
cb = cb || function () { }; // noop.
|
||||
if (!this.cache[this.locale])
|
||||
this._readLocaleFile();
|
||||
// we've observed a new string, update the language file.
|
||||
if (!this.cache[this.locale][str] && this.updateFiles) {
|
||||
this.cache[this.locale][str] = str;
|
||||
// include the current directory and locale,
|
||||
// since these values could change before the
|
||||
// write is performed.
|
||||
this._enqueueWrite({
|
||||
directory: this.directory,
|
||||
locale: this.locale,
|
||||
cb
|
||||
});
|
||||
}
|
||||
else {
|
||||
cb();
|
||||
}
|
||||
return shim.format.apply(shim.format, [this.cache[this.locale][str] || str].concat(args));
|
||||
}
|
||||
__n() {
|
||||
const args = Array.prototype.slice.call(arguments);
|
||||
const singular = args.shift();
|
||||
const plural = args.shift();
|
||||
const quantity = args.shift();
|
||||
let cb = function () { }; // start with noop.
|
||||
if (typeof args[args.length - 1] === 'function')
|
||||
cb = args.pop();
|
||||
if (!this.cache[this.locale])
|
||||
this._readLocaleFile();
|
||||
let str = quantity === 1 ? singular : plural;
|
||||
if (this.cache[this.locale][singular]) {
|
||||
const entry = this.cache[this.locale][singular];
|
||||
str = entry[quantity === 1 ? 'one' : 'other'];
|
||||
}
|
||||
// we've observed a new string, update the language file.
|
||||
if (!this.cache[this.locale][singular] && this.updateFiles) {
|
||||
this.cache[this.locale][singular] = {
|
||||
one: singular,
|
||||
other: plural
|
||||
};
|
||||
// include the current directory and locale,
|
||||
// since these values could change before the
|
||||
// write is performed.
|
||||
this._enqueueWrite({
|
||||
directory: this.directory,
|
||||
locale: this.locale,
|
||||
cb
|
||||
});
|
||||
}
|
||||
else {
|
||||
cb();
|
||||
}
|
||||
// if a %d placeholder is provided, add quantity
|
||||
// to the arguments expanded by util.format.
|
||||
const values = [str];
|
||||
if (~str.indexOf('%d'))
|
||||
values.push(quantity);
|
||||
return shim.format.apply(shim.format, values.concat(args));
|
||||
}
|
||||
setLocale(locale) {
|
||||
this.locale = locale;
|
||||
}
|
||||
getLocale() {
|
||||
return this.locale;
|
||||
}
|
||||
updateLocale(obj) {
|
||||
if (!this.cache[this.locale])
|
||||
this._readLocaleFile();
|
||||
for (const key in obj) {
|
||||
if (Object.prototype.hasOwnProperty.call(obj, key)) {
|
||||
this.cache[this.locale][key] = obj[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
_taggedLiteral(parts, ...args) {
|
||||
let str = '';
|
||||
parts.forEach(function (part, i) {
|
||||
const arg = args[i + 1];
|
||||
str += part;
|
||||
if (typeof arg !== 'undefined') {
|
||||
str += '%s';
|
||||
}
|
||||
});
|
||||
return this.__.apply(this, [str].concat([].slice.call(args, 1)));
|
||||
}
|
||||
_enqueueWrite(work) {
|
||||
this.writeQueue.push(work);
|
||||
if (this.writeQueue.length === 1)
|
||||
this._processWriteQueue();
|
||||
}
|
||||
_processWriteQueue() {
|
||||
const _this = this;
|
||||
const work = this.writeQueue[0];
|
||||
// destructure the enqueued work.
|
||||
const directory = work.directory;
|
||||
const locale = work.locale;
|
||||
const cb = work.cb;
|
||||
const languageFile = this._resolveLocaleFile(directory, locale);
|
||||
const serializedLocale = JSON.stringify(this.cache[locale], null, 2);
|
||||
shim.fs.writeFile(languageFile, serializedLocale, 'utf-8', function (err) {
|
||||
_this.writeQueue.shift();
|
||||
if (_this.writeQueue.length > 0)
|
||||
_this._processWriteQueue();
|
||||
cb(err);
|
||||
});
|
||||
}
|
||||
_readLocaleFile() {
|
||||
let localeLookup = {};
|
||||
const languageFile = this._resolveLocaleFile(this.directory, this.locale);
|
||||
try {
|
||||
// When using a bundler such as webpack, readFileSync may not be defined:
|
||||
if (shim.fs.readFileSync) {
|
||||
localeLookup = JSON.parse(shim.fs.readFileSync(languageFile, 'utf-8'));
|
||||
}
|
||||
}
|
||||
catch (err) {
|
||||
if (err instanceof SyntaxError) {
|
||||
err.message = 'syntax error in ' + languageFile;
|
||||
}
|
||||
if (err.code === 'ENOENT')
|
||||
localeLookup = {};
|
||||
else
|
||||
throw err;
|
||||
}
|
||||
this.cache[this.locale] = localeLookup;
|
||||
}
|
||||
_resolveLocaleFile(directory, locale) {
|
||||
let file = shim.resolve(directory, './', locale + '.json');
|
||||
if (this.fallbackToLanguage && !this._fileExistsSync(file) && ~locale.lastIndexOf('_')) {
|
||||
// attempt fallback to language only
|
||||
const languageFile = shim.resolve(directory, './', locale.split('_')[0] + '.json');
|
||||
if (this._fileExistsSync(languageFile))
|
||||
file = languageFile;
|
||||
}
|
||||
return file;
|
||||
}
|
||||
_fileExistsSync(file) {
|
||||
return shim.exists(file);
|
||||
}
|
||||
}
|
||||
export function y18n(opts, _shim) {
|
||||
shim = _shim;
|
||||
const y18n = new Y18N(opts);
|
||||
return {
|
||||
__: y18n.__.bind(y18n),
|
||||
__n: y18n.__n.bind(y18n),
|
||||
setLocale: y18n.setLocale.bind(y18n),
|
||||
getLocale: y18n.getLocale.bind(y18n),
|
||||
updateLocale: y18n.updateLocale.bind(y18n),
|
||||
locale: y18n.locale
|
||||
};
|
||||
}
|
||||
19
electron/node_modules/y18n/build/lib/platform-shims/node.js
generated
vendored
Normal file
19
electron/node_modules/y18n/build/lib/platform-shims/node.js
generated
vendored
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
import { readFileSync, statSync, writeFile } from 'fs';
|
||||
import { format } from 'util';
|
||||
import { resolve } from 'path';
|
||||
export default {
|
||||
fs: {
|
||||
readFileSync,
|
||||
writeFile
|
||||
},
|
||||
format,
|
||||
resolve,
|
||||
exists: (file) => {
|
||||
try {
|
||||
return statSync(file).isFile();
|
||||
}
|
||||
catch (err) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
};
|
||||
1050
electron/node_modules/yargs-parser/build/index.cjs
generated
vendored
Normal file
1050
electron/node_modules/yargs-parser/build/index.cjs
generated
vendored
Normal file
File diff suppressed because it is too large
Load diff
62
electron/node_modules/yargs-parser/build/lib/index.js
generated
vendored
Normal file
62
electron/node_modules/yargs-parser/build/lib/index.js
generated
vendored
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
/**
|
||||
* @fileoverview Main entrypoint for libraries using yargs-parser in Node.js
|
||||
* CJS and ESM environments.
|
||||
*
|
||||
* @license
|
||||
* Copyright (c) 2016, Contributors
|
||||
* SPDX-License-Identifier: ISC
|
||||
*/
|
||||
var _a, _b, _c;
|
||||
import { format } from 'util';
|
||||
import { normalize, resolve } from 'path';
|
||||
import { camelCase, decamelize, looksLikeNumber } from './string-utils.js';
|
||||
import { YargsParser } from './yargs-parser.js';
|
||||
import { readFileSync } from 'fs';
|
||||
// See https://github.com/yargs/yargs-parser#supported-nodejs-versions for our
|
||||
// version support policy. The YARGS_MIN_NODE_VERSION is used for testing only.
|
||||
const minNodeVersion = (process && process.env && process.env.YARGS_MIN_NODE_VERSION)
|
||||
? Number(process.env.YARGS_MIN_NODE_VERSION)
|
||||
: 12;
|
||||
const nodeVersion = (_b = (_a = process === null || process === void 0 ? void 0 : process.versions) === null || _a === void 0 ? void 0 : _a.node) !== null && _b !== void 0 ? _b : (_c = process === null || process === void 0 ? void 0 : process.version) === null || _c === void 0 ? void 0 : _c.slice(1);
|
||||
if (nodeVersion) {
|
||||
const major = Number(nodeVersion.match(/^([^.]+)/)[1]);
|
||||
if (major < minNodeVersion) {
|
||||
throw Error(`yargs parser supports a minimum Node.js version of ${minNodeVersion}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`);
|
||||
}
|
||||
}
|
||||
// Creates a yargs-parser instance using Node.js standard libraries:
|
||||
const env = process ? process.env : {};
|
||||
const parser = new YargsParser({
|
||||
cwd: process.cwd,
|
||||
env: () => {
|
||||
return env;
|
||||
},
|
||||
format,
|
||||
normalize,
|
||||
resolve,
|
||||
// TODO: figure out a way to combine ESM and CJS coverage, such that
|
||||
// we can exercise all the lines below:
|
||||
require: (path) => {
|
||||
if (typeof require !== 'undefined') {
|
||||
return require(path);
|
||||
}
|
||||
else if (path.match(/\.json$/)) {
|
||||
// Addresses: https://github.com/yargs/yargs/issues/2040
|
||||
return JSON.parse(readFileSync(path, 'utf8'));
|
||||
}
|
||||
else {
|
||||
throw Error('only .json config files are supported in ESM');
|
||||
}
|
||||
}
|
||||
});
|
||||
const yargsParser = function Parser(args, opts) {
|
||||
const result = parser.parse(args.slice(), opts);
|
||||
return result.argv;
|
||||
};
|
||||
yargsParser.detailed = function (args, opts) {
|
||||
return parser.parse(args.slice(), opts);
|
||||
};
|
||||
yargsParser.camelCase = camelCase;
|
||||
yargsParser.decamelize = decamelize;
|
||||
yargsParser.looksLikeNumber = looksLikeNumber;
|
||||
export default yargsParser;
|
||||
65
electron/node_modules/yargs-parser/build/lib/string-utils.js
generated
vendored
Normal file
65
electron/node_modules/yargs-parser/build/lib/string-utils.js
generated
vendored
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
/**
|
||||
* @license
|
||||
* Copyright (c) 2016, Contributors
|
||||
* SPDX-License-Identifier: ISC
|
||||
*/
|
||||
export function camelCase(str) {
|
||||
// Handle the case where an argument is provided as camel case, e.g., fooBar.
|
||||
// by ensuring that the string isn't already mixed case:
|
||||
const isCamelCase = str !== str.toLowerCase() && str !== str.toUpperCase();
|
||||
if (!isCamelCase) {
|
||||
str = str.toLowerCase();
|
||||
}
|
||||
if (str.indexOf('-') === -1 && str.indexOf('_') === -1) {
|
||||
return str;
|
||||
}
|
||||
else {
|
||||
let camelcase = '';
|
||||
let nextChrUpper = false;
|
||||
const leadingHyphens = str.match(/^-+/);
|
||||
for (let i = leadingHyphens ? leadingHyphens[0].length : 0; i < str.length; i++) {
|
||||
let chr = str.charAt(i);
|
||||
if (nextChrUpper) {
|
||||
nextChrUpper = false;
|
||||
chr = chr.toUpperCase();
|
||||
}
|
||||
if (i !== 0 && (chr === '-' || chr === '_')) {
|
||||
nextChrUpper = true;
|
||||
}
|
||||
else if (chr !== '-' && chr !== '_') {
|
||||
camelcase += chr;
|
||||
}
|
||||
}
|
||||
return camelcase;
|
||||
}
|
||||
}
|
||||
export function decamelize(str, joinString) {
|
||||
const lowercase = str.toLowerCase();
|
||||
joinString = joinString || '-';
|
||||
let notCamelcase = '';
|
||||
for (let i = 0; i < str.length; i++) {
|
||||
const chrLower = lowercase.charAt(i);
|
||||
const chrString = str.charAt(i);
|
||||
if (chrLower !== chrString && i > 0) {
|
||||
notCamelcase += `${joinString}${lowercase.charAt(i)}`;
|
||||
}
|
||||
else {
|
||||
notCamelcase += chrString;
|
||||
}
|
||||
}
|
||||
return notCamelcase;
|
||||
}
|
||||
export function looksLikeNumber(x) {
|
||||
if (x === null || x === undefined)
|
||||
return false;
|
||||
// if loaded from config, may already be a number.
|
||||
if (typeof x === 'number')
|
||||
return true;
|
||||
// hexadecimal.
|
||||
if (/^0x[0-9a-f]+$/i.test(x))
|
||||
return true;
|
||||
// don't treat 0123 as a number; as it drops the leading '0'.
|
||||
if (/^0[^.]/.test(x))
|
||||
return false;
|
||||
return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
|
||||
}
|
||||
40
electron/node_modules/yargs-parser/build/lib/tokenize-arg-string.js
generated
vendored
Normal file
40
electron/node_modules/yargs-parser/build/lib/tokenize-arg-string.js
generated
vendored
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
/**
|
||||
* @license
|
||||
* Copyright (c) 2016, Contributors
|
||||
* SPDX-License-Identifier: ISC
|
||||
*/
|
||||
// take an un-split argv string and tokenize it.
|
||||
export function tokenizeArgString(argString) {
|
||||
if (Array.isArray(argString)) {
|
||||
return argString.map(e => typeof e !== 'string' ? e + '' : e);
|
||||
}
|
||||
argString = argString.trim();
|
||||
let i = 0;
|
||||
let prevC = null;
|
||||
let c = null;
|
||||
let opening = null;
|
||||
const args = [];
|
||||
for (let ii = 0; ii < argString.length; ii++) {
|
||||
prevC = c;
|
||||
c = argString.charAt(ii);
|
||||
// split on spaces unless we're in quotes.
|
||||
if (c === ' ' && !opening) {
|
||||
if (!(prevC === ' ')) {
|
||||
i++;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// don't split the string if we're in matching
|
||||
// opening or closing single and double quotes.
|
||||
if (c === opening) {
|
||||
opening = null;
|
||||
}
|
||||
else if ((c === "'" || c === '"') && !opening) {
|
||||
opening = c;
|
||||
}
|
||||
if (!args[i])
|
||||
args[i] = '';
|
||||
args[i] += c;
|
||||
}
|
||||
return args;
|
||||
}
|
||||
12
electron/node_modules/yargs-parser/build/lib/yargs-parser-types.js
generated
vendored
Normal file
12
electron/node_modules/yargs-parser/build/lib/yargs-parser-types.js
generated
vendored
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
/**
|
||||
* @license
|
||||
* Copyright (c) 2016, Contributors
|
||||
* SPDX-License-Identifier: ISC
|
||||
*/
|
||||
export var DefaultValuesForTypeKey;
|
||||
(function (DefaultValuesForTypeKey) {
|
||||
DefaultValuesForTypeKey["BOOLEAN"] = "boolean";
|
||||
DefaultValuesForTypeKey["STRING"] = "string";
|
||||
DefaultValuesForTypeKey["NUMBER"] = "number";
|
||||
DefaultValuesForTypeKey["ARRAY"] = "array";
|
||||
})(DefaultValuesForTypeKey || (DefaultValuesForTypeKey = {}));
|
||||
1045
electron/node_modules/yargs-parser/build/lib/yargs-parser.js
generated
vendored
Normal file
1045
electron/node_modules/yargs-parser/build/lib/yargs-parser.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load diff
1
electron/node_modules/yargs/build/index.cjs
generated
vendored
Normal file
1
electron/node_modules/yargs/build/index.cjs
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
62
electron/node_modules/yargs/build/lib/argsert.js
generated
vendored
Normal file
62
electron/node_modules/yargs/build/lib/argsert.js
generated
vendored
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
import { YError } from './yerror.js';
|
||||
import { parseCommand } from './parse-command.js';
|
||||
const positionName = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth'];
|
||||
export function argsert(arg1, arg2, arg3) {
|
||||
function parseArgs() {
|
||||
return typeof arg1 === 'object'
|
||||
? [{ demanded: [], optional: [] }, arg1, arg2]
|
||||
: [
|
||||
parseCommand(`cmd ${arg1}`),
|
||||
arg2,
|
||||
arg3,
|
||||
];
|
||||
}
|
||||
try {
|
||||
let position = 0;
|
||||
const [parsed, callerArguments, _length] = parseArgs();
|
||||
const args = [].slice.call(callerArguments);
|
||||
while (args.length && args[args.length - 1] === undefined)
|
||||
args.pop();
|
||||
const length = _length || args.length;
|
||||
if (length < parsed.demanded.length) {
|
||||
throw new YError(`Not enough arguments provided. Expected ${parsed.demanded.length} but received ${args.length}.`);
|
||||
}
|
||||
const totalCommands = parsed.demanded.length + parsed.optional.length;
|
||||
if (length > totalCommands) {
|
||||
throw new YError(`Too many arguments provided. Expected max ${totalCommands} but received ${length}.`);
|
||||
}
|
||||
parsed.demanded.forEach(demanded => {
|
||||
const arg = args.shift();
|
||||
const observedType = guessType(arg);
|
||||
const matchingTypes = demanded.cmd.filter(type => type === observedType || type === '*');
|
||||
if (matchingTypes.length === 0)
|
||||
argumentTypeError(observedType, demanded.cmd, position);
|
||||
position += 1;
|
||||
});
|
||||
parsed.optional.forEach(optional => {
|
||||
if (args.length === 0)
|
||||
return;
|
||||
const arg = args.shift();
|
||||
const observedType = guessType(arg);
|
||||
const matchingTypes = optional.cmd.filter(type => type === observedType || type === '*');
|
||||
if (matchingTypes.length === 0)
|
||||
argumentTypeError(observedType, optional.cmd, position);
|
||||
position += 1;
|
||||
});
|
||||
}
|
||||
catch (err) {
|
||||
console.warn(err.stack);
|
||||
}
|
||||
}
|
||||
function guessType(arg) {
|
||||
if (Array.isArray(arg)) {
|
||||
return 'array';
|
||||
}
|
||||
else if (arg === null) {
|
||||
return 'null';
|
||||
}
|
||||
return typeof arg;
|
||||
}
|
||||
function argumentTypeError(observedType, allowedTypes, position) {
|
||||
throw new YError(`Invalid ${positionName[position] || 'manyith'} argument. Expected ${allowedTypes.join(' or ')} but received ${observedType}.`);
|
||||
}
|
||||
449
electron/node_modules/yargs/build/lib/command.js
generated
vendored
Normal file
449
electron/node_modules/yargs/build/lib/command.js
generated
vendored
Normal file
|
|
@ -0,0 +1,449 @@
|
|||
import { assertNotStrictEqual, } from './typings/common-types.js';
|
||||
import { isPromise } from './utils/is-promise.js';
|
||||
import { applyMiddleware, commandMiddlewareFactory, } from './middleware.js';
|
||||
import { parseCommand } from './parse-command.js';
|
||||
import { isYargsInstance, } from './yargs-factory.js';
|
||||
import { maybeAsyncResult } from './utils/maybe-async-result.js';
|
||||
import whichModule from './utils/which-module.js';
|
||||
const DEFAULT_MARKER = /(^\*)|(^\$0)/;
|
||||
export class CommandInstance {
|
||||
constructor(usage, validation, globalMiddleware, shim) {
|
||||
this.requireCache = new Set();
|
||||
this.handlers = {};
|
||||
this.aliasMap = {};
|
||||
this.frozens = [];
|
||||
this.shim = shim;
|
||||
this.usage = usage;
|
||||
this.globalMiddleware = globalMiddleware;
|
||||
this.validation = validation;
|
||||
}
|
||||
addDirectory(dir, req, callerFile, opts) {
|
||||
opts = opts || {};
|
||||
if (typeof opts.recurse !== 'boolean')
|
||||
opts.recurse = false;
|
||||
if (!Array.isArray(opts.extensions))
|
||||
opts.extensions = ['js'];
|
||||
const parentVisit = typeof opts.visit === 'function' ? opts.visit : (o) => o;
|
||||
opts.visit = (obj, joined, filename) => {
|
||||
const visited = parentVisit(obj, joined, filename);
|
||||
if (visited) {
|
||||
if (this.requireCache.has(joined))
|
||||
return visited;
|
||||
else
|
||||
this.requireCache.add(joined);
|
||||
this.addHandler(visited);
|
||||
}
|
||||
return visited;
|
||||
};
|
||||
this.shim.requireDirectory({ require: req, filename: callerFile }, dir, opts);
|
||||
}
|
||||
addHandler(cmd, description, builder, handler, commandMiddleware, deprecated) {
|
||||
let aliases = [];
|
||||
const middlewares = commandMiddlewareFactory(commandMiddleware);
|
||||
handler = handler || (() => { });
|
||||
if (Array.isArray(cmd)) {
|
||||
if (isCommandAndAliases(cmd)) {
|
||||
[cmd, ...aliases] = cmd;
|
||||
}
|
||||
else {
|
||||
for (const command of cmd) {
|
||||
this.addHandler(command);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (isCommandHandlerDefinition(cmd)) {
|
||||
let command = Array.isArray(cmd.command) || typeof cmd.command === 'string'
|
||||
? cmd.command
|
||||
: this.moduleName(cmd);
|
||||
if (cmd.aliases)
|
||||
command = [].concat(command).concat(cmd.aliases);
|
||||
this.addHandler(command, this.extractDesc(cmd), cmd.builder, cmd.handler, cmd.middlewares, cmd.deprecated);
|
||||
return;
|
||||
}
|
||||
else if (isCommandBuilderDefinition(builder)) {
|
||||
this.addHandler([cmd].concat(aliases), description, builder.builder, builder.handler, builder.middlewares, builder.deprecated);
|
||||
return;
|
||||
}
|
||||
if (typeof cmd === 'string') {
|
||||
const parsedCommand = parseCommand(cmd);
|
||||
aliases = aliases.map(alias => parseCommand(alias).cmd);
|
||||
let isDefault = false;
|
||||
const parsedAliases = [parsedCommand.cmd].concat(aliases).filter(c => {
|
||||
if (DEFAULT_MARKER.test(c)) {
|
||||
isDefault = true;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
if (parsedAliases.length === 0 && isDefault)
|
||||
parsedAliases.push('$0');
|
||||
if (isDefault) {
|
||||
parsedCommand.cmd = parsedAliases[0];
|
||||
aliases = parsedAliases.slice(1);
|
||||
cmd = cmd.replace(DEFAULT_MARKER, parsedCommand.cmd);
|
||||
}
|
||||
aliases.forEach(alias => {
|
||||
this.aliasMap[alias] = parsedCommand.cmd;
|
||||
});
|
||||
if (description !== false) {
|
||||
this.usage.command(cmd, description, isDefault, aliases, deprecated);
|
||||
}
|
||||
this.handlers[parsedCommand.cmd] = {
|
||||
original: cmd,
|
||||
description,
|
||||
handler,
|
||||
builder: builder || {},
|
||||
middlewares,
|
||||
deprecated,
|
||||
demanded: parsedCommand.demanded,
|
||||
optional: parsedCommand.optional,
|
||||
};
|
||||
if (isDefault)
|
||||
this.defaultCommand = this.handlers[parsedCommand.cmd];
|
||||
}
|
||||
}
|
||||
getCommandHandlers() {
|
||||
return this.handlers;
|
||||
}
|
||||
getCommands() {
|
||||
return Object.keys(this.handlers).concat(Object.keys(this.aliasMap));
|
||||
}
|
||||
hasDefaultCommand() {
|
||||
return !!this.defaultCommand;
|
||||
}
|
||||
runCommand(command, yargs, parsed, commandIndex, helpOnly, helpOrVersionSet) {
|
||||
const commandHandler = this.handlers[command] ||
|
||||
this.handlers[this.aliasMap[command]] ||
|
||||
this.defaultCommand;
|
||||
const currentContext = yargs.getInternalMethods().getContext();
|
||||
const parentCommands = currentContext.commands.slice();
|
||||
const isDefaultCommand = !command;
|
||||
if (command) {
|
||||
currentContext.commands.push(command);
|
||||
currentContext.fullCommands.push(commandHandler.original);
|
||||
}
|
||||
const builderResult = this.applyBuilderUpdateUsageAndParse(isDefaultCommand, commandHandler, yargs, parsed.aliases, parentCommands, commandIndex, helpOnly, helpOrVersionSet);
|
||||
return isPromise(builderResult)
|
||||
? builderResult.then(result => this.applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, result.innerArgv, currentContext, helpOnly, result.aliases, yargs))
|
||||
: this.applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, builderResult.innerArgv, currentContext, helpOnly, builderResult.aliases, yargs);
|
||||
}
|
||||
applyBuilderUpdateUsageAndParse(isDefaultCommand, commandHandler, yargs, aliases, parentCommands, commandIndex, helpOnly, helpOrVersionSet) {
|
||||
const builder = commandHandler.builder;
|
||||
let innerYargs = yargs;
|
||||
if (isCommandBuilderCallback(builder)) {
|
||||
yargs.getInternalMethods().getUsageInstance().freeze();
|
||||
const builderOutput = builder(yargs.getInternalMethods().reset(aliases), helpOrVersionSet);
|
||||
if (isPromise(builderOutput)) {
|
||||
return builderOutput.then(output => {
|
||||
innerYargs = isYargsInstance(output) ? output : yargs;
|
||||
return this.parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly);
|
||||
});
|
||||
}
|
||||
}
|
||||
else if (isCommandBuilderOptionDefinitions(builder)) {
|
||||
yargs.getInternalMethods().getUsageInstance().freeze();
|
||||
innerYargs = yargs.getInternalMethods().reset(aliases);
|
||||
Object.keys(commandHandler.builder).forEach(key => {
|
||||
innerYargs.option(key, builder[key]);
|
||||
});
|
||||
}
|
||||
return this.parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly);
|
||||
}
|
||||
parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly) {
|
||||
if (isDefaultCommand)
|
||||
innerYargs.getInternalMethods().getUsageInstance().unfreeze(true);
|
||||
if (this.shouldUpdateUsage(innerYargs)) {
|
||||
innerYargs
|
||||
.getInternalMethods()
|
||||
.getUsageInstance()
|
||||
.usage(this.usageFromParentCommandsCommandHandler(parentCommands, commandHandler), commandHandler.description);
|
||||
}
|
||||
const innerArgv = innerYargs
|
||||
.getInternalMethods()
|
||||
.runYargsParserAndExecuteCommands(null, undefined, true, commandIndex, helpOnly);
|
||||
return isPromise(innerArgv)
|
||||
? innerArgv.then(argv => ({
|
||||
aliases: innerYargs.parsed.aliases,
|
||||
innerArgv: argv,
|
||||
}))
|
||||
: {
|
||||
aliases: innerYargs.parsed.aliases,
|
||||
innerArgv: innerArgv,
|
||||
};
|
||||
}
|
||||
shouldUpdateUsage(yargs) {
|
||||
return (!yargs.getInternalMethods().getUsageInstance().getUsageDisabled() &&
|
||||
yargs.getInternalMethods().getUsageInstance().getUsage().length === 0);
|
||||
}
|
||||
usageFromParentCommandsCommandHandler(parentCommands, commandHandler) {
|
||||
const c = DEFAULT_MARKER.test(commandHandler.original)
|
||||
? commandHandler.original.replace(DEFAULT_MARKER, '').trim()
|
||||
: commandHandler.original;
|
||||
const pc = parentCommands.filter(c => {
|
||||
return !DEFAULT_MARKER.test(c);
|
||||
});
|
||||
pc.push(c);
|
||||
return `$0 ${pc.join(' ')}`;
|
||||
}
|
||||
handleValidationAndGetResult(isDefaultCommand, commandHandler, innerArgv, currentContext, aliases, yargs, middlewares, positionalMap) {
|
||||
if (!yargs.getInternalMethods().getHasOutput()) {
|
||||
const validation = yargs
|
||||
.getInternalMethods()
|
||||
.runValidation(aliases, positionalMap, yargs.parsed.error, isDefaultCommand);
|
||||
innerArgv = maybeAsyncResult(innerArgv, result => {
|
||||
validation(result);
|
||||
return result;
|
||||
});
|
||||
}
|
||||
if (commandHandler.handler && !yargs.getInternalMethods().getHasOutput()) {
|
||||
yargs.getInternalMethods().setHasOutput();
|
||||
const populateDoubleDash = !!yargs.getOptions().configuration['populate--'];
|
||||
yargs
|
||||
.getInternalMethods()
|
||||
.postProcess(innerArgv, populateDoubleDash, false, false);
|
||||
innerArgv = applyMiddleware(innerArgv, yargs, middlewares, false);
|
||||
innerArgv = maybeAsyncResult(innerArgv, result => {
|
||||
const handlerResult = commandHandler.handler(result);
|
||||
return isPromise(handlerResult)
|
||||
? handlerResult.then(() => result)
|
||||
: result;
|
||||
});
|
||||
if (!isDefaultCommand) {
|
||||
yargs.getInternalMethods().getUsageInstance().cacheHelpMessage();
|
||||
}
|
||||
if (isPromise(innerArgv) &&
|
||||
!yargs.getInternalMethods().hasParseCallback()) {
|
||||
innerArgv.catch(error => {
|
||||
try {
|
||||
yargs.getInternalMethods().getUsageInstance().fail(null, error);
|
||||
}
|
||||
catch (_err) {
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
if (!isDefaultCommand) {
|
||||
currentContext.commands.pop();
|
||||
currentContext.fullCommands.pop();
|
||||
}
|
||||
return innerArgv;
|
||||
}
|
||||
applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, innerArgv, currentContext, helpOnly, aliases, yargs) {
|
||||
let positionalMap = {};
|
||||
if (helpOnly)
|
||||
return innerArgv;
|
||||
if (!yargs.getInternalMethods().getHasOutput()) {
|
||||
positionalMap = this.populatePositionals(commandHandler, innerArgv, currentContext, yargs);
|
||||
}
|
||||
const middlewares = this.globalMiddleware
|
||||
.getMiddleware()
|
||||
.slice(0)
|
||||
.concat(commandHandler.middlewares);
|
||||
const maybePromiseArgv = applyMiddleware(innerArgv, yargs, middlewares, true);
|
||||
return isPromise(maybePromiseArgv)
|
||||
? maybePromiseArgv.then(resolvedInnerArgv => this.handleValidationAndGetResult(isDefaultCommand, commandHandler, resolvedInnerArgv, currentContext, aliases, yargs, middlewares, positionalMap))
|
||||
: this.handleValidationAndGetResult(isDefaultCommand, commandHandler, maybePromiseArgv, currentContext, aliases, yargs, middlewares, positionalMap);
|
||||
}
|
||||
populatePositionals(commandHandler, argv, context, yargs) {
|
||||
argv._ = argv._.slice(context.commands.length);
|
||||
const demanded = commandHandler.demanded.slice(0);
|
||||
const optional = commandHandler.optional.slice(0);
|
||||
const positionalMap = {};
|
||||
this.validation.positionalCount(demanded.length, argv._.length);
|
||||
while (demanded.length) {
|
||||
const demand = demanded.shift();
|
||||
this.populatePositional(demand, argv, positionalMap);
|
||||
}
|
||||
while (optional.length) {
|
||||
const maybe = optional.shift();
|
||||
this.populatePositional(maybe, argv, positionalMap);
|
||||
}
|
||||
argv._ = context.commands.concat(argv._.map(a => '' + a));
|
||||
this.postProcessPositionals(argv, positionalMap, this.cmdToParseOptions(commandHandler.original), yargs);
|
||||
return positionalMap;
|
||||
}
|
||||
populatePositional(positional, argv, positionalMap) {
|
||||
const cmd = positional.cmd[0];
|
||||
if (positional.variadic) {
|
||||
positionalMap[cmd] = argv._.splice(0).map(String);
|
||||
}
|
||||
else {
|
||||
if (argv._.length)
|
||||
positionalMap[cmd] = [String(argv._.shift())];
|
||||
}
|
||||
}
|
||||
cmdToParseOptions(cmdString) {
|
||||
const parseOptions = {
|
||||
array: [],
|
||||
default: {},
|
||||
alias: {},
|
||||
demand: {},
|
||||
};
|
||||
const parsed = parseCommand(cmdString);
|
||||
parsed.demanded.forEach(d => {
|
||||
const [cmd, ...aliases] = d.cmd;
|
||||
if (d.variadic) {
|
||||
parseOptions.array.push(cmd);
|
||||
parseOptions.default[cmd] = [];
|
||||
}
|
||||
parseOptions.alias[cmd] = aliases;
|
||||
parseOptions.demand[cmd] = true;
|
||||
});
|
||||
parsed.optional.forEach(o => {
|
||||
const [cmd, ...aliases] = o.cmd;
|
||||
if (o.variadic) {
|
||||
parseOptions.array.push(cmd);
|
||||
parseOptions.default[cmd] = [];
|
||||
}
|
||||
parseOptions.alias[cmd] = aliases;
|
||||
});
|
||||
return parseOptions;
|
||||
}
|
||||
postProcessPositionals(argv, positionalMap, parseOptions, yargs) {
|
||||
const options = Object.assign({}, yargs.getOptions());
|
||||
options.default = Object.assign(parseOptions.default, options.default);
|
||||
for (const key of Object.keys(parseOptions.alias)) {
|
||||
options.alias[key] = (options.alias[key] || []).concat(parseOptions.alias[key]);
|
||||
}
|
||||
options.array = options.array.concat(parseOptions.array);
|
||||
options.config = {};
|
||||
const unparsed = [];
|
||||
Object.keys(positionalMap).forEach(key => {
|
||||
positionalMap[key].map(value => {
|
||||
if (options.configuration['unknown-options-as-args'])
|
||||
options.key[key] = true;
|
||||
unparsed.push(`--${key}`);
|
||||
unparsed.push(value);
|
||||
});
|
||||
});
|
||||
if (!unparsed.length)
|
||||
return;
|
||||
const config = Object.assign({}, options.configuration, {
|
||||
'populate--': false,
|
||||
});
|
||||
const parsed = this.shim.Parser.detailed(unparsed, Object.assign({}, options, {
|
||||
configuration: config,
|
||||
}));
|
||||
if (parsed.error) {
|
||||
yargs
|
||||
.getInternalMethods()
|
||||
.getUsageInstance()
|
||||
.fail(parsed.error.message, parsed.error);
|
||||
}
|
||||
else {
|
||||
const positionalKeys = Object.keys(positionalMap);
|
||||
Object.keys(positionalMap).forEach(key => {
|
||||
positionalKeys.push(...parsed.aliases[key]);
|
||||
});
|
||||
Object.keys(parsed.argv).forEach(key => {
|
||||
if (positionalKeys.includes(key)) {
|
||||
if (!positionalMap[key])
|
||||
positionalMap[key] = parsed.argv[key];
|
||||
if (!this.isInConfigs(yargs, key) &&
|
||||
!this.isDefaulted(yargs, key) &&
|
||||
Object.prototype.hasOwnProperty.call(argv, key) &&
|
||||
Object.prototype.hasOwnProperty.call(parsed.argv, key) &&
|
||||
(Array.isArray(argv[key]) || Array.isArray(parsed.argv[key]))) {
|
||||
argv[key] = [].concat(argv[key], parsed.argv[key]);
|
||||
}
|
||||
else {
|
||||
argv[key] = parsed.argv[key];
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
isDefaulted(yargs, key) {
|
||||
const { default: defaults } = yargs.getOptions();
|
||||
return (Object.prototype.hasOwnProperty.call(defaults, key) ||
|
||||
Object.prototype.hasOwnProperty.call(defaults, this.shim.Parser.camelCase(key)));
|
||||
}
|
||||
isInConfigs(yargs, key) {
|
||||
const { configObjects } = yargs.getOptions();
|
||||
return (configObjects.some(c => Object.prototype.hasOwnProperty.call(c, key)) ||
|
||||
configObjects.some(c => Object.prototype.hasOwnProperty.call(c, this.shim.Parser.camelCase(key))));
|
||||
}
|
||||
runDefaultBuilderOn(yargs) {
|
||||
if (!this.defaultCommand)
|
||||
return;
|
||||
if (this.shouldUpdateUsage(yargs)) {
|
||||
const commandString = DEFAULT_MARKER.test(this.defaultCommand.original)
|
||||
? this.defaultCommand.original
|
||||
: this.defaultCommand.original.replace(/^[^[\]<>]*/, '$0 ');
|
||||
yargs
|
||||
.getInternalMethods()
|
||||
.getUsageInstance()
|
||||
.usage(commandString, this.defaultCommand.description);
|
||||
}
|
||||
const builder = this.defaultCommand.builder;
|
||||
if (isCommandBuilderCallback(builder)) {
|
||||
return builder(yargs, true);
|
||||
}
|
||||
else if (!isCommandBuilderDefinition(builder)) {
|
||||
Object.keys(builder).forEach(key => {
|
||||
yargs.option(key, builder[key]);
|
||||
});
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
moduleName(obj) {
|
||||
const mod = whichModule(obj);
|
||||
if (!mod)
|
||||
throw new Error(`No command name given for module: ${this.shim.inspect(obj)}`);
|
||||
return this.commandFromFilename(mod.filename);
|
||||
}
|
||||
commandFromFilename(filename) {
|
||||
return this.shim.path.basename(filename, this.shim.path.extname(filename));
|
||||
}
|
||||
extractDesc({ describe, description, desc }) {
|
||||
for (const test of [describe, description, desc]) {
|
||||
if (typeof test === 'string' || test === false)
|
||||
return test;
|
||||
assertNotStrictEqual(test, true, this.shim);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
freeze() {
|
||||
this.frozens.push({
|
||||
handlers: this.handlers,
|
||||
aliasMap: this.aliasMap,
|
||||
defaultCommand: this.defaultCommand,
|
||||
});
|
||||
}
|
||||
unfreeze() {
|
||||
const frozen = this.frozens.pop();
|
||||
assertNotStrictEqual(frozen, undefined, this.shim);
|
||||
({
|
||||
handlers: this.handlers,
|
||||
aliasMap: this.aliasMap,
|
||||
defaultCommand: this.defaultCommand,
|
||||
} = frozen);
|
||||
}
|
||||
reset() {
|
||||
this.handlers = {};
|
||||
this.aliasMap = {};
|
||||
this.defaultCommand = undefined;
|
||||
this.requireCache = new Set();
|
||||
return this;
|
||||
}
|
||||
}
|
||||
export function command(usage, validation, globalMiddleware, shim) {
|
||||
return new CommandInstance(usage, validation, globalMiddleware, shim);
|
||||
}
|
||||
export function isCommandBuilderDefinition(builder) {
|
||||
return (typeof builder === 'object' &&
|
||||
!!builder.builder &&
|
||||
typeof builder.handler === 'function');
|
||||
}
|
||||
function isCommandAndAliases(cmd) {
|
||||
return cmd.every(c => typeof c === 'string');
|
||||
}
|
||||
export function isCommandBuilderCallback(builder) {
|
||||
return typeof builder === 'function';
|
||||
}
|
||||
function isCommandBuilderOptionDefinitions(builder) {
|
||||
return typeof builder === 'object';
|
||||
}
|
||||
export function isCommandHandlerDefinition(cmd) {
|
||||
return typeof cmd === 'object' && !Array.isArray(cmd);
|
||||
}
|
||||
48
electron/node_modules/yargs/build/lib/completion-templates.js
generated
vendored
Normal file
48
electron/node_modules/yargs/build/lib/completion-templates.js
generated
vendored
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
export const completionShTemplate = `###-begin-{{app_name}}-completions-###
|
||||
#
|
||||
# yargs command completion script
|
||||
#
|
||||
# Installation: {{app_path}} {{completion_command}} >> ~/.bashrc
|
||||
# or {{app_path}} {{completion_command}} >> ~/.bash_profile on OSX.
|
||||
#
|
||||
_{{app_name}}_yargs_completions()
|
||||
{
|
||||
local cur_word args type_list
|
||||
|
||||
cur_word="\${COMP_WORDS[COMP_CWORD]}"
|
||||
args=("\${COMP_WORDS[@]}")
|
||||
|
||||
# ask yargs to generate completions.
|
||||
type_list=$({{app_path}} --get-yargs-completions "\${args[@]}")
|
||||
|
||||
COMPREPLY=( $(compgen -W "\${type_list}" -- \${cur_word}) )
|
||||
|
||||
# if no match was found, fall back to filename completion
|
||||
if [ \${#COMPREPLY[@]} -eq 0 ]; then
|
||||
COMPREPLY=()
|
||||
fi
|
||||
|
||||
return 0
|
||||
}
|
||||
complete -o bashdefault -o default -F _{{app_name}}_yargs_completions {{app_name}}
|
||||
###-end-{{app_name}}-completions-###
|
||||
`;
|
||||
export const completionZshTemplate = `#compdef {{app_name}}
|
||||
###-begin-{{app_name}}-completions-###
|
||||
#
|
||||
# yargs command completion script
|
||||
#
|
||||
# Installation: {{app_path}} {{completion_command}} >> ~/.zshrc
|
||||
# or {{app_path}} {{completion_command}} >> ~/.zprofile on OSX.
|
||||
#
|
||||
_{{app_name}}_yargs_completions()
|
||||
{
|
||||
local reply
|
||||
local si=$IFS
|
||||
IFS=$'\n' reply=($(COMP_CWORD="$((CURRENT-1))" COMP_LINE="$BUFFER" COMP_POINT="$CURSOR" {{app_path}} --get-yargs-completions "\${words[@]}"))
|
||||
IFS=$si
|
||||
_describe 'values' reply
|
||||
}
|
||||
compdef _{{app_name}}_yargs_completions {{app_name}}
|
||||
###-end-{{app_name}}-completions-###
|
||||
`;
|
||||
243
electron/node_modules/yargs/build/lib/completion.js
generated
vendored
Normal file
243
electron/node_modules/yargs/build/lib/completion.js
generated
vendored
Normal file
|
|
@ -0,0 +1,243 @@
|
|||
import { isCommandBuilderCallback } from './command.js';
|
||||
import { assertNotStrictEqual } from './typings/common-types.js';
|
||||
import * as templates from './completion-templates.js';
|
||||
import { isPromise } from './utils/is-promise.js';
|
||||
import { parseCommand } from './parse-command.js';
|
||||
export class Completion {
|
||||
constructor(yargs, usage, command, shim) {
|
||||
var _a, _b, _c;
|
||||
this.yargs = yargs;
|
||||
this.usage = usage;
|
||||
this.command = command;
|
||||
this.shim = shim;
|
||||
this.completionKey = 'get-yargs-completions';
|
||||
this.aliases = null;
|
||||
this.customCompletionFunction = null;
|
||||
this.indexAfterLastReset = 0;
|
||||
this.zshShell =
|
||||
(_c = (((_a = this.shim.getEnv('SHELL')) === null || _a === void 0 ? void 0 : _a.includes('zsh')) ||
|
||||
((_b = this.shim.getEnv('ZSH_NAME')) === null || _b === void 0 ? void 0 : _b.includes('zsh')))) !== null && _c !== void 0 ? _c : false;
|
||||
}
|
||||
defaultCompletion(args, argv, current, done) {
|
||||
const handlers = this.command.getCommandHandlers();
|
||||
for (let i = 0, ii = args.length; i < ii; ++i) {
|
||||
if (handlers[args[i]] && handlers[args[i]].builder) {
|
||||
const builder = handlers[args[i]].builder;
|
||||
if (isCommandBuilderCallback(builder)) {
|
||||
this.indexAfterLastReset = i + 1;
|
||||
const y = this.yargs.getInternalMethods().reset();
|
||||
builder(y, true);
|
||||
return y.argv;
|
||||
}
|
||||
}
|
||||
}
|
||||
const completions = [];
|
||||
this.commandCompletions(completions, args, current);
|
||||
this.optionCompletions(completions, args, argv, current);
|
||||
this.choicesFromOptionsCompletions(completions, args, argv, current);
|
||||
this.choicesFromPositionalsCompletions(completions, args, argv, current);
|
||||
done(null, completions);
|
||||
}
|
||||
commandCompletions(completions, args, current) {
|
||||
const parentCommands = this.yargs
|
||||
.getInternalMethods()
|
||||
.getContext().commands;
|
||||
if (!current.match(/^-/) &&
|
||||
parentCommands[parentCommands.length - 1] !== current &&
|
||||
!this.previousArgHasChoices(args)) {
|
||||
this.usage.getCommands().forEach(usageCommand => {
|
||||
const commandName = parseCommand(usageCommand[0]).cmd;
|
||||
if (args.indexOf(commandName) === -1) {
|
||||
if (!this.zshShell) {
|
||||
completions.push(commandName);
|
||||
}
|
||||
else {
|
||||
const desc = usageCommand[1] || '';
|
||||
completions.push(commandName.replace(/:/g, '\\:') + ':' + desc);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
optionCompletions(completions, args, argv, current) {
|
||||
if ((current.match(/^-/) || (current === '' && completions.length === 0)) &&
|
||||
!this.previousArgHasChoices(args)) {
|
||||
const options = this.yargs.getOptions();
|
||||
const positionalKeys = this.yargs.getGroups()[this.usage.getPositionalGroupName()] || [];
|
||||
Object.keys(options.key).forEach(key => {
|
||||
const negable = !!options.configuration['boolean-negation'] &&
|
||||
options.boolean.includes(key);
|
||||
const isPositionalKey = positionalKeys.includes(key);
|
||||
if (!isPositionalKey &&
|
||||
!options.hiddenOptions.includes(key) &&
|
||||
!this.argsContainKey(args, key, negable)) {
|
||||
this.completeOptionKey(key, completions, current, negable && !!options.default[key]);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
choicesFromOptionsCompletions(completions, args, argv, current) {
|
||||
if (this.previousArgHasChoices(args)) {
|
||||
const choices = this.getPreviousArgChoices(args);
|
||||
if (choices && choices.length > 0) {
|
||||
completions.push(...choices.map(c => c.replace(/:/g, '\\:')));
|
||||
}
|
||||
}
|
||||
}
|
||||
choicesFromPositionalsCompletions(completions, args, argv, current) {
|
||||
if (current === '' &&
|
||||
completions.length > 0 &&
|
||||
this.previousArgHasChoices(args)) {
|
||||
return;
|
||||
}
|
||||
const positionalKeys = this.yargs.getGroups()[this.usage.getPositionalGroupName()] || [];
|
||||
const offset = Math.max(this.indexAfterLastReset, this.yargs.getInternalMethods().getContext().commands.length +
|
||||
1);
|
||||
const positionalKey = positionalKeys[argv._.length - offset - 1];
|
||||
if (!positionalKey) {
|
||||
return;
|
||||
}
|
||||
const choices = this.yargs.getOptions().choices[positionalKey] || [];
|
||||
for (const choice of choices) {
|
||||
if (choice.startsWith(current)) {
|
||||
completions.push(choice.replace(/:/g, '\\:'));
|
||||
}
|
||||
}
|
||||
}
|
||||
getPreviousArgChoices(args) {
|
||||
if (args.length < 1)
|
||||
return;
|
||||
let previousArg = args[args.length - 1];
|
||||
let filter = '';
|
||||
if (!previousArg.startsWith('-') && args.length > 1) {
|
||||
filter = previousArg;
|
||||
previousArg = args[args.length - 2];
|
||||
}
|
||||
if (!previousArg.startsWith('-'))
|
||||
return;
|
||||
const previousArgKey = previousArg.replace(/^-+/, '');
|
||||
const options = this.yargs.getOptions();
|
||||
const possibleAliases = [
|
||||
previousArgKey,
|
||||
...(this.yargs.getAliases()[previousArgKey] || []),
|
||||
];
|
||||
let choices;
|
||||
for (const possibleAlias of possibleAliases) {
|
||||
if (Object.prototype.hasOwnProperty.call(options.key, possibleAlias) &&
|
||||
Array.isArray(options.choices[possibleAlias])) {
|
||||
choices = options.choices[possibleAlias];
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (choices) {
|
||||
return choices.filter(choice => !filter || choice.startsWith(filter));
|
||||
}
|
||||
}
|
||||
previousArgHasChoices(args) {
|
||||
const choices = this.getPreviousArgChoices(args);
|
||||
return choices !== undefined && choices.length > 0;
|
||||
}
|
||||
argsContainKey(args, key, negable) {
|
||||
const argsContains = (s) => args.indexOf((/^[^0-9]$/.test(s) ? '-' : '--') + s) !== -1;
|
||||
if (argsContains(key))
|
||||
return true;
|
||||
if (negable && argsContains(`no-${key}`))
|
||||
return true;
|
||||
if (this.aliases) {
|
||||
for (const alias of this.aliases[key]) {
|
||||
if (argsContains(alias))
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
completeOptionKey(key, completions, current, negable) {
|
||||
var _a, _b, _c, _d;
|
||||
let keyWithDesc = key;
|
||||
if (this.zshShell) {
|
||||
const descs = this.usage.getDescriptions();
|
||||
const aliasKey = (_b = (_a = this === null || this === void 0 ? void 0 : this.aliases) === null || _a === void 0 ? void 0 : _a[key]) === null || _b === void 0 ? void 0 : _b.find(alias => {
|
||||
const desc = descs[alias];
|
||||
return typeof desc === 'string' && desc.length > 0;
|
||||
});
|
||||
const descFromAlias = aliasKey ? descs[aliasKey] : undefined;
|
||||
const desc = (_d = (_c = descs[key]) !== null && _c !== void 0 ? _c : descFromAlias) !== null && _d !== void 0 ? _d : '';
|
||||
keyWithDesc = `${key.replace(/:/g, '\\:')}:${desc
|
||||
.replace('__yargsString__:', '')
|
||||
.replace(/(\r\n|\n|\r)/gm, ' ')}`;
|
||||
}
|
||||
const startsByTwoDashes = (s) => /^--/.test(s);
|
||||
const isShortOption = (s) => /^[^0-9]$/.test(s);
|
||||
const dashes = !startsByTwoDashes(current) && isShortOption(key) ? '-' : '--';
|
||||
completions.push(dashes + keyWithDesc);
|
||||
if (negable) {
|
||||
completions.push(dashes + 'no-' + keyWithDesc);
|
||||
}
|
||||
}
|
||||
customCompletion(args, argv, current, done) {
|
||||
assertNotStrictEqual(this.customCompletionFunction, null, this.shim);
|
||||
if (isSyncCompletionFunction(this.customCompletionFunction)) {
|
||||
const result = this.customCompletionFunction(current, argv);
|
||||
if (isPromise(result)) {
|
||||
return result
|
||||
.then(list => {
|
||||
this.shim.process.nextTick(() => {
|
||||
done(null, list);
|
||||
});
|
||||
})
|
||||
.catch(err => {
|
||||
this.shim.process.nextTick(() => {
|
||||
done(err, undefined);
|
||||
});
|
||||
});
|
||||
}
|
||||
return done(null, result);
|
||||
}
|
||||
else if (isFallbackCompletionFunction(this.customCompletionFunction)) {
|
||||
return this.customCompletionFunction(current, argv, (onCompleted = done) => this.defaultCompletion(args, argv, current, onCompleted), completions => {
|
||||
done(null, completions);
|
||||
});
|
||||
}
|
||||
else {
|
||||
return this.customCompletionFunction(current, argv, completions => {
|
||||
done(null, completions);
|
||||
});
|
||||
}
|
||||
}
|
||||
getCompletion(args, done) {
|
||||
const current = args.length ? args[args.length - 1] : '';
|
||||
const argv = this.yargs.parse(args, true);
|
||||
const completionFunction = this.customCompletionFunction
|
||||
? (argv) => this.customCompletion(args, argv, current, done)
|
||||
: (argv) => this.defaultCompletion(args, argv, current, done);
|
||||
return isPromise(argv)
|
||||
? argv.then(completionFunction)
|
||||
: completionFunction(argv);
|
||||
}
|
||||
generateCompletionScript($0, cmd) {
|
||||
let script = this.zshShell
|
||||
? templates.completionZshTemplate
|
||||
: templates.completionShTemplate;
|
||||
const name = this.shim.path.basename($0);
|
||||
if ($0.match(/\.js$/))
|
||||
$0 = `./${$0}`;
|
||||
script = script.replace(/{{app_name}}/g, name);
|
||||
script = script.replace(/{{completion_command}}/g, cmd);
|
||||
return script.replace(/{{app_path}}/g, $0);
|
||||
}
|
||||
registerFunction(fn) {
|
||||
this.customCompletionFunction = fn;
|
||||
}
|
||||
setParsed(parsed) {
|
||||
this.aliases = parsed.aliases;
|
||||
}
|
||||
}
|
||||
export function completion(yargs, usage, command, shim) {
|
||||
return new Completion(yargs, usage, command, shim);
|
||||
}
|
||||
function isSyncCompletionFunction(completionFunction) {
|
||||
return completionFunction.length < 3;
|
||||
}
|
||||
function isFallbackCompletionFunction(completionFunction) {
|
||||
return completionFunction.length > 3;
|
||||
}
|
||||
88
electron/node_modules/yargs/build/lib/middleware.js
generated
vendored
Normal file
88
electron/node_modules/yargs/build/lib/middleware.js
generated
vendored
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
import { argsert } from './argsert.js';
|
||||
import { isPromise } from './utils/is-promise.js';
|
||||
export class GlobalMiddleware {
|
||||
constructor(yargs) {
|
||||
this.globalMiddleware = [];
|
||||
this.frozens = [];
|
||||
this.yargs = yargs;
|
||||
}
|
||||
addMiddleware(callback, applyBeforeValidation, global = true, mutates = false) {
|
||||
argsert('<array|function> [boolean] [boolean] [boolean]', [callback, applyBeforeValidation, global], arguments.length);
|
||||
if (Array.isArray(callback)) {
|
||||
for (let i = 0; i < callback.length; i++) {
|
||||
if (typeof callback[i] !== 'function') {
|
||||
throw Error('middleware must be a function');
|
||||
}
|
||||
const m = callback[i];
|
||||
m.applyBeforeValidation = applyBeforeValidation;
|
||||
m.global = global;
|
||||
}
|
||||
Array.prototype.push.apply(this.globalMiddleware, callback);
|
||||
}
|
||||
else if (typeof callback === 'function') {
|
||||
const m = callback;
|
||||
m.applyBeforeValidation = applyBeforeValidation;
|
||||
m.global = global;
|
||||
m.mutates = mutates;
|
||||
this.globalMiddleware.push(callback);
|
||||
}
|
||||
return this.yargs;
|
||||
}
|
||||
addCoerceMiddleware(callback, option) {
|
||||
const aliases = this.yargs.getAliases();
|
||||
this.globalMiddleware = this.globalMiddleware.filter(m => {
|
||||
const toCheck = [...(aliases[option] || []), option];
|
||||
if (!m.option)
|
||||
return true;
|
||||
else
|
||||
return !toCheck.includes(m.option);
|
||||
});
|
||||
callback.option = option;
|
||||
return this.addMiddleware(callback, true, true, true);
|
||||
}
|
||||
getMiddleware() {
|
||||
return this.globalMiddleware;
|
||||
}
|
||||
freeze() {
|
||||
this.frozens.push([...this.globalMiddleware]);
|
||||
}
|
||||
unfreeze() {
|
||||
const frozen = this.frozens.pop();
|
||||
if (frozen !== undefined)
|
||||
this.globalMiddleware = frozen;
|
||||
}
|
||||
reset() {
|
||||
this.globalMiddleware = this.globalMiddleware.filter(m => m.global);
|
||||
}
|
||||
}
|
||||
export function commandMiddlewareFactory(commandMiddleware) {
|
||||
if (!commandMiddleware)
|
||||
return [];
|
||||
return commandMiddleware.map(middleware => {
|
||||
middleware.applyBeforeValidation = false;
|
||||
return middleware;
|
||||
});
|
||||
}
|
||||
export function applyMiddleware(argv, yargs, middlewares, beforeValidation) {
|
||||
return middlewares.reduce((acc, middleware) => {
|
||||
if (middleware.applyBeforeValidation !== beforeValidation) {
|
||||
return acc;
|
||||
}
|
||||
if (middleware.mutates) {
|
||||
if (middleware.applied)
|
||||
return acc;
|
||||
middleware.applied = true;
|
||||
}
|
||||
if (isPromise(acc)) {
|
||||
return acc
|
||||
.then(initialObj => Promise.all([initialObj, middleware(initialObj, yargs)]))
|
||||
.then(([initialObj, middlewareObj]) => Object.assign(initialObj, middlewareObj));
|
||||
}
|
||||
else {
|
||||
const result = middleware(acc, yargs);
|
||||
return isPromise(result)
|
||||
? result.then(middlewareObj => Object.assign(acc, middlewareObj))
|
||||
: Object.assign(acc, result);
|
||||
}
|
||||
}, argv);
|
||||
}
|
||||
32
electron/node_modules/yargs/build/lib/parse-command.js
generated
vendored
Normal file
32
electron/node_modules/yargs/build/lib/parse-command.js
generated
vendored
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
export function parseCommand(cmd) {
|
||||
const extraSpacesStrippedCommand = cmd.replace(/\s{2,}/g, ' ');
|
||||
const splitCommand = extraSpacesStrippedCommand.split(/\s+(?![^[]*]|[^<]*>)/);
|
||||
const bregex = /\.*[\][<>]/g;
|
||||
const firstCommand = splitCommand.shift();
|
||||
if (!firstCommand)
|
||||
throw new Error(`No command found in: ${cmd}`);
|
||||
const parsedCommand = {
|
||||
cmd: firstCommand.replace(bregex, ''),
|
||||
demanded: [],
|
||||
optional: [],
|
||||
};
|
||||
splitCommand.forEach((cmd, i) => {
|
||||
let variadic = false;
|
||||
cmd = cmd.replace(/\s/g, '');
|
||||
if (/\.+[\]>]/.test(cmd) && i === splitCommand.length - 1)
|
||||
variadic = true;
|
||||
if (/^\[/.test(cmd)) {
|
||||
parsedCommand.optional.push({
|
||||
cmd: cmd.replace(bregex, '').split('|'),
|
||||
variadic,
|
||||
});
|
||||
}
|
||||
else {
|
||||
parsedCommand.demanded.push({
|
||||
cmd: cmd.replace(bregex, '').split('|'),
|
||||
variadic,
|
||||
});
|
||||
}
|
||||
});
|
||||
return parsedCommand;
|
||||
}
|
||||
9
electron/node_modules/yargs/build/lib/typings/common-types.js
generated
vendored
Normal file
9
electron/node_modules/yargs/build/lib/typings/common-types.js
generated
vendored
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
export function assertNotStrictEqual(actual, expected, shim, message) {
|
||||
shim.assert.notStrictEqual(actual, expected, message);
|
||||
}
|
||||
export function assertSingleKey(actual, shim) {
|
||||
shim.assert.strictEqual(typeof actual, 'string');
|
||||
}
|
||||
export function objectKeys(object) {
|
||||
return Object.keys(object);
|
||||
}
|
||||
1
electron/node_modules/yargs/build/lib/typings/yargs-parser-types.js
generated
vendored
Normal file
1
electron/node_modules/yargs/build/lib/typings/yargs-parser-types.js
generated
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
export {};
|
||||
584
electron/node_modules/yargs/build/lib/usage.js
generated
vendored
Normal file
584
electron/node_modules/yargs/build/lib/usage.js
generated
vendored
Normal file
|
|
@ -0,0 +1,584 @@
|
|||
import { objFilter } from './utils/obj-filter.js';
|
||||
import { YError } from './yerror.js';
|
||||
import setBlocking from './utils/set-blocking.js';
|
||||
function isBoolean(fail) {
|
||||
return typeof fail === 'boolean';
|
||||
}
|
||||
export function usage(yargs, shim) {
|
||||
const __ = shim.y18n.__;
|
||||
const self = {};
|
||||
const fails = [];
|
||||
self.failFn = function failFn(f) {
|
||||
fails.push(f);
|
||||
};
|
||||
let failMessage = null;
|
||||
let globalFailMessage = null;
|
||||
let showHelpOnFail = true;
|
||||
self.showHelpOnFail = function showHelpOnFailFn(arg1 = true, arg2) {
|
||||
const [enabled, message] = typeof arg1 === 'string' ? [true, arg1] : [arg1, arg2];
|
||||
if (yargs.getInternalMethods().isGlobalContext()) {
|
||||
globalFailMessage = message;
|
||||
}
|
||||
failMessage = message;
|
||||
showHelpOnFail = enabled;
|
||||
return self;
|
||||
};
|
||||
let failureOutput = false;
|
||||
self.fail = function fail(msg, err) {
|
||||
const logger = yargs.getInternalMethods().getLoggerInstance();
|
||||
if (fails.length) {
|
||||
for (let i = fails.length - 1; i >= 0; --i) {
|
||||
const fail = fails[i];
|
||||
if (isBoolean(fail)) {
|
||||
if (err)
|
||||
throw err;
|
||||
else if (msg)
|
||||
throw Error(msg);
|
||||
}
|
||||
else {
|
||||
fail(msg, err, self);
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (yargs.getExitProcess())
|
||||
setBlocking(true);
|
||||
if (!failureOutput) {
|
||||
failureOutput = true;
|
||||
if (showHelpOnFail) {
|
||||
yargs.showHelp('error');
|
||||
logger.error();
|
||||
}
|
||||
if (msg || err)
|
||||
logger.error(msg || err);
|
||||
const globalOrCommandFailMessage = failMessage || globalFailMessage;
|
||||
if (globalOrCommandFailMessage) {
|
||||
if (msg || err)
|
||||
logger.error('');
|
||||
logger.error(globalOrCommandFailMessage);
|
||||
}
|
||||
}
|
||||
err = err || new YError(msg);
|
||||
if (yargs.getExitProcess()) {
|
||||
return yargs.exit(1);
|
||||
}
|
||||
else if (yargs.getInternalMethods().hasParseCallback()) {
|
||||
return yargs.exit(1, err);
|
||||
}
|
||||
else {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
};
|
||||
let usages = [];
|
||||
let usageDisabled = false;
|
||||
self.usage = (msg, description) => {
|
||||
if (msg === null) {
|
||||
usageDisabled = true;
|
||||
usages = [];
|
||||
return self;
|
||||
}
|
||||
usageDisabled = false;
|
||||
usages.push([msg, description || '']);
|
||||
return self;
|
||||
};
|
||||
self.getUsage = () => {
|
||||
return usages;
|
||||
};
|
||||
self.getUsageDisabled = () => {
|
||||
return usageDisabled;
|
||||
};
|
||||
self.getPositionalGroupName = () => {
|
||||
return __('Positionals:');
|
||||
};
|
||||
let examples = [];
|
||||
self.example = (cmd, description) => {
|
||||
examples.push([cmd, description || '']);
|
||||
};
|
||||
let commands = [];
|
||||
self.command = function command(cmd, description, isDefault, aliases, deprecated = false) {
|
||||
if (isDefault) {
|
||||
commands = commands.map(cmdArray => {
|
||||
cmdArray[2] = false;
|
||||
return cmdArray;
|
||||
});
|
||||
}
|
||||
commands.push([cmd, description || '', isDefault, aliases, deprecated]);
|
||||
};
|
||||
self.getCommands = () => commands;
|
||||
let descriptions = {};
|
||||
self.describe = function describe(keyOrKeys, desc) {
|
||||
if (Array.isArray(keyOrKeys)) {
|
||||
keyOrKeys.forEach(k => {
|
||||
self.describe(k, desc);
|
||||
});
|
||||
}
|
||||
else if (typeof keyOrKeys === 'object') {
|
||||
Object.keys(keyOrKeys).forEach(k => {
|
||||
self.describe(k, keyOrKeys[k]);
|
||||
});
|
||||
}
|
||||
else {
|
||||
descriptions[keyOrKeys] = desc;
|
||||
}
|
||||
};
|
||||
self.getDescriptions = () => descriptions;
|
||||
let epilogs = [];
|
||||
self.epilog = msg => {
|
||||
epilogs.push(msg);
|
||||
};
|
||||
let wrapSet = false;
|
||||
let wrap;
|
||||
self.wrap = cols => {
|
||||
wrapSet = true;
|
||||
wrap = cols;
|
||||
};
|
||||
self.getWrap = () => {
|
||||
if (shim.getEnv('YARGS_DISABLE_WRAP')) {
|
||||
return null;
|
||||
}
|
||||
if (!wrapSet) {
|
||||
wrap = windowWidth();
|
||||
wrapSet = true;
|
||||
}
|
||||
return wrap;
|
||||
};
|
||||
const deferY18nLookupPrefix = '__yargsString__:';
|
||||
self.deferY18nLookup = str => deferY18nLookupPrefix + str;
|
||||
self.help = function help() {
|
||||
if (cachedHelpMessage)
|
||||
return cachedHelpMessage;
|
||||
normalizeAliases();
|
||||
const base$0 = yargs.customScriptName
|
||||
? yargs.$0
|
||||
: shim.path.basename(yargs.$0);
|
||||
const demandedOptions = yargs.getDemandedOptions();
|
||||
const demandedCommands = yargs.getDemandedCommands();
|
||||
const deprecatedOptions = yargs.getDeprecatedOptions();
|
||||
const groups = yargs.getGroups();
|
||||
const options = yargs.getOptions();
|
||||
let keys = [];
|
||||
keys = keys.concat(Object.keys(descriptions));
|
||||
keys = keys.concat(Object.keys(demandedOptions));
|
||||
keys = keys.concat(Object.keys(demandedCommands));
|
||||
keys = keys.concat(Object.keys(options.default));
|
||||
keys = keys.filter(filterHiddenOptions);
|
||||
keys = Object.keys(keys.reduce((acc, key) => {
|
||||
if (key !== '_')
|
||||
acc[key] = true;
|
||||
return acc;
|
||||
}, {}));
|
||||
const theWrap = self.getWrap();
|
||||
const ui = shim.cliui({
|
||||
width: theWrap,
|
||||
wrap: !!theWrap,
|
||||
});
|
||||
if (!usageDisabled) {
|
||||
if (usages.length) {
|
||||
usages.forEach(usage => {
|
||||
ui.div({ text: `${usage[0].replace(/\$0/g, base$0)}` });
|
||||
if (usage[1]) {
|
||||
ui.div({ text: `${usage[1]}`, padding: [1, 0, 0, 0] });
|
||||
}
|
||||
});
|
||||
ui.div();
|
||||
}
|
||||
else if (commands.length) {
|
||||
let u = null;
|
||||
if (demandedCommands._) {
|
||||
u = `${base$0} <${__('command')}>\n`;
|
||||
}
|
||||
else {
|
||||
u = `${base$0} [${__('command')}]\n`;
|
||||
}
|
||||
ui.div(`${u}`);
|
||||
}
|
||||
}
|
||||
if (commands.length > 1 || (commands.length === 1 && !commands[0][2])) {
|
||||
ui.div(__('Commands:'));
|
||||
const context = yargs.getInternalMethods().getContext();
|
||||
const parentCommands = context.commands.length
|
||||
? `${context.commands.join(' ')} `
|
||||
: '';
|
||||
if (yargs.getInternalMethods().getParserConfiguration()['sort-commands'] ===
|
||||
true) {
|
||||
commands = commands.sort((a, b) => a[0].localeCompare(b[0]));
|
||||
}
|
||||
const prefix = base$0 ? `${base$0} ` : '';
|
||||
commands.forEach(command => {
|
||||
const commandString = `${prefix}${parentCommands}${command[0].replace(/^\$0 ?/, '')}`;
|
||||
ui.span({
|
||||
text: commandString,
|
||||
padding: [0, 2, 0, 2],
|
||||
width: maxWidth(commands, theWrap, `${base$0}${parentCommands}`) + 4,
|
||||
}, { text: command[1] });
|
||||
const hints = [];
|
||||
if (command[2])
|
||||
hints.push(`[${__('default')}]`);
|
||||
if (command[3] && command[3].length) {
|
||||
hints.push(`[${__('aliases:')} ${command[3].join(', ')}]`);
|
||||
}
|
||||
if (command[4]) {
|
||||
if (typeof command[4] === 'string') {
|
||||
hints.push(`[${__('deprecated: %s', command[4])}]`);
|
||||
}
|
||||
else {
|
||||
hints.push(`[${__('deprecated')}]`);
|
||||
}
|
||||
}
|
||||
if (hints.length) {
|
||||
ui.div({
|
||||
text: hints.join(' '),
|
||||
padding: [0, 0, 0, 2],
|
||||
align: 'right',
|
||||
});
|
||||
}
|
||||
else {
|
||||
ui.div();
|
||||
}
|
||||
});
|
||||
ui.div();
|
||||
}
|
||||
const aliasKeys = (Object.keys(options.alias) || []).concat(Object.keys(yargs.parsed.newAliases) || []);
|
||||
keys = keys.filter(key => !yargs.parsed.newAliases[key] &&
|
||||
aliasKeys.every(alias => (options.alias[alias] || []).indexOf(key) === -1));
|
||||
const defaultGroup = __('Options:');
|
||||
if (!groups[defaultGroup])
|
||||
groups[defaultGroup] = [];
|
||||
addUngroupedKeys(keys, options.alias, groups, defaultGroup);
|
||||
const isLongSwitch = (sw) => /^--/.test(getText(sw));
|
||||
const displayedGroups = Object.keys(groups)
|
||||
.filter(groupName => groups[groupName].length > 0)
|
||||
.map(groupName => {
|
||||
const normalizedKeys = groups[groupName]
|
||||
.filter(filterHiddenOptions)
|
||||
.map(key => {
|
||||
if (aliasKeys.includes(key))
|
||||
return key;
|
||||
for (let i = 0, aliasKey; (aliasKey = aliasKeys[i]) !== undefined; i++) {
|
||||
if ((options.alias[aliasKey] || []).includes(key))
|
||||
return aliasKey;
|
||||
}
|
||||
return key;
|
||||
});
|
||||
return { groupName, normalizedKeys };
|
||||
})
|
||||
.filter(({ normalizedKeys }) => normalizedKeys.length > 0)
|
||||
.map(({ groupName, normalizedKeys }) => {
|
||||
const switches = normalizedKeys.reduce((acc, key) => {
|
||||
acc[key] = [key]
|
||||
.concat(options.alias[key] || [])
|
||||
.map(sw => {
|
||||
if (groupName === self.getPositionalGroupName())
|
||||
return sw;
|
||||
else {
|
||||
return ((/^[0-9]$/.test(sw)
|
||||
? options.boolean.includes(key)
|
||||
? '-'
|
||||
: '--'
|
||||
: sw.length > 1
|
||||
? '--'
|
||||
: '-') + sw);
|
||||
}
|
||||
})
|
||||
.sort((sw1, sw2) => isLongSwitch(sw1) === isLongSwitch(sw2)
|
||||
? 0
|
||||
: isLongSwitch(sw1)
|
||||
? 1
|
||||
: -1)
|
||||
.join(', ');
|
||||
return acc;
|
||||
}, {});
|
||||
return { groupName, normalizedKeys, switches };
|
||||
});
|
||||
const shortSwitchesUsed = displayedGroups
|
||||
.filter(({ groupName }) => groupName !== self.getPositionalGroupName())
|
||||
.some(({ normalizedKeys, switches }) => !normalizedKeys.every(key => isLongSwitch(switches[key])));
|
||||
if (shortSwitchesUsed) {
|
||||
displayedGroups
|
||||
.filter(({ groupName }) => groupName !== self.getPositionalGroupName())
|
||||
.forEach(({ normalizedKeys, switches }) => {
|
||||
normalizedKeys.forEach(key => {
|
||||
if (isLongSwitch(switches[key])) {
|
||||
switches[key] = addIndentation(switches[key], '-x, '.length);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
displayedGroups.forEach(({ groupName, normalizedKeys, switches }) => {
|
||||
ui.div(groupName);
|
||||
normalizedKeys.forEach(key => {
|
||||
const kswitch = switches[key];
|
||||
let desc = descriptions[key] || '';
|
||||
let type = null;
|
||||
if (desc.includes(deferY18nLookupPrefix))
|
||||
desc = __(desc.substring(deferY18nLookupPrefix.length));
|
||||
if (options.boolean.includes(key))
|
||||
type = `[${__('boolean')}]`;
|
||||
if (options.count.includes(key))
|
||||
type = `[${__('count')}]`;
|
||||
if (options.string.includes(key))
|
||||
type = `[${__('string')}]`;
|
||||
if (options.normalize.includes(key))
|
||||
type = `[${__('string')}]`;
|
||||
if (options.array.includes(key))
|
||||
type = `[${__('array')}]`;
|
||||
if (options.number.includes(key))
|
||||
type = `[${__('number')}]`;
|
||||
const deprecatedExtra = (deprecated) => typeof deprecated === 'string'
|
||||
? `[${__('deprecated: %s', deprecated)}]`
|
||||
: `[${__('deprecated')}]`;
|
||||
const extra = [
|
||||
key in deprecatedOptions
|
||||
? deprecatedExtra(deprecatedOptions[key])
|
||||
: null,
|
||||
type,
|
||||
key in demandedOptions ? `[${__('required')}]` : null,
|
||||
options.choices && options.choices[key]
|
||||
? `[${__('choices:')} ${self.stringifiedValues(options.choices[key])}]`
|
||||
: null,
|
||||
defaultString(options.default[key], options.defaultDescription[key]),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' ');
|
||||
ui.span({
|
||||
text: getText(kswitch),
|
||||
padding: [0, 2, 0, 2 + getIndentation(kswitch)],
|
||||
width: maxWidth(switches, theWrap) + 4,
|
||||
}, desc);
|
||||
const shouldHideOptionExtras = yargs.getInternalMethods().getUsageConfiguration()['hide-types'] ===
|
||||
true;
|
||||
if (extra && !shouldHideOptionExtras)
|
||||
ui.div({ text: extra, padding: [0, 0, 0, 2], align: 'right' });
|
||||
else
|
||||
ui.div();
|
||||
});
|
||||
ui.div();
|
||||
});
|
||||
if (examples.length) {
|
||||
ui.div(__('Examples:'));
|
||||
examples.forEach(example => {
|
||||
example[0] = example[0].replace(/\$0/g, base$0);
|
||||
});
|
||||
examples.forEach(example => {
|
||||
if (example[1] === '') {
|
||||
ui.div({
|
||||
text: example[0],
|
||||
padding: [0, 2, 0, 2],
|
||||
});
|
||||
}
|
||||
else {
|
||||
ui.div({
|
||||
text: example[0],
|
||||
padding: [0, 2, 0, 2],
|
||||
width: maxWidth(examples, theWrap) + 4,
|
||||
}, {
|
||||
text: example[1],
|
||||
});
|
||||
}
|
||||
});
|
||||
ui.div();
|
||||
}
|
||||
if (epilogs.length > 0) {
|
||||
const e = epilogs
|
||||
.map(epilog => epilog.replace(/\$0/g, base$0))
|
||||
.join('\n');
|
||||
ui.div(`${e}\n`);
|
||||
}
|
||||
return ui.toString().replace(/\s*$/, '');
|
||||
};
|
||||
function maxWidth(table, theWrap, modifier) {
|
||||
let width = 0;
|
||||
if (!Array.isArray(table)) {
|
||||
table = Object.values(table).map(v => [v]);
|
||||
}
|
||||
table.forEach(v => {
|
||||
width = Math.max(shim.stringWidth(modifier ? `${modifier} ${getText(v[0])}` : getText(v[0])) + getIndentation(v[0]), width);
|
||||
});
|
||||
if (theWrap)
|
||||
width = Math.min(width, parseInt((theWrap * 0.5).toString(), 10));
|
||||
return width;
|
||||
}
|
||||
function normalizeAliases() {
|
||||
const demandedOptions = yargs.getDemandedOptions();
|
||||
const options = yargs.getOptions();
|
||||
(Object.keys(options.alias) || []).forEach(key => {
|
||||
options.alias[key].forEach(alias => {
|
||||
if (descriptions[alias])
|
||||
self.describe(key, descriptions[alias]);
|
||||
if (alias in demandedOptions)
|
||||
yargs.demandOption(key, demandedOptions[alias]);
|
||||
if (options.boolean.includes(alias))
|
||||
yargs.boolean(key);
|
||||
if (options.count.includes(alias))
|
||||
yargs.count(key);
|
||||
if (options.string.includes(alias))
|
||||
yargs.string(key);
|
||||
if (options.normalize.includes(alias))
|
||||
yargs.normalize(key);
|
||||
if (options.array.includes(alias))
|
||||
yargs.array(key);
|
||||
if (options.number.includes(alias))
|
||||
yargs.number(key);
|
||||
});
|
||||
});
|
||||
}
|
||||
let cachedHelpMessage;
|
||||
self.cacheHelpMessage = function () {
|
||||
cachedHelpMessage = this.help();
|
||||
};
|
||||
self.clearCachedHelpMessage = function () {
|
||||
cachedHelpMessage = undefined;
|
||||
};
|
||||
self.hasCachedHelpMessage = function () {
|
||||
return !!cachedHelpMessage;
|
||||
};
|
||||
function addUngroupedKeys(keys, aliases, groups, defaultGroup) {
|
||||
let groupedKeys = [];
|
||||
let toCheck = null;
|
||||
Object.keys(groups).forEach(group => {
|
||||
groupedKeys = groupedKeys.concat(groups[group]);
|
||||
});
|
||||
keys.forEach(key => {
|
||||
toCheck = [key].concat(aliases[key]);
|
||||
if (!toCheck.some(k => groupedKeys.indexOf(k) !== -1)) {
|
||||
groups[defaultGroup].push(key);
|
||||
}
|
||||
});
|
||||
return groupedKeys;
|
||||
}
|
||||
function filterHiddenOptions(key) {
|
||||
return (yargs.getOptions().hiddenOptions.indexOf(key) < 0 ||
|
||||
yargs.parsed.argv[yargs.getOptions().showHiddenOpt]);
|
||||
}
|
||||
self.showHelp = (level) => {
|
||||
const logger = yargs.getInternalMethods().getLoggerInstance();
|
||||
if (!level)
|
||||
level = 'error';
|
||||
const emit = typeof level === 'function' ? level : logger[level];
|
||||
emit(self.help());
|
||||
};
|
||||
self.functionDescription = fn => {
|
||||
const description = fn.name
|
||||
? shim.Parser.decamelize(fn.name, '-')
|
||||
: __('generated-value');
|
||||
return ['(', description, ')'].join('');
|
||||
};
|
||||
self.stringifiedValues = function stringifiedValues(values, separator) {
|
||||
let string = '';
|
||||
const sep = separator || ', ';
|
||||
const array = [].concat(values);
|
||||
if (!values || !array.length)
|
||||
return string;
|
||||
array.forEach(value => {
|
||||
if (string.length)
|
||||
string += sep;
|
||||
string += JSON.stringify(value);
|
||||
});
|
||||
return string;
|
||||
};
|
||||
function defaultString(value, defaultDescription) {
|
||||
let string = `[${__('default:')} `;
|
||||
if (value === undefined && !defaultDescription)
|
||||
return null;
|
||||
if (defaultDescription) {
|
||||
string += defaultDescription;
|
||||
}
|
||||
else {
|
||||
switch (typeof value) {
|
||||
case 'string':
|
||||
string += `"${value}"`;
|
||||
break;
|
||||
case 'object':
|
||||
string += JSON.stringify(value);
|
||||
break;
|
||||
default:
|
||||
string += value;
|
||||
}
|
||||
}
|
||||
return `${string}]`;
|
||||
}
|
||||
function windowWidth() {
|
||||
const maxWidth = 80;
|
||||
if (shim.process.stdColumns) {
|
||||
return Math.min(maxWidth, shim.process.stdColumns);
|
||||
}
|
||||
else {
|
||||
return maxWidth;
|
||||
}
|
||||
}
|
||||
let version = null;
|
||||
self.version = ver => {
|
||||
version = ver;
|
||||
};
|
||||
self.showVersion = level => {
|
||||
const logger = yargs.getInternalMethods().getLoggerInstance();
|
||||
if (!level)
|
||||
level = 'error';
|
||||
const emit = typeof level === 'function' ? level : logger[level];
|
||||
emit(version);
|
||||
};
|
||||
self.reset = function reset(localLookup) {
|
||||
failMessage = null;
|
||||
failureOutput = false;
|
||||
usages = [];
|
||||
usageDisabled = false;
|
||||
epilogs = [];
|
||||
examples = [];
|
||||
commands = [];
|
||||
descriptions = objFilter(descriptions, k => !localLookup[k]);
|
||||
return self;
|
||||
};
|
||||
const frozens = [];
|
||||
self.freeze = function freeze() {
|
||||
frozens.push({
|
||||
failMessage,
|
||||
failureOutput,
|
||||
usages,
|
||||
usageDisabled,
|
||||
epilogs,
|
||||
examples,
|
||||
commands,
|
||||
descriptions,
|
||||
});
|
||||
};
|
||||
self.unfreeze = function unfreeze(defaultCommand = false) {
|
||||
const frozen = frozens.pop();
|
||||
if (!frozen)
|
||||
return;
|
||||
if (defaultCommand) {
|
||||
descriptions = { ...frozen.descriptions, ...descriptions };
|
||||
commands = [...frozen.commands, ...commands];
|
||||
usages = [...frozen.usages, ...usages];
|
||||
examples = [...frozen.examples, ...examples];
|
||||
epilogs = [...frozen.epilogs, ...epilogs];
|
||||
}
|
||||
else {
|
||||
({
|
||||
failMessage,
|
||||
failureOutput,
|
||||
usages,
|
||||
usageDisabled,
|
||||
epilogs,
|
||||
examples,
|
||||
commands,
|
||||
descriptions,
|
||||
} = frozen);
|
||||
}
|
||||
};
|
||||
return self;
|
||||
}
|
||||
function isIndentedText(text) {
|
||||
return typeof text === 'object';
|
||||
}
|
||||
function addIndentation(text, indent) {
|
||||
return isIndentedText(text)
|
||||
? { text: text.text, indentation: text.indentation + indent }
|
||||
: { text, indentation: indent };
|
||||
}
|
||||
function getIndentation(text) {
|
||||
return isIndentedText(text) ? text.indentation : 0;
|
||||
}
|
||||
function getText(text) {
|
||||
return isIndentedText(text) ? text.text : text;
|
||||
}
|
||||
59
electron/node_modules/yargs/build/lib/utils/apply-extends.js
generated
vendored
Normal file
59
electron/node_modules/yargs/build/lib/utils/apply-extends.js
generated
vendored
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
import { YError } from '../yerror.js';
|
||||
let previouslyVisitedConfigs = [];
|
||||
let shim;
|
||||
export function applyExtends(config, cwd, mergeExtends, _shim) {
|
||||
shim = _shim;
|
||||
let defaultConfig = {};
|
||||
if (Object.prototype.hasOwnProperty.call(config, 'extends')) {
|
||||
if (typeof config.extends !== 'string')
|
||||
return defaultConfig;
|
||||
const isPath = /\.json|\..*rc$/.test(config.extends);
|
||||
let pathToDefault = null;
|
||||
if (!isPath) {
|
||||
try {
|
||||
pathToDefault = require.resolve(config.extends);
|
||||
}
|
||||
catch (_err) {
|
||||
return config;
|
||||
}
|
||||
}
|
||||
else {
|
||||
pathToDefault = getPathToDefaultConfig(cwd, config.extends);
|
||||
}
|
||||
checkForCircularExtends(pathToDefault);
|
||||
previouslyVisitedConfigs.push(pathToDefault);
|
||||
defaultConfig = isPath
|
||||
? JSON.parse(shim.readFileSync(pathToDefault, 'utf8'))
|
||||
: require(config.extends);
|
||||
delete config.extends;
|
||||
defaultConfig = applyExtends(defaultConfig, shim.path.dirname(pathToDefault), mergeExtends, shim);
|
||||
}
|
||||
previouslyVisitedConfigs = [];
|
||||
return mergeExtends
|
||||
? mergeDeep(defaultConfig, config)
|
||||
: Object.assign({}, defaultConfig, config);
|
||||
}
|
||||
function checkForCircularExtends(cfgPath) {
|
||||
if (previouslyVisitedConfigs.indexOf(cfgPath) > -1) {
|
||||
throw new YError(`Circular extended configurations: '${cfgPath}'.`);
|
||||
}
|
||||
}
|
||||
function getPathToDefaultConfig(cwd, pathToExtend) {
|
||||
return shim.path.resolve(cwd, pathToExtend);
|
||||
}
|
||||
function mergeDeep(config1, config2) {
|
||||
const target = {};
|
||||
function isObject(obj) {
|
||||
return obj && typeof obj === 'object' && !Array.isArray(obj);
|
||||
}
|
||||
Object.assign(target, config1);
|
||||
for (const key of Object.keys(config2)) {
|
||||
if (isObject(config2[key]) && isObject(target[key])) {
|
||||
target[key] = mergeDeep(config1[key], config2[key]);
|
||||
}
|
||||
else {
|
||||
target[key] = config2[key];
|
||||
}
|
||||
}
|
||||
return target;
|
||||
}
|
||||
5
electron/node_modules/yargs/build/lib/utils/is-promise.js
generated
vendored
Normal file
5
electron/node_modules/yargs/build/lib/utils/is-promise.js
generated
vendored
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
export function isPromise(maybePromise) {
|
||||
return (!!maybePromise &&
|
||||
!!maybePromise.then &&
|
||||
typeof maybePromise.then === 'function');
|
||||
}
|
||||
34
electron/node_modules/yargs/build/lib/utils/levenshtein.js
generated
vendored
Normal file
34
electron/node_modules/yargs/build/lib/utils/levenshtein.js
generated
vendored
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
export function levenshtein(a, b) {
|
||||
if (a.length === 0)
|
||||
return b.length;
|
||||
if (b.length === 0)
|
||||
return a.length;
|
||||
const matrix = [];
|
||||
let i;
|
||||
for (i = 0; i <= b.length; i++) {
|
||||
matrix[i] = [i];
|
||||
}
|
||||
let j;
|
||||
for (j = 0; j <= a.length; j++) {
|
||||
matrix[0][j] = j;
|
||||
}
|
||||
for (i = 1; i <= b.length; i++) {
|
||||
for (j = 1; j <= a.length; j++) {
|
||||
if (b.charAt(i - 1) === a.charAt(j - 1)) {
|
||||
matrix[i][j] = matrix[i - 1][j - 1];
|
||||
}
|
||||
else {
|
||||
if (i > 1 &&
|
||||
j > 1 &&
|
||||
b.charAt(i - 2) === a.charAt(j - 1) &&
|
||||
b.charAt(i - 1) === a.charAt(j - 2)) {
|
||||
matrix[i][j] = matrix[i - 2][j - 2] + 1;
|
||||
}
|
||||
else {
|
||||
matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, Math.min(matrix[i][j - 1] + 1, matrix[i - 1][j] + 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return matrix[b.length][a.length];
|
||||
}
|
||||
17
electron/node_modules/yargs/build/lib/utils/maybe-async-result.js
generated
vendored
Normal file
17
electron/node_modules/yargs/build/lib/utils/maybe-async-result.js
generated
vendored
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
import { isPromise } from './is-promise.js';
|
||||
export function maybeAsyncResult(getResult, resultHandler, errorHandler = (err) => {
|
||||
throw err;
|
||||
}) {
|
||||
try {
|
||||
const result = isFunction(getResult) ? getResult() : getResult;
|
||||
return isPromise(result)
|
||||
? result.then((result) => resultHandler(result))
|
||||
: resultHandler(result);
|
||||
}
|
||||
catch (err) {
|
||||
return errorHandler(err);
|
||||
}
|
||||
}
|
||||
function isFunction(arg) {
|
||||
return typeof arg === 'function';
|
||||
}
|
||||
10
electron/node_modules/yargs/build/lib/utils/obj-filter.js
generated
vendored
Normal file
10
electron/node_modules/yargs/build/lib/utils/obj-filter.js
generated
vendored
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
import { objectKeys } from '../typings/common-types.js';
|
||||
export function objFilter(original = {}, filter = () => true) {
|
||||
const obj = {};
|
||||
objectKeys(original).forEach(key => {
|
||||
if (filter(key, original[key])) {
|
||||
obj[key] = original[key];
|
||||
}
|
||||
});
|
||||
return obj;
|
||||
}
|
||||
17
electron/node_modules/yargs/build/lib/utils/process-argv.js
generated
vendored
Normal file
17
electron/node_modules/yargs/build/lib/utils/process-argv.js
generated
vendored
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
function getProcessArgvBinIndex() {
|
||||
if (isBundledElectronApp())
|
||||
return 0;
|
||||
return 1;
|
||||
}
|
||||
function isBundledElectronApp() {
|
||||
return isElectronApp() && !process.defaultApp;
|
||||
}
|
||||
function isElectronApp() {
|
||||
return !!process.versions.electron;
|
||||
}
|
||||
export function hideBin(argv) {
|
||||
return argv.slice(getProcessArgvBinIndex() + 1);
|
||||
}
|
||||
export function getProcessArgvBin() {
|
||||
return process.argv[getProcessArgvBinIndex()];
|
||||
}
|
||||
12
electron/node_modules/yargs/build/lib/utils/set-blocking.js
generated
vendored
Normal file
12
electron/node_modules/yargs/build/lib/utils/set-blocking.js
generated
vendored
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
export default function setBlocking(blocking) {
|
||||
if (typeof process === 'undefined')
|
||||
return;
|
||||
[process.stdout, process.stderr].forEach(_stream => {
|
||||
const stream = _stream;
|
||||
if (stream._handle &&
|
||||
stream.isTTY &&
|
||||
typeof stream._handle.setBlocking === 'function') {
|
||||
stream._handle.setBlocking(blocking);
|
||||
}
|
||||
});
|
||||
}
|
||||
10
electron/node_modules/yargs/build/lib/utils/which-module.js
generated
vendored
Normal file
10
electron/node_modules/yargs/build/lib/utils/which-module.js
generated
vendored
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
export default function whichModule(exported) {
|
||||
if (typeof require === 'undefined')
|
||||
return null;
|
||||
for (let i = 0, files = Object.keys(require.cache), mod; i < files.length; i++) {
|
||||
mod = require.cache[files[i]];
|
||||
if (mod.exports === exported)
|
||||
return mod;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
305
electron/node_modules/yargs/build/lib/validation.js
generated
vendored
Normal file
305
electron/node_modules/yargs/build/lib/validation.js
generated
vendored
Normal file
|
|
@ -0,0 +1,305 @@
|
|||
import { argsert } from './argsert.js';
|
||||
import { assertNotStrictEqual, } from './typings/common-types.js';
|
||||
import { levenshtein as distance } from './utils/levenshtein.js';
|
||||
import { objFilter } from './utils/obj-filter.js';
|
||||
const specialKeys = ['$0', '--', '_'];
|
||||
export function validation(yargs, usage, shim) {
|
||||
const __ = shim.y18n.__;
|
||||
const __n = shim.y18n.__n;
|
||||
const self = {};
|
||||
self.nonOptionCount = function nonOptionCount(argv) {
|
||||
const demandedCommands = yargs.getDemandedCommands();
|
||||
const positionalCount = argv._.length + (argv['--'] ? argv['--'].length : 0);
|
||||
const _s = positionalCount - yargs.getInternalMethods().getContext().commands.length;
|
||||
if (demandedCommands._ &&
|
||||
(_s < demandedCommands._.min || _s > demandedCommands._.max)) {
|
||||
if (_s < demandedCommands._.min) {
|
||||
if (demandedCommands._.minMsg !== undefined) {
|
||||
usage.fail(demandedCommands._.minMsg
|
||||
? demandedCommands._.minMsg
|
||||
.replace(/\$0/g, _s.toString())
|
||||
.replace(/\$1/, demandedCommands._.min.toString())
|
||||
: null);
|
||||
}
|
||||
else {
|
||||
usage.fail(__n('Not enough non-option arguments: got %s, need at least %s', 'Not enough non-option arguments: got %s, need at least %s', _s, _s.toString(), demandedCommands._.min.toString()));
|
||||
}
|
||||
}
|
||||
else if (_s > demandedCommands._.max) {
|
||||
if (demandedCommands._.maxMsg !== undefined) {
|
||||
usage.fail(demandedCommands._.maxMsg
|
||||
? demandedCommands._.maxMsg
|
||||
.replace(/\$0/g, _s.toString())
|
||||
.replace(/\$1/, demandedCommands._.max.toString())
|
||||
: null);
|
||||
}
|
||||
else {
|
||||
usage.fail(__n('Too many non-option arguments: got %s, maximum of %s', 'Too many non-option arguments: got %s, maximum of %s', _s, _s.toString(), demandedCommands._.max.toString()));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
self.positionalCount = function positionalCount(required, observed) {
|
||||
if (observed < required) {
|
||||
usage.fail(__n('Not enough non-option arguments: got %s, need at least %s', 'Not enough non-option arguments: got %s, need at least %s', observed, observed + '', required + ''));
|
||||
}
|
||||
};
|
||||
self.requiredArguments = function requiredArguments(argv, demandedOptions) {
|
||||
let missing = null;
|
||||
for (const key of Object.keys(demandedOptions)) {
|
||||
if (!Object.prototype.hasOwnProperty.call(argv, key) ||
|
||||
typeof argv[key] === 'undefined') {
|
||||
missing = missing || {};
|
||||
missing[key] = demandedOptions[key];
|
||||
}
|
||||
}
|
||||
if (missing) {
|
||||
const customMsgs = [];
|
||||
for (const key of Object.keys(missing)) {
|
||||
const msg = missing[key];
|
||||
if (msg && customMsgs.indexOf(msg) < 0) {
|
||||
customMsgs.push(msg);
|
||||
}
|
||||
}
|
||||
const customMsg = customMsgs.length ? `\n${customMsgs.join('\n')}` : '';
|
||||
usage.fail(__n('Missing required argument: %s', 'Missing required arguments: %s', Object.keys(missing).length, Object.keys(missing).join(', ') + customMsg));
|
||||
}
|
||||
};
|
||||
self.unknownArguments = function unknownArguments(argv, aliases, positionalMap, isDefaultCommand, checkPositionals = true) {
|
||||
var _a;
|
||||
const commandKeys = yargs
|
||||
.getInternalMethods()
|
||||
.getCommandInstance()
|
||||
.getCommands();
|
||||
const unknown = [];
|
||||
const currentContext = yargs.getInternalMethods().getContext();
|
||||
Object.keys(argv).forEach(key => {
|
||||
if (!specialKeys.includes(key) &&
|
||||
!Object.prototype.hasOwnProperty.call(positionalMap, key) &&
|
||||
!Object.prototype.hasOwnProperty.call(yargs.getInternalMethods().getParseContext(), key) &&
|
||||
!self.isValidAndSomeAliasIsNotNew(key, aliases)) {
|
||||
unknown.push(key);
|
||||
}
|
||||
});
|
||||
if (checkPositionals &&
|
||||
(currentContext.commands.length > 0 ||
|
||||
commandKeys.length > 0 ||
|
||||
isDefaultCommand)) {
|
||||
argv._.slice(currentContext.commands.length).forEach(key => {
|
||||
if (!commandKeys.includes('' + key)) {
|
||||
unknown.push('' + key);
|
||||
}
|
||||
});
|
||||
}
|
||||
if (checkPositionals) {
|
||||
const demandedCommands = yargs.getDemandedCommands();
|
||||
const maxNonOptDemanded = ((_a = demandedCommands._) === null || _a === void 0 ? void 0 : _a.max) || 0;
|
||||
const expected = currentContext.commands.length + maxNonOptDemanded;
|
||||
if (expected < argv._.length) {
|
||||
argv._.slice(expected).forEach(key => {
|
||||
key = String(key);
|
||||
if (!currentContext.commands.includes(key) &&
|
||||
!unknown.includes(key)) {
|
||||
unknown.push(key);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
if (unknown.length) {
|
||||
usage.fail(__n('Unknown argument: %s', 'Unknown arguments: %s', unknown.length, unknown.map(s => (s.trim() ? s : `"${s}"`)).join(', ')));
|
||||
}
|
||||
};
|
||||
self.unknownCommands = function unknownCommands(argv) {
|
||||
const commandKeys = yargs
|
||||
.getInternalMethods()
|
||||
.getCommandInstance()
|
||||
.getCommands();
|
||||
const unknown = [];
|
||||
const currentContext = yargs.getInternalMethods().getContext();
|
||||
if (currentContext.commands.length > 0 || commandKeys.length > 0) {
|
||||
argv._.slice(currentContext.commands.length).forEach(key => {
|
||||
if (!commandKeys.includes('' + key)) {
|
||||
unknown.push('' + key);
|
||||
}
|
||||
});
|
||||
}
|
||||
if (unknown.length > 0) {
|
||||
usage.fail(__n('Unknown command: %s', 'Unknown commands: %s', unknown.length, unknown.join(', ')));
|
||||
return true;
|
||||
}
|
||||
else {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
self.isValidAndSomeAliasIsNotNew = function isValidAndSomeAliasIsNotNew(key, aliases) {
|
||||
if (!Object.prototype.hasOwnProperty.call(aliases, key)) {
|
||||
return false;
|
||||
}
|
||||
const newAliases = yargs.parsed.newAliases;
|
||||
return [key, ...aliases[key]].some(a => !Object.prototype.hasOwnProperty.call(newAliases, a) || !newAliases[key]);
|
||||
};
|
||||
self.limitedChoices = function limitedChoices(argv) {
|
||||
const options = yargs.getOptions();
|
||||
const invalid = {};
|
||||
if (!Object.keys(options.choices).length)
|
||||
return;
|
||||
Object.keys(argv).forEach(key => {
|
||||
if (specialKeys.indexOf(key) === -1 &&
|
||||
Object.prototype.hasOwnProperty.call(options.choices, key)) {
|
||||
[].concat(argv[key]).forEach(value => {
|
||||
if (options.choices[key].indexOf(value) === -1 &&
|
||||
value !== undefined) {
|
||||
invalid[key] = (invalid[key] || []).concat(value);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
const invalidKeys = Object.keys(invalid);
|
||||
if (!invalidKeys.length)
|
||||
return;
|
||||
let msg = __('Invalid values:');
|
||||
invalidKeys.forEach(key => {
|
||||
msg += `\n ${__('Argument: %s, Given: %s, Choices: %s', key, usage.stringifiedValues(invalid[key]), usage.stringifiedValues(options.choices[key]))}`;
|
||||
});
|
||||
usage.fail(msg);
|
||||
};
|
||||
let implied = {};
|
||||
self.implies = function implies(key, value) {
|
||||
argsert('<string|object> [array|number|string]', [key, value], arguments.length);
|
||||
if (typeof key === 'object') {
|
||||
Object.keys(key).forEach(k => {
|
||||
self.implies(k, key[k]);
|
||||
});
|
||||
}
|
||||
else {
|
||||
yargs.global(key);
|
||||
if (!implied[key]) {
|
||||
implied[key] = [];
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach(i => self.implies(key, i));
|
||||
}
|
||||
else {
|
||||
assertNotStrictEqual(value, undefined, shim);
|
||||
implied[key].push(value);
|
||||
}
|
||||
}
|
||||
};
|
||||
self.getImplied = function getImplied() {
|
||||
return implied;
|
||||
};
|
||||
function keyExists(argv, val) {
|
||||
const num = Number(val);
|
||||
val = isNaN(num) ? val : num;
|
||||
if (typeof val === 'number') {
|
||||
val = argv._.length >= val;
|
||||
}
|
||||
else if (val.match(/^--no-.+/)) {
|
||||
val = val.match(/^--no-(.+)/)[1];
|
||||
val = !Object.prototype.hasOwnProperty.call(argv, val);
|
||||
}
|
||||
else {
|
||||
val = Object.prototype.hasOwnProperty.call(argv, val);
|
||||
}
|
||||
return val;
|
||||
}
|
||||
self.implications = function implications(argv) {
|
||||
const implyFail = [];
|
||||
Object.keys(implied).forEach(key => {
|
||||
const origKey = key;
|
||||
(implied[key] || []).forEach(value => {
|
||||
let key = origKey;
|
||||
const origValue = value;
|
||||
key = keyExists(argv, key);
|
||||
value = keyExists(argv, value);
|
||||
if (key && !value) {
|
||||
implyFail.push(` ${origKey} -> ${origValue}`);
|
||||
}
|
||||
});
|
||||
});
|
||||
if (implyFail.length) {
|
||||
let msg = `${__('Implications failed:')}\n`;
|
||||
implyFail.forEach(value => {
|
||||
msg += value;
|
||||
});
|
||||
usage.fail(msg);
|
||||
}
|
||||
};
|
||||
let conflicting = {};
|
||||
self.conflicts = function conflicts(key, value) {
|
||||
argsert('<string|object> [array|string]', [key, value], arguments.length);
|
||||
if (typeof key === 'object') {
|
||||
Object.keys(key).forEach(k => {
|
||||
self.conflicts(k, key[k]);
|
||||
});
|
||||
}
|
||||
else {
|
||||
yargs.global(key);
|
||||
if (!conflicting[key]) {
|
||||
conflicting[key] = [];
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach(i => self.conflicts(key, i));
|
||||
}
|
||||
else {
|
||||
conflicting[key].push(value);
|
||||
}
|
||||
}
|
||||
};
|
||||
self.getConflicting = () => conflicting;
|
||||
self.conflicting = function conflictingFn(argv) {
|
||||
Object.keys(argv).forEach(key => {
|
||||
if (conflicting[key]) {
|
||||
conflicting[key].forEach(value => {
|
||||
if (value && argv[key] !== undefined && argv[value] !== undefined) {
|
||||
usage.fail(__('Arguments %s and %s are mutually exclusive', key, value));
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
if (yargs.getInternalMethods().getParserConfiguration()['strip-dashed']) {
|
||||
Object.keys(conflicting).forEach(key => {
|
||||
conflicting[key].forEach(value => {
|
||||
if (value &&
|
||||
argv[shim.Parser.camelCase(key)] !== undefined &&
|
||||
argv[shim.Parser.camelCase(value)] !== undefined) {
|
||||
usage.fail(__('Arguments %s and %s are mutually exclusive', key, value));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
};
|
||||
self.recommendCommands = function recommendCommands(cmd, potentialCommands) {
|
||||
const threshold = 3;
|
||||
potentialCommands = potentialCommands.sort((a, b) => b.length - a.length);
|
||||
let recommended = null;
|
||||
let bestDistance = Infinity;
|
||||
for (let i = 0, candidate; (candidate = potentialCommands[i]) !== undefined; i++) {
|
||||
const d = distance(cmd, candidate);
|
||||
if (d <= threshold && d < bestDistance) {
|
||||
bestDistance = d;
|
||||
recommended = candidate;
|
||||
}
|
||||
}
|
||||
if (recommended)
|
||||
usage.fail(__('Did you mean %s?', recommended));
|
||||
};
|
||||
self.reset = function reset(localLookup) {
|
||||
implied = objFilter(implied, k => !localLookup[k]);
|
||||
conflicting = objFilter(conflicting, k => !localLookup[k]);
|
||||
return self;
|
||||
};
|
||||
const frozens = [];
|
||||
self.freeze = function freeze() {
|
||||
frozens.push({
|
||||
implied,
|
||||
conflicting,
|
||||
});
|
||||
};
|
||||
self.unfreeze = function unfreeze() {
|
||||
const frozen = frozens.pop();
|
||||
assertNotStrictEqual(frozen, undefined, shim);
|
||||
({ implied, conflicting } = frozen);
|
||||
};
|
||||
return self;
|
||||
}
|
||||
1512
electron/node_modules/yargs/build/lib/yargs-factory.js
generated
vendored
Normal file
1512
electron/node_modules/yargs/build/lib/yargs-factory.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load diff
9
electron/node_modules/yargs/build/lib/yerror.js
generated
vendored
Normal file
9
electron/node_modules/yargs/build/lib/yerror.js
generated
vendored
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
export class YError extends Error {
|
||||
constructor(msg) {
|
||||
super(msg || 'yargs error');
|
||||
this.name = 'YError';
|
||||
if (Error.captureStackTrace) {
|
||||
Error.captureStackTrace(this, YError);
|
||||
}
|
||||
}
|
||||
}
|
||||
1
node_modules/@capacitor/android/capacitor/build/.transforms/27bb921a5501919aa572f0b3b7a8c4f7/results.bin
generated
vendored
Normal file
1
node_modules/@capacitor/android/capacitor/build/.transforms/27bb921a5501919aa572f0b3b7a8c4f7/results.bin
generated
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
o/bundleLibRuntimeToDirDebug
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue