🚀 Socket Launch Week Day 5:Introducing Repository Access Permissions and Custom Roles.Learn more
Sign In

@nweb/core

Package Overview
Dependencies
Maintainers
1
Versions
20
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@nweb/core - npm Package Compare versions

Comparing version
1.1.12
to
1.1.13
+6
-4
package.json
{
"name": "@nweb/core",
"version": "1.1.12",
"version": "1.1.13",
"description": "web核心组件",

@@ -14,3 +14,4 @@ "main": "./lib/index",

"retest:dev": "tsc --build tsconfig.json && set active=development && node --trace-warnings bin/app.js",
"build": "tsc --build tsconfig.json",
"build": "npm run build:schema && tsc --build tsconfig.json",
"build:schema": "ts-json-schema-generator --path 'src/VWebApp.ts' --type Environment --out lib/vweb.schema.json",
"run:win": "if exist lib rmdir /s/q lib && npm run startup",

@@ -35,6 +36,7 @@ "run:linux": "rm -rf lib && npm run startup",

"babel-plugin-transform-decorators-legacy": "^1.3.5",
"jest": "^29.6.3",
"nacos": "^2.5.1",
"ts-json-schema-generator": "2.4.0",
"urllib": "^3.16.1",
"yaml": "^2.3.2",
"jest": "^29.6.3"
"yaml": "^2.3.2"
},

@@ -41,0 +43,0 @@ "keywords": [

export declare function Readonly(target: any, property: any, descriptor: any): any;
export declare function Component(name: any): any;
export declare namespace Component {
var type: string;
var keys: string[];
}
export declare function Service(name: any): any;
export declare namespace Service {
var type: string;
var keys: string[];
}
export declare function Initialization(target: any, property: any, descriptor: any): any;
export declare namespace Initialization {
var keys: string[];
}
export declare function Setup(target: any, property: any, descriptor: any): any;
export declare namespace Setup {
var keys: string[];
}
export declare function Resource(name?: any): any;
export declare namespace Resource {
var keys: string[];
}
export declare function Value(express: string, defaultValue?: any): any;
export declare namespace Value {
var keys: string[];
}
export declare function Props(propKeys: string, defaultValue?: any): any;
export declare namespace Props {
var keys: string[];
}
export declare function Lock(target: any, property: any, descriptor?: any): any;
export declare namespace Lock {
var keys: string[];
}
export declare function Comment(value: any): any;
export declare namespace Comment {
var keys: string[];
}
declare type AdviceType = "all" | "service" | "controller" | "bean" | "component";
declare type AdvicePoint = "before" | "after" | "around";
declare interface AdvicePointer {
pattern: string | RegExp;
point: AdvicePoint;
type: AdviceType;
}
export declare class Adviser {
readonly point: AdvicePoint;
readonly matcher: RegExp;
readonly type: AdviceType;
readonly target: any;
constructor(pointer: AdvicePointer, target: any);
matches(component: any, method: Function): boolean;
before(component: any, method: Function): void;
after(component: any, method: Function): void;
around(component: any, method: Function): void;
}
export declare function Advice(pointer: AdvicePointer): any;
export declare namespace Advice {
var keys: string[];
var type: string;
}
type AspectType = 'before' | 'after';
type AspectScope = 'component' | 'bean' | 'service' | string;
export declare class AspectMatcher {
private readonly type;
private readonly pattern;
private readonly scope;
private readonly handle;
private component;
constructor(type: AspectType, pattern: string | RegExp, scope: AspectScope, handle: string);
bind(component: any): void;
match(component: any, method: string): boolean;
before(target: any, method: string, args: any[]): any;
after(target: any, method: string, args: any[], result: any): Promise<void>;
}
export declare function Aspect(point: {
type: AspectType;
pattern: string | RegExp;
scope?: AspectScope;
} | string): any;
export declare function Assist(assist: 'search' | 'get' | 'create' | 'modify' | 'delete' | Function): any;
export declare function Annotation(annotation: Record<string, any>): any;
declare type VWebEvent = 'startup' | 'shutdown' | string;
export declare function EventListener(event: VWebEvent): any;
export declare function Configuration(name: any): any;
export declare namespace Configuration {
var type: string;
var keys: string[];
}
export declare function Bean(name: any): any;
export declare namespace Bean {
var keys: string[];
var type: string;
}
export type ConditionalFilter = (context: any, method?: string) => boolean;
export type ConditionalContext = {
class?: ConditionalFilter;
methods?: Record<string, ConditionalFilter>;
};
export declare function Conditional(filter: ConditionalFilter): any;
export declare function Primary(target: any, property: any, descriptor: any): any;
export declare namespace Primary {
var keys: string[];
var type: string;
}
export * from './util';
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AspectMatcher = exports.Adviser = void 0;
exports.Readonly = Readonly;
exports.Component = Component;
exports.Service = Service;
exports.Initialization = Initialization;
exports.Setup = Setup;
exports.Resource = Resource;
exports.Value = Value;
exports.Props = Props;
exports.Lock = Lock;
exports.Comment = Comment;
exports.Advice = Advice;
exports.Aspect = Aspect;
exports.Assist = Assist;
exports.Annotation = Annotation;
exports.EventListener = EventListener;
exports.Configuration = Configuration;
exports.Bean = Bean;
exports.Conditional = Conditional;
exports.Primary = Primary;
const util_1 = __importDefault(require("../util"));
const util_2 = require("./util");
function Readonly(target, property, descriptor) {
(0, util_2.onlyMethod)(property, descriptor);
return descriptor;
}
function Component(name) {
const set = (target, property) => {
let annotation = {
name: name || util_1.default.uncapitalize(target.name),
type: 'component',
component: true,
prototype: false,
annType: Component
};
(0, util_2.setAnnotation)(target, annotation);
};
if (name instanceof Function) {
let target = name, property = arguments[1];
name = null;
set(target, property);
}
else {
return set;
}
}
Component.type = 'component';
Component.keys = ['name'];
function Service(name) {
const set = (target, property) => {
let annotation = {
name: name || util_1.default.uncapitalize(target.name),
type: 'service',
component: true,
prototype: false,
annType: Service
};
(0, util_2.setAnnotation)(target, annotation);
};
if (name instanceof Function) {
let target = name, property = arguments[1];
name = null;
set(target, property);
}
else {
return set;
}
}
Service.type = 'service';
Service.keys = ['name'];
function Initialization(target, property, descriptor) {
(0, util_2.onlyMethod)(property, descriptor);
let initializations = {};
initializations[property] = true;
(0, util_2.setAnnotation)(target, { initializations, annType: Initialization });
}
Initialization.keys = ['initializations'];
function Setup(target, property, descriptor) {
(0, util_2.onlyMethod)(property, descriptor);
(0, util_2.setAnnotation)(target, { setup: property, annType: Setup });
}
Setup.keys = ['setup'];
function Resource(name) {
const setDescriptor = (target, property, descriptor) => {
let resources = {};
resources[property] = name || property;
(0, util_2.setAnnotation)(target, { resources, annType: Resource });
};
if (name instanceof Object) {
let target = name;
name = void 0;
setDescriptor(target, arguments[1], arguments[2]);
}
else {
return setDescriptor;
}
}
Resource.keys = ['resources'];
function Value(express, defaultValue) {
return (target, property) => {
let values = {};
values[property] = { express, defaultValue };
(0, util_2.setAnnotation)(target, { values, annType: Value });
};
}
Value.keys = ['values'];
function Props(propKeys, defaultValue) {
return (target, property) => {
let props = {};
props[property] = { propKeys, defaultValue };
(0, util_2.setAnnotation)(target, { props, annType: Props });
};
}
Props.keys = ['props'];
function Lock(target, property, descriptor) {
(0, util_2.onlyMethod)(property, descriptor);
let locks = {};
locks[property] = true;
(0, util_2.setAnnotation)(target, { locks });
}
Lock.keys = ['locks'];
function Comment(value) {
const set = (target, property, descriptor) => {
let annotation;
if (property) {
descriptor.writable = false;
descriptor.configurable = false;
descriptor.enumerable = false;
let comments = {};
comments[property] = value;
annotation = { comments };
}
else {
annotation = { comment: value };
}
(0, util_2.setAnnotation)(target, annotation);
};
if (value instanceof Function) {
set(value);
}
else {
return set;
}
}
Comment.keys = ['comment', 'comments'];
class Adviser {
point;
matcher;
type;
target;
constructor(pointer, target) {
let { pattern, point, type } = pointer;
this.point = point;
if (typeof pattern === 'string') {
pattern = new RegExp(pattern.replace(/\*/g, '.*'));
}
this.matcher = pattern;
this.type = type;
this.target = target;
}
matches(component, method) {
const { type } = component.annotation;
return ('all' === this.type || this.type === type) && this.matcher.test(method.constructor.name);
}
before(component, method) {
if (this.matches(component, method) && 'before' === this.point) {
this.target.before(method, component);
}
}
after(component, method) {
if (this.matches(component, method) && 'after' === this.point) {
this.target.after(method, component);
}
}
around(component, method) {
if (this.matches(component, method) && 'around' === this.point) {
this.target.around(method, component);
}
}
}
exports.Adviser = Adviser;
function Advice(pointer) {
return (target, property, descriptor) => {
let annotation = {
name: util_1.default.uncapitalize(target.name),
type: 'advice',
component: true,
advice: new Adviser(pointer, target),
annType: Advice
};
(0, util_2.setAnnotation)(target, annotation);
};
}
Advice.keys = ['pointer'];
Advice.type = 'advice';
class AspectMatcher {
type;
pattern;
scope;
handle;
component;
constructor(type, pattern, scope, handle) {
this.type = type;
this.pattern = typeof pattern === 'string' ? new RegExp(pattern.replace(/\*/g, '.*')) : pattern;
this.scope = scope;
this.handle = handle;
}
bind(component) {
this.component = component;
}
match(component, method) {
if (this.scope !== 'any') {
const type = component.annotation.type;
if (this.scope !== type) {
return new RegExp(this.scope).test(component.annotation.name);
}
}
return this.pattern.test(method);
}
before(target, method, args) {
if (this.type === 'before') {
return this.component[this.handle]?.call(target, method, args);
}
}
async after(target, method, args, result) {
if (this.type === 'after') {
this.component[this.handle]?.call(target, method, args, result);
}
}
}
exports.AspectMatcher = AspectMatcher;
function Aspect(point) {
return (target, property) => {
let type, pattern, scope;
if (typeof point === 'string') {
const [mType, mScope, mPattern] = point.match(/^@(before|after)\s+([a-zA-Z0-9_]+)#(.*)$/);
if (!mType || !mScope || !mPattern) {
throw new Error('Aspect point format error eg: @before componentName#test*');
}
type = mType;
scope = mScope;
pattern = mPattern;
}
else {
type = point.type;
pattern = point.pattern;
scope = point.scope;
}
scope = scope || 'component';
let annotation = {
aspect: {
[property]: new AspectMatcher(type, pattern, scope, property)
}
};
(0, util_2.setAnnotation)(target, annotation);
};
}
function Assist(assist) {
const set = (target, property) => {
if (!assist) {
assist = util_1.default.uncapitalize(target.name);
}
(0, util_2.onlyClass)(property);
(0, util_2.setAnnotation)(target, { assist: assist });
};
if (assist instanceof Function) {
let target = assist;
assist = null;
set(target, arguments[1]);
}
else {
return set;
}
}
function Annotation(annotation) {
return (target) => (0, util_2.setAnnotation)(target, annotation);
}
function EventListener(event) {
return (target, property, descriptor) => {
(0, util_2.onlyMethod)(property, descriptor);
let events = {};
events[event] = property;
(0, util_2.setAnnotation)(target, { events });
};
}
function Configuration(name) {
const set = (target, property) => {
let annotation = {
name: name || util_1.default.uncapitalize(target.name),
type: 'component',
component: true,
prototype: false,
configuration: true,
annType: Configuration
};
(0, util_2.setAnnotation)(target, annotation);
};
if (name instanceof Function) {
let target = name, property = arguments[1];
name = null;
set(target, property);
}
else {
return set;
}
}
Configuration.type = 'configuration';
Configuration.keys = ['name'];
function Bean(name) {
let set = (target, property, descriptor) => {
(0, util_2.onlyMethod)(property, descriptor);
let beans = {};
beans[typeof name === 'string' ? name : property] = property;
(0, util_2.setAnnotation)(target, { beans });
};
if (typeof name === 'string') {
return set;
}
else {
return set(name, arguments[1], arguments[2]);
}
}
Bean.keys = ['bean'];
Bean.type = 'bean';
function Conditional(filter) {
if (typeof filter !== 'function') {
throw new Error('filter must be a function');
}
return (target, property) => {
let conditional = {};
if (typeof target === 'object') {
conditional.methods = { [property]: filter };
}
else {
conditional.class = filter;
}
(0, util_2.setAnnotation)(target, { conditional });
};
}
Bean.keys = ['conditional'];
Bean.type = 'conditional';
function Primary(target, property, descriptor) {
(0, util_2.onlyClass)(property);
(0, util_2.setAnnotation)(target, { primary: true });
}
Primary.keys = ['primary'];
Primary.type = 'primary';
__exportStar(require("./util"), exports);
export declare function onlyClass(property: string): void;
export declare function onlyMethod(property: string, descriptor: any): void;
export declare function setAnnotation(target: any, annotation: Record<string, any>): void;
export declare function getAnnotation(target: any, annoType: any): any;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.onlyClass = onlyClass;
exports.onlyMethod = onlyMethod;
exports.setAnnotation = setAnnotation;
exports.getAnnotation = getAnnotation;
function onlyClass(property) {
if (property) {
throw new Error('Can\'t as as method decorator');
}
}
function onlyMethod(property, descriptor) {
if (!property) {
throw new Error('Can\'t as as class decorator');
}
descriptor.writable = false;
descriptor.configurable = false;
}
function setAnnotation(target, annotation) {
if (!target)
return;
let prototype = target;
if (prototype.prototype) {
prototype = prototype.prototype;
}
if (!prototype.annotation) {
Reflect.defineProperty(prototype, 'annotation', {
writable: false,
configurable: false,
enumerable: false,
value: {}
});
}
let anno = prototype.annotation;
Object.keys(annotation).forEach(prop => {
if (anno[prop]
&& annotation[prop] instanceof Object
&& anno[prop] instanceof Object) {
Object.assign(anno[prop], annotation[prop]);
}
else {
anno[prop] = annotation[prop];
}
});
}
;
function getAnnotation(target, annoType) {
let annotation = target.annotation;
if (annoType) {
let anno = {};
if (anno.type && annotation.type !== anno.type) {
return annotation;
}
anno.keys.forEach(key => anno[key] = annotation[key]);
return anno;
}
return annotation;
}
export declare class Entry {
readonly expired: any;
readonly value: any;
constructor(value: any, expired?: number);
get(): any;
isInvalid(): boolean;
}
export declare class Cache {
static datasource: Map<any, any>;
readonly namespace: any;
constructor(namespace: any);
set(key: any, value: any, expired?: any): void;
get(key: any): any;
clean(): void;
keys(): any;
values(): any;
forEach(fn: any): void;
}
export declare class ArrayCache {
readonly datasource: any;
constructor();
has(key: any): boolean;
set(key: any, value: any): void;
get(key: any, single?: boolean): any;
}
declare const _default: (namespace?: string) => Cache;
export default _default;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ArrayCache = exports.Cache = exports.Entry = void 0;
class Entry {
expired;
value;
constructor(value, expired = 9999999999) {
this.expired = Date.now() + expired;
this.value = value;
}
get() {
return this.value;
}
isInvalid() {
return this.expired && this.expired < Date.now();
}
}
exports.Entry = Entry;
class Cache {
static datasource = new Map();
namespace;
constructor(namespace) {
this.namespace = namespace;
if (!Cache.datasource.has(namespace)) {
Cache.datasource.set(namespace, new Map());
}
}
set(key, value, expired) {
Cache.datasource.get(this.namespace).set(key, new Entry(value, expired));
}
get(key) {
let item = Cache.datasource.get(this.namespace).get(key);
if (item) {
if (item.isInvalid()) {
Cache.datasource.get(this.namespace).delete(key);
}
else {
return item.get();
}
}
}
clean() {
Cache.datasource.get(this.namespace).clear();
}
keys() {
return Cache.datasource.get(this.namespace).keys();
}
values() {
return Cache.datasource.get(this.namespace).values();
}
forEach(fn) {
Cache.datasource.get(this.namespace).forEach(fn);
}
}
exports.Cache = Cache;
class ArrayCache {
datasource;
constructor() {
this.datasource = {};
}
has(key) {
return this.datasource[key] !== undefined;
}
set(key, value) {
if (!this.datasource[key]) {
this.datasource[key] = [];
}
this.datasource[key].push(value);
}
get(key, single = true) {
let value = this.datasource[key] || [];
return single ? value[0] : value;
}
}
exports.ArrayCache = ArrayCache;
exports.default = (namespace = "default") => new Cache(namespace);
export default class Cipher {
private readonly key;
private readonly iv;
constructor(key: string, iv: string);
encrypt(message: string): string;
decrypt(encryptString: string): string;
static getKeyIv(): string;
static getCipher(keyIv: string): Cipher;
}
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
const crypto = __importStar(require("crypto"));
class Cipher {
key;
iv;
constructor(key, iv) {
this.key = Buffer.from(key, 'hex');
this.iv = Buffer.from(iv, 'hex');
}
encrypt(message) {
let cipher = crypto.createCipheriv('aes-256-gcm', this.key, this.iv);
let encrypted = cipher.update(message, 'utf8', 'hex');
encrypted += cipher.final('hex');
let tag = cipher.getAuthTag().toString('hex');
return encrypted + tag;
}
decrypt(encryptString) {
const ciphertext = encryptString.substring(0, encryptString.length - 32);
const tagHex = encryptString.substring(encryptString.length - 32);
const tag = Buffer.from(tagHex, 'hex');
let decipher = crypto.createDecipheriv('aes-256-gcm', this.key, this.iv);
decipher.setAuthTag(tag);
let decrypted = decipher.update(ciphertext, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
static getKeyIv() {
const key = crypto.randomBytes(32).toString('hex');
const iv = crypto.randomBytes(12).toString('hex');
return `${key}${iv}`;
}
static getCipher(keyIv) {
if (!keyIv) {
return;
}
const key = keyIv.substring(0, 64);
const iv = keyIv.substring(64);
return new Cipher(key, iv);
}
}
exports.default = Cipher;
import { Environment } from "../VWebApp";
export declare type ConfigType = 'json' | 'js' | 'yml' | 'yaml';
export declare const ConfigTypes: string[];
export default class Configuration {
private readonly properties;
private environment;
private expressMap;
constructor(conf: string | Environment, active?: string);
get(key: string): any;
parse(express: string): any;
props(key?: string): any;
getEnvironment(): Promise<Environment>;
}
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConfigTypes = void 0;
const loader_1 = __importDefault(require("./loader"));
const util_1 = require("./util");
const util_2 = __importDefault(require("../util"));
const encrypt_1 = __importDefault(require("./encrypt"));
const path = require('path');
const regex = /[$][{]([a-zA-Z0-9._-]+)(:[^}]+)?[}]/g;
const KeyIv = process.env['ENCRYPT_KEY_IV'];
const cipher = encrypt_1.default.getCipher(KeyIv);
const parseEnc = (express) => {
if (KeyIv && /ENC[(]([0-9a-fA-F]+)[)]/g.test(express)) {
const iterable = express.matchAll(/ENC[(]([0-9a-fA-F]+)[)]/g);
for (let match of iterable) {
try {
const value = cipher.decrypt(match[1]);
express = express.replace(match[0], value);
}
catch (e) {
util_1.logger.error('解密出错' + e.message);
}
}
}
return express;
};
const parseExpress = (express, datasource) => {
let val = parseEnc(express);
let matches = express.match(regex);
if (matches) {
for (let match of matches) {
let express = match.substring(2, match.length - 1);
let [prop, ...defaults] = express.split(":");
let defaultValue = defaults ? defaults.join(':') : '';
let value = datasource[prop];
if (value === undefined) {
value = datasource;
for (let key of prop.split('.')) {
value = value[key];
if (!value)
break;
}
}
value = value === undefined ? defaultValue : value;
if (value === undefined) {
console.error(`>>>>>>>>>>>>> Config error on express ${match[1]} >>>>>>>>>>>>>`);
return;
}
if (value === null) {
value = 'null';
}
if (typeof value === "string") {
val = val.replace(match, value);
if (/^null$/.test(val)) {
val = null;
}
else if (/^(true|false)$/.test(val)) {
val = val === 'true';
}
else {
let num = Number(val);
if (!isNaN(num) && !isFinite(num)) {
val = num;
}
}
}
else {
val = value;
}
}
}
return val;
};
const parseConfig = (config) => {
const datasource = { ...process.env, ...config };
const parser = (conf) => {
if (typeof conf === 'object' && conf) {
Object.keys(conf).forEach(prop => {
if (typeof conf.hasOwnProperty !== 'function')
return;
if (!conf.hasOwnProperty(prop))
return;
let val = conf[prop];
if (typeof val === 'string') {
conf[prop] = parseExpress(val, datasource);
}
else {
parser(val);
}
});
}
};
parser(config);
};
exports.ConfigTypes = ['json', 'js', 'yml', 'yaml'];
function loadProperties(confDir, active) {
let properties = {};
let configDir = confDir.replace(/\\'|"/g, '') + path.sep;
let map = util_2.default.file.listFilesSync(configDir, file => {
if (file.isDirectory || !file.ext)
return false;
let extName = file.ext.substring(1);
return exports.ConfigTypes.includes(extName);
}).map((file) => {
let type = file.ext.substring(1);
return {
type,
name: file.simpleName,
path: file.path
};
}).group(f => f.name);
for (let config of ['boot', 'app', 'application']) {
if (map.has(config)) {
util_1.logger.info(`Enable ${config} startup configuration`);
map.get(config).forEach(file => {
properties = util_2.default.assign(properties, (0, util_1.getConfigObject)(file.path));
});
}
}
parseConfig(properties);
let activeProfile = (properties.app?.active || active).replace(/\\'|"/g, '').trim();
if (activeProfile) {
util_1.logger.info(`Profile Active ${activeProfile}`);
}
let includes = properties.app?.includes || [];
if (includes.length) {
let arr = typeof includes === 'string' ? [includes] : includes;
includes = arr.flatMap(e => e.split(','));
util_1.logger.info(`Profile includes ${includes}`);
}
let profiles = [activeProfile, ...includes];
for (let profile of profiles) {
map.get(profile)?.forEach(file => {
properties = util_2.default.assign(properties, (0, util_1.getConfigObject)(file.path));
});
}
parseConfig(properties);
return properties;
}
class Configuration {
properties;
environment;
expressMap;
constructor(conf, active) {
if (typeof conf === 'string') {
this.properties = loadProperties(conf, active);
}
else {
this.properties = conf;
}
this.expressMap = new Map();
}
get(key) {
return this.environment[key];
}
parse(express) {
let val = this.expressMap.get(express);
if (!val) {
val = parseExpress(express, this.environment.props) || parseExpress(express, process.env);
this.expressMap.set(express, val);
}
return val;
}
props(key) {
let props = this.get('props') || {};
return !key ? props : props[key];
}
async getEnvironment() {
if (!this.environment) {
let environment = await (0, loader_1.default)(this.properties);
parseConfig(environment);
this.environment = environment;
}
return this.environment;
}
}
exports.default = Configuration;
import { Environment } from "../VWebApp";
declare const _default: (env: Environment) => Promise<Environment>;
export default _default;
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = __importDefault(require("../util"));
const http = __importStar(require("http"));
const fs = __importStar(require("fs"));
const util_2 = require("./util");
const path_1 = __importDefault(require("path"));
async function reqConfig(link) {
return new Promise((resolve, reject) => {
if (/^http[s]?:\/\//.test(link)) {
http.request(link, res => {
let buffer = void 0;
res.on('data', chunk => {
if (buffer) {
buffer = Buffer.concat([buffer, chunk], buffer.length + chunk.length);
}
else {
buffer = chunk;
}
});
res.on('end', () => {
resolve(buffer.toString());
});
res.on('error', err => {
reject(err);
});
}).end();
}
else {
util_1.default.assert.isTrue(link.endsWith('.json'), '本地配置文件必须是json');
try {
resolve(fs.readFileSync(link).toString());
}
catch (err) {
reject(err);
}
}
});
}
exports.default = async (env) => {
let config = { debug: false, src: 'src', exclude: [], include: [new RegExp('.*[.]js$')], ...env.config };
let props = { ...env.props };
let dependencies = env.dependencies || [];
let modules = { ...env.modules };
let environment = {
...env, config, props, logger: { ...env.logger }, dependencies, modules
};
let provider = {};
config.file = env.file || config.file;
if (config.file) {
let envObj;
util_2.logger.info(`Local config file ${config.file}`);
if (/^http[s]?:\/\//.test(config.file)) {
let content = await reqConfig(config.file);
let type = !content.startsWith('{') ? "yaml" : "json";
envObj = (0, util_2.parsePayload)(content, type);
}
else {
envObj = (0, util_2.getConfigObject)(config.file);
}
util_1.default.assign(envObj, environment);
}
config.nacos = env.nacos || config.nacos;
if (config.nacos) {
util_2.logger.info(`Nacos ${JSON.stringify(config.nacos)}`);
provider = await require('./nacos').default({
...config.nacos,
onUpgrade(upgrade) {
util_1.default.assign(upgrade, environment);
}
});
util_1.default.assign(provider.getConfig(), environment);
}
config.proxy = env.proxy || config.proxy;
if (config.proxy) {
util_2.logger.info(`Proxy use ${JSON.stringify(config.proxy)}`);
let handle = require(path_1.default.resolve(config.proxy));
if (handle.default) {
handle = handle.default;
}
if (typeof handle !== 'function') {
throw new Error(`Proxy handle must be a function, but got ${typeof handle}`);
}
let properties = await handle(environment);
util_1.default.assign(properties, environment);
}
return new Proxy(environment, {
get(target, p) {
if (p in target)
return target[p];
return provider[p];
}
});
};
import { DataType } from "./util";
declare interface NacosListener {
onUpgrade?: (upgrade: any, dataObj?: DataObj) => void;
}
export declare class NacosClient {
private config;
private client;
constructor(config: NacosConfig & NacosListener);
subscribe(dataId: DataId): any;
private getDataObj;
getData(dataId: DataId): Promise<any>;
}
declare const _default: (config: NacosConfig & NacosListener) => Promise<NacosClient>;
export default _default;
export declare interface NacosOptions {
endpoint?: string;
serverPort?: number;
namespace?: string;
accessKey?: string;
secretKey?: string;
httpclient?: any;
httpAgent?: any;
appName?: string;
ssl?: boolean;
refreshInterval?: number;
contextPath?: string;
clusterName?: string;
requestTimeout?: number;
defaultEncoding?: string;
serverAddr?: string;
unit?: string;
nameServerAddr?: string;
cacheDir?: string;
identityKey?: string;
identityValue?: string;
endpointQueryParams?: string;
decodeRes?: (res: any, method?: string, encoding?: string) => any;
httpOptions?: any;
}
export type DataObj = {
type?: DataType;
id: string;
group?: string;
};
export type DataId = string | DataObj;
export declare interface NacosConfig {
serverAddr: string;
namespace: string;
group: string;
dataIds: DataId | DataId[];
type?: DataType;
auth?: {
username?: string;
password?: string;
accessToken?: string;
authorization?: string;
};
options?: NacosOptions;
}
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.NacosClient = void 0;
const util_1 = __importDefault(require("../util"));
const index_1 = require("../index");
const util_2 = require("./util");
class NacosClient {
config;
client;
constructor(config) {
this.config = config;
const options = { ...config, ...(config.options || {}) };
const { NacosConfigClient } = require('nacos');
options.namespace = options.namespace || '';
options.serverAddr = options.serverAddr || '127.0.0.1:8848';
if (options.auth) {
let httpclient = require('urllib');
const request = httpclient.request;
httpclient.request = (link, opts) => {
let { authorization, accessToken, username = 'nacos', password = 'nacos' } = options.auth;
if (accessToken) {
opts.data['accessToken'] = accessToken;
}
else if (authorization) {
opts.headers['Authorization'] = /^Bearer /i.test(authorization) ? authorization : `Bearer ${authorization}`;
}
else {
opts.data = { ...opts.data, username, password };
}
return request(link, { ...config.options?.httpOptions, ...opts });
};
options.httpclient = httpclient;
}
this.client = new NacosConfigClient(options);
util_1.default.assert.isTrue(options.dataIds && options.group, "dataIds & group not found");
}
subscribe(dataId) {
let dataObj = this.getDataObj(dataId);
return this.client.subscribe({ dataId: dataObj.id, group: dataObj.group }, upgrade => {
try {
let obj = (0, util_2.parsePayload)(upgrade, dataObj.type);
const logger = index_1.LoggerFactory.getLogger('Nacos');
if (logger.isDebugEnabled()) {
logger.debug(`dataId:${JSON.stringify(dataObj)} upgrade \n ${upgrade}`);
}
this.config?.onUpgrade(obj, dataObj);
}
catch (e) {
util_2.logger.error(e);
}
});
}
getDataObj(dataId) {
let id = typeof dataId === 'string' ? dataId : dataId.id;
let group = (typeof dataId === 'string' ? this.config.group : (dataId.group || this.config.group)) || 'DEFAULT_GROUP';
let type = (typeof dataId === 'string' ? this.config.type : dataId.type) || 'json';
return { id, group, type };
}
async getData(dataId) {
let { id, group, type } = this.getDataObj(dataId);
let config;
try {
let content = await this.client.getConfig(id, group);
if (content) {
config = (0, util_2.parsePayload)(content, type);
}
else {
util_2.logger.error(`Config ${group}.${id} not found`);
}
}
catch (e) {
util_2.logger.info(`dataId:${dataId} 获取失败:${e.message || e}`);
}
return config;
}
}
exports.NacosClient = NacosClient;
exports.default = async (config) => {
const dataIds = Array.isArray(config.dataIds) ? config.dataIds : [config.dataIds];
let env = {};
let client = new NacosClient(config);
for (let dataId of dataIds) {
let obj = await client.getData(dataId);
await client.subscribe(dataId);
env = { ...env, ...obj };
}
return new Proxy(client, {
get(target, p) {
if (p === 'getConfig') {
return () => env;
}
return target[p];
}
});
};
export type DataType = 'json' | 'yaml' | 'yml';
export declare const logger: {
info(message: any): void;
debug(message: any): void;
error(message: any): void;
};
export declare function parsePayload(content: string, type?: DataType): any;
export declare function getConfigObject(file: string): any;
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.logger = void 0;
exports.parsePayload = parsePayload;
exports.getConfigObject = getConfigObject;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const getLogTime = () => {
let time = new Date().format('yyyy-MM-ddTHH:mm:ss.S');
let [date, ms] = time.split('.');
return `${date}.${'000'.substring(ms.length)}${ms}`;
};
exports.logger = {
info(message) {
console.log(`[${getLogTime()}] [INFO] ConfigLoader - ${message}`);
},
debug(message) {
console.debug(`[${getLogTime()}] [DEBUG] ConfigLoader - \x1B[1m ${message}`);
},
error(message) {
console.error(`[${getLogTime()}] [ERROR] ConfigLoader - ${message}`);
},
};
function parsePayload(content, type = 'json') {
try {
if (type === 'json') {
return eval(`(${content})`);
}
else if (type === 'yaml' || type === 'yml') {
const yaml = require('yaml');
return yaml.parse(content);
}
}
catch (e) {
exports.logger.error(`Parse error ${type} ${content} ${e}`);
}
return {};
}
function getConfigObject(file) {
if (!fs_1.default.existsSync(file))
return;
let { ext } = path_1.default.parse(file);
if (!ext)
return;
try {
let type = ext.substring(1);
if (/json|js|yml|yaml/.test(type)) {
if (type === 'js') {
return require(file);
}
else if (type === 'json' || type === 'yml' || type === 'yaml') {
let content = fs_1.default.readFileSync(file).toString();
if (content.length) {
return parsePayload(fs_1.default.readFileSync(file).toString(), type);
}
}
}
}
catch (e) {
exports.logger.error(`There is an error “${e.message}” in the configuration file ${file}`);
console.trace(e);
process.exit(1);
}
}
export default class LogicError extends Error {
readonly code?: any;
constructor(message: any, code?: any);
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class LogicError extends Error {
code;
constructor(message, code) {
super();
this.message = message;
this.code = code;
}
}
exports.default = LogicError;
import VWebApplicationContext, { Active, Environment } from './VWebApp';
import cache from './cache';
import file from './util/file';
import assert from './util/assert';
import util from './util';
import logger from './logger';
import LogicError from './error/LogicError';
import Open from "./Open";
import MultiMap from './util/MultiMap';
export * from './util';
export * from './VWebApp';
export * from './anno';
export * from './cache';
declare let applicationContext: VWebApplicationContext;
export declare const commandLineColors: {
front: {
bright: string;
grey: string;
reverse: string;
black: string;
red: string;
green: string;
yellow: string;
blue: string;
magenta: string;
cyan: string;
underline: string;
hidden: string;
italic: string;
white: string;
};
background: {
black: string;
red: string;
green: string;
yellow: string;
blue: string;
magenta: string;
cyan: string;
white: string;
};
};
export declare type StartupCallback = (context: VWebApplicationContext) => Promise<void>;
export declare interface StartupOptions {
active?: Active;
conf?: string | Environment;
callback?: StartupCallback;
}
export declare const startup: (options?: StartupOptions | StartupCallback | Active) => Promise<void>;
export declare const LoggerFactory: typeof logger;
export declare const getApplicationContext: () => VWebApplicationContext;
export declare const props: (key: string) => any;
export declare const parseExpress: (express: string) => any;
export declare function defineEnvironment(env: Environment): Environment;
export declare const upgradeProps: (props: any) => import("./VWebApp").Config;
declare global {
interface Logger {
log(...args: any[]): void;
isLevelEnabled(level?: string): boolean;
isTraceEnabled(): boolean;
isDebugEnabled(): boolean;
isInfoEnabled(): boolean;
isWarnEnabled(): boolean;
isErrorEnabled(): boolean;
isFatalEnabled(): boolean;
debug(message: any, ...args: any[]): void;
info(message: any, ...args: any[]): void;
warn(message: any, ...args: any[]): void;
error(message: any, ...args: any[]): void;
fatal(message: any, ...args: any[]): void;
mark(message: any, ...args: any[]): void;
}
const applicationContext: VWebApplicationContext;
interface Object {
readonly applicationContext: VWebApplicationContext;
readonly annotation: any;
readonly logger: Logger;
readonly LoggerFactory: {
getLogger(name: string): Logger;
};
}
}
export interface VWebModule {
startup(context: VWebApplicationContext): Promise<void>;
}
export interface ModuleConfig extends Record<string, any> {
require?: string;
}
export default applicationContext;
export { VWebApplicationContext, assert, file, cache, util, MultiMap, logger, Open, LogicError };
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.LogicError = exports.Open = exports.logger = exports.MultiMap = exports.util = exports.cache = exports.file = exports.assert = exports.VWebApplicationContext = exports.upgradeProps = exports.parseExpress = exports.props = exports.getApplicationContext = exports.LoggerFactory = exports.startup = exports.commandLineColors = void 0;
exports.defineEnvironment = defineEnvironment;
const VWebApp_1 = __importDefault(require("./VWebApp"));
exports.VWebApplicationContext = VWebApp_1.default;
const cache_1 = __importDefault(require("./cache"));
exports.cache = cache_1.default;
const file_1 = __importDefault(require("./util/file"));
exports.file = file_1.default;
const assert_1 = __importDefault(require("./util/assert"));
exports.assert = assert_1.default;
const util_1 = __importDefault(require("./util"));
exports.util = util_1.default;
const logger_1 = __importDefault(require("./logger"));
exports.logger = logger_1.default;
const LogicError_1 = __importDefault(require("./error/LogicError"));
exports.LogicError = LogicError_1.default;
const Open_1 = __importDefault(require("./Open"));
exports.Open = Open_1.default;
const MultiMap_1 = __importDefault(require("./util/MultiMap"));
exports.MultiMap = MultiMap_1.default;
const path = __importStar(require("path"));
__exportStar(require("./util"), exports);
__exportStar(require("./VWebApp"), exports);
__exportStar(require("./anno"), exports);
__exportStar(require("./cache"), exports);
require('@babel/register');
let applicationContext;
exports.commandLineColors = {
front: {
'bright': '\x1B[1m',
'grey': '\x1B[2m',
'reverse': '\x1B[7m',
'black': '\x1B[30m',
'red': '\x1B[31m',
'green': '\x1B[32m',
'yellow': '\x1B[33m',
'blue': '\x1B[34m',
'magenta': '\x1B[35m',
'cyan': '\x1B[36m',
'underline': '\x1B[4m',
'hidden': '\x1B[8m',
'italic': '\x1B[3m',
'white': '\x1B[37m',
},
background: {
'black': '\x1B[40m',
'red': '\x1B[41m',
'green': '\x1B[42m',
'yellow': '\x1B[43m',
'blue': '\x1B[44m',
'magenta': '\x1B[45m',
'cyan': '\x1B[46m',
'white': '\x1B[47m'
}
};
let printLogo = () => {
if (global.__vweb_logo !== false) {
let arr = Object.keys(exports.commandLineColors.front);
let color = arr.randomExtract();
const logo = global.__vweb_logo || `
)
) ( ( ( ( /(
/(( )\\))( ))\\ )\\())
(_))\\ ((_)()\\ /((_) ((_)\\
_)((_) _(()((_) (_)) | |(_)
\\ V / \\ V V / / -_) | '_ \\
\\_/ \\_/\\_/ \\___| |_.__/
${process.env.npm_package_version}
`;
console.log(logo);
}
};
const startup = async (options) => {
try {
let begin = Date.now();
printLogo();
let opts = {};
if (typeof options === 'function') {
opts.callback = options;
}
else if (typeof options === 'string') {
opts.active = options;
}
else {
opts = { ...options };
}
let { callback = (context) => void 0, active = process.env.active || 'development', conf = process.env.conf || (path.resolve('.') + path.sep + 'config') } = opts;
applicationContext = new VWebApp_1.default(conf, active);
await applicationContext.initialize();
(global.__vweb_modules || []).forEach(({ module, config }) => {
applicationContext.mount(module, config);
});
await callback(applicationContext);
await applicationContext.launch();
}
catch (e) {
applicationContext.logger.error('应用启动失败', e);
}
};
exports.startup = startup;
exports.LoggerFactory = logger_1.default;
const getApplicationContext = () => applicationContext;
exports.getApplicationContext = getApplicationContext;
const props = (key) => applicationContext?.props(key);
exports.props = props;
const parseExpress = (express) => applicationContext?.config.parse(express);
exports.parseExpress = parseExpress;
function defineEnvironment(env) {
return env;
}
const upgradeProps = props => {
if (!applicationContext) {
console.log('Application not init');
return;
}
let oldProps = applicationContext.environment.props;
applicationContext.environment.props = { ...oldProps, ...props };
return oldProps;
};
exports.upgradeProps = upgradeProps;
exports.default = applicationContext;
export default function configure(config: any, layouts: any): {
(logEvent: any): void;
shutdown(complete: any): void;
};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = configure;
const os = require('os');
const eol = os.EOL || '\n';
const url = require("url");
function appender(filename, pattern, layout, options, timezoneOffset) {
const app = function (logEvent) {
if (logEvent.level.levelStr === 'ERROR') {
const axios = require('axios');
let error = layout(logEvent, timezoneOffset) + eol;
const { token, name, subject, key, phone, remote } = options;
const sendError = err => {
const arr = [];
let data = {
"msgtype": "markdown",
"markdown": {
"title": `${key}\t${subject}`,
"text": `@${phone}
${new Date().toJSON()}
${key} ${subject}` + err.toString().substring(0, 5000)
},
"at": {
"atMobiles": [phone],
"isAtAll": false
}
};
axios.post(`https://oapi.dingtalk.com/robot/send?access_token=${token}`, data);
};
if (remote) {
let { auth } = url.parse(remote);
let config = {};
if (auth) {
let [username, password] = auth.split(":");
config = {
auth: {
username,
password
}
};
}
let [err] = logEvent.data || [];
let message = err && err.message;
axios.post(remote, { from: '', key, subject, message, error }, config).then(rs => {
sendError(`[点击查看](${rs.data})`);
}).catch(err => {
console.log(err);
});
}
else {
sendError(error);
}
}
};
app.shutdown = function (complete) {
};
return app;
}
function configure(config, layouts) {
let layout = layouts.basicLayout;
if (config.layout) {
layout = layouts.layout(config.layout.type, config.layout);
}
if (!config.alwaysIncludePattern) {
config.alwaysIncludePattern = false;
}
return appender(config.filename, config.pattern, layout, config, config.timezoneOffset);
}
import { Appender, Levels, Logger } from "log4js";
export * from "log4js";
export declare interface LoggerConfig {
appenders?: {
[name: string]: Appender;
};
categories?: {
[name: string]: {
appenders: string[];
level: string;
enableCallStack?: boolean;
};
};
pm2?: boolean;
pm2InstanceVar?: string;
levels?: Levels;
disableClustering?: boolean;
}
declare function log4j(config: LoggerConfig): Logger;
declare namespace log4j {
var getLogger: typeof import(".").getLogger;
}
export declare function getLogger(name: any): Logger;
export default log4j;
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getLogger = getLogger;
__exportStar(require("log4js"), exports);
const log4js = require("log4js");
let logger;
function log4j(config) {
log4js.configure({
appenders: {
console: {
type: 'console'
}
},
categories: {
default: { appenders: ['console'], level: 'info' }
},
...config
});
logger = log4js.getLogger('vweb');
logger.addContext('i', process.env.NODE_APP_INSTANCE || '');
return logger;
}
function getLogger(name) {
if (!name) {
return logger;
}
let log = log4js.getLogger(typeof name === "function" ? name.name : name);
log.addContext('i', process.env.NODE_APP_INSTANCE || '');
return log;
}
log4j.getLogger = getLogger;
exports.default = log4j;
export default class Open {
open(): void;
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class Open {
open() {
throw new Error('Please override this method');
}
}
exports.default = Open;

Sorry, the diff of this file is not supported yet

export declare class AssertError extends Error {
private readonly code;
constructor(message: any, code?: string);
}
export default class Assert {
static isNotBlank(express: any, message: any): void;
static isNotAnyBlank(): void;
static ok(express: any, message: any): void;
static fail(express: any, message: any): void;
static isUndefined(value: any, message: any): void;
static nonUndefined(value: any, message: any): void;
static isNull(value: any, message: any): void;
static nonNull(value: any, message: any): void;
static isTrue(express: any, message: any): void;
static isFalse(express: any, message: any): void;
static isNotEmpty(express: any, message?: any): void;
static isArray(express: any, message?: any): void;
static isFunction(express: any, message?: any): void;
static isObject(express: any, message?: any): void;
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AssertError = void 0;
class AssertError extends Error {
code;
constructor(message, code = 'AssertError') {
super();
this.message = message;
this.code = code;
}
}
exports.AssertError = AssertError;
class Assert {
static isNotBlank(express, message) {
if (typeof express === 'string' && express.trim().length > 0)
return;
throw new Error(message);
}
static isNotAnyBlank() {
let message = arguments[arguments.length - 1];
for (let i = 0; i < arguments.length - 2; i++) {
let express = arguments[i];
if (typeof express === 'string' && express.trim().length > 0)
continue;
throw new Error(message);
}
}
static ok(express, message) {
return Assert.isTrue(express, message);
}
static fail(express, message) {
return Assert.isFalse(express, message);
}
static isUndefined(value, message) {
if (value !== undefined) {
throw new AssertError(message);
}
}
static nonUndefined(value, message) {
if (value === undefined) {
throw new AssertError(message);
}
}
static isNull(value, message) {
if (value !== null) {
throw new AssertError(message);
}
}
static nonNull(value, message) {
if (value === null) {
throw new AssertError(message);
}
}
static isTrue(express, message) {
if (!express) {
throw new AssertError(message);
}
}
static isFalse(express, message) {
if (!!express) {
throw new AssertError(message);
}
}
static isNotEmpty(express, message) {
if (Array.isArray(express)) {
if (!express.length) {
throw new AssertError(message || "is empty");
}
}
if (typeof express === 'string') {
if (!express.length) {
throw new AssertError(message || "is empty");
}
}
if (express instanceof Map) {
if (!express.size) {
throw new AssertError(message || "is empty");
}
}
if (express instanceof Set) {
if (!express.size) {
throw new AssertError(message || "is empty");
}
}
}
static isArray(express, message) {
if (!Array.isArray(express)) {
throw new AssertError(message || 'not array');
}
}
static isFunction(express, message) {
if (typeof express !== "function") {
throw new AssertError(message || 'not function');
}
}
static isObject(express, message) {
if (!(!Array.isArray(express) && typeof express === 'object')) {
throw new AssertError(message || 'not object');
}
}
}
exports.default = Assert;
export default class CmdUtil {
static exec(command: any, args: any): Promise<unknown>;
static exists(cmd: any): Promise<unknown>;
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const process = require('child_process'), { getLogger } = require('../logger'), os = require('os');
const logger = getLogger("cmd");
class CmdUtil {
static exec(command, args) {
return new Promise((resolve, reject) => {
let cmd = `${command} ${args.join(' ')}`;
if (logger.isDebugEnabled()) {
logger.debug(`execute command ${cmd}`);
}
process.exec(cmd, (err, stdout, stderr) => {
if (err) {
reject(err);
}
else {
resolve(stdout + stderr);
}
});
});
}
static exists(cmd) {
const osType = os.type();
let command = osType.toLowerCase().includes('windows') ? 'where' : 'which';
return new Promise(resolve => {
CmdUtil.exec(command, [cmd]).then(rs => {
logger.info(`${cmd} exists`, rs);
resolve(true);
}).catch(err => {
logger.warn(`${cmd} command was not found in your classpath.`);
resolve(false);
});
});
}
}
exports.default = CmdUtil;
export default class CryptoUtil {
static hash(hashName?: string, data?: string): string;
static hmac(hashName?: string, data?: string, key?: string): string;
static md5(data?: string): string;
static sha1(data?: string): string;
static sha256(data?: string): string;
static sha512(data?: string): string;
static md5Hmac(data?: string, key?: string): string;
static sha1Hmac(data?: string, key?: string): string;
static sha256Hmac(data?: string, key?: string): string;
static sha512Hmac(data?: string, key?: string): string;
static aesEncrypt(data?: string, key?: string): string;
static aesDecrypt(data?: string, key?: string): string;
static rsaEncrypt(data?: string, privateKey?: string): string;
static rsaDecrypt(data?: string, publicKey?: string): boolean;
static base64Encode(data?: string): string;
static base64Decode(data?: string): string;
}
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
const crypto = __importStar(require("crypto"));
class CryptoUtil {
static hash(hashName = "", data = "") {
const hash = crypto.createHash(hashName);
hash.update(data);
return hash.digest('hex');
}
static hmac(hashName = "", data = "", key = "") {
const mac = crypto.createHmac(hashName, key);
mac.update(data);
return mac.digest('hex');
}
static md5(data = "") {
return CryptoUtil.hash("md5", data);
}
static sha1(data = "") {
return CryptoUtil.hash("sha1", data);
}
static sha256(data = "") {
return CryptoUtil.hash("sha256", data);
}
static sha512(data = "") {
return CryptoUtil.hash("sha512", data);
}
static md5Hmac(data = "", key = "") {
return CryptoUtil.hmac('md5', data, key);
}
static sha1Hmac(data = "", key = "") {
return CryptoUtil.hmac('sha1', data, key);
}
static sha256Hmac(data = "", key = "") {
return CryptoUtil.hmac('sha256', data, key);
}
static sha512Hmac(data = "", key = "") {
return CryptoUtil.hmac('sha512', data, key);
}
static aesEncrypt(data = "", key = "") {
const cipher = crypto.createCipher('aes192', key);
let encrypted = cipher.update(data, 'utf-8', 'hex');
encrypted += cipher.final('hex');
return encrypted;
}
static aesDecrypt(data = "", key = "") {
const decipher = crypto.createDecipher('aes192', key);
let decrypted = decipher.update(data, 'hex', 'utf-8');
decrypted += decipher.final('utf-8');
return decrypted;
}
static rsaEncrypt(data = "", privateKey = "") {
const sign = crypto.createSign('RSA-SHA256');
sign.update(data);
return sign.sign(privateKey, 'hex');
}
static rsaDecrypt(data = "", publicKey = "") {
const verify = crypto.createVerify('RSA-SHA256');
verify.update(data);
return verify.verify(publicKey, data, 'hex');
}
static base64Encode(data = "") {
return new Buffer(data, "utf-8").toString("base64");
}
static base64Decode(data = "") {
return new Buffer(data, "base64").toString("utf-8");
}
}
exports.default = CryptoUtil;
export default class Duration {
private readonly millis;
constructor(millis?: number);
getMillis(): any;
getSeconds(): number;
getMinutes(): number;
getHours(): number;
getDays(): number;
static ofMillis(millis: number): Duration;
static ofSeconds(seconds: number): Duration;
static ofMinutes(minutes: number): Duration;
static ofHours(hours: number): Duration;
static ofDays(days: number): Duration;
static parse(str: string | number): Duration;
fmt2cn(): string;
fmt2en(): string;
}
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const assert_1 = __importDefault(require("./assert"));
class Duration {
millis;
constructor(millis = 0) {
this.millis = millis;
}
getMillis() {
return this.millis;
}
getSeconds() {
return this.getMillis() / 1000;
}
getMinutes() {
return this.getSeconds() / 60;
}
getHours() {
return this.getMinutes() / 60;
}
getDays() {
return this.getHours() / 24;
}
static ofMillis(millis) {
return new Duration(millis);
}
static ofSeconds(seconds) {
return new Duration(seconds * 1000);
}
static ofMinutes(minutes) {
return new Duration(minutes * 1000 * 60);
}
static ofHours(hours) {
return new Duration(hours * 1000 * 60 * 60);
}
static ofDays(days) {
return new Duration(days * 1000 * 60 * 60 * 24);
}
static parse(str) {
if (typeof str === 'number') {
return new Duration(str);
}
let reg = /^([0-9]+(.[0-9]+)?)([dDhHmMsS])/;
assert_1.default.isTrue(reg.test(str), '格式错误,支持格式为 [0-9]+(.[0-9]+)?[dDhHmMsS]');
let [, num, , unit] = str.match(reg);
let count = Number(num);
if (!unit) {
return new Duration(count);
}
unit = unit.toUpperCase();
switch (unit) {
case 'D':
return Duration.ofDays(count);
case 'H':
return Duration.ofHours(count);
case 'M':
return Duration.ofMinutes(count);
case 'S':
return Duration.ofSeconds(count);
}
throw new Error('UnSupport unit');
}
fmt2cn() {
let str = '';
let minutes = this.millis / 6e4;
if (minutes > 0) {
str += `${minutes}分`;
}
let seconds = this.getSeconds();
if (seconds > 0) {
str += `${seconds}秒`;
}
return str;
}
fmt2en() {
let str = '';
let minutes = this.millis / 6e4;
if (minutes > 0) {
str += `${minutes}′`;
}
let seconds = this.getSeconds();
if (seconds > 0) {
str += `${seconds}″`;
}
return str;
}
}
exports.default = Duration;
declare type Task = (...args: any[]) => any | Promise<any>;
export declare class ExecutorService {
private readonly concurrency;
private queue;
private activeCount;
private readonly tasks;
constructor(concurrency?: number);
private nextTask;
private runTask;
private enqueue;
add(task: Task, ...args: any[]): void;
run(): Promise<any[]>;
clear(): void;
get runSize(): number;
get size(): number;
}
export default class Executors {
static run(tasks: Array<Task>, concurrency?: number): Promise<any[]>;
}
export declare class WorkExecutor {
private readonly corePoolSize;
private readonly maximumPoolSize;
private readonly queue;
private active;
private _work;
constructor(work?: Function);
constructor(work: Function, corePoolSize: number);
constructor(work: Function, corePoolSize: number, maximumPoolSize: number);
static getExecutor(work: Function, corePoolSize?: number, maximumPoolSize?: number): WorkExecutor;
setWork(work: Function): this;
submit(...args: any[]): this;
get size(): number;
get isOver(): boolean;
startup(): any;
}
export {};
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.WorkExecutor = exports.ExecutorService = void 0;
const Queue_1 = __importDefault(require("./Queue"));
class ExecutorService {
concurrency;
queue;
activeCount;
tasks;
constructor(concurrency = 10) {
this.concurrency = concurrency;
this.queue = new Queue_1.default(concurrency);
this.activeCount = 0;
this.tasks = [];
}
nextTask() {
this.activeCount--;
if (this.queue.size > 0) {
this.queue.dequeue()();
}
}
async runTask(task, resolve, ...args) {
this.activeCount++;
const result = (async () => await task(...args))();
resolve(result);
try {
await result;
}
catch {
}
this.nextTask();
}
;
enqueue(task, resolve, ...args) {
this.queue.enqueue(this.runTask.bind(this, task, resolve, args));
(async () => {
await Promise.resolve();
if (this.activeCount < this.concurrency && this.queue.size > 0) {
this.queue.dequeue()();
}
})();
}
;
add(task, ...args) {
this.tasks.push(new Promise(resolve => {
this.enqueue(task, resolve, args);
}));
}
run() {
return Promise.all(this.tasks);
}
clear() {
this.queue.clear();
this.tasks.length = 0;
}
get runSize() {
return this.activeCount;
}
get size() {
return this.queue.size;
}
}
exports.ExecutorService = ExecutorService;
class Executors {
static async run(tasks, concurrency = 10) {
const service = new ExecutorService(concurrency);
for (let task of tasks) {
service.add(task);
}
return await service.run();
}
}
exports.default = Executors;
class WorkExecutor {
corePoolSize;
maximumPoolSize;
queue;
active;
_work;
constructor(work, corePoolSize = 10, maximumPoolSize = Number.MAX_VALUE) {
this._work = work;
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.queue = [];
this.active = 0;
}
static getExecutor(work, corePoolSize = 10, maximumPoolSize = Number.MAX_VALUE) {
return new WorkExecutor(work, corePoolSize, maximumPoolSize);
}
setWork(work) {
this._work = work;
return this;
}
submit(...args) {
this.queue.push(args);
this.startup();
return this;
}
get size() {
return this.queue.length;
}
get isOver() {
return this.queue.length === 0;
}
async startup() {
if (this.isOver || this.active >= this.corePoolSize)
return;
let args = this.queue.shift();
this.active++;
await new Promise(async (resolve, reject) => {
try {
await this._work(...args);
resolve(void 0);
}
catch (e) {
reject(e);
}
});
this.active--;
return this.startup();
}
}
exports.WorkExecutor = WorkExecutor;
export declare class File {
readonly path: any;
readonly isDirectory: any;
readonly name: any;
readonly simpleName: any;
readonly ext: any;
readonly lastModified: any;
readonly dir: any;
constructor(absolutePath: any, stat: any);
matches(regex: any): boolean;
exists(): any;
getExtension(): any;
isFile(type?: string): any;
}
export default class FileUtil {
static listFilesSync(absolutePath: any, filter: (file: File) => boolean): File[];
static forceMkDirSync(dir: any): boolean;
static rmDirSync(path: any): void;
static compressSync(dir: any, output: any): Promise<unknown>;
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.File = void 0;
const fs = require("fs"), path = require("path");
class File {
path;
isDirectory;
name;
simpleName;
ext;
lastModified;
dir;
constructor(absolutePath, stat) {
const { dir, name, ext, base } = path.parse(absolutePath);
this.path = absolutePath;
this.isDirectory = stat.isDirectory();
this.name = base;
this.simpleName = name;
this.ext = ext;
this.lastModified = stat.mtime;
this.dir = dir;
}
matches(regex) {
return new RegExp(regex).test(this.name);
}
exists() {
return fs.existsSync(this.path);
}
getExtension() {
return this.isFile() ? this.name.substring(this.name.lastIndexOf('.') + 1) : '';
}
isFile(type) {
return !this.isDirectory && (!type || this.getExtension().toLowerCase() === type.toLowerCase());
}
}
exports.File = File;
class FileUtil {
static listFilesSync(absolutePath, filter) {
let files = [];
filter = filter || (file => true);
if (fs.existsSync(absolutePath)) {
let stat = fs.statSync(absolutePath);
let file = new File(absolutePath, stat);
if (stat.isDirectory()) {
fs.readdirSync(absolutePath).forEach(f => {
files = files.concat(FileUtil.listFilesSync(absolutePath + '/' + f, filter));
});
}
else {
if (filter(file)) {
files.push(file);
}
}
}
return files;
}
static forceMkDirSync(dir) {
if (fs.existsSync(dir)) {
return true;
}
else {
if (FileUtil.forceMkDirSync(path.dirname(dir))) {
fs.mkdirSync(dir);
return true;
}
}
}
static rmDirSync(path) {
if (fs.existsSync(path)) {
fs.readdirSync(path).forEach(function (file) {
let curPath = path + "/" + file;
if (fs.statSync(curPath).isDirectory()) {
FileUtil.rmDirSync(curPath);
}
else {
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(path);
}
}
;
static compressSync(dir, output) {
return new Promise((resolve, reject) => {
let archive = require("archiver")('zip', { store: true, zlib: { level: 9 } });
output = fs.createWriteStream(output);
output.on('close', function () {
resolve(true);
});
archive.on('warning', function (err) {
reject(err);
});
archive.on('error', function (err) {
reject(err);
});
archive.pipe(output);
archive.directory(dir, false);
archive.finalize();
});
}
}
exports.default = FileUtil;
import Duration from './Duration';
import assert from './assert';
import cmd from './cmd';
import file from './file';
import './js.extensions';
import Assigner from 'assign.js';
export * from './file';
export * from './cmd';
export * from './assert';
export * from './MultiMap';
export * from './Crypto';
export declare class Cipher {
encode(str: any): void;
decode(str: any): void;
}
export declare class Md5 extends Cipher {
private readonly crypto;
constructor();
encode(str: any): any;
}
export declare class Base64 extends Cipher {
encode(str: any): string;
decode(str: any): string;
}
export default class Util {
static md5: Md5;
static base64: Base64;
static dateFormat(date: any, pattern: any): any;
static now(): any;
static shuffle(array: any): any;
static randomExtract(array: any, size: any): any;
static capitalize(str: any): any;
static uncapitalize(str: any): any;
static column2field(str: any): any;
static field2column(str: any): any;
static random(start: any, end: any): number;
static randomNumeric(len: any): string;
static randomAscii(len: any): string;
static randomAlphabetic(len: any): string;
static randomAlphanumeric(len: any): string;
static setReadonly(target: any, obj: any): void;
static isEmpty(obj: any): boolean;
static isAjax(req: any): boolean;
static normalizePort(port: any): any;
static ipAddress(): any;
static decimalChange(num: any, to: any, from?: number, sequential?: boolean): any;
static file: typeof file;
static cmd: typeof cmd;
static assert: typeof assert;
static snowflake: {
code2id: (code: any) => bigint;
id2code: (id: any) => any;
nextId: () => number;
};
static Duration: typeof Duration;
static equals(a: any, b: any): boolean;
static nonEquals(a: any, b: any): boolean;
static isUndefined(val: any): boolean;
static isNull(val: any): boolean;
static id2string(id: any): string;
static string2id(idString: any): number;
static sleep(millisecond: number): Promise<unknown>;
static compare(obj1: any, obj2: any, compare?: string | Compare<any>): boolean;
static assigner: Assigner;
static assign(source: any, target: any): Record<string, any>;
static copyObject(source: any): [] | Record<string, any>;
static parseMethodParams: (method: any) => any;
}
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Base64 = exports.Md5 = exports.Cipher = void 0;
const Snowflake_1 = __importDefault(require("./Snowflake"));
const Duration_1 = __importDefault(require("./Duration"));
const assert_1 = __importDefault(require("./assert"));
const cmd_1 = __importDefault(require("./cmd"));
const file_1 = __importDefault(require("./file"));
require("./js.extensions");
const assign_js_1 = __importDefault(require("assign.js"));
const address_1 = require("address");
const random = (start, end) => {
return Math.round(Math.random() * (end - start) + start);
};
__exportStar(require("./file"), exports);
__exportStar(require("./cmd"), exports);
__exportStar(require("./assert"), exports);
__exportStar(require("./MultiMap"), exports);
__exportStar(require("./Crypto"), exports);
class Cipher {
encode(str) {
throw new Error("Un support operate");
}
decode(str) {
throw new Error("Un support operate");
}
}
exports.Cipher = Cipher;
class Md5 extends Cipher {
crypto;
constructor() {
super();
this.crypto = require('crypto');
}
encode(str) {
return this.crypto.createHash('md5').update(str, "utf-8").digest('hex');
}
}
exports.Md5 = Md5;
class Base64 extends Cipher {
encode(str) {
return Buffer.from(str).toString("base64");
}
decode(str) {
return Buffer.from(str, "base64").toString();
}
}
exports.Base64 = Base64;
class Util {
static md5 = new Md5();
static base64 = new Base64();
static dateFormat(date, pattern) {
return date.format(pattern);
}
static now() {
return Util.dateFormat(new Date(), "yyyy-MM-dd hh:mm:ss");
}
static shuffle(array) {
return !array ? array : array.shuffle();
}
static randomExtract(array, size) {
return !array ? array : array.random(size);
}
static capitalize(str) {
return str.capitalize();
}
static uncapitalize(str) {
return str.uncapitalize();
}
static column2field(str) {
return str.column2field();
}
static field2column(str) {
return str.field2column();
}
static random(start, end) {
return random(start, end);
}
static randomNumeric(len) {
let rs = [...new Array(len)].map(() => random(48, 57));
return String.fromCodePoint(...rs);
}
static randomAscii(len) {
let rs = [...new Array(len)].map(() => random(32, 127));
return String.fromCodePoint(...rs);
}
static randomAlphabetic(len) {
let rs = [...new Array(len)].map(() => random(0, 1) ? random(65, 90) : random(97, 122));
return String.fromCodePoint(...rs);
}
static randomAlphanumeric(len) {
let pool = [[48, 57], [65, 90], [97, 122]];
let rs = [...new Array(len)].map(() => {
let item = pool[random(0, 2)];
return random(item[0], item[1]);
});
return String.fromCodePoint(...rs);
}
static setReadonly(target, obj) {
const desc = {};
Reflect.ownKeys(obj).forEach(prop => {
desc[prop] = {
configurable: false,
writable: false,
enumerable: false,
value: obj[prop]
};
});
Object.defineProperties(this, desc);
}
static isEmpty(obj) {
if (typeof obj === 'string' || Array.isArray(obj))
return !obj.length;
else if (typeof obj === 'object')
return !Object.keys(obj).length;
else
return !obj;
}
static isAjax(req) {
return req && req.headers && req.headers['x-requested-with'] === 'XMLHttpRequest';
}
static normalizePort(port) {
port = parseInt(port, 10);
if (isNaN(port)) {
return port;
}
if (port >= 0) {
return port;
}
return false;
}
static ipAddress() {
if (!global.address) {
global.address = {
ip: (0, address_1.ip)(),
ipv6: (0, address_1.ipv6)(),
mac: async () => {
return new Promise((resolve, reject) => {
(0, address_1.mac)((err, addr) => {
if (err)
reject(err);
else
resolve(addr);
});
});
},
dns: async () => {
return new Promise((resolve, reject) => {
(0, address_1.dns)((err, addr) => {
if (err)
reject(err);
else
resolve(addr);
});
});
},
address: address_1.address
};
}
return global.address;
}
static decimalChange(num, to, from = 10, sequential = false) {
if (to > 62 || from > 62) {
throw new Error('decimal only support [2~62]');
}
const str = sequential ? ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
: ['k', 'T', '2', 'K', 'S', 'i', 'z', '5', 'g', 'b', 'A', '9', 'o', 'q', 'M', 'd', 'N', 'B', 'Y', 'I', 'W', '4', '3', 'p', '7', 'w', 'E', 'x', 'c', 'P', 'r', 'u', 'v', 'l', 'L', 'J', 'Z', 'F', 'f', '6', '8', 'X', 'Q', 's', 'D', 'y', 'O', 't', 'e', 'R', 'G', '1', 'a', 'C', 'j', 'n', 'V', '0', 'H', 'h', 'm', 'U'];
let ten = [];
let ns = num.toString();
const convert = (num, from) => {
let fromString = num.toString();
let sum = 0n;
for (let i = 0; i < fromString.length; i++) {
let idx = str.indexOf(fromString[i]);
if (idx === -1) {
throw new Error('Unsupport decimal');
}
sum += BigInt(idx * Math.pow(from, fromString.length - 1 - i));
}
return sum;
};
const compute = (num, to, arr) => {
if (to === 10) {
return num;
}
let mod = BigInt(num) % BigInt(to);
arr.push(str[mod]);
let sur = BigInt(num) / BigInt(to);
if (sur === 0n)
return arr;
if (sur >= to) {
compute(sur, to, arr);
}
else {
arr.push(str[sur]);
}
};
let arr = [];
let tt = num;
if (from !== 10) {
tt = convert(num, from);
}
if (to === 10) {
return tt.toString();
}
compute(tt, to, arr);
arr.reverse();
return arr.join('');
}
static file = file_1.default;
static cmd = cmd_1.default;
static assert = assert_1.default;
static snowflake = Snowflake_1.default;
static Duration = Duration_1.default;
static equals(a, b) {
if (typeof a === typeof b) {
return a === b;
}
return a == b;
}
static nonEquals(a, b) {
return !Util.equals(a, b);
}
static isUndefined(val) {
return val === undefined;
}
static isNull(val) {
return val === null;
}
static id2string(id) {
if (typeof id !== 'number')
return;
let character = Util.decimalChange(id, 16, 10, true);
let md5 = Util.md5.encode(id.toString());
return 'ad' + character +
md5.substring(character.length + 2, md5.length - 1) +
Util.decimalChange(character.length - 1, 16, 10, true);
}
static string2id(idString) {
if (typeof idString !== 'string' || idString.length !== 32 || !idString.startsWith('ad')) {
return NaN;
}
try {
let len = parseInt(idString.charAt(31), 16) + 1;
let str = idString.substring(2, 2 + len);
return parseInt(Util.decimalChange(str, 10, 16, true));
}
catch (err) {
console.log(err);
return NaN;
}
}
static async sleep(millisecond) {
return new Promise(resolve => {
setTimeout(() => {
resolve(true);
}, millisecond);
});
}
static compare(obj1, obj2, compare) {
return (typeof compare === 'string' && obj1[compare] === obj2) || (typeof compare === 'function' && compare(obj1, obj2));
}
static assigner = new assign_js_1.default({
recursive: true
});
static assign(source, target) {
return Util.assigner.assign(source, target);
}
static copyObject(source) {
return Util.assigner.cloneObject(source);
}
static parseMethodParams = method => {
let paramString = method.valueOf().toString();
let params = paramString.substring(paramString.indexOf("(") + 1, paramString.indexOf(")"));
return params.split(",").map(item => {
let argName = item.trim();
if (/_ref[0-9]*/.test(argName)) {
return '_body';
}
return argName;
});
};
}
exports.default = Util;
interface String {
capitalize(): string;
uncapitalize(): string;
column2field(): string;
field2column(): string;
random(len: number): string;
}
interface Func<T> {
(t: T, index: number, array: T[]): T[];
}
interface Key<T> {
(val: T, index: number, array: T[]): string;
}
interface Value<T> {
(val: T, index: number, array: T[]): any;
}
interface Compare<T> {
(v1: T, v2: T): boolean;
}
interface Array<T> {
shuffle(): this;
random(size: number): Array<T>;
randomExtract(): T;
map2obj(key: keyof T | Key<T>, value?: string | Value<T>): Object;
mapping(key: keyof T): Map<T[keyof T], T>;
mapping<V>(key: keyof T, value: (t: T, key: any, array: Array<T>) => V): Map<T[keyof T], V>;
mapping<K>(key: (t: T, index: number, array: Array<T>) => K): Map<K, T>;
mapping<K, V>(key: (t: T, index: number, array: Array<T>) => K, value: (t: T, key: any, array: Array<T>) => V): Map<K, V>;
mapping<K, V>(key: keyof T | ((t: T, index: number, array: Array<T>) => K), value?: (t: T, key: any, array: Array<T>) => V): Map<T[keyof T] | K, T | V>;
group<K>(key: keyof T): Map<K, Array<T>>;
group<V>(key: keyof T, value: (t: T, key: any, array: Array<T>) => V): Map<T[keyof T], Array<V>>;
group<K, V>(key: ((t: T, index: number, array: Array<T>) => K)): Map<K, Array<T>>;
group<K, V>(key: ((t: T, index: number, array: Array<T>) => K), value: (t: T, key: any, array: Array<T>) => V): Map<K, Array<V>>;
group<K, V>(key: keyof T | ((t: T, index: number, array: Array<T>) => any), value?: (t: T, key: any, array: Array<T>) => V): Map<K, Array<T | V>>;
sum(prop?: keyof T | ((value: T) => number)): number;
max(prop?: keyof T | ((val: T) => number)): number;
min(prop?: keyof T | ((val: T) => number)): number;
average(prop?: keyof T | ((val: T) => number)): number;
getIndex(item: T, compare?: string | Compare<T>): Number;
distinct(prop?: keyof T | ((val: T) => any)): Array<T>;
duplication(prop?: keyof T | ((val: T) => any)): Array<T>;
intersection(array: any[], prop?: keyof T | ((val: T) => any)): Array<T>;
union(array: any[], prop?: keyof T | ((val: T) => any)): Array<T>;
difference(array: any[], prop?: keyof T | ((val: T) => any)): Array<T>;
remove(...items: T[]): T[];
}
interface Math {
add(a: number, b: number): number;
sub(a: number, b: number): number;
multiply(a: number, b: number): number;
divide(a: number, b: number): number;
}
interface Number {
toChines(): string;
}
interface Date {
format(fmt: string): string;
}
interface JSON2 {
parse(json: string): any;
stringify(obj: any): string;
}
declare const convert: <T>(prop?: keyof T | ((val: T) => any)) => (e: T) => any;
declare const getDecimalsPlace: (num: string) => number;
global.JSON2 = {
parse: (json) => {
if (typeof json === 'string') {
return JSON.parse(json);
}
return json;
},
stringify: (obj) => {
if (!obj)
return obj;
return JSON.stringify(obj);
}
};
String.prototype.capitalize = function () {
return this.replace(/(\w)/, function (v) {
return v.toUpperCase();
});
};
String.prototype.uncapitalize = function () {
return this.replace(/(\w)/, function (v) {
return v.toLowerCase();
});
};
String.prototype.column2field = function () {
return this.toLocaleLowerCase().replace(/[_][a-z]/g, function (c) {
return c.charAt(1).toUpperCase();
});
};
String.prototype.field2column = function () {
return this.replace(/([A-Z])/g, function (c) {
return "_" + c;
}).toUpperCase();
};
String.prototype.random = function (len) {
if (len <= 0)
return this;
return this.split("").random(len).join("");
};
Array.prototype.shuffle = function () {
this.sort(function (a, b) {
return Math.random() > 0.5 ? -1 : 1;
});
return this;
};
Array.prototype.randomExtract = function () {
if (!this.length)
return void 0;
let index = Math.round(Math.random() * (this.length - 1));
return this[index];
};
Array.prototype.random = function (size) {
if (!size || this.length < size)
return this.shuffle();
let index = 0, arr = [], len = this.length, rs = [];
arr.push.apply(arr, this);
if (len / size > 2) {
while (rs.length < size) {
rs.push(arr.shuffle().pop());
}
return rs;
}
else {
while (arr.length > size) {
arr.shuffle().pop();
}
return arr;
}
};
Array.prototype.map2obj = function (key, value) {
let arr = this;
let obj = {};
this.forEach((val, index, arr) => {
let k;
if (typeof key === 'string') {
k = val[key];
}
else if (typeof key === 'function') {
k = key(val, index, arr);
}
if (!k)
return;
let v = val;
if (typeof value === 'string') {
v = val[value];
}
else if (typeof value === 'function') {
v = value(val, index, arr);
}
obj[k] = v;
});
return obj;
};
Array.prototype.mapping = function (key, value) {
if (!key)
throw new Error('Undefined group by field');
let mapping = new Map();
let valFn = value || (item => item);
this.forEach((item, index, array) => {
let uniqueKey;
if (typeof key === 'string') {
uniqueKey = item[key];
}
else if (typeof key === 'function') {
uniqueKey = key.call(this, item, index, array);
}
if (mapping.has(uniqueKey)) {
throw new Error(`${uniqueKey} duplicate error`);
}
mapping.set(uniqueKey, valFn(item, uniqueKey, this));
});
return mapping;
};
Array.prototype.group = function (prop, value) {
if (!prop)
throw new Error('Undefined group by field');
let group = new Map();
let valFn = value || ((item) => item);
this.forEach((item, index, array) => {
let uniqueKey;
if (typeof prop === 'string') {
uniqueKey = item[prop];
}
else if (typeof prop === 'function') {
uniqueKey = prop.call(this, item, index, array);
}
if (!group.has(uniqueKey)) {
group.set(uniqueKey, [valFn(item, uniqueKey, this)]);
}
else {
group.get(uniqueKey).push(valFn(item, uniqueKey, this));
}
});
return group;
};
Array.prototype.sum = function (prop) {
let sum = 0;
this.forEach((v) => {
let val = 0;
if (typeof prop === 'string') {
val += Number(v[prop]);
}
else if (typeof prop === 'function') {
val += prop(v);
}
else {
val += Number(v);
}
sum = Math.add(sum, val);
});
return sum;
};
Array.prototype.min = function (prop) {
let min = 0;
this.forEach((val) => {
if (typeof prop === 'string') {
min = Math.min(Number(val[prop]), min);
}
else if (typeof prop === 'function') {
min = Math.min(prop(val), min);
}
else {
min = Math.min(Number(val), min);
}
});
return min;
};
Array.prototype.max = function (prop) {
let max = 0;
this.forEach((val) => {
if (typeof prop === 'string') {
max = Math.max(Number(val[prop]), max);
}
else if (typeof prop === 'function') {
max = Math.max(prop(val), max);
}
else {
max = Math.max(Number(val), max);
}
});
return max;
};
Array.prototype.average = function (prop) {
return Math.divide(this.sum(prop), this.length);
};
Array.prototype.getIndex = function (item, compare) {
if (!compare)
return this.indexOf(item);
for (let i = 0; i < this.length; i++) {
if (typeof compare === 'string' && this[i][compare] === item[compare])
return i;
if (typeof compare === 'function' && compare(this[i], item))
return i;
}
return -1;
};
const convert = (prop) => {
return (e) => {
if (typeof prop === 'string') {
return e[prop];
}
else if (typeof prop === 'function') {
return prop(e);
}
return e;
};
};
Array.prototype.duplication = function (prop) {
return Array.from(new Set(prop ? this.map(convert(prop)) : this));
};
Array.prototype.distinct = function (prop) {
return Array.from(new Set(prop ? this.map(convert(prop)) : this));
};
Array.prototype.intersection = function (array, prop) {
const thisSet = new Set(this.map(convert(prop)));
const arraySet = new Set(array.map(convert(prop)));
let values = [];
thisSet.forEach(item => {
if (arraySet.has(item))
values.push(item);
});
return values;
};
Array.prototype.union = function (array, prop) {
const thisSet = new Set(this.map(convert(prop)));
const arraySet = new Set(array.map(convert(prop)));
return Array.from(thisSet).filter(e => !arraySet.has(e)).concat(Array.from(arraySet));
};
Array.prototype.difference = function (array, prop) {
const thisSet = new Set(this.map(convert(prop)));
const arraySet = new Set(array.map(convert(prop)));
return Array.from(thisSet).filter(e => !arraySet.has(e));
};
Array.prototype.remove = function (...items) {
return items.flatMap(item => {
let idx = this.indexOf(item);
if (idx === -1)
return [];
return this.splice(idx, 1);
});
};
Number.prototype.toChines = function () {
let changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
let unit = ['', '十', '百', '千', '万'];
let num = parseInt(this);
let getWan = (temp) => {
let strArr = temp.toString().split('').reverse();
let newNum = '';
let newArr = [];
strArr.forEach((item, index) => {
newArr.unshift(item === '0' ? changeNum[item] : changeNum[item] + unit[index]);
});
let numArr = [];
newArr.forEach((m, n) => {
if (m !== '零')
numArr.push(n);
});
if (newArr.length > 1) {
newArr.forEach((m, n) => {
if (newArr[newArr.length - 1] === '零') {
if (n <= numArr[numArr.length - 1]) {
newNum += m;
}
}
else {
newNum += m;
}
});
}
else {
newNum = newArr[0];
}
return newNum;
};
let overWan = Math.floor(num / 10000);
let label = num % 10000;
if (label.toString().length < 4) {
label = '0' + label;
}
return overWan ? getWan(overWan) + '万' + getWan(label) : getWan(num);
};
Date.prototype.format = function (fmt) {
let o = {
"M+": this.getMonth() + 1,
"d+": this.getDate(),
"h+": this.getHours(),
"H+": this.getHours(),
"m+": this.getMinutes(),
"s+": this.getSeconds(),
"q+": Math.floor((this.getMonth() + 3) / 3),
"S": this.getMilliseconds()
};
if (/(y+)/.test(fmt))
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (let k in o)
if (new RegExp("(" + k + ")").test(fmt))
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
};
const getDecimalsPlace = (num) => {
try {
return num.split(".")[1].length;
}
catch (e) {
return 0;
}
};
Math.multiply = (multiplier, multiplicand) => {
if (multiplier === 0 || multiplicand === 0)
return 0;
if (!multiplier || !multiplicand) {
return Infinity;
}
let c = 0, d = multiplier.toString(), e = multiplicand.toString();
c += getDecimalsPlace(d);
c += getDecimalsPlace(e);
return Number(d.replace(".", "")) * Number(e.replace(".", "")) / Math.pow(10, c);
};
Math.divide = (divisor, dividend) => {
if (divisor === 0)
return 0;
if (!divisor || !dividend) {
return Infinity;
}
let c, d, e = 0, f = 0;
e = getDecimalsPlace(divisor.toString());
f = getDecimalsPlace(dividend.toString());
return c = Number(divisor.toString().replace(".", "")),
d = Number(dividend.toString().replace(".", "")),
Math.multiply(c / d, Math.pow(10, f - e));
};
Math.add = function (addend, augend) {
let a = addend || 0;
let b = augend || 0;
let c = getDecimalsPlace(a.toString()), d = getDecimalsPlace(b.toString()), e = Math.pow(10, Math.max(c, d));
return (Math.multiply(a, e) + Math.multiply(b, e)) / e;
};
Math.sub = function (subtrahend, minuend) {
let a = subtrahend || 0;
let b = minuend || 0;
let c = getDecimalsPlace(a.toString()), d = getDecimalsPlace(b.toString()), e = Math.pow(10, Math.max(c, d));
return (Math.multiply(a, e) - Math.multiply(b, e)) / e;
};
export default class MultiMap {
readonly keys: any;
readonly values: any;
readonly sizes: any;
constructor();
put(key: any, element: any): void;
get(key: any): any;
forEach(callback?: (key: any, value: any) => void): void;
isEmpty(): boolean;
size(): any;
max(): any;
min(): any;
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class MultiMap {
keys;
values;
sizes;
constructor() {
this.keys = [];
this.values = [];
this.sizes = [];
}
put(key, element) {
let index = this.keys.indexOf(key);
if (index === -1) {
this.keys.push(key);
this.values.push([element]);
this.sizes.push(1);
}
else {
this.values[index].push(element);
this.sizes[index] += 1;
}
}
get(key) {
let idx = this.keys.indexOf(key);
if (idx === -1)
return;
return this.values[idx];
}
forEach(callback = (key, value) => { }) {
if (typeof callback !== 'function') {
throw new Error('Callback not function');
}
for (let i = 0; i < this.keys.length; i++) {
callback(this.keys[i], this.values[i]);
}
}
isEmpty() {
return !this.keys.length;
}
size() {
return this.keys.length;
}
max() {
let maxIndex = 0;
let max = 0;
this.sizes.map((size, index) => {
if (max < size) {
max = size;
maxIndex = index;
}
});
return this.keys[maxIndex];
}
min() {
let minIndex = 0;
let min = 0;
this.sizes.map((size, index) => {
if (min < size) {
min = size;
minIndex = index;
}
});
return this.keys[minIndex];
}
}
exports.default = MultiMap;
export default class Queue<T> {
private head;
private tail;
private _size;
constructor(_size: any);
enqueue(value: T): void;
dequeue(): T;
get size(): number;
clear(): void;
[Symbol.iterator](): Generator<T, void, unknown>;
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class Queue {
head;
tail;
_size;
constructor(_size) {
this.clear();
this.head = void 0;
this.tail = void 0;
this._size = 0;
}
enqueue(value) {
const node = { value };
if (this.head) {
this.tail.next = node;
this.tail = node;
}
else {
this.head = node;
this.tail = node;
}
this._size++;
}
dequeue() {
const current = this.head;
if (!current) {
return;
}
this.head = this.head.next;
this._size--;
return current.value;
}
get size() {
return this._size;
}
clear() {
this.head = undefined;
this.tail = undefined;
this._size = 0;
}
*[Symbol.iterator]() {
let current = this.head;
while (current) {
yield current.value;
current = current.next;
}
}
}
exports.default = Queue;
export declare class Snowflake {
private readonly twepoch;
private readonly workerIdBits;
private readonly dataCenterIdBits;
private readonly maxWrokerId;
private readonly maxDataCenterId;
private readonly sequenceBits;
private readonly workerIdShift;
private readonly dataCenterIdShift;
private readonly timestampLeftShift;
private readonly sequenceMask;
private lastTimestamp;
private readonly workerId;
private readonly dataCenterId;
private sequence;
constructor(workerId?: bigint, dataCenterId?: bigint, sequence?: number);
nextId(): number;
}
declare const _default: {
code2id: (code: any) => bigint;
id2code: (id: any) => any;
nextId: () => number;
};
export default _default;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Snowflake = void 0;
const timeGen = () => BigInt(Date.now());
const tilNextMillis = lastTimestamp => {
let timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return BigInt(timestamp);
};
class Snowflake {
twepoch;
workerIdBits;
dataCenterIdBits;
maxWrokerId;
maxDataCenterId;
sequenceBits;
workerIdShift;
dataCenterIdShift;
timestampLeftShift;
sequenceMask;
lastTimestamp;
workerId;
dataCenterId;
sequence;
constructor(workerId = 1n, dataCenterId = 1n, sequence = 0) {
this.twepoch = 1288834974657n;
this.workerIdBits = 5n;
this.dataCenterIdBits = 5n;
this.maxWrokerId = -1n ^ (-1n << this.workerIdBits);
this.maxDataCenterId = -1n ^ (-1n << this.dataCenterIdBits);
this.sequenceBits = 12n;
this.workerIdShift = this.sequenceBits;
this.dataCenterIdShift = this.sequenceBits + this.workerIdBits;
this.timestampLeftShift = this.sequenceBits + this.workerIdBits + this.dataCenterIdBits;
this.sequenceMask = -1n ^ (-1n << this.sequenceBits);
this.lastTimestamp = -1n;
this.workerId = 1n;
this.dataCenterId = 1n;
this.sequence = 0n;
if (this.workerId > this.maxWrokerId || this.workerId < 0) {
throw new Error('_workerId must max than 0 and small than maxWrokerId-[' + this.maxWrokerId + ']');
}
if (this.dataCenterId > this.maxDataCenterId || this.dataCenterId < 0) {
throw new Error('_dataCenterId must max than 0 and small than maxDataCenterId-[' + this.maxDataCenterId + ']');
}
this.workerId = BigInt(workerId);
this.dataCenterId = BigInt(dataCenterId);
this.sequence = BigInt(sequence);
}
nextId() {
let timestamp = timeGen();
if (timestamp < this.lastTimestamp) {
throw new Error('Clock moved backwards. Refusing to generate id for ' +
(this.lastTimestamp - timestamp));
}
if (this.lastTimestamp === timestamp) {
this.sequence = (this.sequence + 1n) & this.sequenceMask;
if (this.sequence === 0n) {
timestamp = tilNextMillis(this.lastTimestamp);
}
}
else {
this.sequence = 0n;
}
this.lastTimestamp = timestamp;
return ((timestamp - this.twepoch) << this.timestampLeftShift) |
(this.dataCenterId << this.dataCenterIdShift) |
(this.workerId << this.workerIdShift) |
this.sequence;
}
;
}
exports.Snowflake = Snowflake;
const id2code = id => {
let str = id.toString();
let arr = str.match(/[0-9]{4}/g);
if (arr.length * 4 < str) {
arr.push(str.substring(arr.length * 4));
}
return arr.map(e => {
return parseInt(e).toString(36);
}).join('-');
};
const code2id = code => {
let arr = code.split('-');
let rs = arr.map(e => parseInt(e, 36)).join('');
return BigInt(rs);
};
let snowflake = new Snowflake();
exports.default = {
code2id,
id2code,
nextId: () => snowflake.nextId()
};
import Configuration from './conf';
import { ArrayCache } from './cache';
import { Logger, LoggerConfig } from "./logger";
import { NacosConfig } from "./conf/nacos";
import { AspectMatcher } from "./anno";
export declare class StartupListener {
startup(context: VWebApplicationContext): Promise<void>;
}
export default class VWebApplicationContext {
readonly components: {
indexes: {
nameIndex: ArrayCache;
typeIndex: ArrayCache;
};
warehouse: {
[key: string | symbol]: any;
};
modules: any;
events: Map<string, Array<{
name: string;
event: string;
executor: string;
}>>;
};
environment: Environment;
log4j: any;
readonly logger: Logger;
readonly channel: {
[key: string]: any;
};
userDir: string;
readonly timestamp: number;
readonly config: Configuration;
readonly aspects: Array<AspectMatcher>;
constructor(conf: string | Environment, active?: string);
initialize(): Promise<void>;
props(key?: string): any;
mount(target: string | (Module & {
props?: string;
}), config?: {}): void;
compile(...scripts: string[]): any[];
getComponent(nameOrAnnotationOrType: string | Function): any;
getComponentsBySuper<T>(superClass: new (...ars: any[]) => T): Array<T>;
getComponents(annotationOrType: Function): Array<any>;
getComponentsByType<T>(type: new (...ars: any[]) => T): Array<T>;
getComponentByType<T>(type: new (...ars: any[]) => T): T;
getComponentByName(name: string): any;
getComponentsByAnnotation(annotation: Function): Array<any>;
private lookup;
trusteeship(...types: any[]): Array<any>;
register({ name, type }: {
name: any;
type?: string;
}, component: any, overwrite?: boolean): any;
publishEvent(event: string | VWebEvent, data?: any): void;
launch(): Promise<this>;
shutdown(): Promise<void>;
static setRuntimeVariable<R>(variable: Record<string, any>, runnable: () => R): void;
static getRuntimeVariable(key?: string): any;
}
export type Active = 'dev' | 'development' | 'prod' | 'production' | 'test' | 'testing';
export declare interface App {
active?: Active;
includes?: string | string[];
}
export declare interface Config {
[name: string]: any;
}
export declare interface VWebConfig extends Config {
app?: App;
type?: 'file' | 'nacos' | 'proxy';
file?: string;
nacos?: NacosConfig;
proxy?: string;
src?: string;
include?: string | Array<string> | RegExp | Array<RegExp>;
exclude?: string | Array<string> | RegExp | Array<RegExp>;
workdir?: string;
}
export declare interface Environment extends Config {
app?: App;
config?: VWebConfig;
props?: Config;
logger?: LoggerConfig;
dependencies?: Array<string | Config>;
preloads?: Array<string>;
modules?: Config & {
require?: string;
};
}
export declare interface Module extends Config {
name: string;
launch: (this: VWebApplicationContext, config: Config) => Promise<any>;
conf?: string;
}
export declare const defineModule: (module: Module | ((this: VWebApplicationContext, config: Config) => Promise<any>)) => Module;
export declare interface VWebEvent {
event: string;
data?: any;
async?: boolean;
}
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.defineModule = exports.StartupListener = void 0;
const util_1 = __importDefault(require("./util"));
const conf_1 = __importDefault(require("./conf"));
const cache_1 = __importStar(require("./cache"));
const MultiMap_1 = __importDefault(require("./util/MultiMap"));
const logger_1 = __importDefault(require("./logger"));
const fs_1 = __importDefault(require("fs"));
const async_hooks_1 = require("async_hooks");
const asyncLocalStorage = new async_hooks_1.AsyncLocalStorage();
const path = require('path');
const loadModule = function (metadata, config) {
let { name, launch } = metadata;
name = name.replace(/[-][a-z]/g, a => a.substring(1).toUpperCase());
let module = launch.call(this, config);
if (module) {
let { components: { modules, indexes: { nameIndex } }, logger } = this;
nameIndex.set(name, 'module');
modules[name] = new Proxy(module, {
get(target, p, receiver) {
return module[p];
},
set(target, p, value, receiver) {
if (nameIndex.has(p)) {
logger.warn(`Property ${p} is a component property, you change it`);
}
return Reflect.set(target, p, value, receiver);
}
});
logger.info(`Load module ${name} success`);
}
};
const parsePattern = (pattern) => {
return (Array.isArray(pattern) ? pattern : [pattern]).map((item) => {
if (typeof item === 'string') {
let pattern = item.includes('*') ? item.split('.').join('[.]').split('*').join('.*') : item;
return new RegExp(pattern);
}
return item;
});
};
const loadComponentFromType = function (type, consume) {
let module = type;
if (module.prototype?.annotation?.component !== true) {
return [];
}
if (typeof type === 'function') {
try {
module = type.constructor ? Reflect.construct(type, [this]) : type(this);
}
catch (e) {
return [];
}
}
if (module.annotation?.conditional?.class?.call(module, this) === false) {
this.logger.warn(`Component ${module.annotation.name} not match conditional`);
return [];
}
return this.trusteeship(module).map((target) => {
const { annotation: { name, type } } = target;
consume?.call(target, name, type);
return target;
});
};
const loadComponentFromScript = function (scriptFile, consume) {
let module = require(scriptFile);
const components = [];
components.push(...loadComponentFromType.call(this, module, consume));
for (let key in module) {
components.push(...loadComponentFromType.call(this, module[key], consume));
}
return components;
};
const loadModules = function () {
let { config, modules, dependencies, preloads = [] } = this.environment;
let { src, exclude, include } = config;
let excludes = parsePattern(exclude);
let includes = parsePattern(include);
const map = new MultiMap_1.default();
util_1.default.file.listFilesSync(this.userDir + path.sep + src, (file) => {
const { name, path: filePath } = file;
if (name.startsWith('.'))
return false;
if (!excludes.length && !includes.length)
return true;
let relativePath = filePath.replace(this.userDir, '');
relativePath = relativePath.substring(relativePath.indexOf(src) + src.length);
if (excludes.some(exclude => exclude.test(relativePath)))
return false;
if (includes.some(include => include.test(relativePath)))
return true;
return !includes.length;
}).forEach(file => {
if (file.isDirectory)
return;
if (this.logger.isDebugEnabled()) {
this.logger.debug(`Load file ${file.name}`);
}
loadComponentFromScript.call(this, file.path, (name, type) => {
map.put(type, name);
});
});
map.forEach((type, components) => {
this.logger.info(`Load ${type} [${components.join(',')}]`);
});
dependencies.forEach((dependency) => {
let args = [];
if (typeof dependency === 'string') {
dependency = require(dependency);
}
else if (typeof dependency === 'object') {
let { name, props } = dependency;
dependency = require(name);
if (typeof props === 'string') {
props = this.props(props);
}
args.push(props);
}
else {
this.logger.error(`Error dependency define ${dependency} `);
return;
}
dependency = dependency.default || dependency;
let { launch, props, config } = dependency;
if (!launch) {
this.logger.error(`Launch not found, Dependency ${dependency}`);
return;
}
config && args.push(config);
props && args.push(this.props(props));
launch.apply(this, args);
});
Reflect.ownKeys(modules).sort((a, b) => {
return preloads.indexOf(a) - preloads.indexOf(b);
}).forEach((name) => {
let module = modules[name];
if (typeof module !== "function") {
try {
if (module.require) {
let requirePath = module.require;
if (!path.isAbsolute(requirePath)) {
requirePath = path.resolve(this.userDir, requirePath);
}
module = require(requirePath);
}
else {
module = require(`@nweb/${name}`);
}
module = module.default || module;
}
catch (e) {
this.logger.warn(`Ignore ${name} init, cause: ${e.message}`);
return;
}
}
let moduleDefine = {
name,
conf: name,
...(0, exports.defineModule)(module)
};
const config = modules[moduleDefine.conf] || modules[moduleDefine.name];
if (config === false) {
return;
}
loadModule.call(this, moduleDefine, config || {});
});
};
const createComponentProxy = function (component, define) {
let self = this;
let { logger } = self;
let { name, type } = define || component.annotation;
let cache = (0, cache_1.default)('type-wrapper');
let descriptor = cache.get(type) || component.annotation?.annType?.wrapper?.call(component);
const properties = {};
const resources = component.annotation?.resources || {};
Object.keys(resources).forEach(field => {
properties[field] = {
get: () => self.getComponentByName(resources[field])
};
});
const values = component.annotation?.values || {};
Object.keys(values).forEach(field => {
const { express, defaultValue } = values[field];
properties[field] = {
get: () => self.config.parse(express) || defaultValue
};
});
let props = component.annotation?.props || {};
Object.keys(props).forEach(field => {
const { propKeys, defaultValue } = props[field];
properties[field] = {
get: () => {
let propVal = self.config.props(propKeys);
if (propVal !== undefined) {
return propVal;
}
return self.props(propKeys) || defaultValue;
}
};
});
if (Object.keys(properties).length) {
Object.defineProperties(component, properties);
}
if (!descriptor) {
let expansion = {
LoggerFactory: self.log4j,
applicationContext: self,
};
descriptor = function (context, component) {
let getFun = void 0;
try {
let wrapper = (global.__vweb_wrappers || {})[type];
if (!wrapper) {
wrapper = require(`@nweb/${type}-wrapper`);
}
getFun = (wrapper.default || wrapper)?.(context, component)?.get;
logger.info(`Load @nweb/${type}-wrapper success`);
}
catch (e) {
if (e.code !== 'MODULE_NOT_FOUND') {
logger.error(e);
}
}
return {
get(target, p) {
let value = getFun?.(target, p) || target[p];
if (value !== undefined) {
if (typeof value === 'function') {
return new Proxy(value, {
async apply(method, thisArg, args) {
const [aspect] = self.aspects.filter(aspect => aspect.match(target, p));
let beforeReturn = await aspect?.before(target, p, args);
if (beforeReturn !== undefined) {
if (logger.isDebugEnabled()) {
logger.debug(`Component ${thisArg.annotation.name}#${p}(${(args || []).map((e, i) => `arg${i}`).join(', ')}) aspect before trigger`);
}
return beforeReturn;
}
const result = await method.apply(thisArg, args);
if (logger.isDebugEnabled()) {
logger.debug(`Component ${thisArg.annotation.name}#${p}(${(args || []).map((e, i) => `arg${i}`).join(', ')}) return ${result || 'void'}`);
}
if (aspect) {
logger.debug(`Component ${thisArg.annotation.name}#${p}(${(args || []).map((e, i) => `arg${i}`).join(', ')}) aspect after trigger`);
await aspect.after(target, p, args, result);
}
return result;
}
});
}
return value;
}
if (p === 'logger') {
return context.log4j.getLogger(component.constructor?.name || component.annotation?.name || 'default');
}
if (p in expansion) {
return expansion[p];
}
return context.getComponentByName(p);
}
};
};
cache.set(type, descriptor);
}
return new Proxy(component, descriptor(self, component));
};
class StartupListener {
async startup(context) {
throw new Error(`${this.constructor.name}#startup is not found`);
}
}
exports.StartupListener = StartupListener;
class VWebApplicationContext {
components;
environment;
log4j;
logger;
channel;
userDir;
timestamp;
config;
aspects = [];
constructor(conf, active) {
this.components = {
indexes: {
nameIndex: new cache_1.ArrayCache(),
typeIndex: new cache_1.ArrayCache()
},
warehouse: {},
modules: {},
events: new Map()
};
this.components.indexes.nameIndex.set('logger', 'module');
const log4j = require('./logger').default;
this.logger = log4j.getLogger(VWebApplicationContext);
this.timestamp = Date.now();
this.channel = {};
this.config = new conf_1.default(conf, active);
}
async initialize() {
this.environment = await this.config.getEnvironment();
this.userDir = this.environment.config?.workdir || path.resolve('.');
try {
require(this.userDir + path.sep + this.environment.config.src + '/js.extend.js');
}
catch (e) {
}
(0, logger_1.default)(this.environment.logger);
this.log4j = this.components.modules['logger'] = logger_1.default;
loadModules.call(this);
}
props(key) {
if (!key)
return this.environment.props;
let arr = key.split('.');
let val = this.environment.props[arr[0]];
for (let i = 1; i < arr.length; i++) {
let key = arr[i];
if (Array.isArray(val)) {
key = parseInt(key);
}
if (val === undefined) {
this.logger.error(new Error(`Get props ${key} error, because ${arr.slice(0, i)} not found`));
return;
}
val = val[key];
}
return val;
}
mount(target, config = {}) {
let module;
if (typeof target === 'string') {
module = require(target);
module = module.default || module;
}
else {
module = target;
}
config = { ...config, ...module.config };
if (typeof module.props === 'string') {
config = { ...config, ...this.props(module.props) };
}
loadModule.call(this, module, config);
}
compile(...scripts) {
const components = [];
for (let script of scripts) {
if (!fs_1.default.existsSync(script)) {
throw new Error(`${script} not exists`);
}
const files = util_1.default.file.listFilesSync(script, file => file.isFile());
for (let file of files) {
components.push(...loadComponentFromScript.call(this, file));
}
}
for (let component of components) {
for (let key in this.components.modules) {
this.components.modules[key]?.compile(component);
}
}
return components;
}
getComponent(nameOrAnnotationOrType) {
let components = this.lookup(nameOrAnnotationOrType);
if (typeof nameOrAnnotationOrType === 'string') {
return components[0];
}
return components;
}
getComponentsBySuper(superClass) {
return this.lookup(superClass);
}
getComponents(annotationOrType) {
return this.lookup(annotationOrType);
}
getComponentsByType(type) {
return this.lookup(type);
}
getComponentByType(type) {
let components = this.lookup(type);
let component = components.find(c => Boolean(c) && Boolean(c.annotation?.primary));
if (Boolean(component))
return component;
util_1.default.assert.isTrue(components.length <= 1, `Get component by type ${type.constructor?.name || ''} error, find ${components.length} components`);
return components[0];
}
getComponentByName(name) {
let components = this.lookup(name);
util_1.default.assert.isTrue(components.length <= 1, `Get component by name ${name} error, because more than one component found`);
return components[0];
}
getComponentsByAnnotation(annotation) {
return this.getComponents(annotation);
}
lookup(nameOrAnnotationOrType) {
let cache = (0, cache_1.default)('component-cache');
let key = `${nameOrAnnotationOrType}-${typeof nameOrAnnotationOrType === 'function'}`;
let components = cache.get(key);
if (!components) {
let { components: { warehouse, indexes, modules } } = this;
const getByName = name => {
let type = indexes.nameIndex.get(name);
return type === 'module' ? modules[name] : warehouse[name];
};
if (typeof nameOrAnnotationOrType === 'string') {
components = [getByName(nameOrAnnotationOrType)];
}
else {
if (nameOrAnnotationOrType.type) {
components = indexes.typeIndex.get(nameOrAnnotationOrType.type, false).map(getByName);
}
else {
components = [];
for (let key of Reflect.ownKeys(warehouse)) {
try {
if (warehouse[key] instanceof nameOrAnnotationOrType) {
components.push(warehouse[key]);
}
}
catch (e) {
this.logger.error(e);
}
}
}
}
components = components
.map(component => {
try {
if (component && component.annotation && component.annotation.prototype) {
return createComponentProxy.call(this, Reflect.construct(component.constructor, [this]));
}
else {
return component;
}
}
catch (e) {
return component;
}
});
cache.set(key, components);
}
return components;
}
trusteeship(...types) {
let components = [];
for (let i = 0; i < types.length; i++) {
let component = types[i];
if (!component)
continue;
try {
if (component instanceof Function) {
component = Reflect.construct(component, [this]);
}
else if (component.default instanceof Function) {
component = Reflect.construct(component.default, [this]);
}
}
catch (e) {
if (this.logger.isDebugEnabled()) {
this.logger.debug(e);
}
continue;
}
let annotation = component.annotation;
if (!annotation || !annotation.component)
continue;
if (annotation.aspect) {
for (let prop of Object.keys(annotation.aspect)) {
const aspectMatcher = annotation.aspect[prop];
aspectMatcher.bind(component);
this.aspects.push(aspectMatcher);
}
}
this.register(annotation, component);
components.push(component);
}
return components;
}
register({ name, type = 'normal' }, component, overwrite = false) {
(0, cache_1.default)('component-cache').clean();
let { components, logger, environment: { modules } } = this;
let { warehouse, indexes, events } = components;
if (indexes.nameIndex.has(name) && !overwrite) {
logger.warn(`${type} ${name} repeatable`);
return;
}
if (modules[name]) {
logger.warn(`${name} is module`);
return;
}
indexes.typeIndex.set(type, name);
indexes.nameIndex.set(name, 'component');
if (component.annotation?.events) {
Reflect.ownKeys(component.annotation.events).forEach((event) => {
if (!events.has(event)) {
events.set(event, []);
}
let executor = component.annotation.events[event];
events.get(event).push({
name,
event,
executor
});
});
}
return warehouse[name] = createComponentProxy.call(this, component, { name, type });
}
publishEvent(event, data) {
let evt;
if (typeof event === 'string') {
evt = { event, data };
}
else {
evt = event;
}
let listeners = this.components.events.get(evt.event);
if (!listeners) {
this.logger.warn(`Listener not found for the event <${evt.event}>`);
return;
}
const publish = () => {
for (let { name, executor } of listeners) {
for (let component of this.lookup(name)) {
try {
component[executor]?.(evt.data, evt);
}
catch (e) {
this.logger.error(`Event ${evt.event} trigger error`, e);
}
}
}
};
if (evt.async) {
setTimeout(publish, 0);
}
else {
publish();
}
}
async launch() {
const { warehouse, modules } = this.components;
await Promise.all(Reflect.ownKeys(modules).map(name => modules[name])
.sort((a, b) => (a.ordered || -1) - (b.ordered || -1))
.map(module => {
return (async () => {
try {
if (this.logger.isDebugEnabled() && module.startup) {
this.logger.debug(`Module ${module.name || module.constructor.name} startup`);
}
return module.startup?.call(module, this);
}
catch (e) {
this.logger.error(e);
}
})();
}));
let initStart = Date.now();
await Promise.all(Reflect.ownKeys(warehouse).flatMap(name => {
const component = warehouse[name];
let { configuration } = component.annotation || {};
if (configuration) {
let { beans = {} } = component.annotation || {};
return Object.keys(beans).filter(bean => {
const matches = component.annotation?.conditional?.methods?.[bean]?.call(component, this, bean) !== false;
if (!matches) {
this.logger.warn(`Component ${component.annotation.name}#${bean} not match conditional`);
}
return matches;
}).map(beanName => {
let method = beans[beanName];
return (async () => {
let beanObj = await component[method](this);
await this.register({ name: beanName, type: 'bean' }, beanObj);
})();
});
}
})).then(configurations => {
if (configurations.length) {
this.logger.info(`Configuration cost ${Date.now() - initStart} ms`);
}
});
initStart = Date.now();
await Promise.all(Reflect.ownKeys(warehouse).map(name => {
const component = warehouse[name];
let setup = component.annotation?.setup;
if (!setup)
return;
return component[setup]?.bind(component);
}).filter(setup => Boolean(setup))
.map(setup => {
return (async () => {
try {
return await setup();
}
catch (e) {
this.logger.error(e);
}
})();
})).then(res => {
if (res.length) {
this.logger.info(`Setup ready cost ${Date.now() - initStart} ms`);
}
});
initStart = Date.now();
await Promise.all(Reflect.ownKeys(warehouse).flatMap(name => {
const component = warehouse[name];
let { initializations } = component.annotation || {};
if (!initializations)
return;
return Reflect.ownKeys(initializations).filter(initial => {
const matches = component.annotation?.conditional?.methods?.[initial]?.call(component, this, initial) !== false;
if (!matches) {
this.logger.warn(`Component ${component.annotation.name}#${initial.toString()} not match conditional`);
}
return matches;
}).map(initialization => {
try {
return (async () => {
if (this.logger.isDebugEnabled()) {
this.logger.debug(`Do initialize ${name.toString()}#${initialization.toString()}`);
}
return await component[initialization](this);
})();
}
catch (e) {
this.logger.error(e);
}
});
})).then(initializations => {
if (initializations.length) {
this.logger.info(`Initialized cost ${Date.now() - initStart} ms`);
}
});
for (let listener of this.getComponentsByType(StartupListener)) {
try {
await listener.startup(this);
}
catch (e) {
this.logger.error(e);
}
}
this.logger.info(`Started VWeb App in ${Date.now() - this.timestamp} milliseconds`);
this.publishEvent({ event: 'startup' });
return this;
}
async shutdown() {
let { warehouse, modules } = this.components;
for (let prop in warehouse) {
await warehouse[prop]?.shutdown?.();
}
for (let prop in modules) {
await modules[prop]?.shutdown?.();
}
this.publishEvent({ event: 'shutdown' });
}
static setRuntimeVariable(variable, runnable) {
asyncLocalStorage.run(variable, () => runnable());
}
static getRuntimeVariable(key) {
let store = asyncLocalStorage.getStore();
return key ? store?.[key] : store;
}
}
exports.default = VWebApplicationContext;
const defineModule = (module) => {
if (typeof module === 'function') {
return {
name: '',
launch: module
};
}
return module;
};
exports.defineModule = defineModule;