Move image conversion out of plugins

This commit is contained in:
Brahim Hadriche committed 2025-01-26 20:38:08 -05:00
1 parent 3cb3c4b8ab
commit 1964040900
8 files changed
+134 -247

No files matched your search

-1
View File
@@ -91,7 +91,6 @@
"../tools/bs-plugins/json-yaml-plugin.ts",
"../tools/bs-plugins/validation-plugin.ts",
"../tools/bs-plugins/logger-plugin.ts",
"../tools/bs-plugins/image-gen-plugin.ts",
"../tools/bs-plugins/type-gen-plugin.ts",
"../tools/bs-plugins/web-server-plugin.ts",
"../tools/bs-plugins/locale-validation-plugin.ts",
-1
View File
@@ -29,7 +29,6 @@
"../tools/bs-plugins/json-yaml-plugin.ts",
"../tools/bs-plugins/validation-plugin.ts",
"../tools/bs-plugins/logger-plugin.ts",
"../tools/bs-plugins/image-gen-plugin.ts",
"../tools/bs-plugins/type-gen-plugin.ts",
"../tools/bs-plugins/web-server-plugin.ts",
"../tools/bs-plugins/locale-validation-plugin.ts",
-16
View File
@@ -1,7 +1,6 @@
# Playlet Brighterscript Plugins
- [Json5/Yaml support](#json5yaml-support)
- [Convert images](#convert-images)
- [Manifest editing](#manifest-editing)
- [Validation](#validation)
- [Includes](#includes)
@@ -33,21 +32,6 @@ Brightscript can only parse json natively using [ParseJson](https://developer.ro
At the end of the build, the plugin scans for certain files (`jsonc`, `json`, `json5` and `yaml`), and converts them to plain json, while keeping the original file name. That way they are all parsable by the [ParseJson](https://developer.roku.com/en-ca/docs/references/brightscript/language/global-utility-functions.md#parsejsonjsonstring-as-string-flags---as-string-as-object) function, even though their original format is not compatible.
## Convert images
**[Source](/tools/bs-plugins/image-gen-plugin.ts)**
This plugin allows us to convert svg files to png files.
### Why
This is used to convert splash screen, app poster, as well as icons in the app. Having svg images (or vector images in general) as the source of truth is better, in case images need to be modified or resized. Since Roku can't load them, we convert them to png.
### How
Each `.svg` file found will have an associated `.svg.meta.json5` file, which will contain the hash (MD5) of the svg, conversion paramters, and the hash of the output files. This allows us to hash existing files and see if a conversion is needed.
Notice how each `.svg` file can be configured to generate multiple png files. This is especially the case to generate the app artwork (splash screen/poster) with different sizes from the same logo `.svg` file.
## Manifest editing
**[Source](/tools/bs-plugins/manifest-edit-plugin.ts)**
+10 -86
View File
@@ -17,6 +17,7 @@
"argparse": "^2.0.1",
"brighterscript": "0.68.4",
"brighterscript-formatter": "^1.7.8",
"cheerio": "^1.0.0-rc.11",
"convert-svg-to-png": "^0.6.4",
"crypto-js": "^4.2.0",
"dotenv": "^16.4.7",
@@ -1825,25 +1826,22 @@
}
},
"node_modules/cheerio": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/cheerio/-/cheerio-1.0.0.tgz",
"integrity": "sha512-quS9HgjQpdaXOvsZz82Oz7uxtXiy6UIsIQcpBj7HRw2M63Skasm9qlDocAM7jNuaxdhpPU7c4kJN+gA5MCu4ww==",
"version": "1.0.0-rc.11",
"resolved": "https://registry.npmjs.org/cheerio/-/cheerio-1.0.0-rc.11.tgz",
"integrity": "sha512-bQwNaDIBKID5ts/DsdhxrjqFXYfLw4ste+wMKqWA8DyKcS4qwsPP4Bk8ZNaTJjvpiX/qW3BT4sU7d6Bh5i+dag==",
"dev": true,
"dependencies": {
"cheerio-select": "^2.1.0",
"dom-serializer": "^2.0.0",
"domhandler": "^5.0.3",
"domutils": "^3.1.0",
"encoding-sniffer": "^0.2.0",
"htmlparser2": "^9.1.0",
"parse5": "^7.1.2",
"domutils": "^3.0.1",
"htmlparser2": "^8.0.1",
"parse5": "^7.0.0",
"parse5-htmlparser2-tree-adapter": "^7.0.0",
"parse5-parser-stream": "^7.1.2",
"undici": "^6.19.5",
"whatwg-mimetype": "^4.0.0"
"tslib": "^2.4.0"
},
"engines": {
"node": ">=18.17"
"node": ">= 6"
},
"funding": {
"url": "https://github.com/cheeriojs/cheerio?sponsor=1"
@@ -2666,19 +2664,6 @@
"node": ">=8.10.0"
}
},
"node_modules/encoding-sniffer": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/encoding-sniffer/-/encoding-sniffer-0.2.0.tgz",
"integrity": "sha512-ju7Wq1kg04I3HtiYIOrUrdfdDvkyO9s5XM8QAj/bN61Yo/Vb4vgJxy5vi4Yxk01gWHbrofpPtpxM8bKger9jhg==",
"dev": true,
"dependencies": {
"iconv-lite": "^0.6.3",
"whatwg-encoding": "^3.1.1"
},
"funding": {
"url": "https://github.com/fb55/encoding-sniffer?sponsor=1"
}
},
"node_modules/end-of-stream": {
"version": "1.4.4",
"resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz",
@@ -3567,7 +3552,7 @@
"node": ">=14"
}
},
"node_modules/html-to-text/node_modules/htmlparser2": {
"node_modules/htmlparser2": {
"version": "8.0.2",
"resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-8.0.2.tgz",
"integrity": "sha512-GYdjWKDkbRLkZ5geuHs5NY1puJ+PXwP7+fHPRz06Eirsb9ugf6d8kkXav6ADhcODhFFPMIXyxkxSuMf3D6NCFA==",
@@ -3586,25 +3571,6 @@
"entities": "^4.4.0"
}
},
"node_modules/htmlparser2": {
"version": "9.1.0",
"resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-9.1.0.tgz",
"integrity": "sha512-5zfg6mHUoaer/97TxnGpxmbR7zJtPwIYFMZ/H5ucTlPZhKvtum05yiPK3Mgai3a0DyVxv7qYqoweaEd2nrYQzQ==",
"dev": true,
"funding": [
"https://github.com/fb55/htmlparser2?sponsor=1",
{
"type": "github",
"url": "https://github.com/sponsors/fb55"
}
],
"dependencies": {
"domelementtype": "^2.3.0",
"domhandler": "^5.0.3",
"domutils": "^3.1.0",
"entities": "^4.5.0"
}
},
"node_modules/http-errors": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz",
@@ -4873,18 +4839,6 @@
"url": "https://github.com/inikulin/parse5?sponsor=1"
}
},
"node_modules/parse5-parser-stream": {
"version": "7.1.2",
"resolved": "https://registry.npmjs.org/parse5-parser-stream/-/parse5-parser-stream-7.1.2.tgz",
"integrity": "sha512-JyeQc9iwFLn5TbvvqACIF/VXG6abODeB3Fwmv/TGdLk2LfbWkaySGY72at4+Ty7EkPZj854u4CrICqNk2qIbow==",
"dev": true,
"dependencies": {
"parse5": "^7.0.0"
},
"funding": {
"url": "https://github.com/inikulin/parse5?sponsor=1"
}
},
"node_modules/parseley": {
"version": "0.12.1",
"resolved": "https://registry.npmjs.org/parseley/-/parseley-0.12.1.tgz",
@@ -7236,15 +7190,6 @@
"integrity": "sha512-vohX7ywgBjRxDNw+f3wHclSXmO0z9HsEfmGObOuG7G0yi7kZ6OtCG8kAxtDSNklmua5KR6ev2drTFqMGqpYEbg==",
"dev": true
},
"node_modules/undici": {
"version": "6.21.0",
"resolved": "https://registry.npmjs.org/undici/-/undici-6.21.0.tgz",
"integrity": "sha512-BUgJXc752Kou3oOIuU1i+yZZypyZRqNPW0vqoMPl8VaoalSfeR0D8/t4iAS3yirs79SSMTxTag+ZC86uswv+Cw==",
"dev": true,
"engines": {
"node": ">=18.17"
}
},
"node_modules/undici-types": {
"version": "6.20.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.20.0.tgz",
@@ -7441,27 +7386,6 @@
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==",
"dev": true
},
"node_modules/whatwg-encoding": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz",
"integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==",
"dev": true,
"dependencies": {
"iconv-lite": "0.6.3"
},
"engines": {
"node": ">=18"
}
},
"node_modules/whatwg-mimetype": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz",
"integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==",
"dev": true,
"engines": {
"node": ">=18"
}
},
"node_modules/whatwg-url": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
+2
View File
@@ -11,6 +11,7 @@
"argparse": "^2.0.1",
"brighterscript": "0.68.4",
"brighterscript-formatter": "^1.7.8",
"cheerio": "^1.0.0-rc.11",
"convert-svg-to-png": "^0.6.4",
"crypto-js": "^4.2.0",
"dotenv": "^16.4.7",
@@ -62,6 +63,7 @@
"sign-released-package": "node tools/sign-released-package.js",
"screenshot": "node tools/screenshot.js",
"generate-sponsorblock-config": "node tools/generate-sponsorblock-config.js",
"convert-images": "node tools/convert-images.js",
"update-rale-component": "cd tools/RALE && rm TrackerTask.xml && curl -o TrackerTask.zip https://devtools.web.roku.com/roku-advanced-layout-editor/app/TrackerTask.zip && unzip TrackerTask.zip && rm TrackerTask.zip",
"postinstall": "cd playlet-lib && npm install && cd ../playlet-app && npm install && cd ../playlet-web && npm install",
"update-deps": "npx npm-check-updates --deep --upgrade --install always --reject tailwindcss",
-124
View File
@@ -1,124 +0,0 @@
// This plugin converts svg files to png/jpeg files
import {
CompilerPlugin, FileObj, ProgramBuilder,
} from 'brighterscript';
import { readFileSync, writeFileSync } from 'fs';
import { existsSync } from 'fs-extra';
import { globSync } from 'glob';
import md5 from 'crypto-js/md5';
import { join as joinPath } from 'path';
import json5 from 'json5';
const shell = require('shelljs');
const META_EXT = '.meta.json5';
export class ImageGenPlugin implements CompilerPlugin {
public name = 'ImageGenPlugin';
beforePrepublish(builder: ProgramBuilder, files: FileObj[]) {
// Force generate flag
// @ts-ignore
const forceGenerateImages = !!builder.options.forceGenerateImages;
// Debug flag
// @ts-ignore
const debug = !!builder.options.debug;
if (debug && !forceGenerateImages) {
// Since the plugin does a lot of scanning of files, it is fine not to run it in debug mode
// The change will be picked up on release
return;
}
const rootDir = builder.options.rootDir!;
const svgFiles = globSync(`**/*.svg`, { cwd: rootDir });
svgFiles.forEach((svgFile) => {
// Web app can use svg files, no need to convert
if (svgFile.includes('www')) {
return;
}
const metafile = joinPath(rootDir, `${svgFile}${META_EXT}`);
if (!existsSync(metafile)) {
this.createDefaultMetaFile(svgFile, metafile);
}
const meta = json5.parse(readFileSync(metafile, 'utf8'));
this.generateImages(svgFile, meta, metafile, rootDir, files, forceGenerateImages);
});
}
createDefaultMetaFile(svgFile: string, metafile: string) {
const meta = {
inputHash: '',
outputs: [{
outputFilePath: svgFile.replace('.svg', '.png'),
outputHash: '',
width: 64,
height: 64,
}]
}
writeFileSync(metafile, json5.stringify(meta, null, 2));
}
generateImages(svgFile: string, meta: any, metafile: string, rootDir: string, files: FileObj[], forceGenerateImages: boolean) {
let metaChanged = false;
const inputHash = this.checkFileHash(joinPath(rootDir, svgFile), meta.inputHash);
if (!inputHash.valid) {
meta.inputHash = inputHash.hash;
metaChanged = true;
}
for (var i in meta.outputs) {
const output = meta.outputs[i];
const outputFilePath = joinPath(rootDir, output.outputFilePath);
let outputHash = this.checkFileHash(outputFilePath, output.outputHash);
if (inputHash.valid && outputHash.valid && !forceGenerateImages) {
continue;
}
this.generateImage(svgFile, output, rootDir);
outputHash = this.checkFileHash(outputFilePath, output.outputHash);
files.push({ src: outputFilePath, dest: output.outputFilePath })
output.outputHash = outputHash.hash;
metaChanged = true;
}
if (metaChanged) {
writeFileSync(metafile, json5.stringify(meta, null, 2));
}
}
generateImage(svgFile: string, output: any, rootDir: string) {
shell.exec(`node ../../tools/convert-image.js --input "${svgFile}" --options '${JSON.stringify(output)}'`, {
cwd: rootDir
})
}
checkFileHash(file: string, hash: string) {
if (!existsSync(file)) {
return {
valid: false,
hash: ''
}
}
const outputHash = md5(readFileSync(file, 'binary')).toString();
return {
valid: outputHash === hash,
hash: outputHash
}
}
}
export default () => {
return new ImageGenPlugin();
};
-19
View File
@@ -1,19 +0,0 @@
// Description: Converts SVGs to PNGs and resizes them to the correct dimensions.
const { ArgumentParser } = require('argparse')
const { convertFile } = require('convert-svg-to-png');
(async () => {
const parser = new ArgumentParser({
description: 'Sync YouTube profile with Invidious'
});
parser.add_argument('--input', { help: 'Input file path' });
parser.add_argument('--options', { help: 'Options as json string' });
const args = parser.parse_args()
const input = args.input
const options = JSON.parse(args.options)
await convertFile(input, options);
})();
+122
View File
@@ -0,0 +1,122 @@
// Description: Converts SVGs to PNGs and resizes them to the correct dimensions.
const { ArgumentParser, BooleanOptionalAction } = require('argparse')
const { globSync } = require('glob');
const { convertFile } = require('convert-svg-to-png');
const { existsSync, writeFileSync, readFileSync } = require('fs');
const json5 = require('json5');
const md5 = require('crypto-js/md5');
const path = require('path');
const META_EXT = '.meta.json5';
(async () => {
const parser = new ArgumentParser({
description: 'Converts SVGs to PNGs'
});
parser.add_argument('--force', { help: 'Force convert all images', action: BooleanOptionalAction, default: false });
const args = parser.parse_args()
const force = args.force
const svgFiles = findSvgFiles();
console.log(`Found ${svgFiles.length} SVG files`);
for (const svgFile of svgFiles) {
const metafile = `${svgFile.file}${META_EXT}`;
if (!existsSync(metafile)) {
createDefaultMetaFile(svgFile, metafile);
}
const meta = json5.parse(readFileSync(metafile, 'utf8'));
await generateImages(svgFile, meta, metafile, force);
}
console.log('Done.');
})();
function findSvgFiles() {
return [
...findSvgFilesForProject('playlet-app/src'),
...findSvgFilesForProject('playlet-lib/src')
];
}
function findSvgFilesForProject(project) {
return globSync(`**/*.svg`, { cwd: project })
// Web app can use svg files, no need to convert
.filter(file => !file.startsWith('www'))
.map(file => path.join(project, file))
.map(file => { return { file: file, rootDir: project } });
}
function createDefaultMetaFile(svgFile, metafile) {
const meta = {
inputHash: '',
outputs: [{
outputFilePath: svgFile.file.replace(`${svgFile.rootDir}/`, '').replace('.svg', '.png'),
outputHash: '',
width: 64,
height: 64,
}]
}
writeFileSync(metafile, json5.stringify(meta, null, 2));
}
async function generateImages(svgFile, meta, metafile, force) {
let metaChanged = false;
const inputHash = checkFileHash(svgFile.file, meta.inputHash);
if (!inputHash.valid) {
meta.inputHash = inputHash.hash;
metaChanged = true;
}
for (var i in meta.outputs) {
const output = meta.outputs[i];
const outputFilePath = path.join(svgFile.rootDir, output.outputFilePath);
let outputHash = checkFileHash(outputFilePath, output.outputHash);
if (inputHash.valid && outputHash.valid && !force) {
continue;
}
await generateImage(svgFile.file, output, svgFile.rootDir);
outputHash = checkFileHash(outputFilePath, output.outputHash);
console.log(`Generated ${outputFilePath} (${output.width}x${output.height})`);
output.outputHash = outputHash.hash;
metaChanged = true;
}
if (metaChanged) {
writeFileSync(metafile, json5.stringify(meta, null, 2));
console.log(`Updated ${metafile}`);
}
}
function checkFileHash(file, hash) {
if (!existsSync(file)) {
return {
valid: false,
hash: ''
}
}
const outputHash = md5(readFileSync(file, 'binary')).toString();
return {
valid: outputHash === hash,
hash: outputHash
}
}
async function generateImage(inputImage, options, rootDir) {
const opts = { ...options };
opts.outputFilePath = path.join(rootDir, opts.outputFilePath);
await convertFile(inputImage, opts);
}