elegance-js 2.1.7 → 2.1.10

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.
@@ -1,230 +1,14 @@
1
- // src/compile_docs.ts
2
- import { fileURLToPath as fileURLToPath2 } from "url";
3
-
4
- // src/build.ts
5
- import fs from "fs";
6
- import path from "path";
7
1
  import { fileURLToPath } from "url";
8
- import child_process from "node:child_process";
9
- import http from "http";
10
-
11
- // src/log.ts
12
- var quiet = false;
13
- function setQuiet(value) {
14
- quiet = value;
15
- }
16
- function getTimestamp() {
17
- const now = /* @__PURE__ */ new Date();
18
- return now.toLocaleString(void 0, {
19
- year: "2-digit",
20
- month: "2-digit",
21
- day: "2-digit",
22
- hour: "2-digit",
23
- minute: "2-digit",
24
- second: "2-digit"
25
- });
26
- }
27
- function color(text, code) {
28
- return `\x1B[${code}m${text}\x1B[0m`;
29
- }
30
- function logInfo(...args) {
31
- if (quiet) return;
32
- console.info(`Elegance.JS: ${getTimestamp()} ${color("[INFO]:", 34)}`, ...args);
33
- }
34
- function logWarn(...args) {
35
- if (quiet) return;
36
- console.warn(`Elegance.JS: ${getTimestamp()} ${color("[WARN]:", 33)}`, ...args);
37
- }
38
- function logError(...args) {
39
- console.error(`Elegance.JS: ${getTimestamp()} ${color("[ERROR]:", 31)}`, ...args);
40
- }
41
- var log = {
42
- info: logInfo,
43
- warn: logWarn,
44
- error: logError
45
- };
46
-
47
- // src/build.ts
48
- var __filename = fileURLToPath(import.meta.url);
49
- var __dirname = path.dirname(__filename);
50
- var packageDir = path.resolve(__dirname, "..");
51
- var builderPath = path.resolve(packageDir, "./dist/page_compiler.mjs");
52
- var yellow = (text) => {
53
- return `\x1B[38;2;238;184;68m${text}`;
54
- };
55
- var bold = (text) => {
56
- return `\x1B[1m${text}`;
57
- };
58
- var white = (text) => {
59
- return `\x1B[38;2;255;247;229m${text}`;
60
- };
61
- var green = (text) => {
62
- return `\x1B[38;2;65;224;108m${text}`;
63
- };
64
- var finishLog = (...text) => {
65
- log.info(text.map((text2) => `${text2}\x1B[0m`).join(""));
66
- };
67
- var options = process.env.OPTIONS;
68
- var getAllSubdirectories = (dir, baseDir = dir) => {
69
- let directories = [];
70
- const items = fs.readdirSync(dir, { withFileTypes: true });
71
- for (const item of items) {
72
- if (item.isDirectory()) {
73
- const fullPath = path.join(dir, item.name);
74
- const relativePath = path.relative(baseDir, fullPath);
75
- directories.push(relativePath);
76
- directories = directories.concat(getAllSubdirectories(fullPath, baseDir));
77
- }
78
- }
79
- return directories;
80
- };
81
- var child = void 0;
82
- var isBuilding = false;
83
- var runBuild = (filepath, DIST_DIR) => {
84
- const optionsString = JSON.stringify(options);
85
- if (isBuilding) {
86
- return;
87
- }
88
- if (child !== void 0) {
89
- child.removeAllListeners();
90
- child.kill("SIGKILL");
91
- }
92
- child = child_process.spawn("node", [filepath], {
93
- stdio: ["inherit", "inherit", "inherit", "ipc"],
94
- env: { ...process.env, DIST_DIR, OPTIONS: optionsString, PACKAGE_PATH: packageDir }
95
- });
96
- child.on("error", () => {
97
- log.error("Failed to start child process.");
98
- });
99
- child.on("exit", () => {
100
- isBuilding = false;
101
- log.info("Builder process complete");
102
- });
103
- child.on("message", (message) => {
104
- const { data } = message;
105
- if (data === "hard-reload") {
106
- httpStream?.write(`data: hard-reload
107
-
108
- `);
109
- } else if (data === "soft-reload") {
110
- httpStream?.write(`data: reload
111
-
112
- `);
113
- } else if (data === "compile-finish") {
114
- isBuilding = false;
115
- if (options.postCompile) {
116
- finishLog(
117
- white("Calling post-compile hook..")
118
- );
119
- options.postCompile();
120
- }
121
- }
122
- });
123
- };
124
- var build = (DIST_DIR) => {
125
- runBuild(builderPath, DIST_DIR);
126
- };
127
- var isTimedOut = false;
128
- var currentWatchers = [];
129
- var httpStream;
130
- var registerListener = async () => {
131
- const server = http.createServer((req, res) => {
132
- if (req.url === "/events") {
133
- finishLog(white("Client listening for changes.."));
134
- res.writeHead(200, {
135
- "Content-Type": "text/event-stream",
136
- "Cache-Control": "no-cache",
137
- "Connection": "keep-alive",
138
- "Transfer-Encoding": "chunked",
139
- "X-Accel-Buffering": "no",
140
- "Content-Encoding": "none",
141
- "Access-Control-Allow-Origin": "*",
142
- "Access-Control-Allow-Methods": "*",
143
- "Access-Control-Allow-Headers": "*"
144
- });
145
- httpStream = res;
146
- httpStream.write(`data: ping
147
-
148
- `);
149
- } else {
150
- res.writeHead(404, { "Content-Type": "text/plain" });
151
- res.end("Not Found");
152
- }
153
- });
154
- server.listen(options.hotReload.port, () => {
155
- finishLog(bold(green("Hot-Reload server online!")));
156
- });
157
- };
158
- var compile = async (props) => {
159
- options = props;
160
- setQuiet(options.quiet ?? false);
161
- const watch = options.hotReload !== void 0;
162
- const BUILD_FLAG = path.join(options.outputDirectory, "ELEGANCE_BUILD_FLAG");
163
- if (!fs.existsSync(options.outputDirectory)) {
164
- fs.mkdirSync(options.outputDirectory, { recursive: true });
165
- fs.writeFileSync(
166
- path.join(BUILD_FLAG),
167
- "This file just marks this directory as one containing an Elegance Build.",
168
- "utf-8"
169
- );
170
- } else {
171
- if (!fs.existsSync(BUILD_FLAG)) {
172
- throw `The output directory already exists, but is not an Elegance Build directory.`;
173
- }
174
- }
175
- const DIST_DIR = path.join(props.outputDirectory, "dist");
176
- if (!fs.existsSync(DIST_DIR)) {
177
- fs.mkdirSync(DIST_DIR, { recursive: true });
178
- }
179
- if (watch) {
180
- await registerListener();
181
- for (const watcher of currentWatchers) {
182
- watcher.close();
183
- }
184
- let extra = [];
185
- if (options.hotReload?.extraWatchDirectories) {
186
- const dirs = options.hotReload?.extraWatchDirectories ?? [];
187
- if (dirs.length !== 0) {
188
- for (const dir of dirs) {
189
- const subdirs = getAllSubdirectories(dir).map((f) => path.join(dir, f));
190
- extra.push(...subdirs);
191
- }
192
- }
193
- }
194
- const pagesSubDirs = getAllSubdirectories(options.pagesDirectory).map((f) => path.join(options.pagesDirectory, f));
195
- const subdirectories = [...pagesSubDirs, options.pagesDirectory, ...extra];
196
- finishLog(yellow("Hot-Reload Watching Subdirectories: "), ...subdirectories.join(", "));
197
- const watcherFn = async () => {
198
- if (isTimedOut) return;
199
- isTimedOut = true;
200
- process.stdout.write("\x1Bc");
201
- setTimeout(async () => {
202
- build(DIST_DIR);
203
- isTimedOut = false;
204
- }, 100);
205
- };
206
- for (const directory of subdirectories) {
207
- const watcher = fs.watch(
208
- directory,
209
- {},
210
- watcherFn
211
- );
212
- currentWatchers.push(watcher);
213
- }
214
- }
215
- build(DIST_DIR);
216
- };
217
-
218
- // src/compile_docs.ts
2
+ import { compile } from "./build";
219
3
  import { exec, execSync } from "child_process";
220
- import path2 from "path";
221
- var __dirname2 = path2.dirname(fileURLToPath2(import.meta.url));
222
- var PAGES_DIR = path2.join(__dirname2, "../src/docs");
223
- var PUBLIC_DIR = path2.join(__dirname2, "../src/docs/public");
224
- var OUTPUT_DIR = path2.join(__dirname2, "../docs");
225
- var environmentArg = process.argv.find((arg) => arg.startsWith("--environment"));
4
+ import path from "path";
5
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
6
+ const PAGES_DIR = path.join(__dirname, "../src/docs");
7
+ const PUBLIC_DIR = path.join(__dirname, "../src/docs/public");
8
+ const OUTPUT_DIR = path.join(__dirname, "../docs");
9
+ let environmentArg = process.argv.find((arg) => arg.startsWith("--environment"));
226
10
  if (!environmentArg) environmentArg = "--environment='production'";
227
- var environment = environmentArg.split("=")[1];
11
+ const environment = environmentArg.split("=")[1];
228
12
  console.log(`Environment: ${environment}`);
229
13
  compile({
230
14
  pagesDirectory: PAGES_DIR,
@@ -1,52 +1,4 @@
1
- // src/server/loadHook.ts
2
- var loadHook = (deps, fn, bind) => {
3
- const stringFn = fn.toString();
4
- const depsArray = (deps || []).map((dep) => ({
5
- id: dep.id,
6
- bind: dep.bind
7
- }));
8
- let dependencyString = "[";
9
- for (const dep of depsArray) {
10
- dependencyString += `{id:${dep.id}`;
11
- if (dep.bind) dependencyString += `,bind:${dep.bind}`;
12
- dependencyString += `},`;
13
- }
14
- dependencyString += "]";
15
- const isAsync = fn.constructor.name === "AsyncFunction";
16
- const wrapperFn = isAsync ? `async (state) => await (${stringFn})(state, ...state.getAll(${dependencyString}))` : `(state) => (${stringFn})(state, ...state.getAll(${dependencyString}))`;
17
- globalThis.__SERVER_CURRENT_LOADHOOKS__.push({
18
- fn: wrapperFn,
19
- bind: bind || ""
20
- });
21
- };
22
-
23
- // src/server/state.ts
24
- if (!globalThis.__SERVER_CURRENT_STATE_ID__) {
25
- globalThis.__SERVER_CURRENT_STATE_ID__ = 1;
26
- }
27
- var eventListener = (dependencies, eventListener2) => {
28
- const deps = dependencies.map((dep) => ({ id: dep.id, bind: dep.bind }));
29
- let dependencyString = "[";
30
- for (const dep of deps) {
31
- dependencyString += `{id:${dep.id}`;
32
- if (dep.bind) dependencyString += `,bind:${dep.bind}`;
33
- dependencyString += `},`;
34
- }
35
- dependencyString += "]";
36
- const value = {
37
- id: __SERVER_CURRENT_STATE_ID__ += 1,
38
- type: 1 /* STATE */,
39
- value: new Function(
40
- "state",
41
- "event",
42
- `(${eventListener2.toString()})(event, ...state.getAll(${dependencyString}))`
43
- )
44
- };
45
- globalThis.__SERVER_CURRENT_STATE__.push(value);
46
- return value;
47
- };
48
-
49
- // src/components/Link.ts
1
+ import { loadHook, eventListener } from "../index";
50
2
  loadHook(
51
3
  [],
52
4
  () => {
@@ -78,7 +30,7 @@ loadHook(
78
30
  };
79
31
  }
80
32
  );
81
- var navigate = eventListener(
33
+ const navigate = eventListener(
82
34
  [],
83
35
  (event) => {
84
36
  const target = new URL(event.currentTarget.href);
@@ -93,7 +45,7 @@ var navigate = eventListener(
93
45
  client2.navigateLocally(target.href);
94
46
  }
95
47
  );
96
- var Link = (options, ...children) => {
48
+ const Link = (options, ...children) => {
97
49
  if (!options.href) {
98
50
  throw `Link elements must have a HREF attribute set.`;
99
51
  }
package/dist/global.d.ts CHANGED
@@ -35,8 +35,10 @@ declare global {
35
35
  };
36
36
  /** The type for API Endpoints in route.ts files. */
37
37
  type Endpoint = (req: IncomingMessage, res: ServerResponse) => Promise<void>;
38
+ /** Assign any key any value, within the middleware function, and the data will be passed to the pages affected by the middleware. */
39
+ type MiddlewareData = Record<string, any>;
38
40
  /** The type for middleware functions in middleware.ts files. */
39
- type Middleware = (req: IncomingMessage, res: ServerResponse, next: () => void) => Promise<void>;
41
+ type Middleware = (req: IncomingMessage, res: ServerResponse, next: () => void, data: MiddlewareData) => Promise<void>;
40
42
  /** On dynamic pages, the requestHook, if present, shall be called by the server, before serving the page. */
41
43
  type RequestHook = (req: IncomingMessage, res: ServerResponse) => Promise<boolean>;
42
44
  /** The type for const layout in layout.ts files. */
@@ -46,6 +48,7 @@ declare global {
46
48
  /** Parameters that get passed into Page */
47
49
  type PageProps = {
48
50
  pageName: string;
51
+ middlewareData: MiddlewareData;
49
52
  };
50
53
  /** Internal use only. */
51
54
  type PageInformation = {
@@ -1,4 +1,3 @@
1
- // src/helpers/ObjectAttributeType.ts
2
1
  var ObjectAttributeType = /* @__PURE__ */ ((ObjectAttributeType2) => {
3
2
  ObjectAttributeType2[ObjectAttributeType2["GENERIC"] = 0] = "GENERIC";
4
3
  ObjectAttributeType2[ObjectAttributeType2["STATE"] = 1] = "STATE";
@@ -1,5 +1,4 @@
1
- // src/helpers/camelToKebab.ts
2
- var camelToKebabCase = (input) => {
1
+ const camelToKebabCase = (input) => {
3
2
  return input.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
4
3
  };
5
4
  export {
package/dist/index.mjs CHANGED
@@ -1,215 +1,3 @@
1
- // src/internal/deprecate.ts
2
- var ShowDeprecationWarning = (msg) => {
3
- console.warn("\x1B[31m", msg, "\x1B[0m");
4
- console.trace("Stack Trace:");
5
- };
6
-
7
- // src/server/loadHook.ts
8
- var resetLoadHooks = () => globalThis.__SERVER_CURRENT_LOADHOOKS__ = [];
9
- var getLoadHooks = () => globalThis.__SERVER_CURRENT_LOADHOOKS__;
10
- var loadHook = (deps, fn, bind) => {
11
- const stringFn = fn.toString();
12
- const depsArray = (deps || []).map((dep) => ({
13
- id: dep.id,
14
- bind: dep.bind
15
- }));
16
- let dependencyString = "[";
17
- for (const dep of depsArray) {
18
- dependencyString += `{id:${dep.id}`;
19
- if (dep.bind) dependencyString += `,bind:${dep.bind}`;
20
- dependencyString += `},`;
21
- }
22
- dependencyString += "]";
23
- const isAsync = fn.constructor.name === "AsyncFunction";
24
- const wrapperFn = isAsync ? `async (state) => await (${stringFn})(state, ...state.getAll(${dependencyString}))` : `(state) => (${stringFn})(state, ...state.getAll(${dependencyString}))`;
25
- globalThis.__SERVER_CURRENT_LOADHOOKS__.push({
26
- fn: wrapperFn,
27
- bind: bind || ""
28
- });
29
- };
30
- var createLoadHook = (options) => {
31
- ShowDeprecationWarning("WARNING: createLoadHook() is a deprecated function. Use loadHook() from elegance-js/loadHook instead.");
32
- const stringFn = options.fn.toString();
33
- const deps = (options.deps || []).map((dep) => ({
34
- id: dep.id,
35
- bind: dep.bind
36
- }));
37
- let dependencyString = "[";
38
- for (const dep of deps) {
39
- dependencyString += `{id:${dep.id}`;
40
- if (dep.bind) dependencyString += `,bind:${dep.bind}`;
41
- dependencyString += `},`;
42
- }
43
- dependencyString += "]";
44
- const isAsync = options.fn.constructor.name === "AsyncFunction";
45
- const wrapperFn = isAsync ? `async (state) => await (${stringFn})(state, ...state.getAll(${dependencyString}))` : `(state) => (${stringFn})(state, ...state.getAll(${dependencyString}))`;
46
- globalThis.__SERVER_CURRENT_LOADHOOKS__.push({
47
- fn: wrapperFn,
48
- bind: options.bind || ""
49
- });
50
- };
51
-
52
- // src/server/state.ts
53
- if (!globalThis.__SERVER_CURRENT_STATE_ID__) {
54
- globalThis.__SERVER_CURRENT_STATE_ID__ = 1;
55
- }
56
- var state = (value, options) => {
57
- const serverStateEntry = {
58
- id: __SERVER_CURRENT_STATE_ID__ += 1,
59
- value,
60
- type: 1 /* STATE */
61
- };
62
- globalThis.__SERVER_CURRENT_STATE__.push(serverStateEntry);
63
- if (Array.isArray(value)) {
64
- serverStateEntry.reactiveMap = reactiveMap;
65
- }
66
- return serverStateEntry;
67
- };
68
- var reactiveMap = function(template, deps) {
69
- const subject = this;
70
- const dependencies = state(deps || []);
71
- const templateFn = state(template);
72
- loadHook(
73
- [subject, templateFn, dependencies],
74
- (state2, subject2, templateFn2, dependencies2) => {
75
- const el = document.querySelector(
76
- `[map-id="${subject2.id}"]`
77
- );
78
- if (!el) {
79
- console.error(`Couldn't find map tag with map-id=${subject2.id}`);
80
- return;
81
- }
82
- const parentElement = el.parentElement;
83
- const nextSibling = el.nextSibling;
84
- el.remove();
85
- const value = subject2.value;
86
- const deps2 = state2.getAll(dependencies2.value.map((dep) => ({ id: dep.id, bind: dep.bind })));
87
- const attributes = [];
88
- const currentlyWatched = [];
89
- const createElements = () => {
90
- for (let i = 0; i < value.length; i += 1) {
91
- const htmlElement = client.renderRecursively(templateFn2.value(value[i], i, ...deps2), attributes);
92
- htmlElement.setAttribute("map-id", subject2.id.toString());
93
- const elementKey = ((i - 1) * -1).toString();
94
- htmlElement.setAttribute("key", elementKey);
95
- for (const attribute of attributes) {
96
- let values = {};
97
- const type = attribute.type;
98
- switch (type) {
99
- case 2 /* OBSERVER */: {
100
- const { field, subjects, updateCallback } = attribute;
101
- for (const reference of subjects) {
102
- const subject3 = state2.get(reference.id, reference.bind);
103
- const updateFunction = (value2) => {
104
- values[subject3.id] = value2;
105
- try {
106
- const newValue = updateCallback(...Object.values(values));
107
- let attribute2 = field === "class" ? "className" : field;
108
- htmlElement[attribute2] = newValue;
109
- } catch (e) {
110
- console.error(e);
111
- return;
112
- }
113
- };
114
- updateFunction(subject3.value);
115
- state2.observe(subject3, updateFunction, elementKey);
116
- currentlyWatched.push({
117
- key: elementKey,
118
- subject: subject3
119
- });
120
- }
121
- break;
122
- }
123
- case 1 /* STATE */: {
124
- const { field, element, subjects, eventListener: eventListener2 } = attribute;
125
- const lc = field.toLowerCase();
126
- const fn = (event) => {
127
- eventListener2(event, ...subjects);
128
- };
129
- element[lc] = fn;
130
- break;
131
- }
132
- }
133
- }
134
- parentElement.insertBefore(htmlElement, nextSibling);
135
- attributes.splice(0, attributes.length);
136
- }
137
- };
138
- const removeOldElements = () => {
139
- const list = Array.from(document.querySelectorAll(`[map-id="${subject2.id}"]`));
140
- for (const el2 of list) {
141
- el2.remove();
142
- }
143
- for (const watched of currentlyWatched) {
144
- state2.unobserve(watched.subject, watched.key);
145
- }
146
- currentlyWatched.splice(0, currentlyWatched.length);
147
- };
148
- createElements();
149
- const uniqueId = `${Date.now()}`;
150
- state2.observe(subject2, (value2) => {
151
- removeOldElements();
152
- createElements();
153
- }, uniqueId);
154
- }
155
- );
156
- return globalThis.template({
157
- "map-id": subject.id
158
- });
159
- };
160
- var eventListener = (dependencies, eventListener2) => {
161
- const deps = dependencies.map((dep) => ({ id: dep.id, bind: dep.bind }));
162
- let dependencyString = "[";
163
- for (const dep of deps) {
164
- dependencyString += `{id:${dep.id}`;
165
- if (dep.bind) dependencyString += `,bind:${dep.bind}`;
166
- dependencyString += `},`;
167
- }
168
- dependencyString += "]";
169
- const value = {
170
- id: __SERVER_CURRENT_STATE_ID__ += 1,
171
- type: 1 /* STATE */,
172
- value: new Function(
173
- "state",
174
- "event",
175
- `(${eventListener2.toString()})(event, ...state.getAll(${dependencyString}))`
176
- )
177
- };
178
- globalThis.__SERVER_CURRENT_STATE__.push(value);
179
- return value;
180
- };
181
- var initializeState = () => globalThis.__SERVER_CURRENT_STATE__ = [];
182
- var getState = () => {
183
- return globalThis.__SERVER_CURRENT_STATE__;
184
- };
185
- var initializeObjectAttributes = () => globalThis.__SERVER_CURRENT_OBJECT_ATTRIBUTES__ = [];
186
- var getObjectAttributes = () => {
187
- return globalThis.__SERVER_CURRENT_OBJECT_ATTRIBUTES__;
188
- };
189
-
190
- // src/server/observe.ts
191
- var observe = (refs, update) => {
192
- const returnValue = {
193
- type: 2 /* OBSERVER */,
194
- initialValues: refs.map((ref) => ref.value),
195
- update,
196
- refs: refs.map((ref) => ({
197
- id: ref.id,
198
- bind: ref.bind
199
- }))
200
- };
201
- return returnValue;
202
- };
203
- export {
204
- createLoadHook,
205
- eventListener,
206
- getLoadHooks,
207
- getObjectAttributes,
208
- getState,
209
- initializeObjectAttributes,
210
- initializeState,
211
- loadHook,
212
- observe,
213
- resetLoadHooks,
214
- state
215
- };
1
+ export * from "./server/state";
2
+ export * from "./server/loadHook";
3
+ export * from "./server/observe";
@@ -1,5 +1,4 @@
1
- // src/internal/deprecate.ts
2
- var ShowDeprecationWarning = (msg) => {
1
+ const ShowDeprecationWarning = (msg) => {
3
2
  console.warn("\x1B[31m", msg, "\x1B[0m");
4
3
  console.trace("Stack Trace:");
5
4
  };
package/dist/log.mjs CHANGED
@@ -1,5 +1,4 @@
1
- // src/log.ts
2
- var quiet = false;
1
+ let quiet = false;
3
2
  function setQuiet(value) {
4
3
  quiet = value;
5
4
  }
@@ -28,7 +27,7 @@ function logWarn(...args) {
28
27
  function logError(...args) {
29
28
  console.error(`Elegance.JS: ${getTimestamp()} ${color("[ERROR]:", 31)}`, ...args);
30
29
  }
31
- var log = {
30
+ const log = {
32
31
  info: logInfo,
33
32
  warn: logWarn,
34
33
  error: logError
@@ -1,7 +1,5 @@
1
1
  import type { IncomingMessage, ServerResponse } from "http";
2
- export declare const PAGE_MAP: Map<string, PageInformation>;
3
- export declare const LAYOUT_MAP: Map<string, LayoutInformation>;
4
2
  export declare const processPageElements: (element: Child, objectAttributes: Array<any>, recursionLevel: number, stack?: any[]) => Child;
5
- export declare const buildDynamicPage: (DIST_DIR: string, directory: string, pageInfo: PageInformation, req: IncomingMessage, res: ServerResponse) => Promise<false | {
3
+ export declare const buildDynamicPage: (DIST_DIR: string, directory: string, pageInfo: PageInformation, req: IncomingMessage, res: ServerResponse, middlewareData: MiddlewareData) => Promise<false | {
6
4
  resultHTML: any;
7
5
  }>;