@plurid/plurid-react-server 0.0.0-14 → 0.0.0-16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/README.md +69 -5
  2. package/distribution/index.d.mts +244 -0
  3. package/distribution/index.d.ts +244 -6
  4. package/distribution/index.js +1573 -1056
  5. package/distribution/index.js.map +1 -0
  6. package/distribution/index.mjs +1642 -0
  7. package/distribution/index.mjs.map +1 -0
  8. package/package.json +129 -133
  9. package/distribution/__tests__/sanity.test.d.ts +0 -0
  10. package/distribution/data/constants/general/index.d.ts +0 -34
  11. package/distribution/data/constants/index.d.ts +0 -2
  12. package/distribution/data/constants/stiller/index.d.ts +0 -2
  13. package/distribution/data/interfaces/external/index.d.ts +0 -151
  14. package/distribution/data/interfaces/index.d.ts +0 -2
  15. package/distribution/data/interfaces/internal/index.d.ts +0 -83
  16. package/distribution/data/templates/index.d.ts +0 -2
  17. package/distribution/index.es.js +0 -1095
  18. package/distribution/objects/ContentGenerator/index.d.ts +0 -7
  19. package/distribution/objects/LiveServer/index.d.ts +0 -13
  20. package/distribution/objects/Renderer/index.d.ts +0 -22
  21. package/distribution/objects/Renderer/template/index.d.ts +0 -3
  22. package/distribution/objects/Server/index.d.ts +0 -57
  23. package/distribution/objects/Stiller/__tests__/index.test.d.ts +0 -1
  24. package/distribution/objects/Stiller/index.d.ts +0 -24
  25. package/distribution/objects/StillsGenerator/index.d.ts +0 -8
  26. package/distribution/objects/StillsManager/index.d.ts +0 -9
  27. package/distribution/utilities/pttp/index.d.ts +0 -6
  28. package/distribution/utilities/template/index.d.ts +0 -9
  29. package/distribution/utilities/wrapping/index.d.ts +0 -28
@@ -1,1127 +1,1644 @@
1
1
  "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // source/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ PluridLiveServer: () => LiveServer_default,
34
+ PluridStillsGenerator: () => StillsGenerator_default,
35
+ default: () => index_default
5
36
  });
6
-
7
- var fs = require("fs");
8
-
9
- var path = require("path");
10
-
11
- var express = require("express");
12
-
13
- var compression = require("compression");
14
-
15
- var bodyParser = require("body-parser");
16
-
17
- var open = require("open");
18
-
19
- var styledComponents = require("styled-components");
20
-
21
- var pluridFunctions = require("@plurid/plurid-functions");
22
-
23
- var pluridEngine = require("@plurid/plurid-engine");
24
-
25
- var pluridReact = require("@plurid/plurid-react");
26
-
27
- var htmlMinifier = require("html-minifier");
28
-
29
- var React = require("react");
30
-
31
- var server = require("react-dom/server");
32
-
33
- var reactHelmetAsync = require("react-helmet-async");
34
-
35
- var http = require("http");
36
-
37
- var child_process = require("child_process");
38
-
39
- var detectPort = require("detect-port");
40
-
41
- function _interopDefaultLegacy(e) {
42
- return e && typeof e === "object" && "default" in e ? e : {
43
- default: e
44
- };
45
- }
46
-
47
- var fs__default = _interopDefaultLegacy(fs);
48
-
49
- var path__default = _interopDefaultLegacy(path);
50
-
51
- var express__default = _interopDefaultLegacy(express);
52
-
53
- var compression__default = _interopDefaultLegacy(compression);
54
-
55
- var open__default = _interopDefaultLegacy(open);
56
-
57
- var React__default = _interopDefaultLegacy(React);
58
-
59
- var http__default = _interopDefaultLegacy(http);
60
-
61
- var detectPort__default = _interopDefaultLegacy(detectPort);
62
-
63
- function __awaiter(thisArg, _arguments, P, generator) {
64
- function adopt(value) {
65
- return value instanceof P ? value : new P((function(resolve) {
66
- resolve(value);
67
- }));
68
- }
69
- return new (P || (P = Promise))((function(resolve, reject) {
70
- function fulfilled(value) {
71
- try {
72
- step(generator.next(value));
73
- } catch (e) {
74
- reject(e);
75
- }
76
- }
77
- function rejected(value) {
78
- try {
79
- step(generator["throw"](value));
80
- } catch (e) {
81
- reject(e);
82
- }
83
- }
84
- function step(result) {
85
- result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
86
- }
87
- step((generator = generator.apply(thisArg, _arguments || [])).next());
88
- }));
89
- }
90
-
91
- function __await(v) {
92
- return this instanceof __await ? (this.v = v, this) : new __await(v);
93
- }
94
-
95
- function __asyncGenerator(thisArg, _arguments, generator) {
96
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
97
- var g = generator.apply(thisArg, _arguments || []), i, q = [];
98
- return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
99
- return this;
100
- }, i;
101
- function verb(n) {
102
- if (g[n]) i[n] = function(v) {
103
- return new Promise((function(a, b) {
104
- q.push([ n, v, a, b ]) > 1 || resume(n, v);
105
- }));
106
- };
107
- }
108
- function resume(n, v) {
109
- try {
110
- step(g[n](v));
111
- } catch (e) {
112
- settle(q[0][3], e);
113
- }
114
- }
115
- function step(r) {
116
- r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
117
- }
118
- function fulfill(value) {
119
- resume("next", value);
120
- }
121
- function reject(value) {
122
- resume("throw", value);
123
- }
124
- function settle(f, v) {
125
- if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
126
- }
127
- }
128
-
129
- const DEFAULT_SERVER_PORT = process.env.PORT ? parseInt(process.env.PORT) : 8080;
130
-
131
- const DEFAULT_SERVER_OPTIONS_SERVER_NAME = "Plurid Server";
132
-
133
- const DEFAULT_SERVER_OPTIONS_HOSTNAME = "origin";
134
-
135
- const DEFAULT_SERVER_OPTIONS_QUIET = false;
136
-
137
- const DEFAULT_SERVER_OPTIONS_COMPRESSION = true;
138
-
139
- const DEFAULT_SERVER_OPTIONS_OPEN = false;
140
-
141
- const DEFAULT_SERVER_OPTIONS_BUILD_DIRECTORY = "build";
142
-
143
- const DEFAULT_SERVER_OPTIONS_ASSETS_DIRECTORY = "assets";
144
-
145
- const DEFAULT_SERVER_OPTIONS_STILLS_DIRECTORY = "stills";
146
-
147
- const DEFAULT_SERVER_OPTIONS_GATEWAY = "/gateway";
148
-
149
- const DEFAULT_SERVER_OPTIONS = {
150
- SERVER_NAME: DEFAULT_SERVER_OPTIONS_SERVER_NAME,
151
- HOSTNAME: DEFAULT_SERVER_OPTIONS_HOSTNAME,
152
- QUIET: DEFAULT_SERVER_OPTIONS_QUIET,
153
- COMPRESSION: DEFAULT_SERVER_OPTIONS_COMPRESSION,
154
- OPEN: DEFAULT_SERVER_OPTIONS_OPEN,
155
- BUILD_DIRECTORY: DEFAULT_SERVER_OPTIONS_BUILD_DIRECTORY,
156
- ASSETS_DIRECTORY: DEFAULT_SERVER_OPTIONS_ASSETS_DIRECTORY,
157
- STILLS_DIRECTORY: DEFAULT_SERVER_OPTIONS_STILLS_DIRECTORY,
158
- GATEWAY: DEFAULT_SERVER_OPTIONS_GATEWAY
37
+ module.exports = __toCommonJS(index_exports);
38
+
39
+ // source/objects/Server/index.ts
40
+ var import_fs2 = __toESM(require("fs"));
41
+ var import_path2 = __toESM(require("path"));
42
+ var import_express = __toESM(require("express"));
43
+ var import_compression = __toESM(require("compression"));
44
+ var import_open = __toESM(require("open"));
45
+ var import_styled_components2 = require("styled-components");
46
+ var import_plurid_functions = require("@plurid/plurid-functions");
47
+ var import_plurid_engine = require("@plurid/plurid-engine");
48
+ var import_plurid_react2 = require("@plurid/plurid-react");
49
+
50
+ // source/data/constants/general/index.ts
51
+ var DEFAULT_SERVER_PORT = process.env.PORT ? parseInt(process.env.PORT) : 8080;
52
+ var DEFAULT_SERVER_OPTIONS_SERVER_NAME = "Plurid Server";
53
+ var DEFAULT_SERVER_OPTIONS_HOSTNAME = "origin";
54
+ var DEFAULT_SERVER_OPTIONS_QUIET = false;
55
+ var DEFAULT_SERVER_OPTIONS_COMPRESSION = true;
56
+ var DEFAULT_SERVER_OPTIONS_OPEN = false;
57
+ var DEFAULT_SERVER_OPTIONS_BUILD_DIRECTORY = "build";
58
+ var DEFAULT_SERVER_OPTIONS_ASSETS_DIRECTORY = "assets";
59
+ var DEFAULT_SERVER_OPTIONS_STILLS_DIRECTORY = "stills";
60
+ var DEFAULT_SERVER_OPTIONS_GATEWAY = "/gateway";
61
+ var DEFAULT_SERVER_OPTIONS = {
62
+ SERVER_NAME: DEFAULT_SERVER_OPTIONS_SERVER_NAME,
63
+ HOSTNAME: DEFAULT_SERVER_OPTIONS_HOSTNAME,
64
+ QUIET: DEFAULT_SERVER_OPTIONS_QUIET,
65
+ COMPRESSION: DEFAULT_SERVER_OPTIONS_COMPRESSION,
66
+ OPEN: DEFAULT_SERVER_OPTIONS_OPEN,
67
+ BUILD_DIRECTORY: DEFAULT_SERVER_OPTIONS_BUILD_DIRECTORY,
68
+ ASSETS_DIRECTORY: DEFAULT_SERVER_OPTIONS_ASSETS_DIRECTORY,
69
+ STILLS_DIRECTORY: DEFAULT_SERVER_OPTIONS_STILLS_DIRECTORY,
70
+ GATEWAY: DEFAULT_SERVER_OPTIONS_GATEWAY
159
71
  };
160
-
161
- const DEFAULT_RENDERER_LANGUAGE = "en";
162
-
163
- const DEFAULT_RENDERER_ROOT = "root";
164
-
165
- const DEFAULT_RENDERER_PLURID_STATE = "{}";
166
-
167
- const DEFAULT_RENDERER_VENDOR_SCRIPT_SOURCE = "/vendor.js";
168
-
169
- const DEFAULT_RENDERER_MAIN_SCRIPT_SOURCE = "/index.js";
170
-
171
- const DEFAULT__PRELOADED_PLURID_METASTATE__ = "__PRELOADED_PLURID_METASTATE__";
172
-
173
- const CATCH_ALL_ROUTE = "*";
174
-
175
- const NOT_FOUND_ROUTE = process.env.PLURID_SERVER_NOT_FOUND_ROUTE || "/not-found";
176
-
177
- const PTTP_ROUTE = process.env.PLURID_SERVER_PTTP_ROUTE || "/pttp";
178
-
179
- const environment = {
180
- production: process.env.ENV_MODE === "production",
181
- development: process.env.ENV_MODE === "development"
72
+ var DEFAULT_RENDERER_LANGUAGE = "en";
73
+ var DEFAULT_RENDERER_ROOT = "root";
74
+ var DEFAULT_RENDERER_PLURID_STATE = "{}";
75
+ var DEFAULT_RENDERER_VENDOR_SCRIPT_SOURCE = "/vendor.js";
76
+ var DEFAULT_RENDERER_MAIN_SCRIPT_SOURCE = "/index.js";
77
+ var DEFAULT__PRELOADED_PLURID_METASTATE__ = "__PRELOADED_PLURID_METASTATE__";
78
+ var CATCH_ALL_ROUTE = "*";
79
+ var CATCH_ALL_ROUTE_PATTERN = /.*/;
80
+ var NOT_FOUND_ROUTE = process.env.PLURID_SERVER_NOT_FOUND_ROUTE || "/not-found";
81
+ var PTTP_ROUTE = process.env.PLURID_SERVER_PTTP_ROUTE || "/pttp";
82
+ var environment = {
83
+ production: process.env.ENV_MODE === "production",
84
+ development: process.env.ENV_MODE === "development"
182
85
  };
183
86
 
184
- const defaultStillerOptions = {
185
- waitUntil: "networkidle0",
186
- timeout: 3e4,
187
- ignore: []
87
+ // source/data/constants/stiller/index.ts
88
+ var defaultStillerOptions = {
89
+ waitUntil: "networkidle0",
90
+ timeout: 3e4,
91
+ ignore: []
188
92
  };
189
93
 
190
- const cleanTemplate = template => htmlMinifier.minify(template, {
191
- collapseWhitespace: true,
192
- conservativeCollapse: true,
193
- collapseInlineTagWhitespace: false
194
- });
195
-
196
- const resolveBackgroundStyle = store => {
197
- var _a;
198
- const defaultBackground = {
199
- gradientBackground: "hsl(220, 10%, 32%)",
200
- gradientForeground: "hsl(220, 10%, 18%)"
201
- };
202
- try {
203
- const storeJSON = JSON.parse(store);
204
- const generalPluridTheme = (_a = storeJSON === null || storeJSON === void 0 ? void 0 : storeJSON.themes) === null || _a === void 0 ? void 0 : _a.general;
205
- if (!generalPluridTheme) {
206
- return defaultBackground;
207
- }
208
- const gradientBackground = generalPluridTheme.type === "dark" ? generalPluridTheme.backgroundColorTertiary : generalPluridTheme.backgroundColorPrimary;
209
- const gradientForeground = generalPluridTheme.type === "dark" ? generalPluridTheme.backgroundColorPrimary : generalPluridTheme.backgroundColorTertiary;
210
- return {
211
- gradientBackground: gradientBackground,
212
- gradientForeground: gradientForeground
213
- };
214
- } catch (error) {
215
- return defaultBackground;
94
+ // source/utilities/template/index.ts
95
+ var import_html_minifier_terser = require("html-minifier-terser");
96
+ var cleanTemplate = (template2) => {
97
+ return (0, import_html_minifier_terser.minify)(
98
+ template2,
99
+ {
100
+ collapseWhitespace: true,
101
+ conservativeCollapse: true,
102
+ collapseInlineTagWhitespace: false
216
103
  }
104
+ );
217
105
  };
218
-
219
- const recordToString = record => {
220
- if (!record) {
221
- return "";
222
- }
223
- let recordString = "";
224
- for (const [key, value] of Object.entries(record)) {
225
- recordString += `${key}="${value}"`;
106
+ var resolveBackgroundStyle = (store) => {
107
+ const defaultBackground = {
108
+ gradientBackground: "hsl(220, 10%, 32%)",
109
+ gradientForeground: "hsl(220, 10%, 18%)"
110
+ };
111
+ try {
112
+ const storeJSON = JSON.parse(store);
113
+ const generalPluridTheme = storeJSON?.themes?.general;
114
+ if (!generalPluridTheme) {
115
+ return defaultBackground;
226
116
  }
227
- return recordString;
117
+ const gradientBackground = generalPluridTheme.type === "dark" ? generalPluridTheme.backgroundColorTertiary : generalPluridTheme.backgroundColorPrimary;
118
+ const gradientForeground = generalPluridTheme.type === "dark" ? generalPluridTheme.backgroundColorPrimary : generalPluridTheme.backgroundColorTertiary;
119
+ return {
120
+ gradientBackground,
121
+ gradientForeground
122
+ };
123
+ } catch (error) {
124
+ return defaultBackground;
125
+ }
228
126
  };
229
-
230
- const assetsPathRewrite = content => content.replace(/="client\//g, '="/');
231
-
232
- const globalsInjector = globals => {
233
- let globalsScript = "";
234
- for (const [key, value] of Object.entries(globals)) {
235
- const globalScript = `window.${key} = ${value};\n`;
236
- globalsScript += globalScript;
237
- }
238
- return globalsScript;
127
+ var escapeAttribute = (value) => {
128
+ return String(value).replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
129
+ };
130
+ var recordToString = (record) => {
131
+ if (!record) {
132
+ return "";
133
+ }
134
+ return Object.entries(record).map(([key, value]) => `${key}="${escapeAttribute(value)}"`).join(" ");
135
+ };
136
+ var assetsPathRewrite = (content) => {
137
+ return content.replace(
138
+ /="client\//g,
139
+ '="/'
140
+ );
141
+ };
142
+ var safeStore = (store) => {
143
+ return store.replace(
144
+ /</g,
145
+ "\\u003c"
146
+ );
147
+ };
148
+ var globalsInjector = (globals) => {
149
+ let globalsScript = "";
150
+ for (const [key, value] of Object.entries(globals)) {
151
+ const globalScript = `window.${key} = ${value};
152
+ `;
153
+ globalsScript += globalScript;
154
+ }
155
+ return globalsScript;
239
156
  };
240
157
 
241
- const NOT_FOUND_TEMPLATE = cleanTemplate(`\n<!DOCTYPE html>\n<html>\n <head>\n <title>[404] Not Found</title>\n <style>\n html, body {\n margin: 0;\n background: #242b33;\n color: #ddd;\n user-select: none;\n }\n\n .not-found {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n font-family: 'Ubuntu', -apple-system, system-ui, BlinkMacSystemFont, 'Segoe UI', Roboto;\n }\n </style>\n </head>\n\n <body>\n <div class="not-found">[404] Not Found</div>\n </body>\n</html>\n`);
158
+ // source/data/templates/index.ts
159
+ var NOT_FOUND_TEMPLATE = cleanTemplate(`
160
+ <!DOCTYPE html>
161
+ <html>
162
+ <head>
163
+ <title>[404] Not Found</title>
164
+ <style>
165
+ html, body {
166
+ margin: 0;
167
+ background: #242b33;
168
+ color: #ddd;
169
+ user-select: none;
170
+ }
242
171
 
243
- const SERVER_ERROR_TEMPLATE = cleanTemplate(`\n<!DOCTYPE html>\n<html>\n <head>\n <title>[500] Server Error</title>\n <style>\n html, body {\n margin: 0;\n background: #242b33;\n color: #ddd;\n user-select: none;\n }\n\n .error {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n font-family: 'Ubuntu', -apple-system, system-ui, BlinkMacSystemFont, 'Segoe UI', Roboto;\n }\n </style>\n </head>\n\n <body>\n <div class="error">[500] Server Error</div>\n </body>\n</html>\n`);
172
+ .not-found {
173
+ position: absolute;
174
+ top: 50%;
175
+ left: 50%;
176
+ transform: translate(-50%, -50%);
177
+ font-family: 'Ubuntu', -apple-system, system-ui, BlinkMacSystemFont, 'Segoe UI', Roboto;
178
+ }
179
+ </style>
180
+ </head>
181
+
182
+ <body>
183
+ <div class="not-found">[404] Not Found</div>
184
+ </body>
185
+ </html>
186
+ `);
187
+ var SERVER_ERROR_TEMPLATE = cleanTemplate(`
188
+ <!DOCTYPE html>
189
+ <html>
190
+ <head>
191
+ <title>[500] Server Error</title>
192
+ <style>
193
+ html, body {
194
+ margin: 0;
195
+ background: #242b33;
196
+ color: #ddd;
197
+ user-select: none;
198
+ }
244
199
 
245
- const template = data => {
246
- const {htmlLanguage: htmlLanguage, head: head, htmlAttributes: htmlAttributes, bodyAttributes: bodyAttributes, defaultStyle: defaultStyle, styles: styles, headScripts: headScripts, bodyScripts: bodyScripts, vendorScriptSource: vendorScriptSource, mainScriptSource: mainScriptSource, root: root, content: content, defaultPreloadedPluridMetastate: defaultPreloadedPluridMetastate, pluridMetastate: pluridMetastate, globals: globals, minify: minify} = data;
247
- const injectedGlobals = globalsInjector(globals);
248
- const templateString = `\n<!DOCTYPE html>\n<html lang="${htmlLanguage}" ${htmlAttributes}>\n <head>\n ${head}\n\n ${defaultStyle && `<style>\n ${defaultStyle}\n </style>`}\n\n ${styles}\n\n ${headScripts.join("\n")}\n\n <script src="${vendorScriptSource}"><\/script>\n <script defer src="${mainScriptSource}"><\/script>\n </head>\n <body ${bodyAttributes}>\n <div id="${root}">${content}</div>\n\n <script>\n ${injectedGlobals}\n window.${defaultPreloadedPluridMetastate} = ${pluridMetastate};\n <\/script>\n\n ${bodyScripts.join("\n")}\n </body>\n</html>\n `;
249
- if (!minify) {
250
- return templateString;
251
- }
252
- return cleanTemplate(templateString);
200
+ .error {
201
+ position: absolute;
202
+ top: 50%;
203
+ left: 50%;
204
+ transform: translate(-50%, -50%);
205
+ font-family: 'Ubuntu', -apple-system, system-ui, BlinkMacSystemFont, 'Segoe UI', Roboto;
206
+ }
207
+ </style>
208
+ </head>
209
+
210
+ <body>
211
+ <div class="error">[500] Server Error</div>
212
+ </body>
213
+ </html>
214
+ `);
215
+
216
+ // source/objects/Renderer/template/index.ts
217
+ var template = async (data) => {
218
+ const {
219
+ htmlLanguage,
220
+ head,
221
+ htmlAttributes,
222
+ bodyAttributes,
223
+ defaultStyle,
224
+ styles,
225
+ headScripts,
226
+ bodyScripts,
227
+ vendorScriptSource,
228
+ mainScriptSource,
229
+ root,
230
+ content,
231
+ defaultPreloadedPluridMetastate,
232
+ pluridMetastate,
233
+ globals,
234
+ minify: minify2
235
+ } = data;
236
+ const injectedGlobals = globalsInjector(globals);
237
+ const templateString = `
238
+ <!DOCTYPE html>
239
+ <html lang="${htmlLanguage}" ${htmlAttributes}>
240
+ <head>
241
+ ${head}
242
+
243
+ ${defaultStyle && `<style>
244
+ ${defaultStyle}
245
+ </style>`}
246
+
247
+ ${styles}
248
+
249
+ ${headScripts.join("\n")}
250
+
251
+ <script src="${vendorScriptSource}"></script>
252
+ <script defer src="${mainScriptSource}"></script>
253
+ </head>
254
+ <body ${bodyAttributes}>
255
+ <div id="${root}">${content}</div>
256
+
257
+ <script>
258
+ ${injectedGlobals}
259
+ window.${defaultPreloadedPluridMetastate} = ${safeStore(pluridMetastate)};
260
+ </script>
261
+
262
+ ${bodyScripts.join("\n")}
263
+ </body>
264
+ </html>
265
+ `;
266
+ if (!minify2) {
267
+ return templateString;
268
+ }
269
+ return cleanTemplate(templateString);
253
270
  };
254
-
255
- class PluridRenderer {
256
- constructor(configuration) {
257
- const {htmlLanguage: htmlLanguage, head: head, htmlAttributes: htmlAttributes, bodyAttributes: bodyAttributes, defaultStyle: defaultStyle, styles: styles, headScripts: headScripts, bodyScripts: bodyScripts, vendorScriptSource: vendorScriptSource, mainScriptSource: mainScriptSource, content: content, root: root, defaultPreloadedPluridMetastate: defaultPreloadedPluridMetastate, pluridMetastate: pluridMetastate, globals: globals, minify: minify} = configuration;
258
- const {gradientBackground: gradientBackground, gradientForeground: gradientForeground} = resolveBackgroundStyle("");
259
- const defaultStyleBasic = `\n body {\n background: radial-gradient(ellipse at center, ${gradientBackground} 0%, ${gradientForeground} 100%);\n height: 100%;\n margin: 0;\n }\n `;
260
- this.htmlLanguage = htmlLanguage || DEFAULT_RENDERER_LANGUAGE;
261
- this.head = head || "";
262
- this.htmlAttributes = htmlAttributes;
263
- this.bodyAttributes = bodyAttributes || "";
264
- this.defaultStyle = defaultStyle !== null && defaultStyle !== void 0 ? defaultStyle : defaultStyleBasic;
265
- this.styles = styles;
266
- this.headScripts = headScripts;
267
- this.bodyScripts = bodyScripts;
268
- this.vendorScriptSource = vendorScriptSource || DEFAULT_RENDERER_VENDOR_SCRIPT_SOURCE;
269
- this.mainScriptSource = mainScriptSource || DEFAULT_RENDERER_MAIN_SCRIPT_SOURCE;
270
- this.root = root || DEFAULT_RENDERER_ROOT;
271
- this.content = assetsPathRewrite(content) || "";
272
- this.defaultPreloadedPluridMetastate = defaultPreloadedPluridMetastate || DEFAULT__PRELOADED_PLURID_METASTATE__;
273
- this.pluridMetastate = pluridMetastate || DEFAULT_RENDERER_PLURID_STATE;
274
- this.globals = globals !== null && globals !== void 0 ? globals : {};
275
- this.minify = minify !== null && minify !== void 0 ? minify : true;
276
- }
277
- html() {
278
- const data = {
279
- htmlLanguage: this.htmlLanguage,
280
- head: this.head,
281
- htmlAttributes: this.htmlAttributes,
282
- bodyAttributes: this.bodyAttributes,
283
- defaultStyle: this.defaultStyle,
284
- styles: this.styles,
285
- headScripts: this.headScripts,
286
- bodyScripts: this.bodyScripts,
287
- vendorScriptSource: this.vendorScriptSource,
288
- mainScriptSource: this.mainScriptSource,
289
- root: this.root,
290
- content: this.content,
291
- defaultPreloadedPluridMetastate: this.defaultPreloadedPluridMetastate,
292
- pluridMetastate: this.pluridMetastate,
293
- globals: this.globals,
294
- minify: this.minify
295
- };
296
- return template(data);
297
- }
298
- }
299
-
300
- const wrapping = (WrappedComponent, WrappeeComponent, properties) => class extends React__default["default"].Component {
271
+ var template_default = template;
272
+
273
+ // source/objects/Renderer/index.ts
274
+ var PluridRenderer = class {
275
+ htmlLanguage;
276
+ head;
277
+ htmlAttributes;
278
+ bodyAttributes;
279
+ defaultStyle;
280
+ styles;
281
+ headScripts;
282
+ bodyScripts;
283
+ vendorScriptSource;
284
+ mainScriptSource;
285
+ root;
286
+ content;
287
+ defaultPreloadedPluridMetastate;
288
+ pluridMetastate;
289
+ globals;
290
+ minify;
291
+ constructor(configuration) {
292
+ const {
293
+ htmlLanguage,
294
+ head,
295
+ htmlAttributes,
296
+ bodyAttributes,
297
+ defaultStyle,
298
+ styles,
299
+ headScripts,
300
+ bodyScripts,
301
+ vendorScriptSource,
302
+ mainScriptSource,
303
+ content,
304
+ root,
305
+ defaultPreloadedPluridMetastate,
306
+ pluridMetastate,
307
+ globals,
308
+ minify: minify2
309
+ } = configuration;
310
+ const {
311
+ gradientBackground,
312
+ gradientForeground
313
+ // The metastate carries `themes.general` (see `serverComputeMetastate`), so the SSR'd background
314
+ // gradient matches the active theme; `resolveBackgroundStyle` falls back to a default if it can't parse.
315
+ } = resolveBackgroundStyle(pluridMetastate || "");
316
+ const defaultStyleBasic = `
317
+ body {
318
+ background: radial-gradient(ellipse at center, ${gradientBackground} 0%, ${gradientForeground} 100%);
319
+ height: 100%;
320
+ margin: 0;
321
+ }
322
+ `;
323
+ this.htmlLanguage = htmlLanguage || DEFAULT_RENDERER_LANGUAGE;
324
+ this.head = head || "";
325
+ this.htmlAttributes = htmlAttributes;
326
+ this.bodyAttributes = bodyAttributes || "";
327
+ this.defaultStyle = defaultStyle ?? defaultStyleBasic;
328
+ this.styles = styles;
329
+ this.headScripts = headScripts;
330
+ this.bodyScripts = bodyScripts;
331
+ this.vendorScriptSource = vendorScriptSource || DEFAULT_RENDERER_VENDOR_SCRIPT_SOURCE;
332
+ this.mainScriptSource = mainScriptSource || DEFAULT_RENDERER_MAIN_SCRIPT_SOURCE;
333
+ this.root = root || DEFAULT_RENDERER_ROOT;
334
+ this.content = assetsPathRewrite(content) || "";
335
+ this.defaultPreloadedPluridMetastate = defaultPreloadedPluridMetastate || DEFAULT__PRELOADED_PLURID_METASTATE__;
336
+ this.pluridMetastate = pluridMetastate || DEFAULT_RENDERER_PLURID_STATE;
337
+ this.globals = globals ?? {};
338
+ this.minify = minify2 ?? true;
339
+ }
340
+ async html() {
341
+ const data = {
342
+ htmlLanguage: this.htmlLanguage,
343
+ head: this.head,
344
+ htmlAttributes: this.htmlAttributes,
345
+ bodyAttributes: this.bodyAttributes,
346
+ defaultStyle: this.defaultStyle,
347
+ styles: this.styles,
348
+ headScripts: this.headScripts,
349
+ bodyScripts: this.bodyScripts,
350
+ vendorScriptSource: this.vendorScriptSource,
351
+ mainScriptSource: this.mainScriptSource,
352
+ root: this.root,
353
+ content: this.content,
354
+ defaultPreloadedPluridMetastate: this.defaultPreloadedPluridMetastate,
355
+ pluridMetastate: this.pluridMetastate,
356
+ globals: this.globals,
357
+ minify: this.minify
358
+ };
359
+ return template_default(data);
360
+ }
361
+ };
362
+ var Renderer_default = PluridRenderer;
363
+
364
+ // source/objects/ContentGenerator/index.tsx
365
+ var import_react2 = __toESM(require("react"));
366
+ var import_server = require("react-dom/server");
367
+ var import_styled_components = require("styled-components");
368
+ var import_react_helmet_async = require("react-helmet-async");
369
+ var import_plurid_react = require("@plurid/plurid-react");
370
+
371
+ // source/utilities/wrapping/index.tsx
372
+ var import_react = __toESM(require("react"));
373
+ var wrapping = (WrappedComponent, WrappeeComponent, properties) => {
374
+ return class extends import_react.default.Component {
301
375
  constructor(props) {
302
- super(props);
376
+ super(props);
303
377
  }
304
378
  render() {
305
- return React__default["default"].createElement(WrappedComponent, Object.assign({}, properties), React__default["default"].createElement(WrappeeComponent, null));
379
+ return /* @__PURE__ */ import_react.default.createElement(
380
+ WrappedComponent,
381
+ {
382
+ ...properties
383
+ },
384
+ /* @__PURE__ */ import_react.default.createElement(WrappeeComponent, null)
385
+ );
306
386
  }
387
+ };
307
388
  };
308
-
309
- class PluridContentGenerator {
310
- constructor(data) {
311
- this.data = data;
389
+ var wrapping_default = wrapping;
390
+
391
+ // source/objects/ContentGenerator/index.tsx
392
+ var PluridContentGenerator = class {
393
+ data;
394
+ constructor(data) {
395
+ this.data = data;
396
+ }
397
+ async render() {
398
+ const {
399
+ pluridMetastate,
400
+ routes,
401
+ planes,
402
+ exterior,
403
+ shell,
404
+ routerProperties,
405
+ gateway,
406
+ gatewayEndpoint,
407
+ gatewayQuery,
408
+ helmet,
409
+ services,
410
+ stylesheet,
411
+ preserveResult,
412
+ matchedPlane,
413
+ pathname,
414
+ hostname
415
+ } = this.data;
416
+ const RoutedApplication = () => /* @__PURE__ */ import_react2.default.createElement(
417
+ import_plurid_react.PluridProvider,
418
+ {
419
+ metastate: pluridMetastate
420
+ },
421
+ /* @__PURE__ */ import_react2.default.createElement(
422
+ import_plurid_react.PluridRouterStatic,
423
+ {
424
+ path: pathname,
425
+ directPlane: matchedPlane?.value,
426
+ routes,
427
+ planes,
428
+ exterior,
429
+ shell,
430
+ gateway,
431
+ gatewayEndpoint,
432
+ gatewayQuery,
433
+ hostname,
434
+ routerProperties
435
+ }
436
+ )
437
+ );
438
+ let Wrap = wrapping_default(
439
+ import_react_helmet_async.HelmetProvider,
440
+ RoutedApplication,
441
+ {
442
+ context: helmet
443
+ }
444
+ );
445
+ for (const service of services) {
446
+ const preserveProperties = preserveResult?.providers?.[service.name];
447
+ Wrap = wrapping_default(
448
+ service.Provider,
449
+ Wrap,
450
+ {
451
+ ...service.properties,
452
+ ...preserveProperties
453
+ }
454
+ );
312
455
  }
313
- render() {
314
- var _a;
315
- return __awaiter(this, void 0, void 0, (function*() {
316
- const {pluridMetastate: pluridMetastate, routes: routes, planes: planes, exterior: exterior, shell: shell, gateway: gateway, gatewayEndpoint: gatewayEndpoint, gatewayQuery: gatewayQuery, helmet: helmet, services: services, stylesheet: stylesheet, preserveResult: preserveResult, matchedPlane: matchedPlane, pathname: pathname, hostname: hostname} = this.data;
317
- const RoutedApplication = () => React__default["default"].createElement(pluridReact.PluridProvider, {
318
- metastate: pluridMetastate
319
- }, React__default["default"].createElement(pluridReact.PluridRouterStatic, {
320
- path: pathname,
321
- directPlane: matchedPlane === null || matchedPlane === void 0 ? void 0 : matchedPlane.value,
322
- routes: routes,
323
- planes: planes,
324
- exterior: exterior,
325
- shell: shell,
326
- gateway: gateway,
327
- gatewayEndpoint: gatewayEndpoint,
328
- gatewayQuery: gatewayQuery,
329
- hostname: hostname
330
- }));
331
- let Wrap = wrapping(reactHelmetAsync.HelmetProvider, RoutedApplication, {
332
- context: helmet
333
- });
334
- for (const service of services) {
335
- const preserveProperties = (_a = preserveResult === null || preserveResult === void 0 ? void 0 : preserveResult.providers) === null || _a === void 0 ? void 0 : _a[service.name];
336
- Wrap = wrapping(service.Provider, Wrap, Object.assign(Object.assign({}, service.properties), preserveProperties));
337
- }
338
- const content = server.renderToString(React__default["default"].createElement(styledComponents.StyleSheetManager, {
339
- sheet: stylesheet.instance
340
- }, React__default["default"].createElement(Wrap, null)));
341
- return content;
342
- }));
456
+ const content = (0, import_server.renderToString)(
457
+ /* @__PURE__ */ import_react2.default.createElement(
458
+ import_styled_components.StyleSheetManager,
459
+ {
460
+ sheet: stylesheet.instance
461
+ },
462
+ /* @__PURE__ */ import_react2.default.createElement(Wrap, null)
463
+ )
464
+ );
465
+ return content;
466
+ }
467
+ };
468
+ var ContentGenerator_default = PluridContentGenerator;
469
+
470
+ // source/objects/StillsManager/index.ts
471
+ var import_path = __toESM(require("path"));
472
+ var import_fs = require("fs");
473
+ var StillsManager = class {
474
+ options;
475
+ stills = /* @__PURE__ */ new Map();
476
+ constructor(options) {
477
+ this.options = options;
478
+ this.findStills();
479
+ }
480
+ get(url) {
481
+ const still = this.stills.get(url);
482
+ if (!still) {
483
+ return;
343
484
  }
344
- }
345
-
346
- const resolveElementFromPlaneMatch = (planeMatch, elementqlEndpoint) => {
347
- if (typeof planeMatch.data.component === "function") {
348
- return;
485
+ return still.html;
486
+ }
487
+ async findStills() {
488
+ const {
489
+ buildDirectory,
490
+ stillsDirectory
491
+ } = this.options;
492
+ const stillsLocation = `${buildDirectory}/${stillsDirectory}`;
493
+ const stillsPath = import_path.default.join(process.cwd(), stillsLocation);
494
+ if (!(0, import_fs.existsSync)(stillsPath)) {
495
+ return;
349
496
  }
350
- if (typeof planeMatch.data.component === "string") {
351
- return {
352
- name: planeMatch.data.component,
353
- url: elementqlEndpoint
354
- };
497
+ try {
498
+ const stillsMetadata = import_path.default.join(stillsPath, "metadata.json");
499
+ const stillsMetadataFile = await import_fs.promises.readFile(stillsMetadata, "utf-8");
500
+ const stillsMetadataJSON = JSON.parse(stillsMetadataFile);
501
+ if (!Array.isArray(stillsMetadataJSON)) {
502
+ return;
503
+ }
504
+ for (const still of stillsMetadataJSON) {
505
+ const stillFilePath = import_path.default.join(stillsPath, still.name);
506
+ const stillFileData = await import_fs.promises.readFile(stillFilePath, "utf-8");
507
+ const stillFileJSON = JSON.parse(stillFileData);
508
+ if (!stillFileJSON) {
509
+ continue;
510
+ }
511
+ this.stills.set(stillFileJSON.route, stillFileJSON);
512
+ }
513
+ } catch (error) {
514
+ if (this.options.debug !== "none" && !this.options.quiet) {
515
+ const errorText = "Plurid Server Error: Could not read stills.";
516
+ if (this.options.debug === "error") {
517
+ console.error(errorText, error);
518
+ } else {
519
+ console.log(errorText);
520
+ }
521
+ }
522
+ return;
355
523
  }
524
+ }
525
+ };
526
+ var StillsManager_default = StillsManager;
527
+
528
+ // source/utilities/pttp/index.ts
529
+ var resolveElementFromPlaneMatch = (planeMatch, elementqlEndpoint) => {
530
+ if (typeof planeMatch.data.component === "function") {
531
+ return;
532
+ }
533
+ if (typeof planeMatch.data.component === "string") {
356
534
  return {
357
- name: planeMatch.data.component.name,
358
- url: planeMatch.data.component.url || elementqlEndpoint
535
+ name: planeMatch.data.component,
536
+ url: elementqlEndpoint
359
537
  };
538
+ }
539
+ return {
540
+ name: planeMatch.data.component.name,
541
+ url: planeMatch.data.component.url || elementqlEndpoint
542
+ };
360
543
  };
361
544
 
362
- const {IsoMatcher: PluridIsoMatcher} = pluridEngine.routing;
363
-
364
- class PluridServer {
365
- constructor(configuration) {
366
- const {routes: routes, planes: planes, preserves: preserves, helmet: helmet, styles: styles, middleware: middleware, exterior: exterior, shell: shell, services: services, options: options, template: template, usePTTP: usePTTP, pttpHandler: pttpHandler, elementqlEndpoint: elementqlEndpoint} = configuration;
367
- this.routes = routes;
368
- this.planes = planes || [];
369
- this.preserves = preserves;
370
- this.helmet = helmet;
371
- this.styles = styles || [];
372
- this.middleware = middleware || [];
373
- this.exterior = exterior;
374
- this.shell = shell;
375
- this.services = services || [];
376
- this.options = this.handleOptions(options);
377
- this.template = template;
378
- this.usePTTP = usePTTP !== null && usePTTP !== void 0 ? usePTTP : false;
379
- this.pttpHandler = pttpHandler;
380
- this.elementqlEndpoint = elementqlEndpoint;
381
- this.serverApplication = express__default["default"]();
382
- this.port = DEFAULT_SERVER_PORT;
383
- this.isoMatcher = new PluridIsoMatcher({
384
- routes: this.routes,
385
- routePlanes: this.planes
386
- }, this.options.hostname);
387
- this.configureServer();
388
- this.handleEndpoints();
389
- process.addListener("SIGINT", (() => {
390
- this.stop();
391
- process.exit(0);
392
- }));
393
- }
394
- static analysis(pluridServer) {
395
- return {
396
- routes: pluridServer.routes,
397
- options: pluridServer.options
398
- };
545
+ // source/objects/Server/index.ts
546
+ var {
547
+ IsoMatcher: PluridIsoMatcher
548
+ } = import_plurid_engine.routing;
549
+ var PluridServer = class {
550
+ routes;
551
+ planes;
552
+ preserves;
553
+ helmet;
554
+ styles;
555
+ middleware;
556
+ exterior;
557
+ shell;
558
+ routerProperties;
559
+ services;
560
+ options;
561
+ template;
562
+ usePTTP;
563
+ pttpHandler;
564
+ elementqlEndpoint;
565
+ serverApplication;
566
+ server;
567
+ port;
568
+ stills;
569
+ isoMatcher;
570
+ constructor(configuration) {
571
+ const {
572
+ routes,
573
+ planes,
574
+ preserves,
575
+ helmet,
576
+ styles,
577
+ middleware,
578
+ exterior,
579
+ shell,
580
+ routerProperties,
581
+ services,
582
+ options,
583
+ template: template2,
584
+ usePTTP,
585
+ pttpHandler,
586
+ elementqlEndpoint
587
+ } = configuration;
588
+ this.routes = routes;
589
+ this.planes = planes || [];
590
+ this.preserves = preserves;
591
+ this.helmet = helmet;
592
+ this.styles = styles || [];
593
+ this.middleware = middleware || [];
594
+ this.exterior = exterior;
595
+ this.shell = shell;
596
+ this.routerProperties = routerProperties || {};
597
+ this.services = services || [];
598
+ this.options = this.handleOptions(options);
599
+ this.template = template2;
600
+ this.usePTTP = usePTTP ?? false;
601
+ this.pttpHandler = pttpHandler;
602
+ this.elementqlEndpoint = elementqlEndpoint;
603
+ this.serverApplication = (0, import_express.default)();
604
+ this.port = DEFAULT_SERVER_PORT;
605
+ this.stills = new StillsManager_default(this.options);
606
+ this.isoMatcher = new PluridIsoMatcher(
607
+ {
608
+ routes: this.routes,
609
+ routePlanes: this.planes
610
+ },
611
+ this.options.hostname
612
+ );
613
+ this.configureServer();
614
+ this.handleEndpoints();
615
+ if (this.options.attachSignalHandlers) {
616
+ this.attachSignalHandlers();
399
617
  }
400
- start(port = this.port) {
401
- this.port = port;
402
- const serverlink = `http://localhost:${port}`;
403
- if (this.debugAllows("info")) {
404
- console.info(`\n\t[${pluridFunctions.time.stamp()}] ${this.options.serverName} Started on Port ${port}: ${serverlink}\n`);
405
- }
406
- this.server = this.serverApplication.listen(port);
407
- this.open(serverlink);
408
- return this.server;
618
+ }
619
+ handleProcessSignal = () => {
620
+ this.stop();
621
+ process.exit(0);
622
+ };
623
+ signalHandlersAttached = false;
624
+ attachSignalHandlers() {
625
+ if (this.signalHandlersAttached) {
626
+ return;
409
627
  }
410
- stop() {
411
- if (this.server) {
412
- if (this.debugAllows("info")) {
413
- console.info(`\n\t[${pluridFunctions.time.stamp()}] ${this.options.serverName} Stopped on Port ${this.port}\n`);
414
- }
415
- this.server.close();
416
- } else {
417
- if (this.debugAllows("info")) {
418
- console.info(`\n\t[${pluridFunctions.time.stamp()}] ${this.options.serverName} Could not be Stopped on Port ${this.port}\n`);
419
- }
420
- }
628
+ process.on("SIGINT", this.handleProcessSignal);
629
+ process.on("SIGTERM", this.handleProcessSignal);
630
+ this.signalHandlersAttached = true;
631
+ }
632
+ detachSignalHandlers() {
633
+ process.removeListener("SIGINT", this.handleProcessSignal);
634
+ process.removeListener("SIGTERM", this.handleProcessSignal);
635
+ this.signalHandlersAttached = false;
636
+ }
637
+ static analysis(pluridServer) {
638
+ return {
639
+ routes: pluridServer.routes,
640
+ options: pluridServer.options
641
+ };
642
+ }
643
+ start(port = this.port) {
644
+ this.port = port;
645
+ const serverlink = `http://localhost:${port}`;
646
+ if (this.debugAllows("info")) {
647
+ console.info(
648
+ `
649
+ [${import_plurid_functions.time.stamp()}] ${this.options.serverName} Started on Port ${port}: ${serverlink}
650
+ `
651
+ );
421
652
  }
422
- handle() {
423
- return {
424
- post: (path, ...handlers) => {
425
- this.serverApplication.post(path, ...handlers);
426
- return this.serverApplication;
427
- },
428
- patch: (path, ...handlers) => {
429
- this.serverApplication.patch(path, ...handlers);
430
- return this.serverApplication;
431
- },
432
- put: (path, ...handlers) => {
433
- this.serverApplication.put(path, ...handlers);
434
- return this.serverApplication;
435
- },
436
- delete: (path, ...handlers) => {
437
- this.serverApplication.delete(path, ...handlers);
438
- return this.serverApplication;
439
- }
440
- };
653
+ this.server = this.serverApplication.listen(port);
654
+ this.open(serverlink);
655
+ return this.server;
656
+ }
657
+ stop() {
658
+ this.detachSignalHandlers();
659
+ if (this.server) {
660
+ if (this.debugAllows("info")) {
661
+ console.info(
662
+ `
663
+ [${import_plurid_functions.time.stamp()}] ${this.options.serverName} Stopped on Port ${this.port}
664
+ `
665
+ );
666
+ }
667
+ this.server.close();
668
+ } else {
669
+ if (this.debugAllows("info")) {
670
+ console.info(
671
+ `
672
+ [${import_plurid_functions.time.stamp()}] ${this.options.serverName} Could not be Stopped on Port ${this.port}
673
+ `
674
+ );
675
+ }
441
676
  }
442
- instance() {
677
+ }
678
+ handle() {
679
+ return {
680
+ post: (path4, ...handlers) => {
681
+ this.serverApplication.post(path4, ...handlers);
443
682
  return this.serverApplication;
444
- }
445
- handleEndpoints() {
446
- this.serverApplication.get(CATCH_ALL_ROUTE, ((request, response, next) => __awaiter(this, void 0, void 0, (function*() {
447
- this.handleGetRequest(request, response, next);
448
- }))));
449
- if (this.usePTTP) {
450
- this.serverApplication.post(PTTP_ROUTE, bodyParser.json(), ((request, response, next) => __awaiter(this, void 0, void 0, (function*() {
451
- this.handlePTTPRequest(request, response);
452
- }))));
683
+ },
684
+ patch: (path4, ...handlers) => {
685
+ this.serverApplication.patch(path4, ...handlers);
686
+ return this.serverApplication;
687
+ },
688
+ put: (path4, ...handlers) => {
689
+ this.serverApplication.put(path4, ...handlers);
690
+ return this.serverApplication;
691
+ },
692
+ delete: (path4, ...handlers) => {
693
+ this.serverApplication.delete(path4, ...handlers);
694
+ return this.serverApplication;
695
+ }
696
+ };
697
+ }
698
+ instance() {
699
+ return this.serverApplication;
700
+ }
701
+ handleEndpoints() {
702
+ this.serverApplication.get(
703
+ CATCH_ALL_ROUTE_PATTERN,
704
+ async (request, response, next) => {
705
+ this.handleGetRequest(
706
+ request,
707
+ response,
708
+ next
709
+ );
710
+ }
711
+ );
712
+ if (this.usePTTP) {
713
+ this.serverApplication.post(
714
+ PTTP_ROUTE,
715
+ import_express.default.json(),
716
+ // body parsing is built into Express 5
717
+ async (request, response, next) => {
718
+ this.handlePTTPRequest(
719
+ request,
720
+ response
721
+ );
453
722
  }
723
+ );
454
724
  }
455
- handleGetRequest(request, response, next) {
456
- return __awaiter(this, void 0, void 0, (function*() {
457
- const requestID = request.requestID || pluridFunctions.uuid.generate();
458
- try {
459
- if (this.debugAllows("info")) {
460
- console.info(`[${pluridFunctions.time.stamp()} :: ${requestID}] (000 Start) Handling GET ${request.path}`);
461
- }
462
- const ignorable = this.ignoreGetRequest(request.path);
463
- if (ignorable) {
464
- if (this.debugAllows("info")) {
465
- const requestTime = this.computeRequestTime(request);
466
- console.info(`[${pluridFunctions.time.stamp()} :: ${requestID}] (204 No Content) Ignored GET ${request.path}${requestTime}`);
467
- }
468
- next();
469
- return;
470
- }
471
- const {preserveResponded: preserveResponded, preserveResult: preserveResult, preserveAfterServe: preserveAfterServe} = yield this.resolvePreserve(request, response);
472
- if (preserveResponded) {
473
- if (this.debugAllows("info")) {
474
- const requestTime = this.computeRequestTime(request);
475
- console.info(`[${pluridFunctions.time.stamp()} :: ${requestID}] (204 No Content) Preserve handled GET ${request.path}${requestTime}`);
476
- }
477
- return;
478
- }
479
- const {externalRedirect: externalRedirect, matchingPath: matchingPath} = this.resolveMatchingPath(preserveResult, request.originalUrl);
480
- if (externalRedirect) {
481
- if (this.debugAllows("info")) {
482
- const requestTime = this.computeRequestTime(request);
483
- console.info(`[${pluridFunctions.time.stamp()} :: ${requestID}] (302 Redirect) Handled GET ${request.path} redirect to ${matchingPath}${requestTime}`);
484
- }
485
- response.status(302).redirect(matchingPath);
486
- this.resolvePreserveAfterServe(preserveAfterServe, request, response);
487
- return;
488
- }
489
- const isoMatch = this.isoMatcher.match(matchingPath, "route");
490
- if (!isoMatch) {
491
- const isoMatchNotFound = this.isoMatcher.match(NOT_FOUND_ROUTE, "route");
492
- if (!isoMatchNotFound) {
493
- if (this.debugAllows("info")) {
494
- const requestTime = this.computeRequestTime(request);
495
- console.info(`[${pluridFunctions.time.stamp()} :: ${requestID}] (404 Not Found) Handled GET ${matchingPath}${requestTime}`);
496
- }
497
- response.status(404).send(NOT_FOUND_TEMPLATE);
498
- this.resolvePreserveAfterServe(preserveAfterServe, request, response);
499
- return;
500
- }
501
- const renderer = yield this.renderApplication(isoMatchNotFound, preserveResult);
502
- if (this.debugAllows("info")) {
503
- const requestTime = this.computeRequestTime(request);
504
- console.info(`[${pluridFunctions.time.stamp()} :: ${requestID}] (404 Not Found) Handled GET ${matchingPath}${requestTime}`);
505
- }
506
- response.status(404).send(renderer.html());
507
- this.resolvePreserveAfterServe(preserveAfterServe, request, response);
508
- response.status(404).end();
509
- return;
510
- }
511
- const renderer = yield this.renderApplication(isoMatch, preserveResult);
512
- if (this.debugAllows("info")) {
513
- const requestTime = this.computeRequestTime(request);
514
- console.info(`[${pluridFunctions.time.stamp()} :: ${requestID}] (200 OK) Handled GET ${matchingPath}${requestTime}`);
515
- }
516
- response.send(renderer.html());
517
- this.resolvePreserveAfterServe(preserveAfterServe, request, response);
518
- return;
519
- } catch (error) {
520
- if (this.debugAllows("error")) {
521
- const requestTime = this.computeRequestTime(request);
522
- console.error(`[${pluridFunctions.time.stamp()} :: ${requestID}] (500 Server Error) Could not handle GET ${request.path}${requestTime}`, error);
523
- }
524
- response.status(500).send(SERVER_ERROR_TEMPLATE);
525
- return;
526
- }
527
- }));
725
+ }
726
+ async handleGetRequest(request, response, next) {
727
+ const requestID = request.requestID || import_plurid_functions.uuid.generate();
728
+ try {
729
+ if (this.debugAllows("info")) {
730
+ console.info(
731
+ `[${import_plurid_functions.time.stamp()} :: ${requestID}] (000 Start) Handling GET ${request.path}`
732
+ );
733
+ }
734
+ const ignorable = this.ignoreGetRequest(
735
+ request.path
736
+ );
737
+ if (ignorable) {
738
+ if (this.debugAllows("info")) {
739
+ const requestTime = this.computeRequestTime(request);
740
+ console.info(
741
+ `[${import_plurid_functions.time.stamp()} :: ${requestID}] (204 No Content) Ignored GET ${request.path}${requestTime}`
742
+ );
743
+ }
744
+ next();
745
+ return;
746
+ }
747
+ const {
748
+ preserveResponded,
749
+ preserveResult,
750
+ preserveAfterServe
751
+ } = await this.resolvePreserve(
752
+ request,
753
+ response
754
+ );
755
+ if (preserveResponded) {
756
+ if (this.debugAllows("info")) {
757
+ const requestTime = this.computeRequestTime(request);
758
+ console.info(
759
+ `[${import_plurid_functions.time.stamp()} :: ${requestID}] (204 No Content) Preserve handled GET ${request.path}${requestTime}`
760
+ );
761
+ }
762
+ return;
763
+ }
764
+ const {
765
+ externalRedirect,
766
+ matchingPath
767
+ } = this.resolveMatchingPath(
768
+ preserveResult,
769
+ request.originalUrl
770
+ );
771
+ if (externalRedirect) {
772
+ if (this.debugAllows("info")) {
773
+ const requestTime = this.computeRequestTime(request);
774
+ console.info(
775
+ `[${import_plurid_functions.time.stamp()} :: ${requestID}] (302 Redirect) Handled GET ${request.path} redirect to ${matchingPath}${requestTime}`
776
+ );
777
+ }
778
+ response.status(302).redirect(matchingPath);
779
+ this.resolvePreserveAfterServe(
780
+ preserveAfterServe,
781
+ request,
782
+ response
783
+ );
784
+ return;
785
+ }
786
+ const still = this.stills.get(matchingPath);
787
+ if (still) {
788
+ if (this.debugAllows("info")) {
789
+ const requestTime = this.computeRequestTime(request);
790
+ console.info(
791
+ `[${import_plurid_functions.time.stamp()} :: ${requestID}] (200 OK) Still Handled GET ${matchingPath}${requestTime}`
792
+ );
793
+ }
794
+ response.send(still);
795
+ this.resolvePreserveAfterServe(
796
+ preserveAfterServe,
797
+ request,
798
+ response
799
+ );
800
+ return;
801
+ }
802
+ const isoMatch = this.isoMatcher.match(
803
+ matchingPath,
804
+ "route"
805
+ );
806
+ if (!isoMatch) {
807
+ const notFoundStill = this.stills.get(NOT_FOUND_ROUTE);
808
+ if (notFoundStill) {
809
+ if (this.debugAllows("info")) {
810
+ const requestTime = this.computeRequestTime(request);
811
+ console.info(
812
+ `[${import_plurid_functions.time.stamp()} :: ${requestID}] (404 Not Found) Handled GET ${matchingPath}${requestTime}`
813
+ );
814
+ }
815
+ response.status(404).send(notFoundStill);
816
+ this.resolvePreserveAfterServe(
817
+ preserveAfterServe,
818
+ request,
819
+ response
820
+ );
821
+ return;
822
+ }
823
+ const isoMatchNotFound = this.isoMatcher.match(
824
+ NOT_FOUND_ROUTE,
825
+ "route"
826
+ );
827
+ if (!isoMatchNotFound) {
828
+ if (this.debugAllows("info")) {
829
+ const requestTime = this.computeRequestTime(request);
830
+ console.info(
831
+ `[${import_plurid_functions.time.stamp()} :: ${requestID}] (404 Not Found) Handled GET ${matchingPath}${requestTime}`
832
+ );
833
+ }
834
+ response.status(404).send(NOT_FOUND_TEMPLATE);
835
+ this.resolvePreserveAfterServe(
836
+ preserveAfterServe,
837
+ request,
838
+ response
839
+ );
840
+ return;
841
+ }
842
+ const renderer2 = await this.renderApplication(
843
+ isoMatchNotFound,
844
+ preserveResult
845
+ );
846
+ if (this.debugAllows("info")) {
847
+ const requestTime = this.computeRequestTime(request);
848
+ console.info(
849
+ `[${import_plurid_functions.time.stamp()} :: ${requestID}] (404 Not Found) Handled GET ${matchingPath}${requestTime}`
850
+ );
851
+ }
852
+ response.status(404).send(await renderer2.html());
853
+ this.resolvePreserveAfterServe(
854
+ preserveAfterServe,
855
+ request,
856
+ response
857
+ );
858
+ response.status(404).end();
859
+ return;
860
+ }
861
+ const renderer = await this.renderApplication(
862
+ isoMatch,
863
+ preserveResult
864
+ );
865
+ if (this.debugAllows("info")) {
866
+ const requestTime = this.computeRequestTime(request);
867
+ console.info(
868
+ `[${import_plurid_functions.time.stamp()} :: ${requestID}] (200 OK) Handled GET ${matchingPath}${requestTime}`
869
+ );
870
+ }
871
+ response.send(await renderer.html());
872
+ this.resolvePreserveAfterServe(
873
+ preserveAfterServe,
874
+ request,
875
+ response
876
+ );
877
+ return;
878
+ } catch (error) {
879
+ if (this.debugAllows("error")) {
880
+ const requestTime = this.computeRequestTime(request);
881
+ console.error(
882
+ `[${import_plurid_functions.time.stamp()} :: ${requestID}] (500 Server Error) Could not handle GET ${request.path}${requestTime}`,
883
+ error
884
+ );
885
+ }
886
+ response.status(500).send(SERVER_ERROR_TEMPLATE);
887
+ return;
528
888
  }
529
- handlePTTPRequest(request, response) {
530
- return __awaiter(this, void 0, void 0, (function*() {
531
- const requestID = request.requestID || pluridFunctions.uuid.generate();
532
- try {
533
- if (this.debugAllows("info")) {
534
- console.info(`[${pluridFunctions.time.stamp()} :: ${requestID}] (000 Start) Handling POST ${request.path}`);
535
- }
536
- response.setHeader("Access-Control-Allow-Origin", request.headers.origin || "");
537
- response.setHeader("Access-Control-Allow-Credentials", "true");
538
- const data = request.body;
539
- if (!data && !data.path) {
540
- if (this.debugAllows("warn")) {
541
- const requestTime = this.computeRequestTime(request);
542
- console.info(`[${pluridFunctions.time.stamp()} :: ${requestID}] (400 Bad Request) Could not handle POST ${request.path}${requestTime}`);
543
- }
544
- response.status(400).end();
545
- return;
546
- }
547
- if (this.pttpHandler) {
548
- const pttpHandled = yield this.pttpHandler(data.path);
549
- if (pttpHandled) {
550
- if (this.debugAllows("info")) {
551
- const requestTime = this.computeRequestTime(request);
552
- console.info(`[${pluridFunctions.time.stamp()} :: ${requestID}] (200 OK) Handled POST ${request.path}${requestTime} in custom handler`);
553
- }
554
- return;
555
- }
556
- }
557
- const planeMatch = this.isoMatcher.match(data.path);
558
- if (!planeMatch) {
559
- if (this.debugAllows("warn")) {
560
- const requestTime = this.computeRequestTime(request);
561
- console.info(`[${pluridFunctions.time.stamp()} :: ${requestID}] (400 Bad Request) Could not handle POST ${request.path}${requestTime}`);
562
- }
563
- response.status(400).end();
564
- return;
565
- }
566
- const elementMatch = resolveElementFromPlaneMatch(planeMatch, this.elementqlEndpoint);
567
- if (!elementMatch) {
568
- if (this.debugAllows("warn")) {
569
- const requestTime = this.computeRequestTime(request);
570
- console.info(`[${pluridFunctions.time.stamp()} :: ${requestID}] (404 Not Found) Could not handle POST ${request.path}${requestTime}`);
571
- }
572
- response.status(404).end();
573
- return;
574
- }
575
- const elementURL = elementMatch.url;
576
- if (!elementURL) {
577
- if (this.debugAllows("warn")) {
578
- const requestTime = this.computeRequestTime(request);
579
- console.info(`[${pluridFunctions.time.stamp()} :: ${requestID}] (400 Bad Request) Could not handle POST ${request.path}${requestTime}`);
580
- }
581
- response.status(400).end();
582
- return;
583
- }
584
- if (this.debugAllows("info")) {
585
- const requestTime = this.computeRequestTime(request);
586
- console.info(`[${pluridFunctions.time.stamp()} :: ${requestID}] (200 OK) Handled POST ${request.path}${requestTime}`);
587
- }
588
- const elementName = elementMatch.name;
589
- const linksTo = [];
590
- const element = {
591
- url: elementURL,
592
- name: elementName,
593
- json: {
594
- elements: [ {
595
- name: elementName
596
- } ]
597
- },
598
- linksTo: linksTo
599
- };
600
- response.json({
601
- element: element
602
- });
603
- } catch (error) {
604
- if (this.debugAllows("error")) {
605
- const requestTime = this.computeRequestTime(request);
606
- console.error(`[${pluridFunctions.time.stamp()} :: ${requestID}] (500 Server Error) Could not handle POST ${request.path}${requestTime}`, error);
607
- }
608
- response.status(500).send(SERVER_ERROR_TEMPLATE);
609
- return;
889
+ }
890
+ async handlePTTPRequest(request, response) {
891
+ const requestID = request.requestID || import_plurid_functions.uuid.generate();
892
+ try {
893
+ if (this.debugAllows("info")) {
894
+ console.info(
895
+ `[${import_plurid_functions.time.stamp()} :: ${requestID}] (000 Start) Handling POST ${request.path}`
896
+ );
897
+ }
898
+ response.setHeader("Access-Control-Allow-Origin", request.headers.origin || "");
899
+ response.setHeader("Access-Control-Allow-Credentials", "true");
900
+ const data = request.body;
901
+ if (!data || !data.path) {
902
+ if (this.debugAllows("warn")) {
903
+ const requestTime = this.computeRequestTime(request);
904
+ console.info(
905
+ `[${import_plurid_functions.time.stamp()} :: ${requestID}] (400 Bad Request) Could not handle POST ${request.path}${requestTime}`
906
+ );
907
+ }
908
+ response.status(400).end();
909
+ return;
910
+ }
911
+ if (this.pttpHandler) {
912
+ const pttpHandled = await this.pttpHandler(
913
+ data.path
914
+ );
915
+ if (pttpHandled) {
916
+ if (this.debugAllows("info")) {
917
+ const requestTime = this.computeRequestTime(request);
918
+ console.info(
919
+ `[${import_plurid_functions.time.stamp()} :: ${requestID}] (200 OK) Handled POST ${request.path}${requestTime} in custom handler`
920
+ );
921
+ }
922
+ return;
923
+ }
924
+ }
925
+ const planeMatch = this.isoMatcher.match(
926
+ data.path
927
+ );
928
+ if (!planeMatch) {
929
+ if (this.debugAllows("warn")) {
930
+ const requestTime = this.computeRequestTime(request);
931
+ console.info(
932
+ `[${import_plurid_functions.time.stamp()} :: ${requestID}] (400 Bad Request) Could not handle POST ${request.path}${requestTime}`
933
+ );
934
+ }
935
+ response.status(400).end();
936
+ return;
937
+ }
938
+ const elementMatch = resolveElementFromPlaneMatch(
939
+ planeMatch,
940
+ this.elementqlEndpoint
941
+ );
942
+ if (!elementMatch) {
943
+ if (this.debugAllows("warn")) {
944
+ const requestTime = this.computeRequestTime(request);
945
+ console.info(
946
+ `[${import_plurid_functions.time.stamp()} :: ${requestID}] (404 Not Found) Could not handle POST ${request.path}${requestTime}`
947
+ );
948
+ }
949
+ response.status(404).end();
950
+ return;
951
+ }
952
+ const elementURL = elementMatch.url;
953
+ if (!elementURL) {
954
+ if (this.debugAllows("warn")) {
955
+ const requestTime = this.computeRequestTime(request);
956
+ console.info(
957
+ `[${import_plurid_functions.time.stamp()} :: ${requestID}] (400 Bad Request) Could not handle POST ${request.path}${requestTime}`
958
+ );
959
+ }
960
+ response.status(400).end();
961
+ return;
962
+ }
963
+ if (this.debugAllows("info")) {
964
+ const requestTime = this.computeRequestTime(request);
965
+ console.info(
966
+ `[${import_plurid_functions.time.stamp()} :: ${requestID}] (200 OK) Handled POST ${request.path}${requestTime}`
967
+ );
968
+ }
969
+ const elementName = elementMatch.name;
970
+ const linksTo = [];
971
+ const element = {
972
+ url: elementURL,
973
+ name: elementName,
974
+ json: {
975
+ elements: [
976
+ {
977
+ name: elementName
610
978
  }
611
- }));
979
+ ]
980
+ },
981
+ linksTo
982
+ };
983
+ response.json({
984
+ element
985
+ });
986
+ } catch (error) {
987
+ if (this.debugAllows("error")) {
988
+ const requestTime = this.computeRequestTime(request);
989
+ console.error(
990
+ `[${import_plurid_functions.time.stamp()} :: ${requestID}] (500 Server Error) Could not handle POST ${request.path}${requestTime}`,
991
+ error
992
+ );
993
+ }
994
+ response.status(500).send(SERVER_ERROR_TEMPLATE);
995
+ return;
612
996
  }
613
- ignoreGetRequest(path) {
614
- for (const ignore of this.options.ignore) {
615
- const normalizedIgnore = ignore.endsWith("/") && ignore.length > 1 ? ignore.slice(0, ignore.length - 1) : ignore;
616
- if (path === normalizedIgnore) {
617
- return true;
618
- }
619
- if (normalizedIgnore.endsWith("/*")) {
620
- const curatedIgnore = normalizedIgnore.replace("/*", "");
621
- if (path.startsWith(curatedIgnore)) {
622
- return true;
623
- }
624
- }
997
+ }
998
+ ignoreGetRequest(path4) {
999
+ for (const ignore of this.options.ignore) {
1000
+ const normalizedIgnore = ignore.endsWith("/") && ignore.length > 1 ? ignore.slice(0, ignore.length - 1) : ignore;
1001
+ if (path4 === normalizedIgnore) {
1002
+ return true;
1003
+ }
1004
+ if (normalizedIgnore.endsWith("/*")) {
1005
+ const curatedIgnore = normalizedIgnore.replace("/*", "");
1006
+ if (path4.startsWith(curatedIgnore)) {
1007
+ return true;
625
1008
  }
626
- return false;
1009
+ }
627
1010
  }
628
- resolveMatchingPath(preserveResult, path) {
629
- const redirect = preserveResult ? preserveResult.redirect : "";
630
- const externalRedirect = !!(redirect === null || redirect === void 0 ? void 0 : redirect.startsWith("http"));
631
- const matchingPath = redirect || path;
632
- return {
633
- externalRedirect: externalRedirect,
634
- matchingPath: matchingPath
635
- };
1011
+ return false;
1012
+ }
1013
+ resolveMatchingPath(preserveResult, path4) {
1014
+ const redirect = preserveResult ? preserveResult.redirect : "";
1015
+ const externalRedirect = !!redirect?.startsWith("http");
1016
+ const matchingPath = redirect || path4;
1017
+ return {
1018
+ externalRedirect,
1019
+ matchingPath
1020
+ };
1021
+ }
1022
+ async resolvePreserve(request, response) {
1023
+ const catchAll = this.preserves.find(
1024
+ (preserve) => preserve.serve === CATCH_ALL_ROUTE
1025
+ );
1026
+ const notFound = this.preserves.find(
1027
+ (preserve) => preserve.serve === NOT_FOUND_ROUTE
1028
+ );
1029
+ const isoMatch = this.isoMatcher.match(
1030
+ request.originalUrl,
1031
+ "route"
1032
+ );
1033
+ let preserveOnServe;
1034
+ let preserveAfterServe;
1035
+ let preserveOnError;
1036
+ if (isoMatch || catchAll || notFound) {
1037
+ const preserve = catchAll ? catchAll : notFound && !isoMatch ? notFound : this.preserves.find(
1038
+ (preserve2) => preserve2.serve === isoMatch?.data.value
1039
+ );
1040
+ if (preserve) {
1041
+ preserveOnServe = preserve.onServe;
1042
+ preserveAfterServe = preserve.afterServe;
1043
+ preserveOnError = preserve.onError;
1044
+ }
636
1045
  }
637
- resolvePreserve(request, response) {
638
- return __awaiter(this, void 0, void 0, (function*() {
639
- const catchAll = this.preserves.find((preserve => preserve.serve === CATCH_ALL_ROUTE));
640
- const notFound = this.preserves.find((preserve => preserve.serve === NOT_FOUND_ROUTE));
641
- const isoMatch = this.isoMatcher.match(request.originalUrl, "route");
642
- let preserveOnServe;
643
- let preserveAfterServe;
644
- let preserveOnError;
645
- if (isoMatch || catchAll || notFound) {
646
- const preserve = catchAll ? catchAll : notFound && !isoMatch ? notFound : this.preserves.find((preserve => preserve.serve === (isoMatch === null || isoMatch === void 0 ? void 0 : isoMatch.data.value)));
647
- if (preserve) {
648
- preserveOnServe = preserve.onServe;
649
- preserveAfterServe = preserve.afterServe;
650
- preserveOnError = preserve.onError;
651
- }
652
- }
653
- let preserveResult;
654
- if (preserveOnServe) {
655
- const transmission = {
656
- context: {
657
- route: request.originalUrl,
658
- match: isoMatch
659
- },
660
- request: request,
661
- response: response
662
- };
663
- try {
664
- preserveResult = yield preserveOnServe(transmission);
665
- if (preserveResult) {
666
- if (preserveResult.responded) {
667
- return {
668
- preserveResponded: true,
669
- preserveResult: preserveResult,
670
- preserveAfterServe: preserveAfterServe
671
- };
672
- }
673
- }
674
- } catch (error) {
675
- if (preserveOnError) {
676
- const onErrorResponse = yield preserveOnError(error, transmission);
677
- if (onErrorResponse) {
678
- if (onErrorResponse.responded) {
679
- return {
680
- preserveResponded: true,
681
- preserveResult: preserveResult,
682
- preserveAfterServe: preserveAfterServe
683
- };
684
- }
685
- if (!onErrorResponse.depreserve) {
686
- return {
687
- preserveResponded: false,
688
- preserveResult: preserveResult,
689
- preserveAfterServe: preserveAfterServe
690
- };
691
- }
692
- }
693
- }
694
- }
695
- }
1046
+ let preserveResult;
1047
+ if (preserveOnServe) {
1048
+ const transmission = {
1049
+ context: {
1050
+ route: request.originalUrl,
1051
+ match: isoMatch
1052
+ },
1053
+ request,
1054
+ response
1055
+ };
1056
+ try {
1057
+ preserveResult = await preserveOnServe(transmission);
1058
+ if (preserveResult) {
1059
+ if (preserveResult.responded) {
696
1060
  return {
697
- preserveResponded: false,
698
- preserveResult: preserveResult,
699
- preserveAfterServe: preserveAfterServe
1061
+ preserveResponded: true,
1062
+ preserveResult,
1063
+ preserveAfterServe
700
1064
  };
701
- }));
702
- }
703
- resolvePreserveAfterServe(preserveAfterServe, request, response) {
704
- return __awaiter(this, void 0, void 0, (function*() {
705
- if (preserveAfterServe) {
706
- const isoMatch = this.isoMatcher.match(request.originalUrl, "route");
707
- const transmission = {
708
- context: {
709
- route: request.originalUrl,
710
- match: isoMatch
711
- },
712
- request: request,
713
- response: response
714
- };
715
- yield preserveAfterServe(transmission);
1065
+ }
1066
+ }
1067
+ } catch (error) {
1068
+ if (preserveOnError) {
1069
+ const onErrorResponse = await preserveOnError(
1070
+ error,
1071
+ transmission
1072
+ );
1073
+ if (onErrorResponse) {
1074
+ if (onErrorResponse.responded) {
1075
+ return {
1076
+ preserveResponded: true,
1077
+ preserveResult,
1078
+ preserveAfterServe
1079
+ };
716
1080
  }
717
- }));
718
- }
719
- handleGateway(path, request, preserveResult) {
720
- return __awaiter(this, void 0, void 0, (function*() {
721
- const {gatewayEndpoint: gatewayEndpoint} = this.options;
722
- if (path !== gatewayEndpoint) {
723
- return;
1081
+ if (!onErrorResponse.depreserve) {
1082
+ return {
1083
+ preserveResponded: false,
1084
+ preserveResult,
1085
+ preserveAfterServe
1086
+ };
724
1087
  }
725
- ({
726
- path: {
727
- value: gatewayEndpoint
728
- },
729
- pathname: gatewayEndpoint,
730
- parameters: {},
731
- query: {
732
- __gatewayQuery: request.originalUrl
733
- },
734
- fragments: {
735
- texts: [],
736
- elements: []
737
- },
738
- route: gatewayEndpoint
739
- });
740
- return "";
741
- }));
1088
+ }
1089
+ }
1090
+ }
742
1091
  }
743
- renderApplication(isoMatch, preserveResult, matchedPlane) {
744
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s;
745
- return __awaiter(this, void 0, void 0, (function*() {
746
- const globals = preserveResult === null || preserveResult === void 0 ? void 0 : preserveResult.globals;
747
- const mergedHtmlLanguage = ((_a = preserveResult === null || preserveResult === void 0 ? void 0 : preserveResult.template) === null || _a === void 0 ? void 0 : _a.htmlLanguage) || ((_b = this.template) === null || _b === void 0 ? void 0 : _b.htmlLanguage);
748
- const pluridMetastate = yield pluridReact.serverComputeMetastate(isoMatch, this.routes, globals, this.options.hostname);
749
- const {content: content, styles: styles} = yield this.getContentAndStyles(isoMatch, pluridMetastate, preserveResult, matchedPlane);
750
- const stringedStyles = this.styles.reduce(((accumulator, style) => accumulator + style), "");
751
- const preserveStyles = ((_d = (_c = preserveResult === null || preserveResult === void 0 ? void 0 : preserveResult.template) === null || _c === void 0 ? void 0 : _c.styles) === null || _d === void 0 ? void 0 : _d.join(" ")) || "";
752
- const mergedStyles = styles + stringedStyles + preserveStyles;
753
- const {helmet: helmet} = this.helmet;
754
- const head = helmet ? `\n ${helmet.meta.toString()}\n ${helmet.title.toString()}\n ${helmet.base.toString()}\n ${helmet.link.toString()}\n ${helmet.style.toString()}\n ${helmet.noscript.toString()}\n ${helmet.script.toString()}\n ` : "";
755
- const htmlAttributes = Object.assign(Object.assign({}, (_e = this.template) === null || _e === void 0 ? void 0 : _e.htmlAttributes), helmet === null || helmet === void 0 ? void 0 : helmet.htmlAttributes.toComponent());
756
- const mergedHtmlAttributes = recordToString(htmlAttributes) + (((_f = preserveResult === null || preserveResult === void 0 ? void 0 : preserveResult.template) === null || _f === void 0 ? void 0 : _f.htmlAttributes) || "");
757
- const bodyAttributes = (helmet === null || helmet === void 0 ? void 0 : helmet.bodyAttributes.toString()) || "";
758
- const preserveBodyAttributes = ((_g = preserveResult === null || preserveResult === void 0 ? void 0 : preserveResult.template) === null || _g === void 0 ? void 0 : _g.bodyAttributes) || "";
759
- const mergedBodyAttributes = bodyAttributes + preserveBodyAttributes;
760
- const headScripts = ((_h = this.template) === null || _h === void 0 ? void 0 : _h.headScripts) || [];
761
- const mergedHeadScripts = [ ...headScripts, ...((_j = preserveResult === null || preserveResult === void 0 ? void 0 : preserveResult.template) === null || _j === void 0 ? void 0 : _j.headScripts) || [] ];
762
- const bodyScripts = ((_k = this.template) === null || _k === void 0 ? void 0 : _k.bodyScripts) || [];
763
- const mergedBodyScripts = [ ...bodyScripts, ...((_l = preserveResult === null || preserveResult === void 0 ? void 0 : preserveResult.template) === null || _l === void 0 ? void 0 : _l.bodyScripts) || [] ];
764
- const renderer = new PluridRenderer({
765
- htmlLanguage: mergedHtmlLanguage,
766
- head: head,
767
- htmlAttributes: mergedHtmlAttributes,
768
- bodyAttributes: mergedBodyAttributes,
769
- defaultStyle: (_m = this.template) === null || _m === void 0 ? void 0 : _m.defaultStyle,
770
- styles: mergedStyles,
771
- headScripts: mergedHeadScripts,
772
- bodyScripts: mergedBodyScripts,
773
- vendorScriptSource: (_o = this.template) === null || _o === void 0 ? void 0 : _o.vendorScriptSource,
774
- mainScriptSource: (_p = this.template) === null || _p === void 0 ? void 0 : _p.mainScriptSource,
775
- root: (_q = this.template) === null || _q === void 0 ? void 0 : _q.root,
776
- content: content,
777
- defaultPreloadedPluridMetastate: (_r = this.template) === null || _r === void 0 ? void 0 : _r.defaultPreloadedPluridMetastate,
778
- pluridMetastate: JSON.stringify(pluridMetastate),
779
- globals: globals,
780
- minify: (_s = this.template) === null || _s === void 0 ? void 0 : _s.minify
781
- });
782
- return renderer;
783
- }));
1092
+ return {
1093
+ preserveResponded: false,
1094
+ preserveResult,
1095
+ preserveAfterServe
1096
+ };
1097
+ }
1098
+ async resolvePreserveAfterServe(preserveAfterServe, request, response) {
1099
+ if (preserveAfterServe) {
1100
+ const isoMatch = this.isoMatcher.match(
1101
+ request.originalUrl,
1102
+ "route"
1103
+ );
1104
+ const transmission = {
1105
+ context: {
1106
+ route: request.originalUrl,
1107
+ match: isoMatch
1108
+ },
1109
+ request,
1110
+ response
1111
+ };
1112
+ await preserveAfterServe(transmission);
784
1113
  }
785
- getContentAndStyles(isoMatch, pluridMetastate, preserveResult, matchedPlane) {
786
- return __awaiter(this, void 0, void 0, (function*() {
787
- const stylesheet = new styledComponents.ServerStyleSheet;
788
- let content = "";
789
- let styles = "";
790
- try {
791
- const gateway = false;
792
- const gatewayQuery = "";
793
- const {gatewayEndpoint: gatewayEndpoint} = this.options;
794
- const contentHandler = new PluridContentGenerator({
795
- services: this.services,
796
- stylesheet: stylesheet,
797
- exterior: this.exterior,
798
- shell: this.shell,
799
- helmet: this.helmet,
800
- routes: this.routes,
801
- planes: this.planes,
802
- pluridMetastate: pluridMetastate,
803
- gateway: gateway,
804
- gatewayEndpoint: gatewayEndpoint,
805
- gatewayQuery: gatewayQuery,
806
- preserveResult: preserveResult,
807
- pathname: isoMatch.match.value,
808
- hostname: this.options.hostname,
809
- matchedPlane: isoMatch.kind === "RoutePlane" ? {
810
- value: isoMatch.match.value
811
- } : undefined
812
- });
813
- content = yield contentHandler.render();
814
- styles = stylesheet.getStyleTags();
815
- } catch (error) {
816
- if (this.options.debug !== "none" && !this.options.quiet) {
817
- const errorText = `${this.options.serverName} Error: Something went wrong in getContentAndStyles().`;
818
- if (this.debugAllows("error")) {
819
- console.error(errorText, error);
820
- }
821
- }
822
- return {
823
- content: "",
824
- styles: ""
825
- };
826
- } finally {
827
- stylesheet.seal();
828
- }
829
- return {
830
- content: content,
831
- styles: styles
832
- };
833
- }));
1114
+ }
1115
+ async handleGateway(path4, request, preserveResult) {
1116
+ const {
1117
+ gatewayEndpoint
1118
+ } = this.options;
1119
+ if (path4 !== gatewayEndpoint) {
1120
+ return;
834
1121
  }
835
- computeRequestTime(request) {
836
- const requestTime = request.requestTime;
837
- if (!requestTime) {
838
- return "";
1122
+ const gatewayRoute = {
1123
+ path: {
1124
+ value: gatewayEndpoint
1125
+ },
1126
+ pathname: gatewayEndpoint,
1127
+ parameters: {},
1128
+ query: {
1129
+ __gatewayQuery: request.originalUrl
1130
+ },
1131
+ fragments: {
1132
+ texts: [],
1133
+ elements: []
1134
+ },
1135
+ route: gatewayEndpoint
1136
+ };
1137
+ return "";
1138
+ }
1139
+ async renderApplication(isoMatch, preserveResult, matchedPlane) {
1140
+ const globals = preserveResult?.globals;
1141
+ const mergedHtmlLanguage = preserveResult?.template?.htmlLanguage || this.template?.htmlLanguage;
1142
+ const pluridMetastate = await (0, import_plurid_react2.serverComputeMetastate)(
1143
+ isoMatch,
1144
+ this.routes,
1145
+ globals,
1146
+ this.options.hostname
1147
+ );
1148
+ const {
1149
+ content,
1150
+ styles
1151
+ } = await this.getContentAndStyles(
1152
+ isoMatch,
1153
+ pluridMetastate,
1154
+ preserveResult,
1155
+ matchedPlane
1156
+ );
1157
+ const stringedStyles = this.styles.reduce(
1158
+ (accumulator, style) => accumulator + style,
1159
+ ""
1160
+ );
1161
+ const preserveStyles = preserveResult?.template?.styles?.join(" ") || "";
1162
+ const mergedStyles = styles + stringedStyles + preserveStyles;
1163
+ const {
1164
+ helmet
1165
+ } = this.helmet;
1166
+ const head = helmet ? `
1167
+ ${helmet.meta.toString()}
1168
+ ${helmet.title.toString()}
1169
+ ${helmet.base.toString()}
1170
+ ${helmet.link.toString()}
1171
+ ${helmet.style.toString()}
1172
+ ${helmet.noscript.toString()}
1173
+ ${helmet.script.toString()}
1174
+ ` : "";
1175
+ const htmlAttributes = {
1176
+ ...this.template?.htmlAttributes,
1177
+ ...helmet?.htmlAttributes.toComponent()
1178
+ };
1179
+ const mergedHtmlAttributes = recordToString(htmlAttributes) + (preserveResult?.template?.htmlAttributes || "");
1180
+ const bodyAttributes = helmet?.bodyAttributes.toString() || "";
1181
+ const preserveBodyAttributes = preserveResult?.template?.bodyAttributes || "";
1182
+ const mergedBodyAttributes = bodyAttributes + preserveBodyAttributes;
1183
+ const headScripts = this.template?.headScripts || [];
1184
+ const mergedHeadScripts = [
1185
+ ...headScripts,
1186
+ ...preserveResult?.template?.headScripts || []
1187
+ ];
1188
+ const bodyScripts = this.template?.bodyScripts || [];
1189
+ const mergedBodyScripts = [
1190
+ ...bodyScripts,
1191
+ ...preserveResult?.template?.bodyScripts || []
1192
+ ];
1193
+ const renderer = new Renderer_default({
1194
+ htmlLanguage: mergedHtmlLanguage,
1195
+ head,
1196
+ htmlAttributes: mergedHtmlAttributes,
1197
+ bodyAttributes: mergedBodyAttributes,
1198
+ defaultStyle: this.template?.defaultStyle,
1199
+ styles: mergedStyles,
1200
+ headScripts: mergedHeadScripts,
1201
+ bodyScripts: mergedBodyScripts,
1202
+ vendorScriptSource: this.template?.vendorScriptSource,
1203
+ mainScriptSource: this.template?.mainScriptSource,
1204
+ root: this.template?.root,
1205
+ content,
1206
+ defaultPreloadedPluridMetastate: this.template?.defaultPreloadedPluridMetastate,
1207
+ pluridMetastate: JSON.stringify(pluridMetastate),
1208
+ globals,
1209
+ minify: this.template?.minify
1210
+ });
1211
+ return renderer;
1212
+ }
1213
+ async getContentAndStyles(isoMatch, pluridMetastate, preserveResult, matchedPlane) {
1214
+ const stylesheet = new import_styled_components2.ServerStyleSheet();
1215
+ let content = "";
1216
+ let styles = "";
1217
+ try {
1218
+ const gateway = false;
1219
+ const gatewayQuery = "";
1220
+ const {
1221
+ gatewayEndpoint
1222
+ } = this.options;
1223
+ const contentHandler = new ContentGenerator_default({
1224
+ services: this.services,
1225
+ stylesheet,
1226
+ exterior: this.exterior,
1227
+ shell: this.shell,
1228
+ routerProperties: this.routerProperties,
1229
+ helmet: this.helmet,
1230
+ routes: this.routes,
1231
+ planes: this.planes,
1232
+ pluridMetastate,
1233
+ gateway,
1234
+ gatewayEndpoint,
1235
+ gatewayQuery,
1236
+ preserveResult,
1237
+ pathname: isoMatch.match.value,
1238
+ hostname: this.options.hostname,
1239
+ matchedPlane: isoMatch.kind === "RoutePlane" ? {
1240
+ value: isoMatch.match.value
1241
+ } : void 0
1242
+ });
1243
+ content = await contentHandler.render();
1244
+ styles = stylesheet.getStyleTags();
1245
+ } catch (error) {
1246
+ if (this.options.debug !== "none" && !this.options.quiet) {
1247
+ const errorText = `${this.options.serverName} Error: Something went wrong in getContentAndStyles().`;
1248
+ if (this.debugAllows("error")) {
1249
+ console.error(
1250
+ errorText,
1251
+ error
1252
+ );
839
1253
  }
840
- const now = Date.now();
841
- const difference = now - requestTime;
842
- return ` in ${difference} ms`;
1254
+ }
1255
+ return {
1256
+ content: "",
1257
+ styles: ""
1258
+ };
1259
+ } finally {
1260
+ stylesheet.seal();
843
1261
  }
844
- handleOptions(partialOptions) {
845
- var _a, _b;
846
- const options = {
847
- serverName: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.serverName) || DEFAULT_SERVER_OPTIONS.SERVER_NAME,
848
- hostname: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.hostname) || DEFAULT_SERVER_OPTIONS.HOSTNAME,
849
- quiet: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.quiet) || DEFAULT_SERVER_OPTIONS.QUIET,
850
- debug: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.debug) ? partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.debug : environment.production ? "error" : "info",
851
- compression: (_a = partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.compression) !== null && _a !== void 0 ? _a : DEFAULT_SERVER_OPTIONS.COMPRESSION,
852
- open: (_b = partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.open) !== null && _b !== void 0 ? _b : DEFAULT_SERVER_OPTIONS.OPEN,
853
- buildDirectory: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.buildDirectory) || DEFAULT_SERVER_OPTIONS.BUILD_DIRECTORY,
854
- assetsDirectory: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.assetsDirectory) || DEFAULT_SERVER_OPTIONS.ASSETS_DIRECTORY,
855
- gatewayEndpoint: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.gatewayEndpoint) || DEFAULT_SERVER_OPTIONS.GATEWAY,
856
- staticCache: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.staticCache) || 0,
857
- ignore: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.ignore) || [],
858
- stillsDirectory: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.stillsDirectory) || DEFAULT_SERVER_OPTIONS.STILLS_DIRECTORY,
859
- stiller: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.stiller) || defaultStillerOptions
860
- };
861
- return options;
1262
+ return {
1263
+ content,
1264
+ styles
1265
+ };
1266
+ }
1267
+ computeRequestTime(request) {
1268
+ const requestTime = request.requestTime;
1269
+ if (!requestTime) {
1270
+ return "";
862
1271
  }
863
- configureServer() {
864
- const clientPath = path__default["default"].join(this.options.buildDirectory, "./client");
865
- this.serverApplication.disable("x-powered-by");
866
- this.serverApplication.use(((request, _, next) => {
867
- const requestID = pluridFunctions.uuid.generate();
868
- request.requestID = requestID;
869
- const requestTime = Date.now();
870
- request.requestTime = requestTime;
1272
+ const now = Date.now();
1273
+ const difference = now - requestTime;
1274
+ return ` in ${difference} ms`;
1275
+ }
1276
+ handleOptions(partialOptions) {
1277
+ const options = {
1278
+ serverName: partialOptions?.serverName || DEFAULT_SERVER_OPTIONS.SERVER_NAME,
1279
+ hostname: partialOptions?.hostname || DEFAULT_SERVER_OPTIONS.HOSTNAME,
1280
+ quiet: partialOptions?.quiet || DEFAULT_SERVER_OPTIONS.QUIET,
1281
+ debug: partialOptions?.debug ? partialOptions?.debug : environment.production ? "error" : "info",
1282
+ compression: partialOptions?.compression ?? DEFAULT_SERVER_OPTIONS.COMPRESSION,
1283
+ open: partialOptions?.open ?? DEFAULT_SERVER_OPTIONS.OPEN,
1284
+ buildDirectory: partialOptions?.buildDirectory || DEFAULT_SERVER_OPTIONS.BUILD_DIRECTORY,
1285
+ assetsDirectory: partialOptions?.assetsDirectory || DEFAULT_SERVER_OPTIONS.ASSETS_DIRECTORY,
1286
+ gatewayEndpoint: partialOptions?.gatewayEndpoint || DEFAULT_SERVER_OPTIONS.GATEWAY,
1287
+ staticCache: partialOptions?.staticCache || 0,
1288
+ ignore: partialOptions?.ignore || [],
1289
+ stillsDirectory: partialOptions?.stillsDirectory || DEFAULT_SERVER_OPTIONS.STILLS_DIRECTORY,
1290
+ stiller: partialOptions?.stiller || defaultStillerOptions,
1291
+ attachSignalHandlers: partialOptions?.attachSignalHandlers ?? true
1292
+ };
1293
+ return options;
1294
+ }
1295
+ configureServer() {
1296
+ const clientPath = import_path2.default.join(this.options.buildDirectory, "./client");
1297
+ this.serverApplication.disable("x-powered-by");
1298
+ this.serverApplication.use(
1299
+ (request, _, next) => {
1300
+ const requestID = import_plurid_functions.uuid.generate();
1301
+ request.requestID = requestID;
1302
+ const requestTime = Date.now();
1303
+ request.requestTime = requestTime;
1304
+ next();
1305
+ }
1306
+ );
1307
+ if (this.options.compression) {
1308
+ this.serverApplication.use(
1309
+ (0, import_compression.default)()
1310
+ // @types/compression targets Express 4's handler type
1311
+ );
1312
+ this.serverApplication.get(
1313
+ "/vendor.js",
1314
+ (request, response, next) => {
1315
+ response.setHeader(
1316
+ "Content-Type",
1317
+ "application/javascript"
1318
+ );
1319
+ const vendorBrotliExists = import_fs2.default.existsSync(
1320
+ import_path2.default.join(clientPath, "vendor.js.br")
1321
+ );
1322
+ const acceptEncoding = request.header("Accept-Encoding");
1323
+ if (acceptEncoding?.includes("br") && vendorBrotliExists) {
1324
+ request.url += ".br";
1325
+ response.set("Content-Encoding", "br");
871
1326
  next();
872
- }));
873
- if (this.options.compression) {
874
- this.serverApplication.use(compression__default["default"]());
875
- this.serverApplication.get("/vendor.js", ((request, response, next) => {
876
- response.setHeader("Content-Type", "application/javascript");
877
- const vendorBrotliExists = fs__default["default"].existsSync(path__default["default"].join(clientPath, "vendor.js.br"));
878
- const acceptEncoding = request.header("Accept-Encoding");
879
- if ((acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("br")) && vendorBrotliExists) {
880
- request.url += ".br";
881
- response.set("Content-Encoding", "br");
882
- next();
883
- return;
884
- }
885
- next();
886
- }));
1327
+ return;
1328
+ }
1329
+ next();
887
1330
  }
888
- this.serverApplication.use(express__default["default"].static(clientPath, {
889
- maxAge: this.options.staticCache
890
- }));
891
- this.loadMiddleware();
1331
+ );
892
1332
  }
893
- loadMiddleware() {
894
- for (const middleware of this.middleware) {
895
- this.serverApplication.use(((req, res, next) => middleware(req, res, next)));
896
- }
1333
+ this.serverApplication.use(
1334
+ import_express.default.static(clientPath, {
1335
+ maxAge: this.options.staticCache
1336
+ })
1337
+ );
1338
+ this.loadMiddleware();
1339
+ }
1340
+ loadMiddleware() {
1341
+ for (const middleware of this.middleware) {
1342
+ this.serverApplication.use(
1343
+ (req, res, next) => middleware(req, res, next)
1344
+ );
897
1345
  }
898
- open(serverlink) {
899
- try {
900
- const processDoNotOpen = process.env.PLURID_OPEN === "false" ? true : false;
901
- if (processDoNotOpen) {
902
- return;
903
- }
904
- if (this.options.open) {
905
- open__default["default"](serverlink);
906
- }
907
- } catch (error) {
908
- return;
909
- }
1346
+ }
1347
+ open(serverlink) {
1348
+ try {
1349
+ const processDoNotOpen = process.env.PLURID_OPEN === "false" ? true : false;
1350
+ if (processDoNotOpen) {
1351
+ return;
1352
+ }
1353
+ if (this.options.open) {
1354
+ (0, import_open.default)(serverlink);
1355
+ }
1356
+ } catch (error) {
1357
+ return;
910
1358
  }
911
- debugAllows(level) {
912
- if (this.options.quiet) {
913
- return false;
914
- }
915
- if (this.options.debug === "none") {
916
- return false;
917
- }
918
- switch (level) {
919
- case "error":
920
- return true;
921
-
922
- case "warn":
923
- if (this.options.debug === "error") {
924
- return false;
925
- }
926
- return true;
927
-
928
- case "info":
929
- if (this.options.debug === "error" || this.options.debug === "warn") {
930
- return false;
931
- }
932
- return true;
933
-
934
- default:
935
- return false;
936
- }
1359
+ }
1360
+ debugAllows(level) {
1361
+ if (this.options.quiet) {
1362
+ return false;
937
1363
  }
938
- }
939
-
940
- class LiveServer {
941
- constructor(options) {
942
- this.sockets = [];
943
- this.resolveOptions = options => {
944
- const defaultServerPath = "./source/server/index.ts";
945
- const resolvedOptions = {
946
- server: (options === null || options === void 0 ? void 0 : options.server) || defaultServerPath
947
- };
948
- return resolvedOptions;
949
- };
950
- this.options = this.resolveOptions(options);
951
- this.expressServer = express__default["default"]();
952
- this.setupExpressServer();
953
- this.httpServer = http__default["default"].createServer(this.expressServer);
954
- this.setupHttpServer();
1364
+ if (this.options.debug === "none") {
1365
+ return false;
955
1366
  }
956
- setupExpressServer() {}
957
- setupHttpServer() {
958
- this.httpServer.on("connection", (socket => {
959
- this.sockets.push(socket);
960
- socket.once("close", (() => {
961
- this.sockets.splice(this.sockets.indexOf(socket), 1);
962
- }));
963
- }));
964
- this.httpServer.on("error", (error => {
965
- throw error;
966
- }));
1367
+ switch (level) {
1368
+ case "error":
1369
+ return true;
1370
+ case "warn":
1371
+ if (this.options.debug === "error") {
1372
+ return false;
1373
+ }
1374
+ return true;
1375
+ case "info":
1376
+ if (this.options.debug === "error" || this.options.debug === "warn") {
1377
+ return false;
1378
+ }
1379
+ return true;
1380
+ default:
1381
+ return false;
967
1382
  }
968
- start() {}
969
- }
970
-
971
- const replacePluridResolution = html => {
972
- const normalResolution = "width: 1366px; height: 768px;";
973
- const zeroResolution = "width: 0px; height: 0px;";
974
- return html.replace(normalResolution, zeroResolution);
1383
+ }
975
1384
  };
976
-
977
- const isCurrentUserRoot = () => process.getuid() == 0;
978
-
979
- const render = (puppeteer, host, route, configuration) => __awaiter(void 0, void 0, void 0, (function*() {
980
- const start = Date.now();
981
- const browser = yield puppeteer.launch({
982
- defaultViewport: {
983
- width: 1366,
984
- height: 768
985
- },
986
- headless: true,
987
- args: isCurrentUserRoot() ? [ "--no-sandbox" ] : undefined
1385
+ var Server_default = PluridServer;
1386
+
1387
+ // source/objects/LiveServer/index.ts
1388
+ var import_http = __toESM(require("http"));
1389
+ var import_express2 = __toESM(require("express"));
1390
+ var LiveServer = class {
1391
+ options;
1392
+ expressServer;
1393
+ httpServer;
1394
+ sockets = [];
1395
+ constructor(options) {
1396
+ this.options = this.resolveOptions(options);
1397
+ this.expressServer = (0, import_express2.default)();
1398
+ this.setupExpressServer();
1399
+ this.httpServer = import_http.default.createServer(this.expressServer);
1400
+ this.setupHttpServer();
1401
+ }
1402
+ resolveOptions = (options) => {
1403
+ const defaultServerPath = "./source/server/index.ts";
1404
+ const resolvedOptions = {
1405
+ server: options?.server || defaultServerPath
1406
+ };
1407
+ return resolvedOptions;
1408
+ };
1409
+ setupExpressServer() {
1410
+ }
1411
+ setupHttpServer() {
1412
+ this.httpServer.on("connection", (socket) => {
1413
+ this.sockets.push(socket);
1414
+ socket.once("close", () => {
1415
+ this.sockets.splice(this.sockets.indexOf(socket), 1);
1416
+ });
988
1417
  });
989
- const page = yield browser.newPage();
990
- try {
991
- const url = host + route;
992
- yield page.goto(url, {
993
- waitUntil: configuration.waitUntil,
994
- timeout: configuration.timeout
995
- });
996
- } catch (err) {
997
- throw new Error(`${route} timed out.`);
998
- }
999
- const pageContent = yield page.content();
1418
+ this.httpServer.on("error", (error) => {
1419
+ throw error;
1420
+ });
1421
+ }
1422
+ start() {
1423
+ throw new Error(
1424
+ "PluridLiveServer is not implemented yet. Use `PluridServer` (production) or a bundler dev server (tsx/Vite) for live reload."
1425
+ );
1426
+ }
1427
+ };
1428
+ var LiveServer_default = LiveServer;
1429
+
1430
+ // source/objects/StillsGenerator/index.ts
1431
+ var import_path3 = __toESM(require("path"));
1432
+ var import_fs3 = require("fs");
1433
+ var import_child_process = require("child_process");
1434
+ var import_detect_port = __toESM(require("detect-port"));
1435
+ var import_plurid_functions2 = require("@plurid/plurid-functions");
1436
+
1437
+ // source/objects/Stiller/index.ts
1438
+ var replacePluridResolution = (html) => {
1439
+ const normalResolution = "width: 1366px; height: 768px;";
1440
+ const zeroResolution = "width: 0px; height: 0px;";
1441
+ return html.replace(normalResolution, zeroResolution);
1442
+ };
1443
+ var isCurrentUserRoot = () => {
1444
+ return typeof process.getuid === "function" && process.getuid() === 0;
1445
+ };
1446
+ var render = async (browser, host, route, configuration) => {
1447
+ const start = Date.now();
1448
+ const page = await browser.newPage();
1449
+ try {
1450
+ const url = host + route;
1451
+ await page.goto(
1452
+ url,
1453
+ {
1454
+ waitUntil: configuration.waitUntil,
1455
+ timeout: configuration.timeout
1456
+ }
1457
+ );
1458
+ const pageContent = await page.content();
1000
1459
  const html = replacePluridResolution(pageContent);
1001
- yield browser.close();
1002
1460
  const stilltime = Date.now() - start;
1003
- console.info(`\tStilled '${route}' in ${(stilltime / 1e3).toFixed(2)} seconds.`);
1461
+ console.info(` Stilled '${route}' in ${(stilltime / 1e3).toFixed(2)} seconds.`);
1004
1462
  return {
1005
- route: route,
1006
- html: html,
1007
- stilltime: stilltime
1463
+ route,
1464
+ html,
1465
+ stilltime
1008
1466
  };
1009
- }));
1010
-
1011
- class Stiller {
1012
- constructor(options) {
1013
- try {
1014
- this.puppeteer = require("puppeteer");
1015
- } catch (error) {
1016
- console.error("could not load puppeteer: check puppeteer is installed");
1017
- }
1018
- const {host: host, routes: routes, configuration: configuration} = options;
1019
- this.host = host;
1020
- this.routes = routes;
1021
- this.configuration = configuration;
1467
+ } catch (error) {
1468
+ const reason = error instanceof Error ? error.message : String(error);
1469
+ throw new Error(`Could not still '${route}': ${reason}`, { cause: error });
1470
+ } finally {
1471
+ await page.close();
1472
+ }
1473
+ };
1474
+ var Stiller = class {
1475
+ puppeteer = null;
1476
+ host;
1477
+ routes;
1478
+ configuration;
1479
+ constructor(options) {
1480
+ try {
1481
+ this.puppeteer = require("puppeteer");
1482
+ } catch (_error) {
1483
+ this.puppeteer = null;
1022
1484
  }
1023
- still() {
1024
- return __asyncGenerator(this, arguments, (function* still_1() {
1025
- for (const route of this.routes) {
1026
- yield yield __await(yield __await(render(this.puppeteer, this.host, route, this.configuration)));
1027
- }
1028
- }));
1485
+ const {
1486
+ host,
1487
+ routes,
1488
+ configuration
1489
+ } = options;
1490
+ this.host = host;
1491
+ this.routes = routes;
1492
+ this.configuration = configuration;
1493
+ }
1494
+ async *still() {
1495
+ if (!this.puppeteer) {
1496
+ throw new Error(
1497
+ "Plurid Stiller: the optional 'puppeteer' dependency is not installed. Install it to generate stills (npm install puppeteer)."
1498
+ );
1029
1499
  }
1030
- }
1031
-
1032
- class StillsGenerator {
1033
- constructor(options) {
1034
- this.options = this.resolveOptions(options);
1500
+ const browser = await this.puppeteer.launch({
1501
+ defaultViewport: {
1502
+ width: 1366,
1503
+ height: 768
1504
+ },
1505
+ headless: true,
1506
+ args: isCurrentUserRoot() ? ["--no-sandbox"] : void 0
1507
+ });
1508
+ try {
1509
+ for (const route of this.routes) {
1510
+ yield await render(
1511
+ browser,
1512
+ this.host,
1513
+ route,
1514
+ this.configuration
1515
+ );
1516
+ }
1517
+ } finally {
1518
+ await browser.close();
1035
1519
  }
1036
- resolveOptions(options) {
1037
- var _a, _b;
1038
- const stillsGeneratorOptions = {
1039
- server: (_a = options === null || options === void 0 ? void 0 : options.server) !== null && _a !== void 0 ? _a : "./build/server.js",
1040
- build: (_b = options === null || options === void 0 ? void 0 : options.build) !== null && _b !== void 0 ? _b : "./build/"
1041
- };
1042
- return stillsGeneratorOptions;
1520
+ }
1521
+ };
1522
+ var Stiller_default = Stiller;
1523
+
1524
+ // source/objects/StillsGenerator/index.ts
1525
+ var StillsGenerator = class {
1526
+ options;
1527
+ constructor(options) {
1528
+ this.options = this.resolveOptions(options);
1529
+ }
1530
+ resolveOptions(options) {
1531
+ const stillsGeneratorOptions = {
1532
+ server: options?.server ?? "./build/server.js",
1533
+ build: options?.build ?? "./build/"
1534
+ };
1535
+ return stillsGeneratorOptions;
1536
+ }
1537
+ async initialize() {
1538
+ const serverPath = import_path3.default.join(process.cwd(), this.options.server);
1539
+ const buildPath = import_path3.default.join(process.cwd(), this.options.build);
1540
+ let serverModule;
1541
+ try {
1542
+ serverModule = require(serverPath);
1543
+ } catch (error) {
1544
+ const reason = error instanceof Error ? error.message : String(error);
1545
+ throw new Error(
1546
+ `Plurid StillsGenerator: could not load the built server at '${serverPath}'. Build the server first so the generator can read its routes. (${reason})`,
1547
+ { cause: error }
1548
+ );
1043
1549
  }
1044
- initialize() {
1045
- return __awaiter(this, void 0, void 0, (function*() {
1046
- const serverPath = path__default["default"].join(process.cwd(), this.options.server);
1047
- const buildPath = path__default["default"].join(process.cwd(), this.options.build);
1048
- const pluridServer = require(serverPath);
1049
- const serverInformation = PluridServer.analysis(pluridServer);
1050
- const stillerOptions = serverInformation.options.stiller;
1051
- const serverPort = (yield detectPort__default["default"](9900)) + "";
1052
- const child = child_process.fork(serverPath, [], {
1053
- stdio: "pipe",
1054
- env: {
1055
- PORT: serverPort,
1056
- PLURID_OPEN: "false"
1057
- }
1058
- });
1059
- const stillRoutes = [];
1060
- for (const route of serverInformation.routes) {
1061
- if (route.value.includes("/:")) {
1062
- continue;
1063
- }
1064
- if (stillerOptions.ignore.includes(route.value)) {
1065
- continue;
1066
- }
1067
- stillRoutes.push(route);
1068
- }
1069
- const stillRoutesPaths = stillRoutes.map((stillRoute => stillRoute.value));
1070
- console.info("\n\tParsed the following still routes:");
1071
- for (const stillRoutePath of stillRoutesPaths) {
1072
- console.info(`\t ${stillRoutePath}`);
1073
- }
1074
- yield new Promise((resolve => setTimeout(resolve, 1500)));
1075
- const startTime = Date.now();
1076
- const estimatedDuration = 3 * serverInformation.routes.length;
1077
- console.info(`\n\tStarting to generate stills... (this may take about ${estimatedDuration} seconds)\n`);
1078
- const stiller = new Stiller({
1079
- host: "http://localhost:" + serverPort,
1080
- routes: [ ...stillRoutesPaths ],
1081
- configuration: {
1082
- waitUntil: stillerOptions.waitUntil,
1083
- timeout: stillerOptions.timeout
1084
- }
1085
- });
1086
- const sequence = stiller.still();
1087
- const stills = [];
1088
- let next;
1089
- while (!(next = yield sequence.next()).done) {
1090
- stills.push(next.value);
1091
- }
1092
- const endTime = Date.now();
1093
- const duration = (endTime - startTime) / 1e3;
1094
- const plural = stills.length === 1 ? "" : "s";
1095
- console.info(`\n\tGenerated ${stills.length} still${plural} in ${duration.toFixed(2)} seconds.\n`);
1096
- const stillsPath = path__default["default"].join(buildPath, "./stills");
1097
- yield fs.promises.mkdir(stillsPath, {
1098
- recursive: true
1099
- });
1100
- const metadataFile = [];
1101
- for (const still of stills) {
1102
- if (!still) {
1103
- continue;
1104
- }
1105
- const stillName = pluridFunctions.uuid.generate() + ".json";
1106
- const metadataItem = {
1107
- route: still.route,
1108
- name: stillName
1109
- };
1110
- metadataFile.push(metadataItem);
1111
- const stillJSON = JSON.stringify(still, null, 4);
1112
- const stillFile = path__default["default"].join(stillsPath, stillName);
1113
- yield fs.promises.writeFile(stillFile, stillJSON);
1114
- }
1115
- const metadataFilePath = path__default["default"].join(stillsPath, "metadata.json");
1116
- const metadataJSON = JSON.stringify(metadataFile, null, 4);
1117
- yield fs.promises.writeFile(metadataFilePath, metadataJSON);
1118
- child.kill(2);
1119
- }));
1550
+ const pluridServer = serverModule?.default ?? serverModule;
1551
+ const serverInformation = Server_default.analysis(pluridServer);
1552
+ const stillerOptions = serverInformation.options.stiller;
1553
+ const serverPort = await (0, import_detect_port.default)(9900) + "";
1554
+ const child = (0, import_child_process.fork)(serverPath, [], {
1555
+ stdio: "pipe",
1556
+ env: {
1557
+ PORT: serverPort,
1558
+ PLURID_OPEN: "false"
1559
+ }
1560
+ });
1561
+ try {
1562
+ const stillRoutes = [];
1563
+ for (const route of serverInformation.routes) {
1564
+ if (route.value.includes("/:")) {
1565
+ continue;
1566
+ }
1567
+ if (stillerOptions.ignore.includes(route.value)) {
1568
+ continue;
1569
+ }
1570
+ stillRoutes.push(route);
1571
+ }
1572
+ const stillRoutesPaths = stillRoutes.map((stillRoute) => stillRoute.value);
1573
+ console.info("\n Parsed the following still routes:");
1574
+ for (const stillRoutePath of stillRoutesPaths) {
1575
+ console.info(` ${stillRoutePath}`);
1576
+ }
1577
+ await new Promise((resolve) => setTimeout(resolve, 1500));
1578
+ const startTime = Date.now();
1579
+ const estimatedDuration = 3 * serverInformation.routes.length;
1580
+ console.info(`
1581
+ Starting to generate stills... (this may take about ${estimatedDuration} seconds)
1582
+ `);
1583
+ const stiller = new Stiller_default({
1584
+ host: "http://localhost:" + serverPort,
1585
+ routes: [
1586
+ ...stillRoutesPaths
1587
+ ],
1588
+ configuration: {
1589
+ waitUntil: stillerOptions.waitUntil,
1590
+ timeout: stillerOptions.timeout
1591
+ }
1592
+ });
1593
+ const sequence = stiller.still();
1594
+ const stills = [];
1595
+ let next;
1596
+ while (!(next = await sequence.next()).done) {
1597
+ stills.push(next.value);
1598
+ }
1599
+ const endTime = Date.now();
1600
+ const duration = (endTime - startTime) / 1e3;
1601
+ const plural = stills.length === 1 ? "" : "s";
1602
+ console.info(`
1603
+ Generated ${stills.length} still${plural} in ${duration.toFixed(2)} seconds.
1604
+ `);
1605
+ const stillsPath = import_path3.default.join(buildPath, "./stills");
1606
+ await import_fs3.promises.mkdir(
1607
+ stillsPath,
1608
+ {
1609
+ recursive: true
1610
+ }
1611
+ );
1612
+ const metadataFile = [];
1613
+ for (const still of stills) {
1614
+ if (!still) {
1615
+ continue;
1616
+ }
1617
+ const stillName = import_plurid_functions2.uuid.generate() + ".json";
1618
+ const metadataItem = {
1619
+ route: still.route,
1620
+ name: stillName
1621
+ };
1622
+ metadataFile.push(metadataItem);
1623
+ const stillJSON = JSON.stringify(still, null, 4);
1624
+ const stillFile = import_path3.default.join(stillsPath, stillName);
1625
+ await import_fs3.promises.writeFile(stillFile, stillJSON);
1626
+ }
1627
+ const metadataFilePath = import_path3.default.join(stillsPath, "metadata.json");
1628
+ const metadataJSON = JSON.stringify(metadataFile, null, 4);
1629
+ await import_fs3.promises.writeFile(metadataFilePath, metadataJSON);
1630
+ } finally {
1631
+ child.kill("SIGTERM");
1120
1632
  }
1121
- }
1122
-
1123
- exports.PluridLiveServer = LiveServer;
1124
-
1125
- exports.PluridStillsGenerator = StillsGenerator;
1126
-
1127
- exports["default"] = PluridServer;
1633
+ }
1634
+ };
1635
+ var StillsGenerator_default = StillsGenerator;
1636
+
1637
+ // source/index.ts
1638
+ var index_default = Server_default;
1639
+ // Annotate the CommonJS export names for ESM import in node:
1640
+ 0 && (module.exports = {
1641
+ PluridLiveServer,
1642
+ PluridStillsGenerator
1643
+ });
1644
+ //# sourceMappingURL=index.js.map