@cilix/lightjs 0.0.1

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 (5) hide show
  1. package/README.md +1010 -0
  2. package/cli.js +163 -0
  3. package/core.js +2730 -0
  4. package/index.js +364 -0
  5. package/package.json +26 -0
package/index.js ADDED
@@ -0,0 +1,364 @@
1
+ /*
2
+ * Copyright 2023 Matthew Levenstein
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining
5
+ * a copy of this software and associated documentation files (the “Software”),
6
+ * to deal in the Software without restriction, including without limitation
7
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8
+ * and/or sell copies of the Software, and to permit persons to whom the
9
+ * Software is furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all
12
+ * copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
15
+ * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
16
+ * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
17
+ * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
18
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
19
+ * USE OR OTHER DEALINGS IN THE SOFTWARE.
20
+ */
21
+ const fs = require('fs');
22
+ const path = require('path');
23
+ const qs = require('querystring');
24
+ const url = require('url');
25
+ const mimedb = require('mime-db');
26
+ const esbuild = require('esbuild');
27
+ const core = require('./core.js');
28
+
29
+ const Light = {};
30
+ const ssrCache = {};
31
+ const mimeTypes = {};
32
+
33
+ const getPathInfo = (p, base) => {
34
+ const full = base ? path.resolve(base, p) : path.resolve(process.cwd(), p);
35
+ const parent = path.dirname(full);
36
+ const file = path.basename(full);
37
+ return { full, parent, file };
38
+ };
39
+
40
+ const addParentPaths = (code, p) => {
41
+ const len = code.length;
42
+ let out = '';
43
+ for (let i = 0; i < len; i++) {
44
+ if (code.slice(i, i+10) === 'require(".') {
45
+ let f = '';
46
+ i += 9;
47
+ while (code[i] !== '"') f += code[i++];
48
+ out += `require("${path.resolve(p, f)}"`;
49
+ } else {
50
+ out += code[i];
51
+ }
52
+ }
53
+ return out;
54
+ };
55
+
56
+ const esbuild_to_light_error = (e, chunk) => {
57
+ let row = e.location.line - 1;
58
+ let col = e.location.column;
59
+ let pos;
60
+
61
+ for (pos = 0; pos < chunk.code.length; pos++) {
62
+ if (chunk.code[pos] === '\n') row--;
63
+ if (row == 0) {
64
+ if (col > 0) col--;
65
+ else break;
66
+ }
67
+ }
68
+
69
+ return {
70
+ origin: 'light',
71
+ msg: e.text,
72
+ pos: chunk.pos + 3 + pos + 1,
73
+ file: chunk.file
74
+ };
75
+ };
76
+
77
+ Light.compile = async (name, opts) => {
78
+ if (name && typeof name === 'object') {
79
+ opts = name;
80
+ }
81
+ if (!opts) opts = {};
82
+ if (typeof name === 'string') {
83
+ opts.input = name;
84
+ }
85
+ const pathInfo = getPathInfo(opts.input);
86
+ const parentDir = pathInfo.parent;
87
+ const light = core({
88
+ jsTransform: async (chunk) => {
89
+ try {
90
+ const opts = { format: 'cjs', loader: 'ts' };
91
+ const result = await esbuild.transform(chunk.code, opts);
92
+ return addParentPaths(result.code, chunk.parent_dir);
93
+ } catch (e) {
94
+ e.origin = 'esbuild';
95
+ e.chunk = chunk;
96
+ throw e;
97
+ }
98
+ },
99
+ jsPostProcess: async (js) => {
100
+ const result = await esbuild.build({
101
+ stdin: {
102
+ contents: js,
103
+ resolveDir: parentDir
104
+ },
105
+ bundle: true,
106
+ minify: opts.minify,
107
+ write: false
108
+ });
109
+ return result.outputFiles[0].text;
110
+ }
111
+ });
112
+ try {
113
+ let html;
114
+ if (opts.cache) {
115
+ const cacheDir = opts.cacheDir || parentDir;
116
+ const cachePath = path.resolve(cacheDir, pathInfo.file + '.json');
117
+ if (ssrCache[cachePath]) {
118
+ html = light.renderToHTML(ssrCache[cachePath], opts.data, opts.flush);
119
+ /*
120
+ } else if (fs.existsSync(cachePath)) {
121
+ const cache = fs.readFileSync(cachePath, 'utf-8');
122
+ html = await light.renderToHTML(cache, opts.data);
123
+ */
124
+ } else {
125
+ const cache = await light.renderToCache(opts.input, opts.actions);
126
+ // fs.writeFileSync(cachePath, cache);
127
+ ssrCache[cachePath] = cache;
128
+ html = light.renderToHTML(cache, opts.data, opts.flush);
129
+ }
130
+ } else {
131
+ html = await light.render(opts.input, opts.data, opts.flush, opts.actions);
132
+ }
133
+ if (!opts.output) {
134
+ return html;
135
+ } else {
136
+ fs.writeFileSync(opts.output, html);
137
+ }
138
+ } catch (e) {
139
+ let msg;
140
+ if (e.origin === 'esbuild') {
141
+ if (e.chunk) {
142
+ e = esbuild_to_light_error(e.errors[0], e.chunk);
143
+ }
144
+ }
145
+ if (e.origin === 'light') {
146
+ msg = `<pre>${light.printError(e)}</pre>`;
147
+ } else {
148
+ console.log(e);
149
+ msg = `<pre>${e.message}</pre>`;
150
+ }
151
+ if (!opts.output) return msg;
152
+ else {
153
+ fs.writeFileSync(opts.output, msg);
154
+ }
155
+ }
156
+ };
157
+
158
+ const serveStaticFile = (p, res) => {
159
+ let ext = path.extname(p);
160
+ if (!ext)
161
+ return false;
162
+ ext = ext.slice(1);
163
+ try {
164
+ if (p.indexOf('..') !== -1) {
165
+ res.statusCode = 403;
166
+ res.end();
167
+ return true;
168
+ }
169
+ const data = fs.readFileSync(p);
170
+ const mime = (mimeTypes[ext] || { source: 'text/plain' }).source;
171
+ res.writeHead(200, { 'Content-type': `${mime}` });
172
+ res.end(data);
173
+ return true;
174
+ } catch (e) {
175
+ return false;
176
+ }
177
+ };
178
+
179
+ const parseBody = (req, max) => {
180
+ return new Promise((resolve, reject) => {
181
+ let buf = '';
182
+ let data;
183
+ req.on('data', (chunk) => {
184
+ if (buf.length > max) {
185
+ reject('Maximum body size exceeeded');
186
+ } else {
187
+ buf += chunk;
188
+ }
189
+ });
190
+ req.on('end', () => {
191
+ if (buf.length === 0) {
192
+ resolve({});
193
+ return;
194
+ }
195
+ try {
196
+ data = JSON.parse(buf);
197
+ } catch (e) {
198
+ try {
199
+ data = qs.parse(buf);
200
+ } catch (e) {
201
+ reject('Invalid request body format');
202
+ }
203
+ }
204
+ resolve(data);
205
+ })
206
+ req.on('error', (e) => {
207
+ reject(e);
208
+ });
209
+ });
210
+ };
211
+
212
+ const parseQuery = (p) => {
213
+ const purl = url.parse(p);
214
+ if (purl.query) {
215
+ return qs.parse(purl.query);
216
+ }
217
+ return {};
218
+ };
219
+
220
+ function matchRoute (istr, mstr) {
221
+ if (mstr === '*') return {};
222
+ const p0 = istr.split('/').filter(p => p);
223
+ const p1 = mstr.split('/').filter(p => p);
224
+ const out = {};
225
+ if (p0.length > p1.length && p1.length > 0) {
226
+ const last = p1[p1.length - 1];
227
+ if (last[last.length - 1] !== '*') {
228
+ return null;
229
+ }
230
+ } else if (p0.length !== p1.length) return null;
231
+ for (let i = 0; i < p1.length; i++) {
232
+ const p = p1[i];
233
+ if (p[0] !== ':') {
234
+ if (p !== p0[i]) return null;
235
+ else continue;
236
+ }
237
+ if (i === p1.length - 1 && p[p.length - 1] === '*') {
238
+ out[p.slice(1, -1)] = p0[i];
239
+ for (let j = i + 1; j < p0.length; j++) {
240
+ out[p.slice(1, -1)] += `/${p0[j]}`;
241
+ }
242
+ } else {
243
+ out[p.slice(1)] = p0[i];
244
+ }
245
+ }
246
+ return out;
247
+ }
248
+
249
+ function handleAction (req, res, actions) {
250
+ if (req.method === 'POST') {
251
+ if (req.body.type === 'LIGHT_SERVER_FUNCTION') {
252
+ const name = req.body.name;
253
+ const args = req.body.args;
254
+ if (actions[name]) {
255
+ actions[name].apply(undefined, args).then((data) => {
256
+ res.writeHead(200, { 'Content-type': 'application/json; charset=utf-8' });
257
+ if (!data) data = null;
258
+ res.end(JSON.stringify(data));
259
+ }).catch((e) => {
260
+ console.error(e);
261
+ res.writeHead(500, { 'Content-type': 'application/json; charset=utf-8' });
262
+ res.end(JSON.stringify({ message: `Server error when calling ${name}` }));
263
+ });
264
+ } else {
265
+ res.writeHead(500, { 'Content-type': 'application/json; charset=utf-8' });
266
+ res.end(JSON.stringify({ message: `${name} is not defined on the server` }));
267
+ }
268
+ return true;
269
+ }
270
+ }
271
+ return false;
272
+ }
273
+
274
+ Light.router = function (opts) {
275
+ if (!opts) opts = {};
276
+ const routes = opts.routes || {};
277
+ const cache = opts.cache || false;
278
+ const minify = opts.minify || false;
279
+ const actions = opts.actions || {};
280
+ const publicDir = opts.publicDir;
281
+ for (let type in mimedb) {
282
+ if (mimedb[type].extensions) {
283
+ for (let ext of mimedb[type].extensions) {
284
+ mimeTypes[ext] = type;
285
+ }
286
+ }
287
+ }
288
+ return async function (req, res, next) {
289
+ const url = req.url;
290
+ if (publicDir && serveStaticFile(path.join(publicDir, url), res)) {
291
+ return;
292
+ }
293
+ const query = parseQuery(url);
294
+ req.query = query;
295
+ try {
296
+ req.body = await parseBody(req, 1024 * 1024); // 1MB limit
297
+ } catch (e) {
298
+ res.writeHead(400, { 'Content-type': 'application/json; charset=utf-8' });
299
+ res.end(JSON.stringify({ error: e.message }));
300
+ return;
301
+ }
302
+ if (handleAction(req, res, actions)) {
303
+ return;
304
+ }
305
+ let matchedRoute = null;
306
+ let routeParams = {};
307
+ let routeConfig = null;
308
+ for (const [pattern, config] of Object.entries(routes)) {
309
+ const params = matchRoute(url, pattern);
310
+ if (params !== null) {
311
+ matchedRoute = pattern;
312
+ routeParams = params;
313
+ routeConfig = config;
314
+ break;
315
+ }
316
+ }
317
+ if (!matchedRoute) {
318
+ if (next) {
319
+ next();
320
+ } else {
321
+ res.writeHead(404, { 'Content-type': 'text/html; charset=utf-8' });
322
+ res.end('<h1>404 - Not Found</h1>');
323
+ return;
324
+ }
325
+ }
326
+ req.params = routeParams;
327
+ try {
328
+ let html;
329
+ if (typeof routeConfig === 'string') {
330
+ html = await Light.compile({
331
+ input: routeConfig,
332
+ cache: cache,
333
+ minify: minify,
334
+ actions: Object.keys(actions)
335
+ });
336
+ } else if (typeof routeConfig === 'object') {
337
+ const compileOpts = {
338
+ input: routeConfig.input,
339
+ flush: routeConfig.stream ? res.write.bind(res) : undefined,
340
+ cache: cache,
341
+ minify: minify,
342
+ actions: Object.keys(actions)
343
+ };
344
+ if (routeConfig.data) {
345
+ if (typeof routeConfig.data === 'function') {
346
+ compileOpts.data = await routeConfig.data(req, routeParams);
347
+ } else {
348
+ compileOpts.data = routeConfig.data;
349
+ }
350
+ }
351
+ html = await Light.compile(compileOpts);
352
+ }
353
+ res.writeHead(200, { 'Content-type': 'text/html; charset=utf-8' });
354
+ res.end(html);
355
+ } catch (e) {
356
+ console.error('Route error:', e);
357
+ res.writeHead(500, { 'Content-type': 'text/html; charset=utf-8' });
358
+ res.end('<h1>500 - Internal Server Error</h1>');
359
+ }
360
+ };
361
+ };
362
+
363
+ module.exports = Light;
364
+
package/package.json ADDED
@@ -0,0 +1,26 @@
1
+ {
2
+ "name": "@cilix/lightjs",
3
+ "version": "0.0.1",
4
+ "description": "A new kind of JavaScript framework",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "dev": "node cli dev -r *=test.light"
8
+ },
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/mllev/lightjs.git"
12
+ },
13
+ "author": "Matthew Levenstein",
14
+ "license": "MIT",
15
+ "bin": {
16
+ "lightjs": "./cli.js"
17
+ },
18
+ "bugs": {
19
+ "url": "https://github.com/mllev/lightjs/issues"
20
+ },
21
+ "homepage": "https://github.com/mllev/lightjs#readme",
22
+ "dependencies": {
23
+ "esbuild": "^0.25.0",
24
+ "mime-db": "^1.54.0"
25
+ }
26
+ }