renew module work

This commit is contained in:
Stewart Allen 2025-07-07 13:36:03 -04:00
commit 11552df76f
9 changed files with 116 additions and 73 deletions

123
app.js
View file

@ -16,14 +16,12 @@ const version = license.version || "rogue";
const netdb = require('@gridspace/net-level-client');
const PATH = require('path');
const fileCache = {};
const code_src = {};
const append = { mesh:'', kiri:'' };
const code = {};
const mods = {};
const load = [];
const synth = {};
const api = {};
const wrap = {};
let forceUseCache = false;
let serviceWorker = true;
@ -36,7 +34,6 @@ let dversion;
let lastmod;
let logger;
let debug;
let over;
let http;
let util;
let dir;
@ -100,7 +97,8 @@ function init(mod) {
mod.add(handleSetup);
mod.add(handleOptions);
mod.add(handleWasm);
mod.add(serveWasm);
mod.add(serveCode);
mod.add(fullpath({
"/kiri" : redir("/kiri/", 301),
"/mesh" : redir("/mesh/", 301),
@ -120,6 +118,8 @@ function init(mod) {
});
}
mod.add(rewriteHtmlVersion);
// example of how to use the new middleware
// mod.add(appendContent('/kiri/index.html', '<script>console.log("hello")</script>'));
mod.static("/lib/", "src");
mod.static("/obj/", "web/obj");
mod.static("/font/", "web/font");
@ -149,10 +149,10 @@ function init(mod) {
}
// load development and 3rd party modules
// load_modules('mod');
load_modules('mod');
// load optional local modules
// load_modules('mods');
load_modules('mods');
// run loads injected by modules
while (load.length) {
@ -162,6 +162,13 @@ function init(mod) {
logger.log({on_load_fail: e});
}
}
// minify appends
if (!debug) {
for (let key of Object.keys(append)) {
append[key] = minify(append[key]);
}
}
};
// either add module assets to path or require(init.js)
@ -179,7 +186,7 @@ function loadModule(mod, dir) {
// load module and call returned function with helper object
function initModule(mod, file, dir) {
logger.log({module: file});
logger.log({ module: file, dir });
require_fresh(file)({
// express functions added here show up at "/api/" url root
api: api,
@ -192,7 +199,6 @@ function initModule(mod, file, dir) {
args: {},
meta: mod.meta,
debug: debug,
script: script,
moddir: dir,
rootdir: mod.dir,
version: oversion || version
@ -219,28 +225,28 @@ function initModule(mod, file, dir) {
logger: log.new
},
inject: (code, file, opt = {}) => {
// console.log({ inject: opt, code, file });
let codelist = script[code];
if (!codelist) {
return logger.log(`inject missing target "${code}"`);
}
const path = `${dir}/${file}`;
codelist.push(path);
if (opt.cachever) {
cachever[path] = opt.cachever;
const body = fs.readFileSync(dir + '/' + file);
if (opt.first) {
append[code] = body.toString() + '\n' + append[code];
} else {
append[code] += body.toString() + '\n';
}
},
path: {
any: arg => { mod.add(arg) },
pre: arg => { mod.add(prepath(arg)) },
map: arg => { mod.add(fixedmap(arg)) },
code() {
const [ path, file ] = [ ...arguments ];
code[path] = fs.readFileSync(file);
},
full: arg => { mod.add(fullpath(arg)) },
map: arg => { mod.add(fixedmap(arg)) },
pre: arg => { mod.add(prepath(arg)) },
redir: redir,
remap: remap,
setup: fn => { setupFn = fn },
static: (root, pre) => {
mod.static(pre || "/", root);
},
redir: redir,
remap: remap,
setup: fn => { setupFn = fn }
},
handler: {
addCORS: addCorsHeaders,
@ -344,7 +350,20 @@ function handleOptions(req, res, next) {
}
}
function handleWasm(req, res, next) {
function serveCode(req, res, next) {
let { path } = req.app;
if (path.startsWith("/code/")) {
path = path.split('/')[2].split('.')[0];
if (code[path]) {
res.setHeader('Content-Type', 'application/javascript');
res.setHeader('Cache-Control', 'public, max-age=600');
return res.end(code[path]);
}
}
next();
}
function serveWasm(req, res, next) {
let file = req.app.path.split('/').pop();
let ext = (file || '').split('.')[1];
let path = PATH.join(dir,"src","wasm",file);
@ -385,8 +404,7 @@ function generateDevices() {
fs.writeFileSync(PATH.join(dir,"src","pack","devices.js"), `export const devices = ${dstr};`);
}
function minify(path) {
let code = fs.readFileSync(path);
function minify(code) {
let mini = uglify.minify(code.toString(), {
compress: {
merge_vars: false,
@ -512,39 +530,32 @@ function rewriteHtmlVersion(req, res, next) {
"/lib/kiri-run/minion.js"
].indexOf(req.app.path) >= 0) {
addCorsHeaders(req, res);
} else if ([
"/kiri/",
"/kiri/engine.html",
"/kiri/frame.html",
"/mesh/",
"/meta/",
}
if ([
"/lib/main/kiri.js",
"/lib/main/mesh.js",
].indexOf(req.app.path) >= 0) {
addCorsHeaders(req, res);
let real_write = res.write;
let real_end = res.end;
let mlen = '{{version}}'.length;
let vstr = oversion || dversion || version;
if (vstr.length < mlen) {
vstr = vstr.padStart(mlen,0);
} else if (vstr.length > mlen) {
vstr = vstr.substring(0,mlen);
}
res.write = function() {
try {
// console.log('res.write', req.app.path, arguments[0].length);
arguments[0] = arguments[0].toString().replace(/{{version}}/g,vstr);
// console.log('new length', arguments[0].length);
real_write.apply(res, arguments);
} catch (err) {
console.log({ rewrite_error: err });
}
const data = append[req.app.path.split('/')[3].split('.')[0]];
// console.log({ append: req.app.path, data: data?.length });
if (!data) return next();
const real_write = res.write;
const real_end = res.end;
let body = '';
res.write = function (chunk, encoding) {
body += chunk.toString(encoding);
};
res.end = function() {
// console.log('res.write', req.app.path, arguments[0]?.length);
if (arguments[0]) {
arguments[0] = arguments[0].toString().replace(/{{version}}/g,vstr);
res.end = function (chunk, encoding) {
if (chunk) {
body += chunk.toString(encoding);
}
real_end.apply(res, arguments);
body += data;
res.setHeader('Content-Length', Buffer.byteLength(body));
real_write.call(res, body);
real_end.call(res);
};
}

View file

@ -2,9 +2,8 @@ self.kiri.load(api => {
console.log('BAMBU MODULE RUNNING');
const { kiri, moto } = self;
const { ui } = kiri;
const h = moto.webui;
const { uc: ui } = api;
const { $, h } = api.web;
const defams = ";; DEFINE BAMBU-AMS ";
const readonly = true;
const stock_colors = Object.values({

View file

@ -8,6 +8,7 @@ self.kiri.load(api => {
});
api.stats.set('kiri', self.kiri.version + 'e');
});
if (self.mesh && self.mesh.api) {
self.mesh.api.electron = {};
}

View file

@ -18,11 +18,15 @@ import { selection } from './selection.js';
import { stats } from '../kiri/stats.js';
import { widgets } from './widgets.js';
import { updateTool } from '../kiri-mode/cam/tools.js';
import { version } from '../moto/license.js';
import { space as SPACE } from '../moto/space.js';
import { LANG } from './lang.js';
import { LOCAL, SETUP, SECURE } from './main.js';
import { UI } from './ui.js';
import web from '../moto/webui.js';
let UC = UI.prefix('kiri').inputAction(settings.conf.update),
und = undefined,
clone = Object.clone,
@ -80,6 +84,7 @@ let UC = UI.prefix('kiri').inputAction(settings.conf.update),
},
local = {
get: (key) => localGet(key),
getItem: (key) => localGet(key),
getInt: (key) => parseInt(localGet(key)),
getFloat: (key) => parseFloat(localGet(key)),
getBoolean: (key, def = true) => {
@ -89,6 +94,7 @@ let UC = UI.prefix('kiri').inputAction(settings.conf.update),
toggle: (key, val, def) => localSet(key, val ?? !api.local.getBoolean(key, def)),
put: (key, val) => localSet(key, val),
set: (key, val) => localSet(key, val),
setItem: (key, val) => localSet(key, val),
},
tweak = {
line_precision(v) { api.work.config({ base: { clipperClean: v } }) },
@ -152,6 +158,7 @@ export const api = {
settings,
show,
space,
SPACE,
stacks: STACKS,
stats,
tool: {
@ -166,7 +173,9 @@ export const api = {
layer_hi: 0,
layer_max: 0
},
version,
view,
web,
widgets,
work,
};

View file

@ -18,7 +18,7 @@ import { init as initWEDM } from '../kiri-mode/wedm/client.js';
import { init as initWJET } from '../kiri-mode/wjet/client.js';
let { CAM, SLA, FDM, LASER, DRAG, WJET, WEDM } = MODES,
{ client, catalog, platform, selection } = api,
{ client, catalog, platform, selection, stats } = api,
LANG = api.language.current,
WIN = self.window,
DOC = self.document,
@ -1859,8 +1859,9 @@ function init_two() {
// load script extensions
if (SETUP.s) SETUP.s.forEach(function(lib) {
let scr = DOC.createElement('script');
scr.setAttribute('defer',true);
scr.setAttribute('src',`/code/${lib}.js?${version}`);
scr.setAttribute('async', true);
scr.setAttribute('defer', true);
scr.setAttribute('src',`/code/${lib}.js?${version}}`);
DOC.body.appendChild(scr);
stats.add('load_'+lib);
api.event.emit('load.lib', lib);

View file

@ -774,6 +774,7 @@ function showHelpFile(local,then) {
WIN.open("//docs.grid.space/", "_help");
return;
}
const LANG = api.language.current;
$('kiri-version').innerHTML = `${LANG.version} ${version}`;
showModal('help');
api.event.emit('help.show', local);

View file

@ -8,26 +8,34 @@ import '../kiri/lang-en.js';
import { run } from '../kiri/init.js';
const load = [];
let load = [];
function safeExec(fn) {
try {
fn(kiri.api);
} catch (error) {
console.log('load error', fn, error);
}
}
function checkReady() {
if (document.readyState === 'complete') {
let api = run();
kiri.api = api;
kiri.api = run();
for (let fn of load) {
try {
fn(api);
} catch (error) {
console.log('load error', fn, error);
}
safeExec(fn);
}
load = undefined;
}
}
self.kiri = {
load(fn) {
console.log('KIRI LOAD', [...arguments]);
load.push(fn);
// console.log('KIRI LOAD', [...arguments]);
if (load) {
load.push(fn);
} else {
safeExec(fn);
}
}
};

View file

@ -92,6 +92,9 @@ function init() {
// hide url params
history.replaceState({}, '', '/mesh/');
// for electron
self.mesh = { api };
}
// restore space layout and view from previous session

View file

@ -168,4 +168,14 @@ export {
$C,
h,
estop
};
}
export default {
$,
$d,
$h,
$c,
$C,
h,
estop
}