UNPKG

vite-plugin-entry-shaking-debugger

Version:
205 lines (184 loc) 8.53 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); const node_path = require('node:path'); const node_url = require('node:url'); const sirv = require('sirv'); const require$$0 = require('tty'); const fs = require('fs'); const module$1 = require('module'); const path = require('path'); const promises = require('node:fs/promises'); const vite = require('vite'); var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null; function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; } const sirv__default = /*#__PURE__*/_interopDefaultCompat(sirv); const require$$0__default = /*#__PURE__*/_interopDefaultCompat(require$$0); function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var picocolors = {exports: {}}; let tty = require$$0__default; let isColorSupported = !("NO_COLOR" in process.env || process.argv.includes("--no-color")) && ("FORCE_COLOR" in process.env || process.argv.includes("--color") || process.platform === "win32" || (tty.isatty(1) && process.env.TERM !== "dumb") || "CI" in process.env); let formatter = (open, close, replace = open) => input => { let string = "" + input; let index = string.indexOf(close, open.length); return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close }; let replaceClose = (string, close, replace, index) => { let start = string.substring(0, index) + replace; let end = string.substring(index + close.length); let nextIndex = end.indexOf(close); return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end }; let createColors = (enabled = isColorSupported) => ({ isColorSupported: enabled, reset: enabled ? s => `\x1b[0m${s}\x1b[0m` : String, bold: enabled ? formatter("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m") : String, dim: enabled ? formatter("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m") : String, italic: enabled ? formatter("\x1b[3m", "\x1b[23m") : String, underline: enabled ? formatter("\x1b[4m", "\x1b[24m") : String, inverse: enabled ? formatter("\x1b[7m", "\x1b[27m") : String, hidden: enabled ? formatter("\x1b[8m", "\x1b[28m") : String, strikethrough: enabled ? formatter("\x1b[9m", "\x1b[29m") : String, black: enabled ? formatter("\x1b[30m", "\x1b[39m") : String, red: enabled ? formatter("\x1b[31m", "\x1b[39m") : String, green: enabled ? formatter("\x1b[32m", "\x1b[39m") : String, yellow: enabled ? formatter("\x1b[33m", "\x1b[39m") : String, blue: enabled ? formatter("\x1b[34m", "\x1b[39m") : String, magenta: enabled ? formatter("\x1b[35m", "\x1b[39m") : String, cyan: enabled ? formatter("\x1b[36m", "\x1b[39m") : String, white: enabled ? formatter("\x1b[37m", "\x1b[39m") : String, gray: enabled ? formatter("\x1b[90m", "\x1b[39m") : String, bgBlack: enabled ? formatter("\x1b[40m", "\x1b[49m") : String, bgRed: enabled ? formatter("\x1b[41m", "\x1b[49m") : String, bgGreen: enabled ? formatter("\x1b[42m", "\x1b[49m") : String, bgYellow: enabled ? formatter("\x1b[43m", "\x1b[49m") : String, bgBlue: enabled ? formatter("\x1b[44m", "\x1b[49m") : String, bgMagenta: enabled ? formatter("\x1b[45m", "\x1b[49m") : String, bgCyan: enabled ? formatter("\x1b[46m", "\x1b[49m") : String, bgWhite: enabled ? formatter("\x1b[47m", "\x1b[49m") : String, }); picocolors.exports = createColors(); picocolors.exports.createColors = createColors; var picocolorsExports = picocolors.exports; const colors = /*@__PURE__*/getDefaultExportFromCjs(picocolorsExports); const require$1 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))); const packageMainPath = require$1.resolve("vite-plugin-entry-shaking"); const packageJsonPath = path.resolve(packageMainPath, "../../package.json"); const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8")); const { name, version } = packageJson; const VERSION = version; const PLUGIN_NAME = name; const PLUGIN_MESSAGE_PREFIX = "vpes"; const wsMessageName = (name) => `${PLUGIN_MESSAGE_PREFIX}:${name}`; const READY = wsMessageName("getInitialState"); const TYPE = "t"; const MAP = "m"; const SET = "s"; const VAL = "v"; const stringify = (v) => JSON.stringify(v, replacer); const parse = (v) => JSON.parse(v, reviver); const isObject = (v) => typeof v === "object" && v !== null; const replacer = (_, v) => v instanceof Map ? { [TYPE]: MAP, [VAL]: [...v] } : v instanceof Set ? { [TYPE]: SET, [VAL]: [...v] } : v; const reviver = (_, v) => isObject(v) && v[TYPE] === MAP ? new Map(v[VAL]) : isObject(v) && v[TYPE] === SET ? new Set(v[VAL]) : v; const JSONMap = { stringify, parse }; const _ = wsMessageName; function createChannel({ hot, config }, ctx, consumer) { subscribeToEventBus(hot, ctx); const { root } = config; hot.on(READY, () => { hot.send( READY, JSONMap.stringify({ root, consumer, entries: ctx.entries, metrics: ctx.metrics, logs: ctx.logger.logs, options: { diagnostics: ctx.options.diagnostics, debug: ctx.options.debug }, diagnostics: { list: ctx.diagnostics.list, listPerPath: ctx.diagnostics.listPerPath } }) ); }); } function subscribeToEventBus(hot, ctx) { ctx.eventBus?.subscribe((event, data) => { hot.send(_(event), JSONMap.stringify(data.length > 1 ? [...data] : data[0])); }); } const CURR_DIR = node_path.dirname(node_url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)))); node_path.resolve(CURR_DIR, "../dist/client"); const PATH_TO_CONSUMER_PACKAGE = vite.normalizePath(node_path.resolve(process.cwd(), "package.json")); async function getConsumerPackageInfo() { try { const packageJsonContent = await promises.readFile(PATH_TO_CONSUMER_PACKAGE, "utf-8"); const { name, version } = JSON.parse(packageJsonContent); return { name, version }; } catch (error) { return { name: "Debugger" }; } } const PATH_TO_CLIENT = node_path.resolve(node_path.dirname(node_url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)))), "../dist/client"); async function attachDebugger(server, ctx) { const { base } = server.config; const debuggerPath = `${base}__debugger`; const sirvConfig = { dev: true, single: true }; server.middlewares.use(debuggerPath, sirv__default(PATH_TO_CLIENT, sirvConfig)); const consumer = await getConsumerPackageInfo(); createChannel(server, ctx, consumer); printUrls(server, debuggerPath, consumer); } function printUrls(server, debuggerRoute, consumer) { const printViteUrls = server.printUrls; server.printUrls = () => { printViteUrls(); const resolvedLocalUrls = server.resolvedUrls?.local ?? []; const pluginHeader = colors.green(`${colors.bold(PLUGIN_NAME)} v${VERSION}`); const pluginName = colors.dim("debugger"); server.config.logger.info(` ${pluginHeader} ${pluginName} `); resolvedLocalUrls.forEach((url, i) => { const baseUrl = url.endsWith("/") && debuggerRoute.startsWith("/") ? url.slice(0, -1) : url; const debugPath = debuggerRoute.endsWith("/") ? debuggerRoute : `${debuggerRoute}/`; const debugUrl = `${baseUrl}${debugPath}`; if (!i) { openBrowser(baseUrl); openBrowser(debugUrl, 300); } server.config.logger.info( colors.dim(colors.green(" \u279C")) + colors.dim(` ${colors.bold("Local:")} ${colors.cyan(debugUrl)}`) ); if (consumer.name && consumer.version) { const debuggee = `${consumer.name}@${consumer.version}`; server.config.logger.info( colors.dim(colors.green(" \u279C")) + colors.dim(` Debugging ${colors.bold(debuggee)}`) ); } }); }; } async function openBrowser(address, delay = 0) { setTimeout(async () => { await import('open').then((r) => r.default(address, { newInstance: true })).catch(() => { }); }, delay); } exports.attachDebugger = attachDebugger; exports.default = attachDebugger;