UNPKG

@simplito/webendpoint-manager

Version:

ClI tool for managing PrivMX Webendpoint assets

477 lines (476 loc) 22.7 kB
#!/usr/bin/env node 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()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); return g.next = verb(0), g["throw"] = verb(1), g["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 (g && (g = 0, op[0] && (_ = 0)), _) 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 }; } }; import { confirm, input } from '@inquirer/prompts'; import { join, resolve as pathResolve } from 'path'; import { rm } from 'node:fs/promises'; import { existsSync, readFileSync, createWriteStream, renameSync, mkdirSync, rmSync } from 'fs'; import { Readable } from 'stream'; import * as cp from 'child_process'; import * as UUID from 'uuid'; // @ts-ignore import AdmZip from 'adm-zip'; import ora from 'ora'; function pressEnterToContinue() { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, input({ message: 'Press ENTER to continue' })]; case 1: _a.sent(); return [2 /*return*/]; } }); }); } function getZipUrlOfLatest() { return __awaiter(this, void 0, void 0, function () { var latestInfoUrl, headers, zipInfo; return __generator(this, function (_a) { switch (_a.label) { case 0: latestInfoUrl = 'https://api.github.com/repos/simplito/privmx-webendpoint/releases/latest'; headers = { Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' }; return [4 /*yield*/, fetch(latestInfoUrl, { headers: headers })]; case 1: zipInfo = _a.sent(); if (!zipInfo.ok) return [3 /*break*/, 3]; return [4 /*yield*/, zipInfo.json()]; case 2: return [2 /*return*/, (_a.sent()).zipball_url]; case 3: return [2 /*return*/, null]; } }); }); } var fetchGithubRepository = function (version, saveTo) { return __awaiter(void 0, void 0, void 0, function () { var actualVersion, _a, versionName, link, fileName, resp, savedFilePath, writer_1; return __generator(this, function (_b) { switch (_b.label) { case 0: if (!version) return [3 /*break*/, 1]; _a = version; return [3 /*break*/, 3]; case 1: return [4 /*yield*/, getZipUrlOfLatest()]; case 2: _a = (_b.sent()).split('/').pop(); _b.label = 3; case 3: actualVersion = _a; versionName = actualVersion.startsWith('v') ? actualVersion : "v".concat(actualVersion); link = "https://github.com/simplito/privmx-webendpoint/releases/download/".concat(versionName, "/privmx-webendpoint-").concat(versionName, ".zip"); fileName = link.split('/').pop() || 'wasm-assets.zip'; return [4 /*yield*/, fetch(link, { redirect: 'follow' })]; case 4: resp = _b.sent(); savedFilePath = join(saveTo, fileName); if (!existsSync(savedFilePath)) return [3 /*break*/, 6]; return [4 /*yield*/, rm(savedFilePath)]; case 5: _b.sent(); _b.label = 6; case 6: if (!(resp.ok && resp.body)) return [3 /*break*/, 8]; writer_1 = createWriteStream(savedFilePath); Readable.fromWeb(resp.body).pipe(writer_1); return [4 /*yield*/, new Promise(function (resolve, reject) { writer_1.on('finish', resolve); writer_1.on('error', reject); })]; case 7: _b.sent(); return [3 /*break*/, 9]; case 8: throw new Error('Unable to download assets aborting.'); case 9: return [2 /*return*/, { path: savedFilePath, isCompressed: true }]; } }); }); }; var fetchNpmJSPackage = function (version, saveTo) { return __awaiter(void 0, void 0, void 0, function () { var versionName, pkgName, tmpPkgDir, assetsPath, licenseFile; return __generator(this, function (_a) { versionName = version.startsWith('v') ? version.substring(1) : version; pkgName = "@simplito/privmx-webendpoint".concat(version.length > 0 ? '@' + versionName : ''); tmpPkgDir = ''; while (true) { tmpPkgDir = pathResolve(saveTo, 'tmp-' + UUID.v4()); if (!existsSync(tmpPkgDir)) { break; } } mkdirSync(tmpPkgDir, { recursive: true }); cp.execSync('npm init -y', { cwd: tmpPkgDir }); cp.execSync('npm i ' + pkgName, { cwd: tmpPkgDir }); assetsPath = pathResolve(tmpPkgDir, 'node_modules/@simplito/privmx-webendpoint/webAssets'); licenseFile = pathResolve(assetsPath, 'LICENSE.md'); rmSync(licenseFile); return [2 /*return*/, { path: assetsPath, isCompressed: false, cleanup: function () { rmSync(tmpPkgDir, { recursive: true, force: true }); } }]; }); }); }; function extractAssets(archivePath, extractPath) { return __awaiter(this, void 0, void 0, function () { var assetsZip; return __generator(this, function (_a) { assetsZip = new AdmZip(join(process.cwd(), archivePath)); assetsZip.getEntries().forEach(function (zipFile) { if (zipFile.name.endsWith('js') || zipFile.name.endsWith('.wasm')) { assetsZip.extractEntryTo(zipFile, extractPath, false); } }); return [2 /*return*/]; }); }); } function clearArchive(archivePath) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: if (!existsSync(archivePath)) return [3 /*break*/, 2]; return [4 /*yield*/, rm(archivePath)]; case 1: _a.sent(); _a.label = 2; case 2: return [2 /*return*/]; } }); }); } function checkDestPath(destPath) { return __awaiter(this, void 0, void 0, function () { var override; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!existsSync(destPath)) return [3 /*break*/, 4]; return [4 /*yield*/, confirm({ message: 'Assets already exists, override ?', default: false })]; case 1: override = _a.sent(); if (!override) return [3 /*break*/, 3]; return [4 /*yield*/, rm(destPath, { recursive: true, force: true })]; case 2: _a.sent(); return [2 /*return*/, false]; case 3: return [2 /*return*/, true]; case 4: return [2 /*return*/, false]; } }); }); } function getLicenseConfirmation() { return __awaiter(this, void 0, void 0, function () { var confirmation; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, confirm({ message: 'PrivMX Endpoint and PrivMX Bridge are licensed under the PrivMX Free License.\n' + ' See the License for the specific language governing permissions and limitations under the License at https://privmx.dev/licensing, proceed ?', default: true })]; case 1: confirmation = _a.sent(); return [2 /*return*/, confirmation]; } }); }); } function choseDestFolder() { return __awaiter(this, void 0, void 0, function () { var destinationFolder; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, input({ message: 'Please specify the destination folder for the assets (e.g., ./public/privmx-assets):', default: './public/privmx-assets' })]; case 1: destinationFolder = _a.sent(); return [2 /*return*/, destinationFolder]; } }); }); } function setupNext(destinationFolder) { return __awaiter(this, void 0, void 0, function () { var withoutPublic; return __generator(this, function (_a) { switch (_a.label) { case 0: console.log('\n-- Paste following script tags in to your root layout <head> tag --'); withoutPublic = destinationFolder.replace('/public', ''); if (withoutPublic.startsWith('.')) { withoutPublic = withoutPublic.slice(1); } console.log("\u001B[34m\n<Script src=\"".concat(withoutPublic, "/privmx-endpoint-web.js\"></Script>\n<Script src=\"").concat(withoutPublic, "/driver-web-context.js\"></Script>\n<Script src=\"").concat(withoutPublic, "/endpoint-wasm-module.js\"></Script>\u001B[0m\n")); return [4 /*yield*/, pressEnterToContinue()]; case 1: _a.sent(); console.log('-- Setup your next.config.mjs to handle specified headers --'); console.log("\u001B[34m\n/** @type {import(\"next\").NextConfig} */\nconst nextConfig = {\n headers: async () => {\n return [\n {\n source: \"/(.*)\",\n headers: [\n {\n key: \"Cross-Origin-Embedder-Policy\",\n value: \"require-corp\",\n },\n {\n key: \"Cross-Origin-Opener-Policy\",\n value: \"same-origin\",\n },\n ],\n },\n ];\n },\n};\n\nexport default nextConfig;\n\u001B[0m\n"); return [2 /*return*/]; } }); }); } function setupVite(destinationFolder) { return __awaiter(this, void 0, void 0, function () { var withoutPublic; return __generator(this, function (_a) { switch (_a.label) { case 0: console.log('\n-- Paste following script tags in to your index.html <head> tag --'); withoutPublic = destinationFolder.replace('/public', ''); if (withoutPublic.startsWith('.')) { withoutPublic = withoutPublic.slice(1); } console.log("\u001B[34m\n<script src=\"".concat(withoutPublic, "/privmx-endpoint-web.js\"></script>\n<script src=\"").concat(withoutPublic, "/driver-web-context.js\"></script>\n<script src=\"").concat(withoutPublic, "/endpoint-wasm-module.js\"></script>\u001B[0m\n")); return [4 /*yield*/, pressEnterToContinue()]; case 1: _a.sent(); console.log('-- Setup your vite.config.ts to handle specified headers --\n'); console.log("\u001B[34m\nimport { defineConfig } from \"vite\";\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [\n {\n name: \"configure-response-headers\",\n configureServer: (server) => {\n server.middlewares.use((_req, res, next) => {\n res.setHeader(\"Cross-Origin-Embedder-Policy\", \"require-corp\");\n res.setHeader(\"Cross-Origin-Opener-Policy\", \"same-origin\");\n next();\n });\n },\n },\n ],\n});\n\u001B[0m\n"); return [2 /*return*/]; } }); }); } function getProjectDependencies() { var packageJsonPath = join(process.cwd(), 'package.json'); if (!existsSync(packageJsonPath)) { ora('No package.json found. Exiting...').fail(); process.exit(1); } var packageJson; try { var packageJsonContent = readFileSync(packageJsonPath, 'utf8'); packageJson = JSON.parse(packageJsonContent); } catch (error) { console.error('Error reading or parsing package.json:', error); process.exit(1); } var dependencies = packageJson.dependencies || {}; var devDependencies = packageJson.devDependencies || {}; return [dependencies, devDependencies]; } var PROJECT_TYPES = [ { name: 'Vite', matchFn: function (packageJson) { return __awaiter(void 0, void 0, void 0, function () { var dep, devDep, isVite; return __generator(this, function (_a) { dep = packageJson[0], devDep = packageJson[1]; isVite = 'vite' in dep || 'vite' in devDep; return [2 /*return*/, isVite]; }); }); }, setup: function (assetsPath) { return __awaiter(void 0, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, setupVite(assetsPath)]; case 1: _a.sent(); return [2 /*return*/]; } }); }); } }, { name: 'Next', matchFn: function (packageJson) { return __awaiter(void 0, void 0, void 0, function () { var dep, devDep, isNext; return __generator(this, function (_a) { dep = packageJson[0], devDep = packageJson[1]; isNext = 'next' in dep || 'next' in devDep; return [2 /*return*/, isNext]; }); }); }, setup: function (assetsPath) { return __awaiter(void 0, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, setupNext(assetsPath)]; case 1: _a.sent(); return [2 /*return*/]; } }); }); } } ]; var DEFAULT_PROJECT_TYPE = { name: 'Default', matchFn: function () { return __awaiter(void 0, void 0, void 0, function () { return __generator(this, function (_a) { console.log('Unknown project type'); return [2 /*return*/, true]; }); }); }, setup: function () { return __awaiter(void 0, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/]; }); }); } }; function extractParam(params) { var args = {}; var repositoryArg = params.find(function (param) { return param.startsWith('--repository'); }); if (repositoryArg) { Object.assign(args, { repository: repositoryArg.split('=')[1] }); } var versionArg = params.find(function (param) { return param.startsWith('--version'); }); if (versionArg) { Object.assign(args, { version: versionArg.split('=')[1] }); } return args; } function main() { return __awaiter(this, void 0, void 0, function () { var params, projectDependencies, userProjectType, _i, PROJECT_TYPES_1, projectType, answer, version, destFolder, abort, isLicenseAccepted, fetcher, spinner, fetchedAsset, e_1; return __generator(this, function (_a) { switch (_a.label) { case 0: params = extractParam(process.argv); projectDependencies = getProjectDependencies(); userProjectType = DEFAULT_PROJECT_TYPE; _i = 0, PROJECT_TYPES_1 = PROJECT_TYPES; _a.label = 1; case 1: if (!(_i < PROJECT_TYPES_1.length)) return [3 /*break*/, 5]; projectType = PROJECT_TYPES_1[_i]; return [4 /*yield*/, projectType.matchFn(projectDependencies)]; case 2: if (!_a.sent()) return [3 /*break*/, 4]; return [4 /*yield*/, confirm({ message: "Detected as ".concat(projectType.name, " project \n Please confirm if detected properly: Y/N") })]; case 3: answer = _a.sent(); if (!answer) { return [3 /*break*/, 4]; } userProjectType = projectType; return [3 /*break*/, 5]; case 4: _i++; return [3 /*break*/, 1]; case 5: version = params.version ? params.version : ''; return [4 /*yield*/, choseDestFolder()]; case 6: destFolder = _a.sent(); return [4 /*yield*/, checkDestPath(destFolder)]; case 7: abort = _a.sent(); if (abort) { process.exit(0); } return [4 /*yield*/, getLicenseConfirmation()]; case 8: isLicenseAccepted = _a.sent(); if (!isLicenseAccepted) { ora('License not accepted, aborting...').fail(); process.exit(0); } spinner = ora("Fetching assets of version: ".concat(version.length > 0 ? version : 'latest')).start(); if (params.repository && params.repository.startsWith('https://github.com/simplito')) { fetcher = fetchGithubRepository; } else { fetcher = fetchNpmJSPackage; } _a.label = 9; case 9: _a.trys.push([9, 16, , 17]); return [4 /*yield*/, fetcher(version, './')]; case 10: fetchedAsset = _a.sent(); if (!fetchedAsset.isCompressed) return [3 /*break*/, 13]; spinner.text = 'Extracting...'; return [4 /*yield*/, extractAssets(fetchedAsset.path, destFolder)]; case 11: _a.sent(); return [4 /*yield*/, clearArchive(fetchedAsset.path)]; case 12: _a.sent(); return [3 /*break*/, 14]; case 13: renameSync(fetchedAsset.path, destFolder); if (fetchedAsset.cleanup) { fetchedAsset.cleanup(); } _a.label = 14; case 14: spinner.succeed("Assets fetched to: ".concat(destFolder)); return [4 /*yield*/, userProjectType.setup(destFolder)]; case 15: _a.sent(); return [3 /*break*/, 17]; case 16: e_1 = _a.sent(); if (e_1 instanceof Error && e_1.name === 'ExitPromptError') { spinner.fail('Aborting script...'); return [2 /*return*/]; } spinner.fail(e_1.message || e_1); return [3 /*break*/, 17]; case 17: return [2 /*return*/]; } }); }); } main() .then(function () { ora('For more information please visit our documentation: https://docs.privmx.dev/').info(); }) .catch(function (e) { if (e instanceof Error && e.name === 'ExitPromptError') { ora('Aborting script...').fail(); return; } console.error(e); process.exit(1); });