UNPKG

@modyo/cli

Version:

Modyo CLI Command line to expose local development tools

96 lines (95 loc) 3.4 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const node_os_1 = require("node:os"); const path = tslib_1.__importStar(require("node:path")); const fs = tslib_1.__importStar(require("node:fs/promises")); const emoji_regex_1 = tslib_1.__importDefault(require("emoji-regex")); const debug_1 = tslib_1.__importDefault(require("debug")); const path_exists_1 = tslib_1.__importDefault(require("../utils/path-exists")); const debug = (0, debug_1.default)('push/resource-extractor.ts'); const debugError = (0, debug_1.default)('error::push/resource-extractor.ts'); function getInlineResource(element) { return `${element.children[0].data};`; } class ResourceExtractor { constructor($, config) { this.$ = $; this.config = config; } async extract() { const resources = await Promise.all(this.$(this.config.selector) .toArray() .map(async (rawElement) => { const element = rawElement; const filename = this.getFilename(element); if (!filename) { return getInlineResource(element); } if (this.isExcluded(filename)) { return ''; } const file = await this.readFile(filename); if (!file) { return ''; } return this.getResource(filename, file); })); const resource = resources.filter(Boolean).join(node_os_1.EOL); const cleaned = this.clean(resource); await this.debug(cleaned); return cleaned; } getFilename(element) { return element.attribs[this.config.attribute] ? element.attribs[this.config.attribute].replace(/^\//, '') : ''; } isExcluded(filename) { return this.config.exclude.test(filename); } async readFile(filename) { try { const filePath = path.resolve(this.config.sourcePath, filename); return await fs.readFile(filePath, { encoding: 'utf8' }); } catch (_a) { debugError(`External file ${filename} no included`); return undefined; } } getResource(filename, file) { const lines = file.split(/\r?\n/g); const cleanLines = lines[lines.length - 1].includes('sourceMappingURL') ? lines.slice(0, -1) : lines; if (this.config.useLiquid.test(filename)) { return [ '{%raw%}', ...cleanLines, '{%endraw%}', ] .join(node_os_1.EOL); } return cleanLines.join(node_os_1.EOL); } async debug(resource) { if (process.env.DEBUG !== '*') { return; } if (!(await (0, path_exists_1.default)('.debug'))) { debug('creating .debug dir'); await fs.mkdir(path.join('.debug')); } const filename = this.config.selector.includes('css') ? 'style.css' : 'script.js'; await fs.writeFile(path.resolve('.debug', filename), resource, 'utf8'); } clean(resource) { if (this.config.removeEmojis) { const emojiRegex = (0, emoji_regex_1.default)(); return resource.replace(emojiRegex, ''); } return resource; } } exports.default = ResourceExtractor;