camel case for prebuilt

This commit is contained in:
Sebastian 2023-03-02 14:09:44 -03:00
parent 2d5fbb22cd
commit 36956f404c
No known key found for this signature in database
GPG Key ID: 173909D1A5F66069
4 changed files with 212 additions and 56 deletions

View File

@ -74,34 +74,39 @@ function git_hash() {
return fs.readFileSync(path.join(GIT_ROOT, ".git", rev)).toString().trim(); return fs.readFileSync(path.join(GIT_ROOT, ".git", rev)).toString().trim();
} }
} }
function toCamelCaseName(name) {
return name
.replace(/^[A-Z]/, letter => `${letter.toLowerCase()}`) //first letter lowercase
.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`) //snake case
.concat(".en.html"); //extension
}
function templatePlugin(options) { function templatePlugin(options) {
return { return {
name: "template-backend", name: "template-backend",
setup(build) { setup(build) {
build.onEnd(() => { build.onEnd(() => {
for (const page of options.pages) { for (const pageName of options.pages) {
const css = fs.readFileSync(path.join(build.initialOptions.outdir, `${page}.css`),"utf8").toString() const css = fs.readFileSync(path.join(build.initialOptions.outdir, `${pageName}.css`),"utf8").toString()
const js = fs.readFileSync(path.join(build.initialOptions.outdir, `${page}.js`),"utf8").toString() const js = fs.readFileSync(path.join(build.initialOptions.outdir, `${pageName}.js`),"utf8").toString()
const scripts = `<script>${js}</script>` const location = path.join(build.initialOptions.outdir, toCamelCaseName(pageName))
const style = `<style>${css}</style>`
const render = new Function(`${js}; return page.buildTimeRendering();`)() const render = new Function(`${js}; return page.buildTimeRendering();`)()
const html = ` const html = `
<!doctype html> <!doctype html>
<html> <html>
<head> <head>
${render.head} ${render.head}
${style} <style>${css}</style>
</head> </head>
<script id="built_time_data"> <script id="built_time_data">
</script> </script>
<body> <body>
${render.body} ${render.body}
${scripts} <script>${js}</script>
<script>page.mount()</script> <script>page.mount()</script>
</body> </body>
</html>` </html>`
fs.writeFileSync(path.join(build.initialOptions.outdir, `${page}.html`), html); fs.writeFileSync(location, html);
} }
}); });
}, },

View File

@ -4,14 +4,14 @@
"version": "0.0.5", "version": "0.0.5",
"license": "AGPL-3.0-or-later", "license": "AGPL-3.0-or-later",
"scripts": { "scripts": {
"compile": "rollup -c", "compile": "tsc && ./build.mjs",
"build": "rollup -c", "build": "pnpm compile",
"dev": "rollup -c -w", "prepare": "tsc",
"render-examples": "ts-node -O '{\"module\": \"commonjs\"}' -T render-examples.ts dist/pages dist/examples", "render-examples": "ts-node -O '{\"module\": \"commonjs\"}' -T render-examples.ts dist/pages dist/examples",
"lint-check": "eslint '{src,tests}/**/*.{js,jsx,ts,tsx}'", "lint-check": "eslint '{src,tests}/**/*.{js,jsx,ts,tsx}'",
"lint-fix": "eslint --fix '{src,tests}/**/*.{js,jsx,ts,tsx}'", "lint-fix": "eslint --fix '{src,tests}/**/*.{js,jsx,ts,tsx}'",
"typedoc": "typedoc src", "typedoc": "typedoc src",
"clean": "rimraf build docs single dist", "clean": "rimraf dist",
"serve-dist": "sirv --port ${PORT:=8080} --cors --single dist" "serve-dist": "sirv --port ${PORT:=8080} --cors --single dist"
}, },
"engines": { "engines": {

View File

@ -15,9 +15,9 @@
*/ */
/** /**
* *
* @author Sebastian Javier Marchano (sebasjm) * @author Sebastian Javier Marchano (sebasjm)
*/ */
import mustache from "mustache"; import mustache from "mustache";
import fs from "fs"; import fs from "fs";
@ -26,62 +26,97 @@ import { format, formatDuration, intervalToDuration } from "date-fns";
/** /**
* This script will emulate what the merchant backend will do when being requested * This script will emulate what the merchant backend will do when being requested
* *
*/ */
const sourceDirectory = process.argv[2] const sourceDirectory = process.argv[2];
const destDirectory = process.argv[3] const destDirectory = process.argv[3];
if (!sourceDirectory || !destDirectory) { if (!sourceDirectory || !destDirectory) {
console.log('usage: render-mustache <source-directory> <dest-directory>') console.log("usage: render-mustache <source-directory> <dest-directory>");
process.exit(1); process.exit(1);
} }
if (!fs.existsSync(destDirectory)) { if (!fs.existsSync(destDirectory)) {
fs.mkdirSync(destDirectory); fs.mkdirSync(destDirectory);
} }
function fromCamelCaseName(name) {
const result = name
.replace(/^[a-z]/, (letter) => `${letter.toUpperCase()}`) //first letter lowercase
.replace(/_[a-z]/g, (letter) => `${letter[1].toUpperCase()}`); //snake case
return result;
}
/** /**
* Load all the html files * Load all the html files
*/ */
const files = fs.readdirSync(sourceDirectory).filter(f => /.html/.test(f)) const files = fs.readdirSync(sourceDirectory).filter((f) => /.html/.test(f));
files.forEach(file => { files.forEach((file) => {
const html = fs.readFileSync(`${sourceDirectory}/${file}`, 'utf8') const html = fs.readFileSync(`${sourceDirectory}/${file}`, "utf8");
const testName = file.replace('.html', '') const testName = file.replace(".en.html", "");
const exampleFileName = `./src/pages/${testName}.examples` const exampleFileName = `./src/pages/${fromCamelCaseName(testName)}.examples`;
if (!fs.existsSync(exampleFileName + ".ts")) { if (!fs.existsSync(exampleFileName + ".ts")) {
console.log(`skipping ${testName}: no examples found`); console.log(`skipping ${testName}: no examples found`);
return; return;
} }
// eslint-disable-next-line @typescript-eslint/no-var-requires // eslint-disable-next-line @typescript-eslint/no-var-requires
const { exampleData } = require(exampleFileName) const { exampleData } = require(exampleFileName);
Object.keys(exampleData).forEach(exampleName => { Object.keys(exampleData).forEach((exampleName) => {
const example = exampleData[exampleName] const example = exampleData[exampleName];
//enhance the example with more information //enhance the example with more information
example.contract_terms_json = () => JSON.stringify(example.contract_terms); example.contract_terms_json = () => JSON.stringify(example.contract_terms);
example.contract_terms.timestamp_str = () => example.contract_terms.timestamp && format(example.contract_terms.timestamp.t_s, 'dd MMM yyyy HH:mm:ss'); example.contract_terms.timestamp_str = () =>
example.contract_terms.timestamp &&
format(example.contract_terms.timestamp.t_s, "dd MMM yyyy HH:mm:ss");
example.contract_terms.hasProducts = () => example.contract_terms.products?.length > 0; example.contract_terms.hasProducts = () =>
example.contract_terms.hasAuditors = () => example.contract_terms.auditors?.length > 0; example.contract_terms.products?.length > 0;
example.contract_terms.hasExchanges = () => example.contract_terms.exchanges?.length > 0; example.contract_terms.hasAuditors = () =>
example.contract_terms.auditors?.length > 0;
example.contract_terms.hasExchanges = () =>
example.contract_terms.exchanges?.length > 0;
example.contract_terms.products.forEach(p => { example.contract_terms.products.forEach((p) => {
p.delivery_date_str = () => p.delivery_date && format(p.delivery_date.t_s, 'dd MM yyyy HH:mm:ss') p.delivery_date_str = () =>
p.hasTaxes = () => p.taxes?.length > 0 p.delivery_date && format(p.delivery_date.t_s, "dd MM yyyy HH:mm:ss");
}) p.hasTaxes = () => p.taxes?.length > 0;
example.contract_terms.has_delivery_info = () => example.contract_terms.delivery_date || example.contract_terms.delivery_location });
example.contract_terms.has_delivery_info = () =>
example.contract_terms.delivery_date ||
example.contract_terms.delivery_location;
example.contract_terms.delivery_date_str = () => example.contract_terms.delivery_date && format(example.contract_terms.delivery_date.t_s, 'dd MM yyyy HH:mm:ss') example.contract_terms.delivery_date_str = () =>
example.contract_terms.pay_deadline_str = () => example.contract_terms.pay_deadline && format(example.contract_terms.pay_deadline.t_s, 'dd MM yyyy HH:mm:ss') example.contract_terms.delivery_date &&
example.contract_terms.wire_transfer_deadline_str = () => example.contract_terms.wire_transfer_deadline && format(example.contract_terms.wire_transfer_deadline.t_s, 'dd MM yyyy HH:mm:ss') format(example.contract_terms.delivery_date.t_s, "dd MM yyyy HH:mm:ss");
example.contract_terms.refund_deadline_str = () => example.contract_terms.refund_deadline && format(example.contract_terms.refund_deadline.t_s, 'dd MM yyyy HH:mm:ss') example.contract_terms.pay_deadline_str = () =>
example.contract_terms.auto_refund_str = () => example.contract_terms.auto_refund && formatDuration(intervalToDuration({ start: 0, end: example.contract_terms.auto_refund.d_us })) example.contract_terms.pay_deadline &&
format(example.contract_terms.pay_deadline.t_s, "dd MM yyyy HH:mm:ss");
example.contract_terms.wire_transfer_deadline_str = () =>
example.contract_terms.wire_transfer_deadline &&
format(
example.contract_terms.wire_transfer_deadline.t_s,
"dd MM yyyy HH:mm:ss",
);
example.contract_terms.refund_deadline_str = () =>
example.contract_terms.refund_deadline &&
format(example.contract_terms.refund_deadline.t_s, "dd MM yyyy HH:mm:ss");
example.contract_terms.auto_refund_str = () =>
example.contract_terms.auto_refund &&
formatDuration(
intervalToDuration({
start: 0,
end: example.contract_terms.auto_refund.d_us,
}),
);
const output = mustache.render(html, example); const output = mustache.render(html, example);
fs.writeFileSync(`${destDirectory}/${testName}.${exampleName}.html`, output) fs.writeFileSync(
}) `${destDirectory}/${testName}.${exampleName}.html`,
}) output,
);
});
});

View File

@ -0,0 +1,116 @@
/*
This file is part of GNU Taler
(C) 2021 Taler Systems S.A.
GNU Taler is free software; you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software
Foundation; either version 3, or (at your option) any later version.
GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
*/
// rollup.config.js
import linaria from '@linaria/rollup';
import nodeResolve from "@rollup/plugin-node-resolve";
import alias from "@rollup/plugin-alias";
import image from '@rollup/plugin-image';
import json from "@rollup/plugin-json";
import ts from "@rollup/plugin-typescript";
import replace from "@rollup/plugin-replace";
import css from 'rollup-plugin-css-only';
import html from '@rollup/plugin-html';
import commonjs from "@rollup/plugin-commonjs";
const template = async ({
files,
}) => {
const scripts = (files.js || []).map(({ code }) => `<script>${code}</script>`).join('\n');
const css = (files.css || []).map(({ source }) => `<style>${source}</style>`).join('\n');
const ssr = (files.js || []).map(({ code }) => code).join('\n');
const page = new Function(`${ssr}; return page.buildTimeRendering();`)()
return `
<!doctype html>
<html>
<head>
${page.head}
${css}
</head>
<script id="built_time_data">
</script>
<body>
${page.body}
${scripts}
<script>page.mount()</script>
</body>
</html>`;
};
const makePlugins = (name) => [
alias({
entries: [
{ find: 'react', replacement: 'preact/compat' },
{ find: 'react-dom', replacement: 'preact/compat' }
]
}),
replace({
"process.env.NODE_ENV": JSON.stringify("production"),
preventAssignment: true,
}),
commonjs({
include: [/node_modules/, /dist/],
extensions: [".js"],
ignoreGlobal: true,
sourceMap: true,
}),
nodeResolve({
browser: true,
preferBuiltins: true,
}),
json(),
image(),
linaria({
sourceMap: process.env.NODE_ENV !== 'production',
}),
css(),
ts({
sourceMap: false,
outputToFilesystem: false,
}),
html({ template, fileName: name }),
];
function formatHtmlName(name) {
return name
.replace(/^[A-Z]/, letter => `${letter.toLowerCase()}`) //first letter lowercase
.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`) //snake case
.concat(".en.html"); //extension
}
const pageDefinition = (name) => ({
input: `src/pages/${name}.tsx`,
output: {
file: `dist/pages/${name}.js`,
format: "iife",
exports: 'named',
name: 'page',
},
plugins: makePlugins(formatHtmlName(name)),
});
export default [
pageDefinition("OfferTip"),
pageDefinition("OfferRefund"),
pageDefinition("DepletedTip"),
pageDefinition("RequestPayment"),
pageDefinition("ShowOrderDetails"),
]