UNPKG

@cliz/cp

Version:

Online pbcopy + pbpaste

86 lines (85 loc) 2.76 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.copy = void 0; const cli_1 = require("@cliz/cli"); const md5_1 = require("@zodash/md5"); const random_1 = require("@zodash/random"); const websocket_1 = require("@znode/websocket"); const utils_1 = require("../utils"); const config_1 = require("../config"); const debug = require('debug')('cliz-cp'); async function copy(options) { var _a; const copiedData = await getCopyData(options.filepath); let encryptedText; let signature; if (!copiedData) { throw new Error('No Copied Data Found'); } const url = (_a = options === null || options === void 0 ? void 0 : options.relay) !== null && _a !== void 0 ? _a : config_1.default.server; return new Promise((resolve, reject) => { const ws = new websocket_1.Client(url); ws.on('connection', () => { debug('socket connect'); onConnect(); }); ws.on('close', (error) => { debug('socket close:', error); }); ws.on('error', (error) => { console.error('socket error:', error); ws.disconnect(); reject(error); }); ws.on('paste', ({ receiver }) => { return onPaste(receiver); }); ws.on('paste.done', ({ receiver }) => { ws.disconnect(); }); async function onConnect() { const code = (0, random_1.token)(); ws.emit('wait.receiver.request', { code, }); signature = (0, md5_1.md5)(copiedData); encryptedText = (0, utils_1.encrypt)(code, copiedData); debug(`Signature: ${signature}`); debug('=== copied data start ==='); debug(copiedData); debug('=== copied data end =='); resolve(code); } function onPaste(receiver) { ws.emit('sender.paste.to.receiver', { receiver, signature, payload: encryptedText, }); } }); } exports.copy = copy; async function getCopyData(filepath) { return filepath ? getFileData(filepath) : getPipeData(); } async function getFileData(filepath) { const _filepath = /^\//.test(filepath) ? filepath : cli_1.api.path.join(process.cwd(), filepath); const text = await cli_1.api.fs.readFile(_filepath, { encoding: 'utf-8' }); return text; } async function getPipeData() { if (!process.stdin.isTTY) { let script = ''; process.stdin.setEncoding('utf8'); for await (const chunk of process.stdin) { script += chunk; } return script; } return null; }