corebasic 1.0.212 → 1.0.214

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,297 @@
1
+ import * as ObjectId from './ObjectId.js';
2
+ import * as Mobile from './mobilecodes.js';
3
+ // Parse JSON file: fileToJson
4
+ import { readFile, writeFile } from 'fs/promises';
5
+ import 'jsonminify';
6
+ // S3 Object Storage
7
+ import { S3Client, ListBucketsCommand, ListObjectsV2Command, GetObjectCommand, PutObjectCommand, CreateBucketCommand, DeleteObjectCommand } from '@aws-sdk/client-s3';
8
+ import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
9
+ let bucketName = process.env.APP_DEPLOYMENT_NAME ?? ((global?.app?.name ?? "app") + '-dev');
10
+ let _ = (async () => { try {
11
+ const data = await S3.send(new CreateBucketCommand({ Bucket: bucketName }));
12
+ }
13
+ catch { } })(); // Create Bucket
14
+ export let pipeline = { execute: execute };
15
+ export function log(...args) {
16
+ let res = [];
17
+ args.forEach(arg => res.push(typeof arg === "object" ? JSON.stringify(arg, null, '\t') : arg));
18
+ console.log(...res);
19
+ }
20
+ export function uid() {
21
+ return ObjectId.ObjectId();
22
+ }
23
+ export function isEmpty(str) {
24
+ if (!str)
25
+ return true;
26
+ return str.match(/\S/) ? false : true; // matches a non space character
27
+ }
28
+ export let GLOBAL_META = { company: "GLOBAL", outlet: "GLOBAL" };
29
+ export function isEmptyJson(json) {
30
+ for (var i in json)
31
+ return false;
32
+ return true;
33
+ }
34
+ export function uniqueObjects(array, key) {
35
+ // remove duplicates from array of objects with key
36
+ return [
37
+ ...new Map(array.map(item => [item[key], item])).values()
38
+ ];
39
+ }
40
+ // --------------
41
+ // Parse Numbers
42
+ // --------------
43
+ export function parseFloatValue(val) {
44
+ return parseFloat(val) ? parseFloat(val) : 0;
45
+ }
46
+ export function parseIntValue(val) {
47
+ return parseInt(val) ? parseInt(val) : 0;
48
+ }
49
+ // ----------------
50
+ // Dates
51
+ // ----------------
52
+ export function now() {
53
+ return new Date();
54
+ }
55
+ export function toAppDate(date) {
56
+ if (Object.prototype.toString.call(date) === '[object String]')
57
+ date = new Date(date);
58
+ var temp = date;
59
+ if (isNaN(temp) || date === '')
60
+ return '';
61
+ var day = temp.getDate().toString();
62
+ if (day.length === 1)
63
+ day = "0" + day;
64
+ var month = (temp.getMonth() + 1).toString();
65
+ if (month.length == 1)
66
+ month = "0" + month;
67
+ return (day + "/" + month + "/" + temp.getFullYear().toString());
68
+ }
69
+ export function toDate(arg, currentTime) {
70
+ var st = arg.split('/');
71
+ var temp = new Date(st[2], parseInt(st[1]) - 1, st[0]);
72
+ temp.setHours(0);
73
+ temp.setMinutes(0);
74
+ temp.setSeconds(0);
75
+ temp.setMilliseconds(0);
76
+ if (currentTime) {
77
+ var curdate = getCurrentDate();
78
+ temp.setHours(curdate.getHours());
79
+ temp.setMinutes(curdate.getMinutes());
80
+ temp.setSeconds(curdate.getSeconds());
81
+ temp.setMilliseconds(curdate.getMilliseconds());
82
+ }
83
+ if (isNaN(temp))
84
+ return undefined;
85
+ return temp;
86
+ }
87
+ export function getDatesBetweenTwoDates(start, end) {
88
+ var arr = [];
89
+ var dt = new Date(start);
90
+ dt.setHours(0);
91
+ dt.setMinutes(0);
92
+ dt.setSeconds(0);
93
+ dt.setMilliseconds(0);
94
+ while (dt <= end) {
95
+ arr.push(new Date(dt));
96
+ dt.setDate(dt.getDate() + 1);
97
+ }
98
+ return arr;
99
+ }
100
+ export function deepCopy(obj) {
101
+ if (Object.prototype.toString.call(obj) === '[object Array]') {
102
+ var out = [], i = 0, len = obj.length;
103
+ for (; i < len; i++) {
104
+ if (Object.prototype.toString.call(obj[i]) === '[object Date]')
105
+ out[i] = new Date(obj[i]);
106
+ else
107
+ out[i] = arguments.callee(obj[i]);
108
+ }
109
+ return out;
110
+ }
111
+ if (typeof obj === 'object') {
112
+ var out = {}, i;
113
+ for (i in obj) {
114
+ if (Object.prototype.toString.call(obj[i]) === '[object Date]')
115
+ out[i] = new Date(obj[i]);
116
+ else
117
+ out[i] = arguments.callee(obj[i]);
118
+ }
119
+ return out;
120
+ }
121
+ return obj;
122
+ }
123
+ export function formatAMPM(date) {
124
+ var hours = date.getHours();
125
+ var minutes = date.getMinutes();
126
+ var ampm = hours >= 12 ? 'pm' : 'am';
127
+ hours = hours % 12;
128
+ hours = hours ? hours : 12; // the hour '0' should be '12'
129
+ minutes = minutes < 10 ? '0' + minutes : minutes;
130
+ var strTime = hours + ':' + minutes + ' ' + ampm;
131
+ return strTime;
132
+ }
133
+ export function sum(array) {
134
+ var res = 0;
135
+ for (var i in array)
136
+ res += parseFloat(array[i]) ? parseFloat(array[i]) : 0;
137
+ return res;
138
+ }
139
+ export function addMonths(date, monthsToAdd) {
140
+ const day = date.getDate();
141
+ date.setMonth(date.getMonth() + monthsToAdd);
142
+ // If the day rolled over, clamp to last day of target month
143
+ if (date.getDate() !== day) {
144
+ date.setDate(0);
145
+ }
146
+ return date;
147
+ }
148
+ export function addYears(date, yearsToAdd) {
149
+ return addMonths(date, yearsToAdd * 12);
150
+ }
151
+ export function addUTCMonths(date, monthsToAdd) {
152
+ const day = date.getUTCDate();
153
+ date.setUTCMonth(date.getUTCMonth() + monthsToAdd);
154
+ // If the day rolled over, clamp to last day of target month
155
+ if (date.getUTCDate() !== day) {
156
+ date.setUTCDate(0);
157
+ }
158
+ return date;
159
+ }
160
+ export function addUTCYears(date, yearsToAdd) {
161
+ return addUTCMonths(date, yearsToAdd * 12);
162
+ }
163
+ export function addDays(date, daysToAdd) {
164
+ date.setDate(date.getDate() + daysToAdd);
165
+ return date;
166
+ }
167
+ export function addHours(date, hoursToAdd) {
168
+ date.setHours(date.getHours() + hoursToAdd);
169
+ return date;
170
+ }
171
+ export function addUTCDays(date, daysToAdd) {
172
+ date.setUTCDate(date.getUTCDate() + daysToAdd);
173
+ return date;
174
+ }
175
+ export function addUTCHours(date, hoursToAdd) {
176
+ date.setUTCHours(date.getUTCHours() + hoursToAdd);
177
+ return date;
178
+ }
179
+ export function validityToMillisecs(start, validity) {
180
+ const now = new Date(start);
181
+ let [count, period] = validity.trim().split(' ').filter(item => item.trim());
182
+ count = parseIntValue(count);
183
+ period = period.toLowerCase();
184
+ const timeline = {
185
+ year: _ => addYears(now, count),
186
+ years: _ => addYears(now, count),
187
+ month: _ => addMonths(now, count),
188
+ months: _ => addMonths(now, count),
189
+ day: _ => now.setDate(now.getDate() + count),
190
+ days: _ => now.setDate(now.getDate() + count),
191
+ week: _ => now.setDate(now.getDate() + (count * 7)),
192
+ weeks: _ => now.setDate(now.getDate() + (count * 7)),
193
+ hour: _ => now.setHours(now.getHours() + count),
194
+ hours: _ => now.setHours(now.getHours() + count),
195
+ minute: _ => now.setMinutes(now.getMinutes() + count),
196
+ minutes: _ => now.setMinutes(now.getMinutes() + count),
197
+ };
198
+ timeline[period]();
199
+ return now.getTime();
200
+ }
201
+ export function validityToUTCMillisecs(start, validity) {
202
+ const now = new Date(start);
203
+ let [count, period] = validity.trim().split(' ').filter(item => item.trim());
204
+ count = parseIntValue(count);
205
+ period = period.toLowerCase();
206
+ const timeline = {
207
+ year: _ => addUTCYears(now, count),
208
+ years: _ => addUTCYears(now, count),
209
+ month: _ => addUTCMonths(now, count),
210
+ months: _ => addUTCMonths(now, count),
211
+ day: _ => now.setUTCDate(now.getUTCDate() + count),
212
+ days: _ => now.setUTCDate(now.getUTCDate() + count),
213
+ week: _ => now.setUTCDate(now.getUTCDate() + (count * 7)),
214
+ weeks: _ => now.setUTCDate(now.getUTCDate() + (count * 7)),
215
+ hour: _ => now.setUTCHours(now.getUTCHours() + count),
216
+ hours: _ => now.setUTCHours(now.getUTCHours() + count),
217
+ minute: _ => now.setUTCMinutes(now.getUTCMinutes() + count),
218
+ minutes: _ => now.setUTCMinutes(now.getUTCMinutes() + count),
219
+ };
220
+ timeline[period]();
221
+ return now.getTime();
222
+ }
223
+ // ----------------
224
+ // JSON
225
+ // ----------------
226
+ export async function fileToJson(path, file) {
227
+ let data = (await readFile(new URL(file, path).toString().replace('file://', ''), 'utf8'));
228
+ return JSON.parse(JSON.minify(data));
229
+ }
230
+ // ----------------
231
+ // File
232
+ // ----------------
233
+ export async function fileToString(file) {
234
+ return await readFile(file, 'utf8');
235
+ }
236
+ export async function stringToFile(file, data) {
237
+ return await writeFile(file, data);
238
+ }
239
+ // ----------------
240
+ // Pipeline Execute
241
+ // ----------------
242
+ function execute(pipeline, errfn) {
243
+ startPipeline(pipeline, 0, undefined, errfn);
244
+ }
245
+ function startPipeline(pipeline, index, data, errfn) {
246
+ index = index == undefined ? 0 : index;
247
+ if (index == pipeline.length)
248
+ return;
249
+ pipeline[index](data).then(data => startPipeline(pipeline, index + 1, data)).catch(err => { if (errfn)
250
+ errfn(err); });
251
+ }
252
+ // -----------------
253
+ // S3 Object Storage
254
+ // -----------------
255
+ export async function getUrl(path, expiry = 3600) {
256
+ return await getSignedUrl(S3, new GetObjectCommand({ Bucket: bucketName, Key: path }), { expiresIn: expiry });
257
+ }
258
+ export async function putUrl(path, expiry = 3600) {
259
+ return await getSignedUrl(S3, new PutObjectCommand({ Bucket: bucketName, Key: path }), { expiresIn: expiry });
260
+ }
261
+ // ---------------------------
262
+ // Express Middleware Exclude
263
+ // ---------------------------
264
+ export const excludeMiddleware = function (middleware, ...paths) {
265
+ return function (req, res, next) {
266
+ const pathCheck = paths.some(path => {
267
+ let url = req.path.split('/');
268
+ let cmp = path.split('/');
269
+ if (url.length !== cmp.length)
270
+ return false;
271
+ let f = cmp.map((p, index) => p.startsWith(":") ? url[index] : p).join('/');
272
+ return f === req.path;
273
+ });
274
+ pathCheck ? next() : middleware(req, res, next);
275
+ };
276
+ };
277
+ // --------------------
278
+ // Parse Mobile Number
279
+ // --------------------
280
+ export function parseMob(mob, code) {
281
+ code = code ?? "IN";
282
+ if (isEmpty(mob))
283
+ return mob;
284
+ if (mob.startsWith("MOB_"))
285
+ return mob;
286
+ mob = mob.trim().replace(/(,| |-|\+)/g, ''); // remove comma, space, hyphen and plus
287
+ mob = mob.startsWith("0") ? mob.replace(/^0*/, '') : mob; // remove starting n zeroes
288
+ let prefix = Mobile.codes[code].phone;
289
+ if (!mob.startsWith(prefix)) {
290
+ mob = `${prefix}${mob}`;
291
+ }
292
+ else { // mob.startsWith(prefix)
293
+ if (mob.length < Mobile.codes[code].phoneLength + prefix.length) // mob just happens to start with prefix
294
+ mob = `${prefix}${mob}`;
295
+ }
296
+ return mob;
297
+ }
package/package.json CHANGED
@@ -1,9 +1,10 @@
1
1
  {
2
2
  "name": "corebasic",
3
3
  "type": "module",
4
- "version": "1.0.212",
4
+ "version": "1.0.214",
5
5
  "description": "",
6
- "main": "index.ts",
6
+ "main": "dist/index.js",
7
+ "types": "./index.ts",
7
8
  "scripts": {
8
9
  "test": "echo \"Error: no test specified\" && exit 1"
9
10
  },
package/tsc-notes ADDED
@@ -0,0 +1,14 @@
1
+
2
+
3
+ # Install
4
+ npm install typescript
5
+ cp node_modules/@typescript .
6
+
7
+ rm -rf node_modules
8
+ git checkout .
9
+
10
+
11
+
12
+ # Run From corebasic root folder
13
+ ./@typescript/typescript-linux-x64/lib/tsc
14
+
package/tsconfig.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ // Visit https://aka.ms/tsconfig to read more about this file
3
+ "compilerOptions": {
4
+
5
+ "rewriteRelativeImportExtensions": true,
6
+
7
+
8
+ // File Layout
9
+ "rootDir": ".",
10
+ "outDir": "./dist",
11
+
12
+ // Environment Settings
13
+ // See also https://aka.ms/tsconfig/module
14
+ "module": "nodenext",
15
+ "target": "esnext",
16
+ // "types": [],
17
+ // For nodejs:
18
+ // "lib": ["esnext"],
19
+ // "types": ["node"],
20
+ // and npm install -D @types/node
21
+
22
+ // Other Outputs
23
+ "sourceMap": false,
24
+ "declaration": false,
25
+ "declarationMap": false,
26
+
27
+ // Stricter Typechecking Options
28
+ "noUncheckedIndexedAccess": false,
29
+ "exactOptionalPropertyTypes": false,
30
+
31
+ // Style Options
32
+ // "noImplicitReturns": true,
33
+ // "noImplicitOverride": true,
34
+ // "noUnusedLocals": true,
35
+ // "noUnusedParameters": true,
36
+ // "noFallthroughCasesInSwitch": true,
37
+ // "noPropertyAccessFromIndexSignature": true,
38
+
39
+ // Recommended Options
40
+ "strict": false,
41
+ "jsx": "react-jsx",
42
+ "verbatimModuleSyntax": true,
43
+ "isolatedModules": true,
44
+ "noUncheckedSideEffectImports": true,
45
+ "moduleDetection": "force",
46
+ "skipLibCheck": true,
47
+ }
48
+ }