using vite to bundle njs scripts

This commit is contained in:
Miao Wang 2024-04-15 12:40:09 +08:00
parent e82195a2d4
commit d2f1d2d75b
10 changed files with 349 additions and 144 deletions

View File

@ -0,0 +1,2 @@
export { legacyIndexRender } from "./legacy_index";
export { fancyIndexBeforeRender, fancyIndexAfterRender } from "./fancy_index";

View File

@ -0,0 +1,34 @@
import Mark from "markup-js";
function fancyIndexRender(r, templateUrl) {
r.subrequest(
templateUrl,
{
args: "",
body: "",
method: "GET",
},
function (rTmpl) {
if (rTmpl.status != 200) {
return r.return(rTmpl.status);
}
const tmpl = rTmpl.responseText;
const result = Mark.up(tmpl, {
url: r.variables.request_uri.replace(/\/+/g, "/").replace(/\?.*$/, ""),
});
r.status = 200;
r.headersOut["Content-Type"] = "text/html";
r.sendHeader();
r.send(result);
r.finish();
},
);
}
export function fancyIndexBeforeRender(r) {
return fancyIndexRender(r, "/fancy-index/before.html");
}
export function fancyIndexAfterRender(r) {
return fancyIndexRender(r, "/fancy-index/after.html");
}

View File

@ -0,0 +1,74 @@
import Mark from "markup-js";
import processingHandlers from "../lib/mirrorListDataProcessing";
import { TUNASYNC_JSON_PATH } from "../lib/consts";
export function legacyIndexRender(r) {
r.subrequest(
"/legacy_index.html",
{
args: "",
body: "",
method: "GET",
},
function (rTmpl) {
if (rTmpl.status != 200) {
return r.return(rTmpl.status);
}
var tmpl = rTmpl.responseText;
r.subrequest(
"/static/njs/options.json",
{
args: "",
body: "",
method: "GET",
},
function (rOpt) {
if (rOpt.status != 200) {
return r.return(rOpt.status);
}
let global_options;
try {
global_options = JSON.parse(rOpt.responseText);
} catch (e) {
return r.return(500);
}
const {
unlistedMirrors: unlisted,
genMainMirrorList,
postProcessStatusData,
} = processingHandlers(global_options.options);
const help_url = Object.fromEntries(
global_options.helps.map((h) => [h.mirrorid, h.url]),
);
r.subrequest(
TUNASYNC_JSON_PATH,
{
args: "",
body: "",
method: "GET",
},
function (rMirs) {
let mirs = [];
if (rMirs.status == 200) {
try {
mirs = JSON.parse(rMirs.responseText);
} catch (e) {}
}
const renMirs = genMainMirrorList(
postProcessStatusData(mirs, unlisted),
help_url,
);
var result = Mark.up(tmpl, { mirs: renMirs });
r.status = 200;
r.headersOut["Content-Type"] = "text/html";
r.sendHeader();
r.send(result);
r.finish();
},
);
},
);
},
);
}

View File

@ -9,6 +9,9 @@ import { Liquid, Tag as LiquidTag } from "liquidjs";
import Babel from "@babel/core"; import Babel from "@babel/core";
import BabelPresetEnv from "@babel/preset-env"; import BabelPresetEnv from "@babel/preset-env";
import fs from "node:fs"; import fs from "node:fs";
import { build as viteBuild, normalizePath } from "vite";
import glob from "fast-glob";
import { getBabelOutputPlugin } from "@rollup/plugin-babel";
const visualizer = await (async () => { const visualizer = await (async () => {
if (process.env.VISUALIZER) { if (process.env.VISUALIZER) {
@ -138,6 +141,85 @@ export default defineConfig(({ mode }) => ({
dirs: [resolve(__dirname, "_src/components")], dirs: [resolve(__dirname, "_src/components")],
resolvers: [], resolvers: [],
}), }),
(() => {
const savedConfig = {
njsOutputDir: "static/njs",
};
return {
name: "add-njs",
config(config) {
savedConfig.minify = config.build?.minify;
savedConfig.root = config.root;
savedConfig.mode = config.mode;
savedConfig.njsFiles = glob.sync("entrypoints-njs/**", {
cwd: config.root,
});
savedConfig.sourcemap = config.build?.sourcemap;
savedConfig.logLevel = config.logLevel;
},
async generateBundle(opts, bundle) {
const { minify, root, mode, njsOutputDir, njsFiles, logLevel } =
savedConfig;
if (opts.format === "system") {
const entryChunk = Object.values(bundle).find(
(output) => output.type === "chunk" && output.isEntry,
);
if (!!entryChunk && entryChunk.fileName.includes("-legacy")) {
return;
}
}
if (njsFiles.length == 0) {
return;
}
const res = await viteBuild({
mode,
root,
configFile: false,
logLevel,
plugins: [
getBabelOutputPlugin({
presets: [
"babel-preset-njs",
],
plugins: [
],
configFile: false,
}),
],
build: {
write: false,
minify,
assetsDir: njsOutputDir,
sourcemap: savedConfig.sourcemap,
rollupOptions: {
input: Object.fromEntries(
njsFiles.map((filename) => [
filename,
path.join(root, filename),
]),
),
output: {
format: "esm",
entryFileNames: ({ name }) => {
const shortName = path.basename(name).split(".")[0];
return path.join(njsOutputDir, `${shortName}.njs`);
},
chunkFileNames: `${njsOutputDir}/[name].njs`,
},
preserveEntrySignatures: "strict",
},
},
esbuild: false,
});
const outputs = Array.isArray(res) ? res : [res];
outputs.forEach((output) => {
output.output.forEach((chunk) => {
bundle[chunk.fileName] = chunk;
});
});
},
};
})(),
legacy({ legacy({
//use empty array to target the oldest browsers possible //use empty array to target the oldest browsers possible
targets: [], targets: [],

154
package-lock.json generated
View File

@ -9,14 +9,17 @@
"dependencies": { "dependencies": {
"@babel/core": "^7.24.4", "@babel/core": "^7.24.4",
"@babel/preset-env": "^7.24.4", "@babel/preset-env": "^7.24.4",
"@rollup/plugin-babel": "^6.0.4",
"@vitejs/plugin-legacy": "^5.3.2", "@vitejs/plugin-legacy": "^5.3.2",
"@vitejs/plugin-vue": "^5.0.4", "@vitejs/plugin-vue": "^5.0.4",
"@webcomponents/template": "^1.5.1", "@webcomponents/template": "^1.5.1",
"babel-preset-njs": "^0.7.0",
"bootstrap": "^5.3.3", "bootstrap": "^5.3.3",
"bootstrap-sass": "^3.4.3", "bootstrap-sass": "^3.4.3",
"core-js": "^3.36.1", "core-js": "^3.36.1",
"element-polyfill": "^1.1.0", "element-polyfill": "^1.1.0",
"events-polyfill": "^2.1.2", "events-polyfill": "^2.1.2",
"fast-glob": "^3.3.2",
"formdata-polyfill": "^4.0.10", "formdata-polyfill": "^4.0.10",
"highlight.js": "^11.9.0", "highlight.js": "^11.9.0",
"lato-webfont": "^2.15.1", "lato-webfont": "^2.15.1",
@ -504,6 +507,90 @@
"@babel/core": "^7.0.0" "@babel/core": "^7.0.0"
} }
}, },
"node_modules/@babel/plugin-proposal-export-namespace-from": {
"version": "7.18.9",
"resolved": "https://registry.npmjs.org/@babel/plugin-proposal-export-namespace-from/-/plugin-proposal-export-namespace-from-7.18.9.tgz",
"integrity": "sha512-k1NtHyOMvlDDFeb9G5PhUXuGj8m/wiwojgQVEhJ/fsVsMCpLyOP4h0uGEjYJKrRI+EVPlb5Jk+Gt9P97lOGwtA==",
"deprecated": "This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-export-namespace-from instead.",
"dependencies": {
"@babel/helper-plugin-utils": "^7.18.9",
"@babel/plugin-syntax-export-namespace-from": "^7.8.3"
},
"engines": {
"node": ">=6.9.0"
},
"peerDependencies": {
"@babel/core": "^7.0.0-0"
}
},
"node_modules/@babel/plugin-proposal-logical-assignment-operators": {
"version": "7.20.7",
"resolved": "https://registry.npmjs.org/@babel/plugin-proposal-logical-assignment-operators/-/plugin-proposal-logical-assignment-operators-7.20.7.tgz",
"integrity": "sha512-y7C7cZgpMIjWlKE5T7eJwp+tnRYM89HmRvWM5EQuB5BoHEONjmQ8lSNmBUwOyy/GFRsohJED51YBF79hE1djug==",
"deprecated": "This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-logical-assignment-operators instead.",
"dependencies": {
"@babel/helper-plugin-utils": "^7.20.2",
"@babel/plugin-syntax-logical-assignment-operators": "^7.10.4"
},
"engines": {
"node": ">=6.9.0"
},
"peerDependencies": {
"@babel/core": "^7.0.0-0"
}
},
"node_modules/@babel/plugin-proposal-object-rest-spread": {
"version": "7.20.7",
"resolved": "https://registry.npmjs.org/@babel/plugin-proposal-object-rest-spread/-/plugin-proposal-object-rest-spread-7.20.7.tgz",
"integrity": "sha512-d2S98yCiLxDVmBmE8UjGcfPvNEUbA1U5q5WxaWFUGRzJSVAZqm5W6MbPct0jxnegUZ0niLeNX+IOzEs7wYg9Dg==",
"deprecated": "This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-object-rest-spread instead.",
"dependencies": {
"@babel/compat-data": "^7.20.5",
"@babel/helper-compilation-targets": "^7.20.7",
"@babel/helper-plugin-utils": "^7.20.2",
"@babel/plugin-syntax-object-rest-spread": "^7.8.3",
"@babel/plugin-transform-parameters": "^7.20.7"
},
"engines": {
"node": ">=6.9.0"
},
"peerDependencies": {
"@babel/core": "^7.0.0-0"
}
},
"node_modules/@babel/plugin-proposal-optional-catch-binding": {
"version": "7.18.6",
"resolved": "https://registry.npmjs.org/@babel/plugin-proposal-optional-catch-binding/-/plugin-proposal-optional-catch-binding-7.18.6.tgz",
"integrity": "sha512-Q40HEhs9DJQyaZfUjjn6vE8Cv4GmMHCYuMGIWUnlxH6400VGxOuwWsPt4FxXxJkC/5eOzgn0z21M9gMT4MOhbw==",
"deprecated": "This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-optional-catch-binding instead.",
"dependencies": {
"@babel/helper-plugin-utils": "^7.18.6",
"@babel/plugin-syntax-optional-catch-binding": "^7.8.3"
},
"engines": {
"node": ">=6.9.0"
},
"peerDependencies": {
"@babel/core": "^7.0.0-0"
}
},
"node_modules/@babel/plugin-proposal-optional-chaining": {
"version": "7.21.0",
"resolved": "https://registry.npmjs.org/@babel/plugin-proposal-optional-chaining/-/plugin-proposal-optional-chaining-7.21.0.tgz",
"integrity": "sha512-p4zeefM72gpmEe2fkUr/OnOXpWEf8nAgk7ZYVqqfFiyIG7oFfVZcCrU64hWn5xp4tQ9LkV4bTIa5rD0KANpKNA==",
"deprecated": "This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-optional-chaining instead.",
"dependencies": {
"@babel/helper-plugin-utils": "^7.20.2",
"@babel/helper-skip-transparent-expression-wrappers": "^7.20.0",
"@babel/plugin-syntax-optional-chaining": "^7.8.3"
},
"engines": {
"node": ">=6.9.0"
},
"peerDependencies": {
"@babel/core": "^7.0.0-0"
}
},
"node_modules/@babel/plugin-proposal-private-property-in-object": { "node_modules/@babel/plugin-proposal-private-property-in-object": {
"version": "7.21.0-placeholder-for-preset-env.2", "version": "7.21.0-placeholder-for-preset-env.2",
"resolved": "https://registry.npmjs.org/@babel/plugin-proposal-private-property-in-object/-/plugin-proposal-private-property-in-object-7.21.0-placeholder-for-preset-env.2.tgz", "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-private-property-in-object/-/plugin-proposal-private-property-in-object-7.21.0-placeholder-for-preset-env.2.tgz",
@ -515,6 +602,22 @@
"@babel/core": "^7.0.0-0" "@babel/core": "^7.0.0-0"
} }
}, },
"node_modules/@babel/plugin-proposal-unicode-property-regex": {
"version": "7.18.6",
"resolved": "https://registry.npmjs.org/@babel/plugin-proposal-unicode-property-regex/-/plugin-proposal-unicode-property-regex-7.18.6.tgz",
"integrity": "sha512-2BShG/d5yoZyXZfVePH91urL5wTG6ASZU9M4o03lKK8u8UW1y08OMttBSOADTcJrnPMpvDXRG3G8fyLh4ovs8w==",
"deprecated": "This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-unicode-property-regex instead.",
"dependencies": {
"@babel/helper-create-regexp-features-plugin": "^7.18.6",
"@babel/helper-plugin-utils": "^7.18.6"
},
"engines": {
"node": ">=4"
},
"peerDependencies": {
"@babel/core": "^7.0.0-0"
}
},
"node_modules/@babel/plugin-syntax-async-generators": { "node_modules/@babel/plugin-syntax-async-generators": {
"version": "7.8.4", "version": "7.8.4",
"resolved": "https://registry.npmjs.org/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.8.4.tgz", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.8.4.tgz",
@ -2063,6 +2166,31 @@
"url": "https://opencollective.com/popperjs" "url": "https://opencollective.com/popperjs"
} }
}, },
"node_modules/@rollup/plugin-babel": {
"version": "6.0.4",
"resolved": "https://registry.npmjs.org/@rollup/plugin-babel/-/plugin-babel-6.0.4.tgz",
"integrity": "sha512-YF7Y52kFdFT/xVSuVdjkV5ZdX/3YtmX0QulG+x0taQOtJdHYzVU61aSSkAgVJ7NOv6qPkIYiJSgSWWN/DM5sGw==",
"dependencies": {
"@babel/helper-module-imports": "^7.18.6",
"@rollup/pluginutils": "^5.0.1"
},
"engines": {
"node": ">=14.0.0"
},
"peerDependencies": {
"@babel/core": "^7.0.0",
"@types/babel__core": "^7.1.9",
"rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0"
},
"peerDependenciesMeta": {
"@types/babel__core": {
"optional": true
},
"rollup": {
"optional": true
}
}
},
"node_modules/@rollup/pluginutils": { "node_modules/@rollup/pluginutils": {
"version": "5.1.0", "version": "5.1.0",
"resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-5.1.0.tgz", "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-5.1.0.tgz",
@ -2502,6 +2630,32 @@
"@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0"
} }
}, },
"node_modules/babel-preset-njs": {
"version": "0.7.0",
"resolved": "https://registry.npmjs.org/babel-preset-njs/-/babel-preset-njs-0.7.0.tgz",
"integrity": "sha512-nY1iK+YdlGppIZwY5YSv+GLiik+/kgRyNKgY+9/7c+RgOLN/WgeWMabwCjVFVvqBsannRCWx7qCvXrBlAWfMGg==",
"dependencies": {
"@babel/helper-plugin-utils": "^7.21.5",
"@babel/plugin-proposal-export-namespace-from": "^7.18.9",
"@babel/plugin-proposal-logical-assignment-operators": "^7.20.7",
"@babel/plugin-proposal-object-rest-spread": "^7.20.7",
"@babel/plugin-proposal-optional-catch-binding": "^7.18.6",
"@babel/plugin-proposal-optional-chaining": "^7.21.0",
"@babel/plugin-proposal-unicode-property-regex": "^7.18.6",
"@babel/plugin-transform-classes": "^7.21.0",
"@babel/plugin-transform-destructuring": "^7.21.3",
"@babel/plugin-transform-dotall-regex": "^7.18.6",
"@babel/plugin-transform-for-of": "^7.21.5",
"@babel/plugin-transform-new-target": "^7.18.6",
"@babel/plugin-transform-object-super": "^7.18.6",
"@babel/plugin-transform-parameters": "^7.21.3",
"@babel/plugin-transform-spread": "^7.20.7",
"@babel/plugin-transform-unicode-regex": "^7.18.6"
},
"peerDependencies": {
"@babel/core": "^7.0.0-0"
}
},
"node_modules/balanced-match": { "node_modules/balanced-match": {
"version": "1.0.2", "version": "1.0.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",

View File

@ -9,14 +9,17 @@
"dependencies": { "dependencies": {
"@babel/core": "^7.24.4", "@babel/core": "^7.24.4",
"@babel/preset-env": "^7.24.4", "@babel/preset-env": "^7.24.4",
"@rollup/plugin-babel": "^6.0.4",
"@vitejs/plugin-legacy": "^5.3.2", "@vitejs/plugin-legacy": "^5.3.2",
"@vitejs/plugin-vue": "^5.0.4", "@vitejs/plugin-vue": "^5.0.4",
"@webcomponents/template": "^1.5.1", "@webcomponents/template": "^1.5.1",
"babel-preset-njs": "^0.7.0",
"bootstrap": "^5.3.3", "bootstrap": "^5.3.3",
"bootstrap-sass": "^3.4.3", "bootstrap-sass": "^3.4.3",
"core-js": "^3.36.1", "core-js": "^3.36.1",
"element-polyfill": "^1.1.0", "element-polyfill": "^1.1.0",
"events-polyfill": "^2.1.2", "events-polyfill": "^2.1.2",
"fast-glob": "^3.3.2",
"formdata-polyfill": "^4.0.10", "formdata-polyfill": "^4.0.10",
"highlight.js": "^11.9.0", "highlight.js": "^11.9.0",
"lato-webfont": "^2.15.1", "lato-webfont": "^2.15.1",

View File

@ -1,4 +0,0 @@
import legacyIndexRender from 'legacy_index.njs';
import _renders from 'fancy_index.njs';
var fancyIndexBeforeRender = _renders.fancyIndexBeforeRender;
var fancyIndexAfterRender = _renders.fancyIndexAfterRender;

View File

@ -1,32 +0,0 @@
import Mark from 'markup.min.njs';
function fancyIndexRender(r, templateUrl){
r.subrequest(templateUrl, {
args: '',
body: '',
method: 'GET'
}, function(rTmpl){
if(rTmpl.status != 200){
return r.return(rTmpl.status);
}
var tmpl = rTmpl.responseText;
var result = Mark.up(tmpl, {
url: r.variables.request_uri.replace(/\/+/g, '/').replace(/\?.*$/, ''),
});
r.status = 200;
r.headersOut['Content-Type'] = 'text/html';
r.sendHeader();
r.send(result);
r.finish();
});
}
function fancyIndexBeforeRender(r){
return fancyIndexRender(r, '/fancy-index/before.html');
}
function fancyIndexAfterRender(r){
return fancyIndexRender(r, '/fancy-index/after.html');
}
export default {fancyIndexBeforeRender, fancyIndexAfterRender};

View File

@ -1,101 +0,0 @@
import Mark from 'markup.min.njs';
function legacyIndexRender(r){
function getMirDate(d){
var result;
if (d.last_update_ts) {
var date = new Date(d.last_update_ts * 1000);
if (date.getFullYear() > 2000) {
result = `${('000'+date.getFullYear()).substr(-4)}-${('0'+(date.getMonth()+1)).substr(-2)}-${('0'+date.getDate()).substr(-2)}` +
` ${('0'+date.getHours()).substr(-2)}:${('0'+date.getMinutes()).substr(-2)}`;
} else {
result = "0000-00-00 00:00";
}
} else {
result = d.last_update.replace(/(\d\d:\d\d):\d\d(\s\+\d\d\d\d)?/, '$1');
}
return result;
}
r.subrequest('/legacy_index.html', {
args: '',
body: '',
method: 'GET'
}, function(rTmpl){
if(rTmpl.status != 200){
return r.return(rTmpl.status);
}
var tmpl = rTmpl.responseText;
r.subrequest('/static/njs/options.json', {
args: '',
body: '',
method: 'GET'
}, function(rOpt){
if(rOpt.status != 200){
return r.return(rOpt.status);
}
var global_options;
try{
global_options = JSON.parse(rOpt.responseText);
}catch(e){
return r.return(500);
}
var label_map = global_options.options.label_map;
var help_url = {};
global_options.helps.forEach((h) => help_url[h.mirrorid] = h.url);
var new_mirrors = {};
global_options.options.new_mirrors.forEach((m) => new_mirrors[m] = true);
var unlisted = global_options.options.unlisted_mirrors;
var force_help = {}
global_options.options.force_redirect_help_mirrors.forEach((m) => force_help[m] = true);
var descriptions = {};
global_options.options.mirror_desc.forEach((m) => descriptions[m.name] = m.desc);
r.subrequest('/static/tunasync.json', {
args: '',
body: '',
method: 'GET'
}, function(rMirs){
var mirs = unlisted;
if(rMirs.status == 200){
try{
mirs = mirs.concat(JSON.parse(rMirs.responseText));
}catch(e){
}
}
var renMirs = mirs.filter(m => m.status != "disabled" && m.is_master !== false).map(m => {
var status = m.status;
var target = m;
if(m.link_to){
var _target = mirs.filter(_m => _m.name == m.link_to)[0];
if(_target){
target = _target;
status = target.status;
}
}
return {
status: status,
name: m.name,
description: descriptions[m.name],
url: force_help[m.name] ? help_url[m.name] : m.url ? m.url : '/' + m.name + '/',
is_new: !!new_mirrors[m.name],
github_release: m.url && m.url.startsWith('/github-release/'),
help_url: help_url[m.name],
last_update: getMirDate(target),
label: label_map[status],
show_status: status != 'success'
};
});
renMirs.sort((a, b) => a.name < b.name ? -1: 1 );
var result = Mark.up(tmpl, {mirs: renMirs});
r.status = 200;
r.headersOut['Content-Type'] = 'text/html';
r.sendHeader();
r.send(result);
r.finish();
})
})
});
}
export default legacyIndexRender;

File diff suppressed because one or more lines are too long