@leonid-shutov/uncommonjs 1.0.0-alpha.0
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.
- package/LICENSE +21 -0
- package/README.md +1 -0
- package/eslint.config.js +5 -0
- package/lib/application.js +29 -0
- package/lib/deps.js +22 -0
- package/lib/errors.js +72 -0
- package/lib/loader.js +69 -0
- package/lib/rest.js +86 -0
- package/lib/service.js +30 -0
- package/package.json +27 -0
- package/prettier.config.js +10 -0
- package/uncommon.js +7 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023 leonid
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
Loader
|
package/eslint.config.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fsp = require('node:fs').promises;
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
const vm = require('node:vm');
|
|
6
|
+
const errors = require('./errors.js');
|
|
7
|
+
const { loadModules } = require('./deps.js');
|
|
8
|
+
const { loadDir } = require('./loader.js');
|
|
9
|
+
|
|
10
|
+
const getDefaultApplicationPath = () => path.join(process.cwd(), 'application');
|
|
11
|
+
|
|
12
|
+
const readLayers = (applicationPath) =>
|
|
13
|
+
fsp
|
|
14
|
+
.readFile(path.join(applicationPath, '.layers'), 'utf8')
|
|
15
|
+
.then((data) => data.split(/[\r\n\s]+/).filter((s) => s.length !== 0));
|
|
16
|
+
|
|
17
|
+
const loadApplication = async (sandbox = {}, options) => {
|
|
18
|
+
Object.assign(sandbox, errors);
|
|
19
|
+
const applicationPath = options?.path ?? getDefaultApplicationPath();
|
|
20
|
+
const promises = [loadModules(), readLayers(applicationPath)];
|
|
21
|
+
const [modules, layers] = await Promise.all(promises);
|
|
22
|
+
Object.assign(sandbox, modules);
|
|
23
|
+
const context = vm.createContext(sandbox);
|
|
24
|
+
const load = loadDir.bind(undefined, context, context);
|
|
25
|
+
for (const layer of layers) await load(path.join(applicationPath, layer));
|
|
26
|
+
return sandbox;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
module.exports = { loadApplication };
|
package/lib/deps.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { builtinModules } = require('node:module');
|
|
4
|
+
|
|
5
|
+
const loadNpm = () => {
|
|
6
|
+
const { dependencies } = require(process.cwd() + '/package.json');
|
|
7
|
+
if (dependencies === undefined) return {};
|
|
8
|
+
const modules = Object.keys(dependencies);
|
|
9
|
+
return Object.fromEntries(modules.map((module) => [module, require(module)]));
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
const loadInternals = () =>
|
|
13
|
+
Object.fromEntries(
|
|
14
|
+
builtinModules.map((name) => [name, require(`node:${name}`)]),
|
|
15
|
+
);
|
|
16
|
+
|
|
17
|
+
const loadModules = () => ({
|
|
18
|
+
npm: loadNpm(),
|
|
19
|
+
node: loadInternals(),
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
module.exports = { loadModules };
|
package/lib/errors.js
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const PASS = Symbol('pass');
|
|
4
|
+
|
|
5
|
+
class DomainError extends Error {
|
|
6
|
+
constructor(message, options) {
|
|
7
|
+
const { code, ...restOptions } = options;
|
|
8
|
+
super(message, restOptions);
|
|
9
|
+
this.code = code;
|
|
10
|
+
this.name = this.constructor.name;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const createDomainError = (className, factoryOptions) =>
|
|
15
|
+
class extends (factoryOptions.parent ?? DomainError) {
|
|
16
|
+
constructor(message, options) {
|
|
17
|
+
message ??= factoryOptions.message;
|
|
18
|
+
const code = options?.code ?? factoryOptions.code;
|
|
19
|
+
super(message, { ...options, code });
|
|
20
|
+
this.name = className;
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
const UnexpectedError = createDomainError('UnexpectedError', {
|
|
25
|
+
message: 'Unexpected Error',
|
|
26
|
+
code: 'UNEXPECTED_ERROR',
|
|
27
|
+
});
|
|
28
|
+
UnexpectedError.from = (description) =>
|
|
29
|
+
new UnexpectedError(`Unexpected error while ${description.toLowerCase()}`);
|
|
30
|
+
|
|
31
|
+
const NotFoundError = createDomainError('NotFoundError', {
|
|
32
|
+
message: 'Not Found',
|
|
33
|
+
code: 'NOT_FOUND',
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
NotFoundError.from = (entity, options) =>
|
|
37
|
+
new NotFoundError(`${entity} not found`, {
|
|
38
|
+
...options,
|
|
39
|
+
code: options?.code ?? `${entity.toUpperCase()}_NOT_FOUND`,
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
const AlreadyExistsError = createDomainError('AlreadyExistsError', {
|
|
43
|
+
message: 'Already Exists',
|
|
44
|
+
code: 'ALREADY_EXISTS',
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
AlreadyExistsError.from = (entity, options) =>
|
|
48
|
+
new AlreadyExistsError(`${entity} already exists`, {
|
|
49
|
+
...options,
|
|
50
|
+
code: options?.code ?? `${entity.toUpperCase()}_ALREADY_EXISTS`,
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
const ConstraintViolationError = createDomainError('ConstraintViolationError', {
|
|
54
|
+
message: 'Constraint violation',
|
|
55
|
+
code: 'CONSTRAINT_VIOLATION',
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
const AuthorizationError = createDomainError('AuthorizationError', {
|
|
59
|
+
message: 'Authorization Error',
|
|
60
|
+
code: 'AUTHORIZATION_ERROR',
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
module.exports = {
|
|
64
|
+
PASS,
|
|
65
|
+
DomainError,
|
|
66
|
+
createDomainError,
|
|
67
|
+
UnexpectedError,
|
|
68
|
+
NotFoundError,
|
|
69
|
+
AlreadyExistsError,
|
|
70
|
+
ConstraintViolationError,
|
|
71
|
+
AuthorizationError,
|
|
72
|
+
};
|
package/lib/loader.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const path = require('node:path');
|
|
4
|
+
const fsp = require('node:fs/promises');
|
|
5
|
+
const vm = require('node:vm');
|
|
6
|
+
const { isService, loadService } = require('./service.js');
|
|
7
|
+
|
|
8
|
+
const chronology = ['before.js', 'after.js'];
|
|
9
|
+
const isChronological = (filePath) =>
|
|
10
|
+
chronology.some((file) => filePath.endsWith(file));
|
|
11
|
+
const orderFiles = (files) => {
|
|
12
|
+
const before = files.find(({ name }) => name === 'before.js');
|
|
13
|
+
const after = files.find(({ name }) => name === 'after.js');
|
|
14
|
+
const ordered = files.filter(({ name }) => !chronology.includes(name));
|
|
15
|
+
ordered.sort();
|
|
16
|
+
if (before !== undefined) ordered.unshift(before);
|
|
17
|
+
if (after !== undefined) ordered.push(after);
|
|
18
|
+
return ordered;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
const removeIndex = (key) => key.replace(/^\d+-/, '');
|
|
22
|
+
|
|
23
|
+
const loadFile = async (context, container, filePath, key) => {
|
|
24
|
+
const src = await fsp.readFile(filePath, 'utf8');
|
|
25
|
+
const code = `'use strict';\n${src}`;
|
|
26
|
+
const script = new vm.Script(code);
|
|
27
|
+
const sandbox = { ...context };
|
|
28
|
+
const result = await script.runInContext(vm.createContext(sandbox));
|
|
29
|
+
if (isChronological(filePath)) return void (await result());
|
|
30
|
+
for (const [method, definition] of Object.entries(result)) {
|
|
31
|
+
if (isService(definition, context)) {
|
|
32
|
+
result[method] = loadService(definition, context);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
sandbox.self = result;
|
|
36
|
+
if (container[key] === undefined) container[key] = result;
|
|
37
|
+
else Object.assign(container[key], result);
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
const loadDir = async (context, container, dirPath, key) => {
|
|
41
|
+
key ??= dirPath.split('/').at(-1);
|
|
42
|
+
const nextContainer = container[key] ?? {};
|
|
43
|
+
container[key] = nextContainer;
|
|
44
|
+
const files = [];
|
|
45
|
+
const directories = [];
|
|
46
|
+
const entries = await fsp.readdir(dirPath, { withFileTypes: true });
|
|
47
|
+
for (const entry of entries) {
|
|
48
|
+
if (entry.isFile()) files.push(entry);
|
|
49
|
+
else directories.push(entry);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const orderedFiles = orderFiles(files);
|
|
53
|
+
for (const { name } of orderedFiles) {
|
|
54
|
+
if (!name.endsWith('.js')) continue;
|
|
55
|
+
const location = path.join(dirPath, name);
|
|
56
|
+
let basename = path.basename(name, '.js');
|
|
57
|
+
basename = removeIndex(basename);
|
|
58
|
+
if (basename === key) await loadFile(context, container, location, key);
|
|
59
|
+
else await loadFile(context, nextContainer, location, basename);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
for (const { name } of directories) {
|
|
63
|
+
const location = path.join(dirPath, name);
|
|
64
|
+
if (name === '>') await loadDir(context, container, location, key);
|
|
65
|
+
else await loadDir(context, nextContainer, location, name);
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
module.exports = { loadFile, loadDir };
|
package/lib/rest.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { Schema } = require('metaschema');
|
|
4
|
+
|
|
5
|
+
const {
|
|
6
|
+
NotFoundError,
|
|
7
|
+
AlreadyExistsError,
|
|
8
|
+
ConstraintViolationError,
|
|
9
|
+
AuthorizationError,
|
|
10
|
+
} = require('./errors.js');
|
|
11
|
+
const { loadApplication } = require('./application.js');
|
|
12
|
+
|
|
13
|
+
class ValidationError extends AggregateError {}
|
|
14
|
+
|
|
15
|
+
const validateRequest = (schema = {}, { query, body }) => {
|
|
16
|
+
const validationErrors = [];
|
|
17
|
+
if (schema.query !== undefined) {
|
|
18
|
+
const { errors } = Schema.from(schema.query).check(query);
|
|
19
|
+
validationErrors.push(...errors);
|
|
20
|
+
}
|
|
21
|
+
if (schema.body !== undefined) {
|
|
22
|
+
const { errors } = Schema.from(schema.body).check(body);
|
|
23
|
+
validationErrors.push(...errors);
|
|
24
|
+
}
|
|
25
|
+
if (validationErrors.length > 0) throw new ValidationError(validationErrors);
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
const getStatus = (error) => {
|
|
29
|
+
if (error instanceof ValidationError) return 400;
|
|
30
|
+
if (error instanceof AuthorizationError) return 401;
|
|
31
|
+
if (error instanceof NotFoundError) return 404;
|
|
32
|
+
if (error instanceof AlreadyExistsError) return 409;
|
|
33
|
+
if (error instanceof ConstraintViolationError) return 422;
|
|
34
|
+
return 500;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
const bodyFromDefinition = (response, definition) => {
|
|
38
|
+
if (typeof definition.response === 'function') {
|
|
39
|
+
return definition.response(response);
|
|
40
|
+
}
|
|
41
|
+
if (definition.response === undefined) return response;
|
|
42
|
+
return definition.response ?? null;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
const createHandler = (definition) => {
|
|
46
|
+
const schema = { query: definition.query, body: definition.body };
|
|
47
|
+
return async ({ path, query, body, ...rest }) => {
|
|
48
|
+
try {
|
|
49
|
+
validateRequest(schema, { query, body });
|
|
50
|
+
const response = await definition.handler({ path, query, body, ...rest });
|
|
51
|
+
return {
|
|
52
|
+
status: definition.status ?? 200,
|
|
53
|
+
body: bodyFromDefinition(response, definition),
|
|
54
|
+
};
|
|
55
|
+
} catch (error) {
|
|
56
|
+
console.error(error);
|
|
57
|
+
return {
|
|
58
|
+
status: getStatus(error),
|
|
59
|
+
body: error instanceof ValidationError ? error.errors : error.message,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
const createRouter = (apis) => {
|
|
66
|
+
const router = {};
|
|
67
|
+
for (const api of apis) {
|
|
68
|
+
for (const [path, methods] of Object.entries(api)) {
|
|
69
|
+
router[path] ??= {};
|
|
70
|
+
for (const [method, definition] of Object.entries(methods)) {
|
|
71
|
+
const handler = createHandler(definition);
|
|
72
|
+
router[path][method] = handler;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return router;
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
const loadRestApplication = async (sandbox = {}, options) => {
|
|
80
|
+
await loadApplication(sandbox, options);
|
|
81
|
+
const apis = Object.values(sandbox.api);
|
|
82
|
+
const router = createRouter(apis);
|
|
83
|
+
return router;
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
module.exports = { loadRestApplication };
|
package/lib/service.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const isService = (definition, context) =>
|
|
4
|
+
definition?.method !== undefined && context.PASS !== undefined;
|
|
5
|
+
|
|
6
|
+
const loadService = (definition, context) => {
|
|
7
|
+
const { description, method, expectedErrors } = definition;
|
|
8
|
+
const logger = context.logger ?? context.console ?? { info: () => {} };
|
|
9
|
+
return async (...args) => {
|
|
10
|
+
const interpolatedDesc =
|
|
11
|
+
typeof description === 'function' ? description(...args) : description;
|
|
12
|
+
try {
|
|
13
|
+
logger.info(interpolatedDesc);
|
|
14
|
+
return await method(...args);
|
|
15
|
+
} catch (error) {
|
|
16
|
+
let domainError = expectedErrors?.[error.code];
|
|
17
|
+
if (domainError === context.PASS) throw error;
|
|
18
|
+
if (domainError === undefined) {
|
|
19
|
+
domainError =
|
|
20
|
+
description !== undefined
|
|
21
|
+
? context.UnexpectedError.from(interpolatedDesc)
|
|
22
|
+
: new context.UnexpectedError();
|
|
23
|
+
}
|
|
24
|
+
domainError.cause = error;
|
|
25
|
+
throw domainError;
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
module.exports = { isService, loadService };
|
package/package.json
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@leonid-shutov/uncommonjs",
|
|
3
|
+
"version": "1.0.0-alpha.0",
|
|
4
|
+
"author": "Leonid Shutov <leonid.shutov.main@gmail.com>",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"homepage": "https://github.com/leonid-shutov/uncommonjs#readme",
|
|
7
|
+
"main": "uncommon.js",
|
|
8
|
+
"scripts": {
|
|
9
|
+
"lint": "eslint lib/"
|
|
10
|
+
},
|
|
11
|
+
"repository": {
|
|
12
|
+
"type": "git",
|
|
13
|
+
"url": "git+https://github.com/leonid-shutov/uncommonjs.git"
|
|
14
|
+
},
|
|
15
|
+
"publishConfig": {
|
|
16
|
+
"access": "public"
|
|
17
|
+
},
|
|
18
|
+
"devDependencies": {
|
|
19
|
+
"@types/node": "^20.17.30",
|
|
20
|
+
"eslint": "^9.31.0",
|
|
21
|
+
"eslint-config-metarhia": "^9.1.1",
|
|
22
|
+
"prettier": "^3.6.2"
|
|
23
|
+
},
|
|
24
|
+
"dependencies": {
|
|
25
|
+
"metaschema": "^2.2.2"
|
|
26
|
+
}
|
|
27
|
+
}
|