@cabloy/utils 1.0.48 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2 @@
1
+ import { Environment } from '@marcbachmann/cel-js';
2
+ export declare const celEnvBase: Environment;
@@ -0,0 +1,4 @@
1
+ import type { Environment, ParseResult } from '@marcbachmann/cel-js';
2
+ export declare function evaluateExpressions<T = any>(expressions: any, context?: object, celEnv?: Environment, dry?: boolean): T;
3
+ export declare function evaluate<T = any>(expression: string, context?: object, celEnv?: Environment): T;
4
+ export declare function parse(expression: string, celEnv?: Environment): ParseResult;
@@ -0,0 +1,4 @@
1
+ export * from './base.ts';
2
+ export * from './evaluate.ts';
3
+ export * from './types.ts';
4
+ export * from './utils.ts';
@@ -0,0 +1,5 @@
1
+ export declare function regexp(str: string): string;
2
+ export declare function cel(str: string): string;
3
+ export declare function raw(str: string): string;
4
+ export declare function createFunction(expression: string, scopeKeys?: string[]): Function;
5
+ export declare function evaluateSimple(expression: string, scope?: object): any;
package/dist/index.d.ts CHANGED
@@ -1,8 +1,7 @@
1
- export * from './cel.ts';
1
+ export * from './celjs/index.ts';
2
2
  export * from './check.ts';
3
3
  export * from './hash.ts';
4
4
  export * from './match.ts';
5
- export * from './types.ts';
6
5
  export * from './utils.ts';
7
6
  export * from './vona.ts';
8
7
  export * from './zod.ts';
package/dist/index.js CHANGED
@@ -1,8 +1,428 @@
1
- export * from "./cel.js";
2
- export * from "./check.js";
3
- export * from "./hash.js";
4
- export * from "./match.js";
5
- export * from "./types.js";
6
- export * from "./utils.js";
7
- export * from "./vona.js";
8
- export * from "./zod.js";
1
+ import { Environment } from '@marcbachmann/cel-js';
2
+ import objectHash from 'object-hash';
3
+ import { toLowerCaseFirstChar, stringToCapitalize } from '@cabloy/word-utils';
4
+
5
+ const isUndefined = obj => typeof obj === 'undefined';
6
+ const isNil = val => isUndefined(val) || val === null;
7
+ const isObject = fn => !isNil(fn) && typeof fn === 'object';
8
+ function isEmptyObject(obj) {
9
+ if (!obj) return true;
10
+ return Object.keys(obj).length === 0;
11
+ }
12
+ function isPlainObject(fn) {
13
+ if (!isObject(fn)) {
14
+ return false;
15
+ }
16
+ const proto = Object.getPrototypeOf(fn);
17
+ if (proto === null) {
18
+ return true;
19
+ }
20
+ const ctor = Object.prototype.hasOwnProperty.call(proto, 'constructor') && proto.constructor;
21
+ return typeof ctor === 'function' && ctor instanceof ctor && Function.prototype.toString.call(ctor) === Function.prototype.toString.call(Object);
22
+ }
23
+ function addLeadingSlash(path) {
24
+ return path && typeof path === 'string' ? path.charAt(0) !== '/' ? `/${path}` : path : '';
25
+ }
26
+ function normalizePath(path) {
27
+ return path ? path.startsWith('/') ? `/${path.replace(/\/+$/, '')}`.replace(/\/+/g, '/') : `/${path.replace(/\/+$/, '')}` : '/';
28
+ }
29
+ const stripEndSlash = path => path[path.length - 1] === '/' ? path.slice(0, path.length - 1) : path;
30
+ const isFunction = val => typeof val === 'function';
31
+ const isString = val => typeof val === 'string';
32
+ const isNumber = val => typeof val === 'number';
33
+ const isConstructor = val => val === 'constructor';
34
+ const isEmpty = array => !(array && array.length > 0);
35
+ const isSymbol = val => typeof val === 'symbol';
36
+ function isClass(fn) {
37
+ return typeof fn === 'function' && !!fn.name && fn.prototype?.constructor === fn;
38
+ }
39
+ function isClassStrict(fn) {
40
+ return typeof fn === 'function' && /^class(?:\s|\{)/.test(fn.toString());
41
+ }
42
+ function isPromise(obj) {
43
+ return obj instanceof Promise || obj && typeof obj.then === 'function';
44
+ }
45
+ function isNilOrEmptyString(str) {
46
+ return str === undefined || str === null || str === '';
47
+ }
48
+ function checkMeta(meta, data) {
49
+ // check none
50
+ if (!meta) return true;
51
+ // loop
52
+ for (const key in meta) {
53
+ const metaItem = meta[key];
54
+ if (isNil(metaItem)) continue;
55
+ if (!Array.isArray(metaItem) && metaItem !== data?.[key]) return false;
56
+ if (Array.isArray(metaItem) && !metaItem.includes(data?.[key])) return false;
57
+ }
58
+ // default
59
+ return true;
60
+ }
61
+ function safeBoolean(value) {
62
+ if (isNil(value) || value === 'false' || value === '0') return false;
63
+ return Boolean(value);
64
+ }
65
+
66
+ function deprecated(oldUsage, newUsage) {
67
+ const message = '`'.concat(oldUsage, '` is deprecated and will be removed in a later version. Use `').concat(newUsage, '` instead');
68
+ console.warn(message);
69
+ }
70
+ async function catchError(fnMethod) {
71
+ let error;
72
+ let data;
73
+ try {
74
+ data = await fnMethod();
75
+ } catch (err) {
76
+ error = err;
77
+ }
78
+ return error ? [undefined, error] : [data, undefined];
79
+ }
80
+ function catchErrorSync(fnMethod) {
81
+ let error;
82
+ let data;
83
+ try {
84
+ data = fnMethod();
85
+ } catch (err) {
86
+ error = err;
87
+ }
88
+ return error ? [undefined, error] : [data, undefined];
89
+ }
90
+ async function sleep(ms) {
91
+ return new Promise(resolve => setTimeout(resolve, ms));
92
+ }
93
+ function replaceTemplate(content, scope) {
94
+ if (!content) return content;
95
+ return content.toString().replace(/(\\)?\{\{ *([\w.]+) *\}\}/g, (block, skip, key) => {
96
+ if (skip) {
97
+ return block.substring(skip.length);
98
+ }
99
+ const value = getProperty(scope, key);
100
+ return value !== undefined ? value : '';
101
+ });
102
+ }
103
+ function setProperty(obj, name, value) {
104
+ const names = name.split('.');
105
+ if (names.length === 1) {
106
+ obj[name] = value;
107
+ } else {
108
+ for (let i = 0; i < names.length - 1; i++) {
109
+ const _obj = obj[names[i]];
110
+ if (_obj) {
111
+ obj = _obj;
112
+ } else {
113
+ obj = obj[names[i]] = {};
114
+ }
115
+ }
116
+ obj[names[names.length - 1]] = value;
117
+ }
118
+ }
119
+ function getProperty(obj, name, sep) {
120
+ return _getProperty(obj, name, sep, false);
121
+ }
122
+ function getPropertyObject(obj, name, sep) {
123
+ return _getProperty(obj, name, sep, true);
124
+ }
125
+ const __keysIgnore = ['constructor', 'prototype', '__proto__'];
126
+ function _getProperty(_obj, name, sep, forceObject) {
127
+ if (!_obj) return undefined;
128
+ let obj = _obj;
129
+ const names = name.split(sep || '.');
130
+ // loop
131
+ for (const _name of names) {
132
+ const [name, index] = _parsePropertyKey(_name);
133
+ if (__keysIgnore.includes(name)) throw new Error(`invalid prop: ${name}`);
134
+ if (obj[name] === undefined) {
135
+ // not check obj[name] === null
136
+ if (forceObject) {
137
+ if (index === undefined) {
138
+ obj[name] = {};
139
+ } else {
140
+ obj[name] = [];
141
+ }
142
+ } else {
143
+ obj = obj[name];
144
+ break;
145
+ }
146
+ }
147
+ obj = obj[name];
148
+ if (index !== undefined) {
149
+ obj = obj[index];
150
+ }
151
+ }
152
+ return obj;
153
+ }
154
+ function _parsePropertyKey(name) {
155
+ const matched = name.match(/([^[]+)\[(\d+)\]/);
156
+ if (!matched) return [name, undefined];
157
+ return [matched[1], Number.parseInt(matched[2])];
158
+ }
159
+ function getRandomInt(size, start = 0) {
160
+ return Math.floor(Math.random() * size) + start;
161
+ }
162
+ function combineParamsAndQuery(path, options) {
163
+ return combineQueries(defaultPathSerializer(path, options?.params), options?.query);
164
+ }
165
+ function combineQueries(pagePath, queries) {
166
+ pagePath = pagePath ?? '/';
167
+ //
168
+ if (!queries) return pagePath;
169
+ //
170
+ const query2 = [];
171
+ const parts = [];
172
+ if (queries) {
173
+ for (const key in queries) {
174
+ const value = queries[key];
175
+ if (isNil(value)) continue;
176
+ if (typeof value === 'object') {
177
+ query2.push([key, value]);
178
+ } else {
179
+ parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
180
+ }
181
+ }
182
+ }
183
+ // query2
184
+ for (const [key, value] of query2) {
185
+ parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(JSON.stringify(value))}`);
186
+ }
187
+ if (parts.length === 0) return pagePath;
188
+ //
189
+ const str = parts.join('&');
190
+ //
191
+ const pos = pagePath.indexOf('?');
192
+ if (pos === -1) return `${pagePath}?${str}`;
193
+ if (pos === pagePath.length - 1) return `${pagePath}${str}`;
194
+ return `${pagePath}&${str}`;
195
+ }
196
+ const PATH_PARAM_RE = /\{([^{}/]+)\}/g;
197
+ const PATH_PARAM_RE2 = /:([^/]+)/g;
198
+ function defaultPathSerializer(pathName, pathParams) {
199
+ pathParams = pathParams ?? {};
200
+ for (const item of [PATH_PARAM_RE, PATH_PARAM_RE2]) {
201
+ pathName = pathName.replace(item, (_, _part) => {
202
+ if (_part.includes('?')) _part = _part.substring(0, _part.length - 1);
203
+ const value = pathParams?.[_part];
204
+ if (value === undefined || value === null) return '';
205
+ if (typeof value === 'object') return encodeURIComponent(JSON.stringify(value));
206
+ return encodeURIComponent(value);
207
+ });
208
+ }
209
+ return pathName;
210
+ }
211
+ function ensureArray(arr, sep) {
212
+ if (arr === undefined || arr === null) return undefined;
213
+ if (arr === '') return [];
214
+ if (Array.isArray(arr)) return arr;
215
+ if (typeof arr === 'string' && sep !== null) return arr.split(sep ?? ',');
216
+ return [arr];
217
+ }
218
+ function stringLazy(fn) {
219
+ return {
220
+ toString: fn
221
+ };
222
+ }
223
+
224
+ const celEnvBase = new Environment({
225
+ unlistedVariablesAreDyn: true,
226
+ enableOptionalTypes: true,
227
+ homogeneousAggregateLiterals: false
228
+ });
229
+ const params = [];
230
+ for (let i = 0; i < 10; i++) {
231
+ params.push('dyn');
232
+ celEnvBase.registerFunction(`concat(${params.join(',')}):list`, _concat);
233
+ }
234
+ celEnvBase.registerFunction('join(list):string', list => {
235
+ return _join(list);
236
+ });
237
+ celEnvBase.registerFunction('join(list,string):string', (list, sep) => {
238
+ return _join(list, sep);
239
+ });
240
+ celEnvBase.registerFunction('get(map,string):dyn', (obj, name) => {
241
+ return getProperty(obj, name);
242
+ });
243
+ celEnvBase.registerFunction('get(map,string,string):dyn', (obj, name, sep) => {
244
+ return getProperty(obj, name, sep);
245
+ });
246
+ celEnvBase.registerOperator('string + int', (str, n) => str + String(n));
247
+ celEnvBase.registerOperator('int + string', (n, str) => String(n) + str);
248
+ function _concat(...args) {
249
+ return [].concat(...args);
250
+ }
251
+ function _join(list, sep) {
252
+ if (!list) return '';
253
+ return list.join(sep);
254
+ }
255
+
256
+ const StringPrefixRegexp = 'regexp://';
257
+ const StringPrefixCel = 'cel://';
258
+ const StringPrefixRaw = 'raw://';
259
+
260
+ function regexp(str) {
261
+ return `${StringPrefixRegexp}${str}`;
262
+ }
263
+ function cel(str) {
264
+ return `${StringPrefixCel}${str}`;
265
+ }
266
+ function raw(str) {
267
+ return `${StringPrefixRaw}${str}`;
268
+ }
269
+ function createFunction(expression, scopeKeys) {
270
+ let fn;
271
+ try {
272
+ const js = `return (${expression})`;
273
+ fn = scopeKeys && scopeKeys.length > 0 ? new Function(scopeKeys.join(','), js) : new Function(js);
274
+ } catch (_err) {
275
+ fn = scopeKeys && scopeKeys.length > 0 ? new Function(scopeKeys.join(','), expression) : new Function(expression);
276
+ }
277
+ return fn;
278
+ }
279
+ function evaluateSimple(expression, scope) {
280
+ const scopeKeys = scope ? Object.keys(scope) : undefined;
281
+ const scopeValues = scope ? Object.values(scope) : undefined;
282
+ const fn = createFunction(expression, scopeKeys);
283
+ return scopeValues ? fn(...scopeValues) : fn();
284
+ }
285
+
286
+ function evaluateExpressions(expressions, context, celEnv, dry) {
287
+ if (isNil(expressions)) return _returnExpressionWithDry(expressions, dry);
288
+ if (Array.isArray(expressions)) {
289
+ return expressions.map(item => _evaluateExpressionInner(item, context, celEnv, dry));
290
+ } else if (typeof expressions === 'object') {
291
+ const res = {};
292
+ for (const key in expressions) {
293
+ res[key] = _evaluateExpressionInner(expressions[key], context, celEnv, dry);
294
+ }
295
+ return res;
296
+ }
297
+ // others
298
+ return _evaluateExpressionInner(expressions, context, celEnv, dry);
299
+ }
300
+ function _evaluateExpressionInner(expression, context, celEnv, dry) {
301
+ if (isNil(expression)) return _returnExpressionWithDry(expression, dry);
302
+ if (typeof expression === 'object') return evaluateExpressions(expression, context, celEnv, dry);
303
+ if (typeof expression !== 'string') return _returnExpressionWithDry(expression, dry);
304
+ if (!expression.startsWith(StringPrefixCel)) return _returnExpressionWithDry(expression, dry);
305
+ return dry ? true : evaluate(expression.substring(StringPrefixCel.length), context, celEnv);
306
+ }
307
+ function _returnExpressionWithDry(expression, dry) {
308
+ return dry ? false : expression;
309
+ }
310
+ function evaluate(expression, context, celEnv) {
311
+ if (expression.startsWith(StringPrefixRaw)) {
312
+ return expression.substring(StringPrefixRaw.length);
313
+ } else if (expression.startsWith(StringPrefixRegexp)) {
314
+ return evaluateSimple(expression.substring(StringPrefixRegexp.length));
315
+ }
316
+ return (celEnv ?? celEnvBase).evaluate(expression, context);
317
+ }
318
+ function parse(expression, celEnv) {
319
+ return (celEnv ?? celEnvBase).parse(expression);
320
+ }
321
+
322
+ function hashkey(key) {
323
+ if (key === undefined || key === null) {
324
+ return '';
325
+ }
326
+ if (Array.isArray(key) || typeof key === 'object') {
327
+ return objectHash(key, {
328
+ respectType: false
329
+ });
330
+ }
331
+ if (typeof key !== 'string') {
332
+ return String(key);
333
+ }
334
+ return key;
335
+ }
336
+
337
+ function matchSelector(match, selector, matchThis, ...matchArgs) {
338
+ if (!Array.isArray(match)) {
339
+ // prepare
340
+ if (typeof match === 'string' && match.startsWith(StringPrefixRegexp)) {
341
+ match = evaluateSimple(match.substring(StringPrefixRegexp.length));
342
+ }
343
+ return typeof match === 'string' && match.startsWith(StringPrefixCel) && !!evaluateExpressions(match, {
344
+ selector,
345
+ context: matchArgs[0] && typeof matchArgs[0] === 'object' ? {
346
+ ...matchArgs[0]
347
+ } : matchArgs[0]
348
+ }) || typeof match === 'string' && !match.startsWith(StringPrefixCel) && typeof selector === 'string' && match === selector || match instanceof RegExp && typeof selector === 'string' && match.test(selector) || typeof match === 'function' && match.call(matchThis, selector, ...matchArgs);
349
+ }
350
+ return match.some(item => matchSelector(item, selector));
351
+ }
352
+
353
+ function combineResourceNameParts(resourceName, moduleName, simplify, simplifyProviderId) {
354
+ simplify = simplify ?? true;
355
+ simplifyProviderId = simplifyProviderId ?? true;
356
+ if (!resourceName) resourceName = '';
357
+ // module path + arg
358
+ if (typeof moduleName !== 'string') moduleName = moduleName.relativeName;
359
+ const parts = moduleName.split('-');
360
+ // path
361
+ const res = [];
362
+ if (!simplifyProviderId || parts[0] !== 'a') res.push(parts[0]);
363
+ if (!simplify || !resourceName.startsWith(parts[1])) res.push(parts[1]);
364
+ if (resourceName) res.push(resourceName);
365
+ return res;
366
+ }
367
+ function combineResourceName(resourceName, moduleName, simplify, simplifyProviderId) {
368
+ const parts = combineResourceNameParts(resourceName, moduleName, simplify, simplifyProviderId);
369
+ return toLowerCaseFirstChar(stringToCapitalize(parts));
370
+ }
371
+ function combineApiPath(path, moduleName, prefix, simplify, globalPrefixConfig) {
372
+ const globalPrefix = typeof prefix === 'string' ? prefix : prefix === false ? '' : globalPrefixConfig;
373
+ simplify = simplify ?? true;
374
+ if (!path) path = '';
375
+ // ignore globalPrefix
376
+ if (path.startsWith('//')) return path.substring(1);
377
+ // ignore module path
378
+ if (path.startsWith('/')) return `${globalPrefix}${path}`;
379
+ // globalPrefix + module path + arg
380
+ const parts = combineResourceNameParts(path, moduleName ?? '', simplify, true);
381
+ return `${globalPrefix}/${parts.join('/')}`;
382
+ }
383
+ function combineApiPathControllerAndAction(moduleName, controllerPath, actionPath, prefix, simplify, globalPrefixConfig) {
384
+ if (actionPath === undefined) actionPath = '';
385
+ // routePath
386
+ let routePath;
387
+ if (typeof actionPath !== 'string') {
388
+ // regexp
389
+ throw new TypeError('regexp not supported');
390
+ } else if (actionPath.startsWith('/')) {
391
+ // absolute
392
+ routePath = combineApiPath(actionPath, moduleName, prefix, simplify, globalPrefixConfig);
393
+ } else {
394
+ // relative
395
+ if (!controllerPath) {
396
+ routePath = combineApiPath(actionPath, moduleName, prefix, simplify, globalPrefixConfig);
397
+ } else {
398
+ routePath = combineApiPath(controllerPath, moduleName, prefix, simplify, globalPrefixConfig);
399
+ if (actionPath) {
400
+ routePath = `${routePath}/${actionPath}`;
401
+ }
402
+ }
403
+ }
404
+ return routePath;
405
+ }
406
+ function combineApiPathControllerAndActionRaw(moduleName, controllerPath, actionPath, simplify) {
407
+ let apiPath = combineApiPathControllerAndAction(moduleName, controllerPath, actionPath, '/_api_', simplify);
408
+ if (typeof apiPath !== 'string') return apiPath;
409
+ if (apiPath.startsWith('/_api_')) {
410
+ apiPath = apiPath.substring('/_api_'.length);
411
+ } else {
412
+ apiPath = `/${apiPath}`;
413
+ }
414
+ return apiPath;
415
+ }
416
+
417
+ function zodCustomError(path, message) {
418
+ const error = new Error();
419
+ error.code = 422;
420
+ error.message = [{
421
+ code: 'custom',
422
+ path,
423
+ message
424
+ }];
425
+ return error;
426
+ }
427
+
428
+ export { StringPrefixCel, StringPrefixRaw, StringPrefixRegexp, addLeadingSlash, catchError, catchErrorSync, cel, celEnvBase, checkMeta, combineApiPath, combineApiPathControllerAndAction, combineApiPathControllerAndActionRaw, combineParamsAndQuery, combineQueries, combineResourceName, combineResourceNameParts, createFunction, defaultPathSerializer, deprecated, ensureArray, evaluate, evaluateExpressions, evaluateSimple, getProperty, getPropertyObject, getRandomInt, hashkey, isClass, isClassStrict, isConstructor, isEmpty, isEmptyObject, isFunction, isNil, isNilOrEmptyString, isNumber, isObject, isPlainObject, isPromise, isString, isSymbol, isUndefined, matchSelector, normalizePath, parse, raw, regexp, replaceTemplate, safeBoolean, setProperty, sleep, stringLazy, stripEndSlash, zodCustomError };
package/dist/utils.d.ts CHANGED
@@ -6,8 +6,6 @@ export declare function replaceTemplate(content: string, scope: object): string;
6
6
  export declare function setProperty<T>(obj: object, name: string, value: T): void;
7
7
  export declare function getProperty<T>(obj: object | undefined, name: string, sep?: string): T | undefined;
8
8
  export declare function getPropertyObject<T>(obj: object | undefined, name: string, sep?: string): T | undefined;
9
- export declare function createFunction(expression: string, scopeKeys?: string[]): Function;
10
- export declare function evaluateSimple(expression: string, scope?: object): any;
11
9
  export declare function getRandomInt(size: number, start?: number): number;
12
10
  export declare function combineParamsAndQuery(path: string, options?: {
13
11
  params?: object;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@cabloy/utils",
3
3
  "type": "module",
4
- "version": "1.0.48",
4
+ "version": "2.0.1",
5
5
  "description": "cabloy utils",
6
6
  "publishConfig": {
7
7
  "access": "public"
@@ -25,16 +25,14 @@
25
25
  "dist"
26
26
  ],
27
27
  "dependencies": {
28
- "@cabloy/cel-js": "^0.7.4",
29
- "@cabloy/module-info": "^1.3.31",
28
+ "@cabloy/module-info": "^1.3.32",
30
29
  "@cabloy/word-utils": "^2.0.1",
31
- "chevrotain": "^11.0.3",
30
+ "@marcbachmann/cel-js": "^6.4.0",
32
31
  "object-hash": "^3.0.0"
33
32
  },
34
33
  "gitHead": "0eab9dc4a5622caffe89e7b1b3f02c08ccbc4c4b",
35
34
  "scripts": {
36
- "lint": "eslint .",
37
35
  "clean": "rimraf dist tsconfig.tsbuildinfo",
38
- "tsc:publish": "npm run clean && tsc"
36
+ "tsc:publish": "npm run clean && vona :bin:buildGeneral && tsc"
39
37
  }
40
38
  }
package/dist/cel.d.ts DELETED
@@ -1,5 +0,0 @@
1
- import type * as Celjs from '@cabloy/cel-js' with { 'resolution-mode': 'import' };
2
- import type { CstNode } from 'chevrotain';
3
- export declare function evaluateExpressions<T = any>(expressions: any, context?: object, functions?: Record<string, CallableFunction>, dry?: boolean): T;
4
- export declare function evaluate<T = any>(expression: CstNode | string, context?: object, functions?: Record<string, CallableFunction>): T;
5
- export declare function parse(expression: string): Celjs.ParseResult;
package/dist/cel.js DELETED
@@ -1,73 +0,0 @@
1
- import * as celjs from '@cabloy/cel-js';
2
- import { isNil } from "./check.js";
3
- import { hashkey } from "./hash.js";
4
- import { StringPrefixCel, StringPrefixRaw } from "./types.js";
5
- import { getProperty } from "./utils.js";
6
- export function evaluateExpressions(expressions, context, functions, dry) {
7
- if (isNil(expressions))
8
- return _returnExpressionWithDry(expressions, dry);
9
- if (Array.isArray(expressions)) {
10
- return expressions.map(item => _evaluateExpressionInner(item, context, functions, dry));
11
- }
12
- else if (typeof expressions === 'object') {
13
- const res = {};
14
- for (const key in expressions) {
15
- res[key] = _evaluateExpressionInner(expressions[key], context, functions, dry);
16
- }
17
- return res;
18
- }
19
- // others
20
- return _evaluateExpressionInner(expressions, context, functions, dry);
21
- }
22
- function _evaluateExpressionInner(expression, context, functions, dry) {
23
- if (isNil(expression))
24
- return _returnExpressionWithDry(expression, dry);
25
- if (typeof expression === 'object')
26
- return evaluateExpressions(expression, context, functions, dry);
27
- if (typeof expression !== 'string')
28
- return _returnExpressionWithDry(expression, dry);
29
- if (!expression.startsWith(StringPrefixCel))
30
- return _returnExpressionWithDry(expression, dry);
31
- return dry ? true : evaluate(expression.substring(StringPrefixCel.length), context, functions);
32
- }
33
- function _returnExpressionWithDry(expression, dry) {
34
- return dry ? false : expression;
35
- }
36
- export function evaluate(expression, context, functions) {
37
- // functions
38
- functions = _prepareFunctions(functions);
39
- // CstNode
40
- if (typeof expression === 'object' && expression.children) {
41
- return celjs.evaluate(expression, context, functions);
42
- }
43
- // string
44
- if (typeof expression === 'string') {
45
- if (expression.startsWith(StringPrefixRaw)) {
46
- return expression.substring(StringPrefixRaw.length);
47
- }
48
- return celjs.evaluate(expression, context, functions);
49
- }
50
- // others
51
- return expression;
52
- }
53
- export function parse(expression) {
54
- return celjs.parse(expression);
55
- }
56
- function _prepareFunctions(functions) {
57
- return Object.assign({
58
- concat: (...args) => {
59
- return [].concat(...args);
60
- },
61
- join: (arr, sep) => {
62
- if (!arr)
63
- return '';
64
- return arr.join(sep);
65
- },
66
- get: (obj, name, sep) => {
67
- return getProperty(obj, name, sep);
68
- },
69
- hashkey: (key) => {
70
- return hashkey(key);
71
- },
72
- }, functions);
73
- }
package/dist/check.js DELETED
@@ -1,72 +0,0 @@
1
- export const isUndefined = (obj) => typeof obj === 'undefined';
2
- export const isNil = (val) => isUndefined(val) || val === null;
3
- export const isObject = (fn) => !isNil(fn) && typeof fn === 'object';
4
- export function isEmptyObject(obj) {
5
- if (!obj)
6
- return true;
7
- return Object.keys(obj).length === 0;
8
- }
9
- export function isPlainObject(fn) {
10
- if (!isObject(fn)) {
11
- return false;
12
- }
13
- const proto = Object.getPrototypeOf(fn);
14
- if (proto === null) {
15
- return true;
16
- }
17
- const ctor = Object.prototype.hasOwnProperty.call(proto, 'constructor') && proto.constructor;
18
- return (typeof ctor === 'function' &&
19
- ctor instanceof ctor &&
20
- Function.prototype.toString.call(ctor) === Function.prototype.toString.call(Object));
21
- }
22
- export function addLeadingSlash(path) {
23
- return path && typeof path === 'string' ? (path.charAt(0) !== '/' ? `/${path}` : path) : '';
24
- }
25
- export function normalizePath(path) {
26
- return path
27
- ? path.startsWith('/')
28
- ? (`/${path.replace(/\/+$/, '')}`).replace(/\/+/g, '/')
29
- : `/${path.replace(/\/+$/, '')}`
30
- : '/';
31
- }
32
- export const stripEndSlash = (path) => (path[path.length - 1] === '/' ? path.slice(0, path.length - 1) : path);
33
- export const isFunction = (val) => typeof val === 'function';
34
- export const isString = (val) => typeof val === 'string';
35
- export const isNumber = (val) => typeof val === 'number';
36
- export const isConstructor = (val) => val === 'constructor';
37
- export const isEmpty = (array) => !(array && array.length > 0);
38
- export const isSymbol = (val) => typeof val === 'symbol';
39
- export function isClass(fn) {
40
- return typeof fn === 'function' && !!fn.name && fn.prototype?.constructor === fn;
41
- }
42
- export function isClassStrict(fn) {
43
- return typeof fn === 'function' && /^class(?:\s|\{)/.test(fn.toString());
44
- }
45
- export function isPromise(obj) {
46
- return obj instanceof Promise || (obj && typeof obj.then === 'function');
47
- }
48
- export function isNilOrEmptyString(str) {
49
- return str === undefined || str === null || str === '';
50
- }
51
- export function checkMeta(meta, data) {
52
- // check none
53
- if (!meta)
54
- return true;
55
- // loop
56
- for (const key in meta) {
57
- const metaItem = meta[key];
58
- if (isNil(metaItem))
59
- continue;
60
- if (!Array.isArray(metaItem) && metaItem !== data?.[key])
61
- return false;
62
- if (Array.isArray(metaItem) && !metaItem.includes(data?.[key]))
63
- return false;
64
- }
65
- // default
66
- return true;
67
- }
68
- export function safeBoolean(value) {
69
- if (isNil(value) || value === 'false' || value === '0')
70
- return false;
71
- return Boolean(value);
72
- }
package/dist/hash.js DELETED
@@ -1,13 +0,0 @@
1
- import objectHash from 'object-hash';
2
- export function hashkey(key) {
3
- if (key === undefined || key === null) {
4
- return '';
5
- }
6
- if (Array.isArray(key) || typeof key === 'object') {
7
- return objectHash(key, { respectType: false });
8
- }
9
- if (typeof key !== 'string') {
10
- return String(key);
11
- }
12
- return key;
13
- }
package/dist/match.js DELETED
@@ -1,16 +0,0 @@
1
- import { evaluateExpressions } from "./cel.js";
2
- import { StringPrefixCel, StringPrefixRegexp } from "./types.js";
3
- import { evaluateSimple } from "./utils.js";
4
- export function matchSelector(match, selector, matchThis, ...matchArgs) {
5
- if (!Array.isArray(match)) {
6
- // prepare
7
- if (typeof match === 'string' && match.startsWith(StringPrefixRegexp)) {
8
- match = evaluateSimple(match.substring(StringPrefixRegexp.length));
9
- }
10
- return ((typeof match === 'string' && match.startsWith(StringPrefixCel) && !!evaluateExpressions(match, { selector, context: matchArgs[0], args: matchArgs })) ||
11
- (typeof match === 'string' && !match.startsWith(StringPrefixCel) && typeof selector === 'string' && match === selector) ||
12
- (match instanceof RegExp && typeof selector === 'string' && match.test(selector)) ||
13
- (typeof match === 'function' && match.call(matchThis, selector, ...matchArgs)));
14
- }
15
- return match.some(item => matchSelector(item, selector));
16
- }
package/dist/types.js DELETED
@@ -1,3 +0,0 @@
1
- export const StringPrefixRegexp = 'regexp://';
2
- export const StringPrefixCel = 'cel://';
3
- export const StringPrefixRaw = 'raw://';
package/dist/utils.js DELETED
@@ -1,196 +0,0 @@
1
- export function deprecated(oldUsage, newUsage) {
2
- const message = '`'
3
- .concat(oldUsage, '` is deprecated and will be removed in a later version. Use `')
4
- .concat(newUsage, '` instead');
5
- console.warn(message);
6
- }
7
- export async function catchError(fnMethod) {
8
- let error;
9
- let data;
10
- try {
11
- data = await fnMethod();
12
- }
13
- catch (err) {
14
- error = err;
15
- }
16
- return error ? [undefined, error] : [data, undefined];
17
- }
18
- export function catchErrorSync(fnMethod) {
19
- let error;
20
- let data;
21
- try {
22
- data = fnMethod();
23
- }
24
- catch (err) {
25
- error = err;
26
- }
27
- return error ? [undefined, error] : [data, undefined];
28
- }
29
- export async function sleep(ms) {
30
- return new Promise(resolve => setTimeout(resolve, ms));
31
- }
32
- export function replaceTemplate(content, scope) {
33
- if (!content)
34
- return content;
35
- return content.toString().replace(/(\\)?\{\{ *([\w.]+) *\}\}/g, (block, skip, key) => {
36
- if (skip) {
37
- return block.substring(skip.length);
38
- }
39
- const value = getProperty(scope, key);
40
- return value !== undefined ? value : '';
41
- });
42
- }
43
- export function setProperty(obj, name, value) {
44
- const names = name.split('.');
45
- if (names.length === 1) {
46
- obj[name] = value;
47
- }
48
- else {
49
- for (let i = 0; i < names.length - 1; i++) {
50
- const _obj = obj[names[i]];
51
- if (_obj) {
52
- obj = _obj;
53
- }
54
- else {
55
- obj = obj[names[i]] = {};
56
- }
57
- }
58
- obj[names[names.length - 1]] = value;
59
- }
60
- }
61
- export function getProperty(obj, name, sep) {
62
- return _getProperty(obj, name, sep, false);
63
- }
64
- export function getPropertyObject(obj, name, sep) {
65
- return _getProperty(obj, name, sep, true);
66
- }
67
- const __keysIgnore = ['constructor', 'prototype', '__proto__'];
68
- function _getProperty(_obj, name, sep, forceObject) {
69
- if (!_obj)
70
- return undefined;
71
- let obj = _obj;
72
- const names = name.split(sep || '.');
73
- // loop
74
- for (const _name of names) {
75
- const [name, index] = _parsePropertyKey(_name);
76
- if (__keysIgnore.includes(name))
77
- throw new Error(`invalid prop: ${name}`);
78
- if (obj[name] === undefined) { // not check obj[name] === null
79
- if (forceObject) {
80
- if (index === undefined) {
81
- obj[name] = {};
82
- }
83
- else {
84
- obj[name] = [];
85
- }
86
- }
87
- else {
88
- obj = obj[name];
89
- break;
90
- }
91
- }
92
- obj = obj[name];
93
- if (index !== undefined) {
94
- obj = obj[index];
95
- }
96
- }
97
- return obj;
98
- }
99
- function _parsePropertyKey(name) {
100
- const matched = name.match((/([^[]+)\[(\d+)\]/));
101
- if (!matched)
102
- return [name, undefined];
103
- return [matched[1], Number.parseInt(matched[2])];
104
- }
105
- export function createFunction(expression, scopeKeys) {
106
- let fn;
107
- try {
108
- const js = `return (${expression})`;
109
- fn = scopeKeys && scopeKeys.length > 0 ? new Function(scopeKeys.join(','), js) : new Function(js);
110
- }
111
- catch (_err) {
112
- fn = scopeKeys && scopeKeys.length > 0 ? new Function(scopeKeys.join(','), expression) : new Function(expression);
113
- }
114
- return fn;
115
- }
116
- export function evaluateSimple(expression, scope) {
117
- const scopeKeys = scope ? Object.keys(scope) : undefined;
118
- const scopeValues = scope ? Object.values(scope) : undefined;
119
- const fn = createFunction(expression, scopeKeys);
120
- return scopeValues ? fn(...scopeValues) : fn();
121
- }
122
- export function getRandomInt(size, start = 0) {
123
- return Math.floor(Math.random() * size) + start;
124
- }
125
- export function combineParamsAndQuery(path, options) {
126
- return combineQueries(defaultPathSerializer(path, options?.params), options?.query);
127
- }
128
- export function combineQueries(pagePath, queries) {
129
- pagePath = pagePath ?? '/';
130
- //
131
- if (!queries)
132
- return pagePath;
133
- //
134
- const query2 = [];
135
- const parts = [];
136
- if (queries) {
137
- for (const key in queries) {
138
- const value = queries[key];
139
- if (value && typeof value === 'object') {
140
- query2.push([key, value]);
141
- }
142
- else {
143
- parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
144
- }
145
- }
146
- }
147
- // query2
148
- for (const [key, value] of query2) {
149
- parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(JSON.stringify(value))}`);
150
- }
151
- if (parts.length === 0)
152
- return pagePath;
153
- //
154
- const str = parts.join('&');
155
- //
156
- const pos = pagePath.indexOf('?');
157
- if (pos === -1)
158
- return `${pagePath}?${str}`;
159
- if (pos === pagePath.length - 1)
160
- return `${pagePath}${str}`;
161
- return `${pagePath}&${str}`;
162
- }
163
- const PATH_PARAM_RE = /\{([^{}/]+)\}/g;
164
- const PATH_PARAM_RE2 = /:([^/]+)/g;
165
- export function defaultPathSerializer(pathName, pathParams) {
166
- pathParams = pathParams ?? {};
167
- for (const item of [PATH_PARAM_RE, PATH_PARAM_RE2]) {
168
- pathName = pathName.replace(item, (_, _part) => {
169
- if (_part.includes('?'))
170
- _part = _part.substring(0, _part.length - 1);
171
- const value = pathParams?.[_part];
172
- if (value === undefined || value === null)
173
- return '';
174
- if (typeof value === 'object')
175
- return encodeURIComponent(JSON.stringify(value));
176
- return encodeURIComponent(value);
177
- });
178
- }
179
- return pathName;
180
- }
181
- export function ensureArray(arr, sep) {
182
- if (arr === undefined || arr === null)
183
- return undefined;
184
- if (arr === '')
185
- return [];
186
- if (Array.isArray(arr))
187
- return arr;
188
- if (typeof arr === 'string' && sep !== null)
189
- return arr.split(sep ?? ',');
190
- return [arr];
191
- }
192
- export function stringLazy(fn) {
193
- return {
194
- toString: fn,
195
- };
196
- }
package/dist/vona.js DELETED
@@ -1,78 +0,0 @@
1
- import { stringToCapitalize, toLowerCaseFirstChar } from '@cabloy/word-utils';
2
- export function combineResourceNameParts(resourceName, moduleName, simplify, simplifyProviderId) {
3
- simplify = simplify ?? true;
4
- simplifyProviderId = simplifyProviderId ?? true;
5
- if (!resourceName)
6
- resourceName = '';
7
- // module path + arg
8
- if (typeof moduleName !== 'string')
9
- moduleName = moduleName.relativeName;
10
- const parts = moduleName.split('-');
11
- // path
12
- const res = [];
13
- if (!simplifyProviderId || parts[0] !== 'a')
14
- res.push(parts[0]);
15
- if (!simplify || !resourceName.startsWith(parts[1]))
16
- res.push(parts[1]);
17
- if (resourceName)
18
- res.push(resourceName);
19
- return res;
20
- }
21
- export function combineResourceName(resourceName, moduleName, simplify, simplifyProviderId) {
22
- const parts = combineResourceNameParts(resourceName, moduleName, simplify, simplifyProviderId);
23
- return toLowerCaseFirstChar(stringToCapitalize(parts));
24
- }
25
- export function combineApiPath(path, moduleName, prefix, simplify, globalPrefixConfig) {
26
- const globalPrefix = typeof prefix === 'string' ? prefix : prefix === false ? '' : globalPrefixConfig;
27
- simplify = simplify ?? true;
28
- if (!path)
29
- path = '';
30
- // ignore globalPrefix
31
- if (path.startsWith('//'))
32
- return path.substring(1);
33
- // ignore module path
34
- if (path.startsWith('/'))
35
- return `${globalPrefix}${path}`;
36
- // globalPrefix + module path + arg
37
- const parts = combineResourceNameParts(path, moduleName ?? '', simplify, true);
38
- return `${globalPrefix}/${parts.join('/')}`;
39
- }
40
- export function combineApiPathControllerAndAction(moduleName, controllerPath, actionPath, prefix, simplify, globalPrefixConfig) {
41
- if (actionPath === undefined)
42
- actionPath = '';
43
- // routePath
44
- let routePath;
45
- if (typeof actionPath !== 'string') {
46
- // regexp
47
- throw new TypeError('regexp not supported');
48
- }
49
- else if (actionPath.startsWith('/')) {
50
- // absolute
51
- routePath = combineApiPath(actionPath, moduleName, prefix, simplify, globalPrefixConfig);
52
- }
53
- else {
54
- // relative
55
- if (!controllerPath) {
56
- routePath = combineApiPath(actionPath, moduleName, prefix, simplify, globalPrefixConfig);
57
- }
58
- else {
59
- routePath = combineApiPath(controllerPath, moduleName, prefix, simplify, globalPrefixConfig);
60
- if (actionPath) {
61
- routePath = `${routePath}/${actionPath}`;
62
- }
63
- }
64
- }
65
- return routePath;
66
- }
67
- export function combineApiPathControllerAndActionRaw(moduleName, controllerPath, actionPath, simplify) {
68
- let apiPath = combineApiPathControllerAndAction(moduleName, controllerPath, actionPath, '/_api_', simplify);
69
- if (typeof apiPath !== 'string')
70
- return apiPath;
71
- if (apiPath.startsWith('/_api_')) {
72
- apiPath = apiPath.substring('/_api_'.length);
73
- }
74
- else {
75
- apiPath = `/${apiPath}`;
76
- }
77
- return apiPath;
78
- }
package/dist/zod.js DELETED
@@ -1,12 +0,0 @@
1
- export function zodCustomError(path, message) {
2
- const error = new Error();
3
- error.code = 422;
4
- error.message = [
5
- {
6
- code: 'custom',
7
- path,
8
- message,
9
- },
10
- ];
11
- return error;
12
- }
File without changes