Update SpaccDotWebServer to add all currently needed features, update example

This commit is contained in:
octospacc 2024-02-24 20:26:34 +01:00
parent 618842883d
commit 63dc2e648f
5 changed files with 295 additions and 263 deletions

View File

@ -1,16 +1,16 @@
<!DOCTYPE html><html><head><!--
--><meta charset="utf-8"/><!--
--><meta name="viewport" content="width=device-width, initial-scale=1.0"/><!--
--><title>Example</title><!--
--><link rel="stylesheet" href="/static/Example.css"/><!--
--></head><body><!--
--><div id="transition"></div><!--
--><div id="app">
<script>
window.process = null;
window.require = () => window.SpaccDotWebServer;
window.resFilesData = { "Example.css": "data:text/css;base64,Ym9keSB7CgliYWNrZ3JvdW5kLWNvbG9yOiBsaWdodGdyYXk7Cgljb2xvcjogYmxhY2s7Cn0KCmgyIHsKCXBvc2l0aW9uOiByZWxhdGl2ZTsKCXRvcDogM2VtOwoJcm90YXRlOiAxNWRlZzsKCWNvbG9yOiBwdXJwbGU7Cn0K" };
</script>
<script src="./SpaccDotWeb.Server.js"></script>
<script>
window.require = () => window.SpaccDotWebServer;
window.SpaccDotWebServer.resFilesData = { "Example.css": "data:text/css;base64,Ym9keSB7CgliYWNrZ3JvdW5kLWNvbG9yOiBsaWdodGdyYXk7Cgljb2xvcjogYmxhY2s7Cn0KCmgyIHsKCXdpZHRoOiBtYXgtY29udGVudDsKCXJvdGF0ZTogMTVkZWc7Cgljb2xvcjogRGVlcFBpbms7Cn0K" };
</script>
<script src="./Example.Server.js"></script>
</div><!--
--></body></html>

View File

@ -1,16 +1,20 @@
const SpaccDotWebServer = require('./SpaccDotWeb.Server.js')({
const SpaccDotWebServer = require('./SpaccDotWeb.Server.js');
const server = SpaccDotWebServer.setup({
appName: 'Example',
// staticPrefix: '/static/',
// staticFiles: [],
linkStyles: [ 'Example.css' ],
// linkScripts: [],
// htmlPager: htmlPager(content) => `...`,
// pageTitler: pageTitler(title) => `...`,
// appPager: appPager(content, title) => `...`,
// htmlPager: htmlPager(content, title) => `...`,
});
if (process && process.argv[2] === 'html') {
SpaccDotWebServer.writeStaticHtml(__filename);
if (SpaccDotWebServer.envIsNode && process.argv[2] === 'html') {
server.writeStaticHtml();
console.log('Dumped Static HTML!');
} else {
SpaccDotWebServer.initServer({
server.initServer({
// defaultResponse: { code: 500, headers: {} },
// endpointsFalltrough: false,
// port: 3000,
@ -19,7 +23,7 @@ if (process && process.argv[2] === 'html') {
// appElement: 'div#app',
// transitionElement: 'div#transition',
endpoints: [
[ (ctx) => (['GET', 'POST'].includes(ctx.request.method) && ctx.request.url.toLowerCase().startsWith('/main/')), (ctx) => {
[ (ctx) => (['GET', 'POST'].includes(ctx.request.method) && ctx.urlSections[0] === 'main'), (ctx) => {
if (ctx.request.method === 'POST') {
if (ctx.bodyParameters?.add) {
ctx.setCookie(`count=${parseInt(ctx.getCookie('count') || 0) + 1}`);
@ -32,13 +36,13 @@ if (process && process.argv[2] === 'html') {
${ctx.request.method === 'POST' ? `<p>POST body parameters:</p><pre>${JSON.stringify(ctx.bodyParameters)}</pre>` : ''}
<p>This page was rendered at ${Date()}.</p>
<p>These were your cookies at time of request:</p>
<pre>${ctx.getCookie()}</pre>
<pre>${ctx.getCookie() || '[None]'}</pre>
<form method="POST">
<input type="submit" name="add" value="Add 1 to cookie"/>
<input type="submit" name="reset" value="Reset cookies"/>
</form>
`;
ctx.renderPage(content);
ctx.renderPage(content, 'Test');
// return { code: 200, headers: { 'content-type': 'text/html; charset=utf-8' }, body: content }
} ],
@ -46,4 +50,5 @@ if (process && process.argv[2] === 'html') {
// [ (ctx) => (ctx.request.method === 'GET'), (ctx) => ({ code: 302, headers: { location: '/main/' } }) ],
],
});
console.log('Running Server...');
};

View File

@ -4,8 +4,7 @@ body {
}
h2 {
position: relative;
top: 3em;
width: max-content;
rotate: 15deg;
color: purple;
color: DeepPink;
}

View File

@ -1,10 +1,15 @@
/* TODO:
* built-in logging
* other things listed in the file
*/
(() => {
const envIsNode = (typeof module === 'object' && typeof module.exports === 'object');
const envIsBrowser = (typeof window !== 'undefined' && typeof window.document !== 'undefined');
let fs, path, mime, multipart;
const allOpts = {};
const main = (globalOptions={}) => {
const envIsNode = (typeof module === 'object' && typeof module.exports === 'object');
const envIsBrowser = (typeof window !== 'undefined' && typeof window.document !== 'undefined');
const allOpts = {};
let fs, path, mime, multipart;
const setup = (globalOptions={}) => {
allOpts.global = globalOptions;
allOpts.global.staticPrefix ||= '/static/';
allOpts.global.staticFiles ||= [];
@ -16,25 +21,28 @@
allOpts.global.staticFiles.push(item);
};
};
allOpts.global.htmlPager ||= (content) => `<!DOCTYPE html><html><head><!--
allOpts.global.pageTitler ||= (title) => `${title || ''}${title && allOpts.global.appName ? ' — ' : ''}${allOpts.global.appName || ''}`,
allOpts.global.appPager ||= (content, title) => content,
allOpts.global.htmlPager ||= (content, title) => `<!DOCTYPE html><html><head><!--
--><meta charset="utf-8"/><!--
--><meta name="viewport" content="width=device-width, initial-scale=1.0"/><!--
--><title>${allOpts.global.pageTitler(title)}</title><!--
-->${allOpts.global.linkStyles.map((item) => {
return `<link rel="stylesheet" href="${allOpts.global.staticFiles.includes(item) ? (allOpts.global.staticPrefix + item) : item}"/>`;
}).join('')}<!--
--></head><body><!--
--><div id="transition"></div><!--
--><div id="app">${content}</div><!--
--><div id="app">${allOpts.global.appPager(content, title)}</div><!--
--></body></html>`;
const result = {};
result.initServer = (serverOptions={}) => initServer(serverOptions);
if (envIsNode) {
result.writeStaticHtml = (mainScriptPath) => writeStaticHtml(mainScriptPath);
result.writeStaticHtml = writeStaticHtml;
};
return result;
};
};
const initServer = (serverOptions) => {
const initServer = (serverOptions) => {
allOpts.server = serverOptions;
allOpts.server.defaultResponse ||= { code: 500, headers: {} };
allOpts.server.endpointsFalltrough ||= false;
@ -54,40 +62,46 @@
});
navigatePage();
};
};
};
const writeStaticHtml = (mainScriptPath) => {
fs.writeFileSync((mainScriptPath.split('.').slice(0, -1).join('.') + '.html'), allOpts.global.htmlPager(`
const writeStaticHtml = () => {
// TODO: fix script paths
// TODO: this should somehow set envIsBrowser to true to maybe allow for correct template rendering, but how to do it without causing race conditions? maybe we should expose another variable
fs.writeFileSync((process.mainModule.filename.split('.').slice(0, -1).join('.') + '.html'), allOpts.global.htmlPager(`
<script src="./${path.basename(__filename)}"></script>
<script>
window.process = null;
window.require = () => window.SpaccDotWebServer;
window.resFilesData = { ${allOpts.global.staticFiles.map((file) => {
const filePath = (mainScriptPath.split(path.sep).slice(0, -1).join(path.sep) + path.sep + file);
window.SpaccDotWebServer.resFilesData = { ${allOpts.global.staticFiles.map((file) => {
const filePath = (process.mainModule.filename.split(path.sep).slice(0, -1).join(path.sep) + path.sep + file);
return `"${file}": "data:${mime.lookup(filePath)};base64,${fs.readFileSync(filePath).toString('base64')}"`;
})} };
</script>
<script src="./${path.basename(__filename)}"></script>
<script src="./${path.basename(mainScriptPath)}"></script>
<script src="./${path.basename(process.mainModule.filename)}"></script>
`));
};
};
const handleRequest = async (request, response={}) => {
const handleRequest = async (request, response={}) => {
// build request context and handle special tasks
let result = allOpts.server.defaultResponse;
const context = {
request,
response,
urlSections: request.url.slice(1).toLowerCase().split('?')[0].split('/'),
urlParameters: (new URLSearchParams(request.url.split('?')[1]?.join('?'))),
bodyParameters: (request.method === 'POST' && await parseBodyParams(request)), // TODO which other methods need body?
getCookie: (cookie) => getCookie(request, cookie),
setCookie: (cookie) => setCookie(response, cookie),
renderPage: (content) => renderPage(response, content),
renderPage: (content, title) => renderPage(response, content, title),
redirectTo: (url) => redirectTo(response, url),
};
// client transitions
if (envIsBrowser && document.querySelector(allOpts.server.transitionElement)) {
document.querySelector(allOpts.server.transitionElement).style.display = 'block';
};
// serve static files
if (envIsNode && request.method === 'GET' && request.url.toLowerCase().startsWith(allOpts.global.staticPrefix)) {
const resPath = request.url.split(allOpts.global.staticPrefix).slice(1).join(allOpts.global.staticPrefix);
const filePath = (__dirname + path.sep + resPath); // TODO i think we need to read this another way if the module is in a different directory from the importing program
const filePath = (process.mainModule.path + path.sep + resPath); // TODO i think we need to read this another way if the module is in a different directory from the importing program
if (allOpts.global.staticFiles.includes(resPath) && fs.existsSync(filePath)) {
result = { code: 200, headers: { 'content-type': mime.lookup(filePath) }, body: fs.readFileSync(filePath) };
} else {
@ -96,7 +110,7 @@
} else {
// handle custom endpoints
for (const [check, procedure] of allOpts.server.endpoints) {
if (check(context)) {
if (await check(context)) {
result = await procedure(context);
if (!allOpts.server.endpointsFalltrough) {
break;
@ -112,22 +126,23 @@
};
response.end(result.body);
};
};
};
const renderPage = (response, content) => {
const renderPage = (response, content, title) => {
// TODO titles and things
// TODO status code could need to be different in different situations and so should be set accordingly?
if (envIsNode) {
response.setHeader('content-type', 'text/html; charset=utf-8');
response.end(allOpts.global.htmlPager(content));
response.end(allOpts.global.htmlPager(content, title));
};
if (envIsBrowser) {
document.querySelector(allOpts.server.appElement).innerHTML = content;
document.title = allOpts.global.pageTitler(title);
document.querySelector(allOpts.server.appElement).innerHTML = allOpts.global.appPager(content, title);
for (const srcElem of document.querySelectorAll(`[src^="${allOpts.global.staticPrefix}"]`)) {
srcElem.src = resFilesData[srcElem.getAttribute('src')];
srcElem.src = window.SpaccDotWebServer.resFilesData[srcElem.getAttribute('src')];
};
for (const linkElem of document.querySelectorAll(`link[rel="stylesheet"][href^="${allOpts.global.staticPrefix}"]`)) {
linkElem.href = resFilesData[linkElem.getAttribute('href').slice(allOpts.global.staticPrefix.length)];
linkElem.href = window.SpaccDotWebServer.resFilesData[linkElem.getAttribute('href').slice(allOpts.global.staticPrefix.length)];
};
for (const aElem of document.querySelectorAll('a[href^="/"]')) {
aElem.href = `#${aElem.getAttribute('href')}`;
@ -145,10 +160,13 @@
});
};
};
if (document.querySelector(allOpts.server.transitionElement)) {
document.querySelector(allOpts.server.transitionElement).style.display = 'none';
};
};
};
const redirectTo = (response, url) => {
const redirectTo = (response, url) => {
if (envIsNode) {
response.statusCode = 302;
response.setHeader('location', url);
@ -157,9 +175,9 @@
if (envIsBrowser) {
location.hash = url;
};
};
};
const parseBodyParams = async (request) => {
const parseBodyParams = async (request) => {
try {
let params = {};
if (envIsNode) {
@ -193,12 +211,12 @@
console.log(err);
request.connection?.destroy();
};
};
};
const getCookie = (request, name) => {
const getCookie = (request, name) => {
let cookies;
if (envIsNode) {
cookies = request.headers?.cookie;
cookies = (request.headers?.cookie || '');
};
if (envIsBrowser) {
cookies = clientCookieApi();
@ -215,9 +233,9 @@
// get all cookies
return cookies;
};
};
};
const setCookie = (response, cookie) => {
const setCookie = (response, cookie) => {
if (envIsNode) {
response.setHeader('Set-Cookie', cookie);
// TODO update current cookie list in existing request to reflect new assignment
@ -225,15 +243,16 @@
if (envIsBrowser) {
clientCookieApi(cookie);
};
};
};
// try to use the built-in cookie API, fallback to a Storage-based wrapper in case it fails (for example on file:///)
const clientCookieApi = (envIsBrowser && (document.cookie || (!document.cookie && (document.cookie = '_=_') && document.cookie) ? (set) => (set ? (document.cookie = set) : document.cookie) : (set) => {
// try to use the built-in cookie API, fallback to a Storage-based wrapper in case it fails (for example on file:///)
const clientCookieApi = (envIsBrowser && (document.cookie || (!document.cookie && (document.cookie = '_=_') && document.cookie) ? (set) => (set ? (document.cookie = set) : document.cookie) : (set) => {
const gid = allOpts.global.appName; // TODO: introduce a conf field that is specifically a GID for less potential problems?
// also, TODO: what to do when no app name or any id is set?
if (set) {
let api = sessionStorage;
const tokens = set.split(';');
const [key, ...rest] = tokens[0].split('=');
let [key, ...rest] = tokens[0].split('=');
for (let token of tokens) {
token = token.trim();
if (['expires', 'max-age'].includes(token.split('=')[0].toLowerCase())) {
@ -241,7 +260,14 @@
break;
};
};
api.setItem(`${gid}/${key}`, rest.join('='));
key = `${gid}/${key}`;
const value = rest.join('=');
if (value) {
api.setItem(key, value);
} else {
sessionStorage.removeItem(key);
localStorage.removeItem(key);
};
} else /*(get)*/ {
let items = '';
for (const item of Object.entries({ ...localStorage, ...sessionStorage })) {
@ -251,16 +277,18 @@
}
return items.slice(0, -1);
};
}));
}));
if (envIsNode) {
const exportObj = { envIsNode, envIsBrowser, setup };
if (envIsNode) {
fs = require('fs');
path = require('path');
mime = require('mime-types');
multipart = require('parse-multipart-data');
module.exports = main;
};
if (envIsBrowser) {
window.SpaccDotWebServer = main;
};
module.exports = exportObj;
};
if (envIsBrowser) {
window.SpaccDotWebServer = exportObj;
};
})();

4
package-lock.json generated
View File

@ -1,12 +1,12 @@
{
"name": "SpaccDotWeb",
"version": "indev",
"version": "0.2.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "SpaccDotWeb",
"version": "indev",
"version": "0.2.1",
"dependencies": {
"mime-types": "^2.1.35",
"parse-multipart-data": "^1.5.0"