@rws-framework/ai-tools 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/.bin/add-v.sh +10 -0
  2. package/.bin/emerge.sh +11 -0
  3. package/.emerge-vis-output/rws-server/emerge-file_result_dependency_graph.graphml +2067 -0
  4. package/.emerge-vis-output/rws-server/emerge-filesystem_graph.graphml +1505 -0
  5. package/.emerge-vis-output/rws-server/emerge-statistics-and-metrics.json +1 -0
  6. package/.emerge-vis-output/rws-server/emerge-statistics-metrics.txt +1147 -0
  7. package/.emerge-vis-output/rws-server/html/emerge.html +501 -0
  8. package/.emerge-vis-output/rws-server/html/jsconfig.json +9 -0
  9. package/.emerge-vis-output/rws-server/html/resources/css/custom.css +211 -0
  10. package/.emerge-vis-output/rws-server/html/resources/js/emerge_common.js +45 -0
  11. package/.emerge-vis-output/rws-server/html/resources/js/emerge_data.js +13 -0
  12. package/.emerge-vis-output/rws-server/html/resources/js/emerge_git.js +1414 -0
  13. package/.emerge-vis-output/rws-server/html/resources/js/emerge_graph.js +539 -0
  14. package/.emerge-vis-output/rws-server/html/resources/js/emerge_heatmap.js +220 -0
  15. package/.emerge-vis-output/rws-server/html/resources/js/emerge_hull.js +180 -0
  16. package/.emerge-vis-output/rws-server/html/resources/js/emerge_main.js +1003 -0
  17. package/.emerge-vis-output/rws-server/html/resources/js/emerge_search.js +71 -0
  18. package/.emerge-vis-output/rws-server/html/resources/js/emerge_ui.js +199 -0
  19. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/css/bootstrap-grid.css +4124 -0
  20. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/css/bootstrap-grid.css.map +1 -0
  21. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/css/bootstrap-grid.min.css +7 -0
  22. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/css/bootstrap-grid.min.css.map +1 -0
  23. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/css/bootstrap-grid.rtl.css +4123 -0
  24. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/css/bootstrap-grid.rtl.css.map +1 -0
  25. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/css/bootstrap-grid.rtl.min.css +7 -0
  26. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/css/bootstrap-grid.rtl.min.css.map +1 -0
  27. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/css/bootstrap-reboot.css +488 -0
  28. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/css/bootstrap-reboot.css.map +1 -0
  29. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/css/bootstrap-reboot.min.css +7 -0
  30. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/css/bootstrap-reboot.min.css.map +1 -0
  31. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/css/bootstrap-reboot.rtl.css +485 -0
  32. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/css/bootstrap-reboot.rtl.css.map +1 -0
  33. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/css/bootstrap-reboot.rtl.min.css +7 -0
  34. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/css/bootstrap-reboot.rtl.min.css.map +1 -0
  35. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/css/bootstrap-utilities.css +4266 -0
  36. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/css/bootstrap-utilities.css.map +1 -0
  37. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/css/bootstrap-utilities.min.css +7 -0
  38. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/css/bootstrap-utilities.min.css.map +1 -0
  39. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/css/bootstrap-utilities.rtl.css +4257 -0
  40. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/css/bootstrap-utilities.rtl.css.map +1 -0
  41. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/css/bootstrap-utilities.rtl.min.css +7 -0
  42. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/css/bootstrap-utilities.rtl.min.css.map +1 -0
  43. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/css/bootstrap.css +10878 -0
  44. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/css/bootstrap.css.map +1 -0
  45. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/css/bootstrap.min.css +7 -0
  46. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/css/bootstrap.min.css.map +1 -0
  47. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/css/bootstrap.rtl.css +10842 -0
  48. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/css/bootstrap.rtl.css.map +1 -0
  49. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/css/bootstrap.rtl.min.css +7 -0
  50. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/css/bootstrap.rtl.min.css.map +1 -0
  51. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/js/bootstrap.bundle.js +7075 -0
  52. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/js/bootstrap.bundle.js.map +1 -0
  53. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/js/bootstrap.bundle.min.js +7 -0
  54. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/js/bootstrap.bundle.min.js.map +1 -0
  55. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/js/bootstrap.esm.js +5202 -0
  56. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/js/bootstrap.esm.js.map +1 -0
  57. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/js/bootstrap.esm.min.js +7 -0
  58. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/js/bootstrap.esm.min.js.map +1 -0
  59. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/js/bootstrap.js +5249 -0
  60. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/js/bootstrap.js.map +1 -0
  61. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/js/bootstrap.min.js +7 -0
  62. package/.emerge-vis-output/rws-server/html/vendors/bootstrap/js/bootstrap.min.js.map +1 -0
  63. package/.emerge-vis-output/rws-server/html/vendors/d3/d3.v7.8.4.min.js +2 -0
  64. package/.emerge-vis-output/rws-server/html/vendors/d3/d3.v7.min.js +2 -0
  65. package/.emerge-vis-output/rws-server/html/vendors/dark-mode-switch/css/dark-mode.css +148 -0
  66. package/.emerge-vis-output/rws-server/html/vendors/dark-mode-switch/js/dark-mode-switch.min.js +1 -0
  67. package/.emerge-vis-output/rws-server/html/vendors/daterangepicker/daterangepicker.css +410 -0
  68. package/.emerge-vis-output/rws-server/html/vendors/daterangepicker/daterangepicker.min.js +8 -0
  69. package/.emerge-vis-output/rws-server/html/vendors/daterangepicker/moment.min.js +7 -0
  70. package/.emerge-vis-output/rws-server/html/vendors/hull/hull.js +373 -0
  71. package/.emerge-vis-output/rws-server/html/vendors/jquery/jquery-3.6.0.min.js +2 -0
  72. package/.emerge-vis-output/rws-server/html/vendors/popper/popper.min.js +6 -0
  73. package/.emerge-vis-output/rws-server/html/vendors/simpleheat/simpleheat.js +141 -0
  74. package/.eslintrc.json +53 -0
  75. package/README.md +862 -0
  76. package/package.json +49 -0
  77. package/src/index.ts +22 -0
  78. package/src/models/convo/ConvoLoader.ts +415 -0
  79. package/src/models/convo/VectorStore.ts +33 -0
  80. package/src/models/prompts/_prompt.ts +388 -0
  81. package/src/services/VectorStoreService.ts +15 -0
  82. package/tsconfig.json +24 -0
package/README.md ADDED
@@ -0,0 +1,862 @@
1
+ # Realtime Web Suit server setup and configuration guide
2
+
3
+ Realtime Web Suit is a flexible fullstack-server for seting up web servers, WebSocket servers and more while keeping it in sync with your frontend.
4
+
5
+
6
+ *(TBA: RWS Prisma models + RWS Custom CLI Engine + Nest + Nest-RWS front routing mapper)*
7
+
8
+ ## Table of Contents
9
+ 1. [Prerequisites](#prerequisites)
10
+ 2. [Setting Up](#setting-up)
11
+ - [Install Package](#install-package)
12
+ - [Package File](#package-file)
13
+ - [TS Config File](#tsconfig-file)
14
+ - [Initialize Server Setup](#initialize-server-setup)
15
+ - [Server Configuration](#server-configuration)
16
+ 3. [Creating Server Configuration](#creating-server-configuration)
17
+ - [Example Webpack Config](#example-webpack-config)
18
+ - [RWS Webpack Config](#rws-webpack-config)
19
+ - [RWS App Configuration](#rws-app-configuration)
20
+ 4. [Commands](#commands)
21
+ - [Sample Command](#sample-command)
22
+ - [New Command](#new-command)
23
+ - [Database Models](#database-models)
24
+ 5. [Route Configuration](#route-configuration)
25
+ - [Request Route Configuration](#request-route-configuration)
26
+ - [Websocket Route Configuration](#websocket-route-configuration)
27
+ 6. [Running the Server](#running-the-server)
28
+ - [Server Initialization](#server-initialization)
29
+ - [DB Service](#db-service)
30
+ - [Implementation](#implementation)
31
+ 7. [BASH Installs for Node Libraries](#bash-installs-for-node-libraries)
32
+
33
+
34
+ ## Prerequisites
35
+
36
+ Make sure you have Node.js and yarn installed on your local machine. If not, you can download it from the [official Node.js website](https://nodejs.org).
37
+
38
+ ## Setting Up
39
+
40
+ ### Install yarn
41
+
42
+ ```bash
43
+ npm install -g yarn
44
+ ```
45
+
46
+ ### Install package
47
+
48
+ ```bash
49
+ yarn add @rws-framework/server
50
+ ```
51
+
52
+ ### Package file
53
+
54
+ **To use serve you need this packages in your package.json:**
55
+
56
+ ```json
57
+ {
58
+ "dependencies": {,
59
+ "@types/archiver": "^6.0.2",
60
+ "@types/body-parser": "^1.19.5",
61
+ "@types/express": "^4.17.21",
62
+ "compression": "^1.7.4",
63
+ "dotenv": "^16.3.1",
64
+ "jsonwebtoken": "9.0.2",
65
+ "nodemon": "^1.12.1",
66
+ "npm-run-all": "^4.1.1",
67
+ "puppeteer": "^21.0.3",
68
+ "readable-stream": "^4.5.2",
69
+ "reflect-metadata": "^0.2.1",
70
+ "@rws-framework/server": "*",
71
+ "ts-transformer-keys": "^0.4.4",
72
+ "tsconfig-paths-webpack-plugin": "^4.1.0",
73
+ "typescript": "^5.3.3",
74
+ "webpack-node-externals": "^3.0.0"
75
+ },
76
+ "devDependencies": {
77
+ "@types/chai": "^4.3.5",
78
+ "@types/chai-like": "^1.1.1",
79
+ "@types/chai-things": "^0.0.35",
80
+ "@types/compression": "^1.7.5",
81
+ "@types/jsonwebtoken": "9.0.2",
82
+ "@types/lodash": "^4.14.202",
83
+ "@types/mocha": "^10.0.1",
84
+ "chai": "^4.3.7",
85
+ "chai-like": "^1.1.1",
86
+ "chai-things": "^0.2.0",
87
+ "mocha": "^10.2.0",
88
+ "ts-node": "^10.9.1",
89
+ "webpack": "^5.75.0",
90
+ "webpack-bundle-analyzer": "^4.10.1",
91
+ "webpack-cli": "^5.1.4"
92
+ }
93
+ }
94
+ ```
95
+
96
+ ### Tsconfig file
97
+
98
+ **tsconfig.json:**
99
+
100
+ ```json
101
+ {
102
+ "compilerOptions": {
103
+ "baseUrl": ".",
104
+ "experimentalDecorators": true,
105
+ "emitDecoratorMetadata": true,
106
+ "target": "ES2018",
107
+ "module": "commonjs",
108
+ "moduleResolution": "node",
109
+ "strict": true,
110
+ "esModuleInterop": true,
111
+ "sourceMap": true,
112
+ "resolveJsonModule": true,
113
+ "outDir": "dist",
114
+ "strictNullChecks": false,
115
+ "allowSyntheticDefaultImports": true,
116
+ "paths": {
117
+ }
118
+ },
119
+ "include": ["./src"],
120
+ "exclude": []
121
+ }
122
+ ```
123
+
124
+ ### Initialzie server setup (by default uses src/config/config.ts)
125
+
126
+ ```bash
127
+
128
+ yarn rws init
129
+ ```
130
+
131
+ ### OR with specifig config path
132
+
133
+ ```bash
134
+
135
+ yarn rws init path/to/cfg.ts/from/src
136
+ ```
137
+
138
+ ## Creating Server Configuration
139
+
140
+ Create a new file named `config.ts` in the root of your project. This file will export a function that returns a configuration object.
141
+
142
+ ### Example webpack config
143
+
144
+ ```Js
145
+ const path = require('path');
146
+ const keysTransformer = require('ts-transformer-keys/transformer').default;
147
+ const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
148
+
149
+ const RWSWebPackSettings = require('@rws-framework/server/rws.webpack.config');
150
+
151
+ RWSWebPackSettings.resolve.plugins = [
152
+ new TsconfigPathsPlugin({configFile: './tsconfig.json'})
153
+ ]
154
+
155
+ RWSWebPackSettings.output.path = path.resolve(__dirname, 'build');
156
+ RWSWebPackSettings.output.filename = 'jtrainer.server.js',
157
+
158
+
159
+ RWSWebPackSettings.devtool = 'source-map';
160
+ RWSWebPackSettings.mode = 'development';
161
+
162
+ // console.log(RWSWebPackSettings);
163
+
164
+ module.exports = RWSWebPackSettings;
165
+ ```
166
+
167
+ ### RWS webpack config
168
+
169
+
170
+ **rws.webpack.config.js:**
171
+ ```Js
172
+ const path = require('path');
173
+ const keysTransformer = require('ts-transformer-keys/transformer').default;
174
+ const webpackFilters = require('./webpackFilters');
175
+ const nodeExternals = require('webpack-node-externals');
176
+ const UtilsService = require('./_tools');
177
+
178
+ const rootPackageNodeModules = path.resolve(UtilsService.findRootWorkspacePath(process.cwd()), 'node_modules')
179
+
180
+ const modules_setup = [rootPackageNodeModules];
181
+
182
+ // console.log(modules_setup)s;
183
+
184
+ module.exports = {
185
+ entry: `${process.cwd()}/src/index.ts`,
186
+ mode: 'development',
187
+ target: 'node',
188
+ devtool: 'source-map',
189
+ output: {
190
+ path: path.resolve(__dirname, 'build'),
191
+ filename: 'rws.server.js',
192
+ sourceMapFilename: '[file].map',
193
+ },
194
+ resolve: {
195
+ modules: modules_setup,
196
+ extensions: ['.ts', '.js', '.node'],
197
+ alias: {
198
+
199
+ },
200
+ symlinks: false
201
+ },
202
+ context: process.cwd(),
203
+ module: {
204
+ rules: [
205
+ {
206
+ test: /\.(ts)$/,
207
+ use: [
208
+ {
209
+ loader: 'ts-loader',
210
+ options: {
211
+ allowTsInNodeModules: true,
212
+ configFile: path.resolve(process.cwd() + '/tsconfig.json'),
213
+ // compilerOptions: {
214
+ // paths: {
215
+ // '*': [rootPackageNodeModules + '/*']
216
+ // }
217
+ // }
218
+ }
219
+ }
220
+ ],
221
+ exclude: /node_modules\/(?!@rws-framework/server)/,
222
+ },
223
+ {
224
+ test: /\.node$/,
225
+ use: 'node-loader',
226
+ }
227
+ ],
228
+ },
229
+ plugins: [
230
+ ],
231
+ stats: {
232
+ warningsFilter: webpackFilters,
233
+ },
234
+ externals: [nodeExternals({
235
+ allowlist: ['@rws-framework/server'],
236
+ })],
237
+ };
238
+ ```
239
+
240
+ ### RWS App Configuration
241
+
242
+ Define the connection details for your MongoDB instance and server configurations:
243
+
244
+ **src/config/config.ts**:
245
+
246
+ ```typescript
247
+ import { ConsoleService, IAppConfig } from "@rws-framework/server";
248
+
249
+ import JWTUser from "../user/model";
250
+ import { getModels } from "../models";
251
+ import ControllerList from '../controllers/index';
252
+ import TimeTrackerSocket from "../sockets/ChatSocket";
253
+ import routes from '../routing/routes';
254
+ import ws_routes from '../routing/sockets';
255
+ import CommandList from '../commands';
256
+ import dotenv from 'dotenv';
257
+
258
+
259
+ export default (): IAppConfig => {
260
+ dotenv.config();
261
+ const DB_NAME: string = process.env.MONGO_DB_NAME;
262
+ const DB_HOST: string = process.env.MONGO_HOST;
263
+ const DB_PORT: number = parseInt(process.env.MONGO_PORT);
264
+ const DB_USER: string = process.env.MONGO_INITDB_ROOT_USERNAME;
265
+ const DB_PASS: string = process.env.MONGO_INITDB_ROOT_PASSWORD;
266
+
267
+ const AWS_ACCESS_KEY: string = process.env.AWS_ACCESS_KEY;
268
+ const AWS_SECRET_KEY: string = process.env.AWS_SECRET_KEY;
269
+
270
+ const APP_DOMAIN: string = process.env.APP_DOMAIN;
271
+ const PUB_FOLDER: string = process.env.PUB_FOLDER;
272
+
273
+ const APP_PORT: number = parseInt(process.env.APP_PORT);
274
+ const APP_WS_PORT: number = parseInt(process.env.APP_WS_PORT);
275
+ const TESTING_PORT: number = parseInt(process.env.TESTING_PORT);
276
+ const APP_SSL: boolean = process.env.APP_SSL === 'True';
277
+ const APP_CORS_ALLOW: string = process.env.APP_CORS_ALLOW ? process.env.APP_CORS_ALLOW : APP_DOMAIN;
278
+
279
+ const dbString: string = `mongodb+srv://${DB_USER}:${DB_PASS}@${DB_HOST}/${DB_NAME}?retryWrites=true&w=majority`;
280
+
281
+ return {
282
+ features: {
283
+ ws_enabled: true,
284
+ routing_enabled: true,
285
+ ssl: APP_SSL
286
+ },
287
+ mongo_url: dbString,
288
+ mongo_db: DB_NAME,
289
+ port: APP_PORT,
290
+ ws_port: APP_WS_PORT,
291
+ test_port: TESTING_PORT,
292
+ domain: APP_DOMAIN,
293
+ cors_domain: APP_CORS_ALLOW,
294
+ ssl_cert: '',
295
+ ssl_key: '',
296
+ secret_key: '',
297
+ user_class: JWTUser,
298
+ user_models: getModels(),
299
+ controller_list: ControllerList,
300
+ ws_routes: ws_routes,
301
+ http_routes: routes(),
302
+ commands: CommandList,
303
+ aws_lambda_region: null,
304
+ aws_access_key: AWS_ACCESS_KEY,
305
+ aws_secret_key: AWS_SECRET_KEY,
306
+ aws_lambda_role: null,
307
+ aws_lambda_bucket: null,
308
+ pub_dir: PUB_FOLDER,
309
+ }
310
+ }
311
+ ```
312
+
313
+ ### Commands
314
+
315
+ ***A sample command***:
316
+
317
+ ```typescript
318
+ import { ICmdParams, RWSCommand } from '@rws-framework/server';
319
+
320
+ class HelloCommand extends RWSCommand {
321
+ constructor(){
322
+ super('hello', module); // "module" in constructor is required
323
+ }
324
+
325
+ execute(params?: ICmdParams): void {
326
+ console.log('<HELLO COMMAND>\n')
327
+ console.log(' Thanks for installing RWS junction instance, ' + params.user + '\n\n');
328
+ console.log(' This is output of example command for RWS JS server framework.');
329
+ console.log(' (src/commands/HelloCommand.ts).');
330
+ console.log(' Develop your server with "yarn dev"\n');
331
+ console.log(' Or build and start with "yarn build" and "yarn server"');
332
+ console.log('\n\n\n Params passed to this command (those starting with "_" are autogenrated by console script)');
333
+ console.log(params);
334
+ console.log('\n</HELLO COMMAND>')
335
+ }
336
+ }
337
+
338
+ export default new HelloCommand();
339
+ ```
340
+
341
+ Command name is set in RWSCommand class constructor params
342
+
343
+ args are passed to execute() method
344
+
345
+ ```typescript
346
+ class NewCommand extends RWSCommand {
347
+ constructor(){
348
+ super('newcommand');
349
+ }
350
+
351
+ execute(args){
352
+ console.log('DATABASE NAME IS: ', args._rws_config.mongo_db)
353
+ }
354
+ }
355
+ ```
356
+
357
+ args are passed like this:
358
+
359
+ ```bash
360
+ npx rws newcommand arg1=val1,arg2=val2
361
+ ```
362
+
363
+ ### Database models
364
+
365
+ You need to create and export your models in a separate models.ts file. In this example, the getModels() function returns an array of RWS models:
366
+
367
+ ```typescript
368
+ import TimeSeries from "./TimeSeries";
369
+ import TimeTracker from "./TimeTracker";
370
+
371
+ export function getModels(): any[] {
372
+ return [
373
+ TimeTracker,
374
+ TimeSeries
375
+ ]
376
+ }
377
+ ```
378
+
379
+ RWSModel example:
380
+
381
+ ```typescript
382
+ import { RWSannotations, RWSModel } from "@rws-framework/server";
383
+
384
+ import ITimeTracker from "./interfaces/ITimeTracker";
385
+ import 'reflect-metadata';
386
+
387
+ import TimeSeries from "./TimeSeries";
388
+ const { InverseTimeSeries, TrackType } = RWSannotations.modelAnnotations;
389
+
390
+ class TimeTracker extends RWSModel<TimeTracker> implements ITimeTracker {
391
+ @TrackType(String, { required: true }, ['unique'])
392
+ asset_id: string;
393
+
394
+ @TrackType(Number)
395
+ elapsed_time: number = 0;
396
+
397
+ @TrackType(String, { required: true })
398
+ obj_id: string;
399
+
400
+ @TrackType(String)
401
+ asset_type: string;
402
+
403
+ @TrackType(Date)
404
+ trace_date: Date;
405
+
406
+ @TrackType(String)
407
+ user_id: string;
408
+
409
+ @TrackType(Boolean)
410
+ instructor: boolean;
411
+
412
+ @TrackType(Object)
413
+ params: any;
414
+
415
+ @InverseTimeSeries('time_tracker_measurements', 'measurements')
416
+ measurements_ids: string[] = [];
417
+ measurements: TimeSeries[] = [];
418
+
419
+ static _collection = 'time_tracker';
420
+ // static _interface = ITimeTracker;
421
+
422
+ constructor(data?: ITimeTracker) {
423
+ super(data);
424
+
425
+ this.trace_date = new Date();
426
+ }
427
+
428
+
429
+ addTime(series: TimeSeries){
430
+ this.measurements_ids.push(series.id);
431
+ this.measurements.push(series);
432
+
433
+ let sum = 0;
434
+
435
+ this.measurements.forEach(measurement => {
436
+ sum += measurement.value;
437
+ });
438
+
439
+ this.elapsed_time = sum;
440
+ }
441
+
442
+ getTimes(): TimeSeries[]{
443
+ return this.measurements;
444
+ }
445
+ }
446
+
447
+ export default TimeTracker;
448
+ ```
449
+
450
+ **AFTER EVERY MODEL FIELD CHANGE RUN:**
451
+
452
+ ```shell
453
+ yarn rws init
454
+ ```
455
+
456
+ this will update prisma schema for async DB Calls with new fields and their types
457
+
458
+ ## Route Configuration
459
+
460
+ ### Request Route Configuration
461
+ Define your http routes in file that returns array IHTTPRoutes interfaces
462
+
463
+ ```typescript
464
+ import routes from './routing/routes';
465
+ ```
466
+
467
+ **routes.ts**:
468
+
469
+ *"name"* is annotation route name for controllers
470
+ *"path"* is request path
471
+
472
+ ```typescript
473
+ import {IHTTPRoute} from "@rws-framework/server";
474
+
475
+ export default (): IHTTPRoute[] => {
476
+ return [
477
+ {
478
+ prefix: '/prefix',
479
+ routes: [
480
+ {
481
+ name: 'prefix:controller:route',
482
+ path: '/prefix/route/path/with/:param'
483
+ },
484
+ ]
485
+ },
486
+ {
487
+ name: 'home:route',
488
+ path: '/*',
489
+ noParams: true, // this route will not process parameters and put them to request object
490
+ },
491
+ ]
492
+ }
493
+ ```
494
+
495
+ Controller routing usage:
496
+
497
+ ```typescript
498
+ import {
499
+ RWSannotations,
500
+ RWSController,
501
+ IRequestParams
502
+ } from "@rws-framework/server";
503
+
504
+ const { Route } = RWSannotations.routingAnnotations;
505
+ class HomeController extends RWSController{
506
+ @Route('home:index', 'GET')
507
+ public indexAction(params: IRequestParams): Object
508
+ {
509
+
510
+ return {
511
+ 'success': true
512
+ 'data': {
513
+ //your response stuff
514
+ }
515
+ } // Send a response for the root route
516
+ }
517
+ }
518
+
519
+ export default HomeController.getSingleton();
520
+ ```
521
+
522
+ A controller action with route ":param" usage - this one is called ":bookId'
523
+
524
+ ```typescript
525
+ @Route('train:get:book', 'GET')
526
+ public async getBookAction(params: IRequestParams<any>): Promise<IBook>
527
+ {
528
+ return await Book.findOneBy({ id: params.req.params.bookId });
529
+ }
530
+ ```
531
+
532
+ A controller action that outputs "template_name" HTML file from "pub_dir" config setting.
533
+
534
+ default responseType for @Route is 'json'
535
+
536
+ ```typescript
537
+ @Route('home:index', 'GET', { responseType: 'html' })
538
+ public indexAction(params: IRequestParams<any>): any
539
+ {
540
+ return {
541
+ template_name: 'index',
542
+ template_params: {
543
+ hello: 'world'
544
+ }
545
+ }
546
+ }
547
+ ```
548
+
549
+ ### Websocket Route Configuration
550
+
551
+ Define your websocket routes in file that returns object with key being event name to be handled and a socket class definition that extends RWSSocket
552
+
553
+ ```typescript
554
+ import TimeTrackerSocket from "./sockets/TimeTrackerSocket";
555
+
556
+ const ws_routes = {
557
+ 'time': TimeTrackerSocket
558
+ },
559
+ ```
560
+
561
+ those routes goes to config file in "ws_routes" field
562
+
563
+ ## Running the Server
564
+
565
+ Create a new index.ts file in the root of your project. This file will import the serverInit function from @rws-framework/server, and your configuration function from config.ts.
566
+
567
+ **serverInit() takes in IAppConfig interface:**
568
+
569
+ ```typescript
570
+ import { RWSHTTPRoutingEntry, WsRoutes, RWSController, RWSCommand } from "../index"
571
+
572
+ export default interface IAppConfig {
573
+ features?: {
574
+ ws_enabled?: boolean
575
+ routing_enabled?: boolean
576
+ test_routes?: boolean
577
+ ssl?: boolean
578
+ }
579
+ mongo_url: string
580
+ mongo_db: string
581
+ port: number
582
+ ws_port?: number
583
+ domain: string
584
+ test_port?: number
585
+ test_ws_port?: number
586
+ ssl_cert: string
587
+ ssl_key: string
588
+ secret_key: string
589
+ user_class: any
590
+ user_models: any[]
591
+ controller_list: RWSController[]
592
+ ws_routes: WsRoutes
593
+ http_routes: RWSHTTPRoutingEntry[]
594
+ front_routes?: Record<string, unknown>[],
595
+ commands?: RWSCommand[]
596
+ aws_lambda_region?: string
597
+ aws_access_key?: string
598
+ aws_secret_key?: string
599
+ aws_lambda_role?: string
600
+ aws_lambda_bucket?: string
601
+ pub_dir?: string
602
+ cors_domain?: string
603
+ }
604
+ ```
605
+
606
+ The **serverInit()** cfg to AppConfigService singleton in @RWS module.
607
+ It reinstantiates if created empty and had passed config once.
608
+
609
+ Every service in @RWS uses AppConfigService
610
+
611
+ **serverInit()** from ***{packageDir}/init.ts***
612
+ ```typescript
613
+ import IAppConfig from "./interfaces/IAppConfig";
614
+ import getConfigService, { AppConfigService } from "./services/AppConfigService";
615
+ import ServerService, { IInitOpts } from "./services/ServerService";
616
+ import ConsoleService from "./services/ConsoleService";
617
+ import UtilsService from "./services/UtilsService";
618
+
619
+ import fs from "fs";
620
+ import ProcessService from "./services/ProcessService";
621
+
622
+
623
+ async function init(cfg: IAppConfig, serverOptions: IInitOpts = {}, addToConfig: (configService: AppConfigService) => Promise<void> = null){
624
+ const AppConfigService = getConfigService(cfg);
625
+ const port = await AppConfigService.get('port');
626
+ const ws_port = await AppConfigService.get('ws_port');
627
+ const wsRoutes = await AppConfigService.get('ws_routes');
628
+ const httpRoutes = await AppConfigService.get('http_routes');
629
+ const controler_list = await AppConfigService.get('controller_list');
630
+ const pub_dir = await AppConfigService.get('pub_dir');
631
+ const cors_domain = await AppConfigService.get('cors_domain');
632
+
633
+ const sslCert = AppConfigService.get('ssl_cert');
634
+ const sslKey = AppConfigService.get('ssl_key');
635
+
636
+ if(addToConfig !== null){
637
+ await addToConfig(AppConfigService);
638
+ }
639
+
640
+ let https = true;
641
+
642
+ if(!sslCert || !sslKey){
643
+ https = false;
644
+ }
645
+
646
+ const executeDir: string = process.cwd();
647
+ const packageRootDir = UtilsService.findRootWorkspacePath(executeDir)
648
+ const moduleCfgDir = `${packageRootDir}/node_modules/.rws`;
649
+ const moduleCfgFile = `${moduleCfgDir}/_rws_installed`;
650
+
651
+ if(!fs.existsSync(moduleCfgFile)){
652
+ ConsoleService.log(ConsoleService.color().yellow('No config path generated for CLI. Trying to initialize with "yarn rws init config/config"'));
653
+ await ProcessService.runShellCommand('yarn rws init config/config');
654
+ UtilsService.setRWSVar('_rws_installed', 'OK');
655
+ }
656
+
657
+ const theServer = await ServerService.initializeApp({...{
658
+ wsRoutes: wsRoutes,
659
+ httpRoutes: httpRoutes,
660
+ controllerList: controler_list,
661
+ pub_dir: pub_dir,
662
+ domain: `http${(await AppConfigService.get('features')?.ssl ? 's' : '')}://${await AppConfigService.get('domain')}`,
663
+ cors_domain: cors_domain
664
+ },...serverOptions});
665
+
666
+ const wsStart = async () => {
667
+ return (await theServer.websocket.starter());
668
+ }
669
+
670
+ const httpStart = async () => {
671
+ return (await theServer.http.starter());
672
+ }
673
+
674
+ wsStart();
675
+ await httpStart();
676
+ }
677
+
678
+ export default init;
679
+
680
+
681
+ ```
682
+
683
+ ###
684
+
685
+ **DBService**
686
+
687
+ reading config from config singleton filled with cfg data passed to @RWS
688
+
689
+ ```typescript
690
+ class DBService extends TheService {
691
+ private client: PrismaClient;
692
+ private opts:IDBClientCreate = null;
693
+ private connected = false;
694
+
695
+ constructor(opts: IDBClientCreate = null){
696
+ super();
697
+ }
698
+
699
+ private connectToDB(opts: IDBClientCreate = null) {
700
+ if(opts){
701
+ this.opts = opts;
702
+ }else{
703
+ this.opts = {
704
+ dbUrl: getConfig().get('mongo_url'),
705
+ dbName: getConfig().get('mongo_db'),
706
+ }
707
+ }
708
+
709
+ if(!this.opts.dbUrl){
710
+ return;
711
+ }
712
+
713
+ try{
714
+ this.client = new PrismaClient({
715
+ datasources: {
716
+ db: {
717
+ url: this.opts.dbUrl
718
+ },
719
+ },
720
+ });
721
+
722
+ this.connected = true;
723
+ } catch (e){
724
+ ConsoleService.error('PRISMA CONNECTION ERROR');
725
+ }
726
+ }
727
+
728
+ private async createBaseMongoClient(): Promise<MongoClient>
729
+ {
730
+ const dbUrl = this.opts?.dbUrl || getConfig().get('mongo_url');
731
+ const client = new MongoClient(dbUrl);
732
+
733
+ await client.connect();
734
+
735
+ return client;
736
+
737
+ }
738
+
739
+ //(...)
740
+ ```
741
+ ## Implementation
742
+ ### index.ts from your root/src directory##:
743
+
744
+ ```typescript
745
+ import { serverInit, ConsoleService, getAppConfig } from "@rws-framework/server";
746
+ import config from './config/config'
747
+ import BedrockService from "./services/BedrockService";
748
+
749
+ // import path from 'path';
750
+
751
+ async function main(){
752
+ await serverInit(config());
753
+
754
+ getAppConfig().set('extra_param', 'value');
755
+ }
756
+
757
+ main().then(() => {
758
+ ConsoleService.log("Initialization complete");
759
+ }).catch((e) => {
760
+ ConsoleService.error(e);
761
+ console.error(e);
762
+ });
763
+
764
+ ```
765
+
766
+ *The prisma client will have generated Prisma models called exactly like _collection variable in RWS models. You can dierectly act on it without traversing dynamic prisma collections array inside the started client import.*
767
+
768
+ ```typescript
769
+ import { track_type } from "@prisma/client";
770
+ ```
771
+
772
+ to start server in dev env:
773
+
774
+
775
+ **in root package.json:**
776
+ ```Json
777
+ {
778
+ "scripts": {
779
+ "dev": "npm-run-all --parallel watch:transpile watch:run",
780
+ "watch:run": "nodemon \"./build/rws.server.js\" --watch \"./build\"",
781
+ "watch:transpile": "webpack --config webpack.config.js --watch",
782
+ "build": "webpack --config webpack.config.js --output-path ./dist",
783
+ "server": "node dist/rws.server.js",
784
+ "hello": "npx rws hello user=$USER",
785
+ "postinstall": "npx rws init config=config/config && yarn hello",
786
+ "test": "npx mocha"
787
+ }
788
+ }
789
+
790
+ ```
791
+
792
+ ## Executing server
793
+
794
+
795
+ ### build:
796
+
797
+ ```bash
798
+ yarn build
799
+ ```
800
+
801
+ ### watch:
802
+
803
+ ```bash
804
+ yarn dev
805
+ ```
806
+ ### run:
807
+
808
+ ```bash
809
+ yarn server
810
+ ```
811
+
812
+ ### test:
813
+
814
+ ```bash
815
+ yarn test
816
+ ```
817
+
818
+ *("hello" is a sample command)*
819
+
820
+ ## BASH installs for node libraries
821
+
822
+ for local servers - libs are in docker/ Dockerfiles
823
+
824
+ ```bash
825
+ apt-get install -y \
826
+ libgtk-3-0 \
827
+ libxss1 \
828
+ libasound2 \
829
+ libnss3 \
830
+ libxtst6 \
831
+ gconf-service \
832
+ libatk1.0-0 \
833
+ libatk-bridge2.0-0 \
834
+ libc6 \
835
+ libcairo2 \
836
+ libcups2 \
837
+ libdbus-1-3 \
838
+ libexpat1 \
839
+ libfontconfig1 \
840
+ libgcc1 \
841
+ libgconf-2-4 \
842
+ libgdk-pixbuf2.0-0 \
843
+ libglib2.0-0 \
844
+ libnspr4 \
845
+ libpango-1.0-0 \
846
+ libpangocairo-1.0-0 \
847
+ libstdc++6 \
848
+ libx11-6 \
849
+ libx11-xcb1 \
850
+ libxcb1 \
851
+ libxcomposite1 \
852
+ libxcursor1 \
853
+ libxdamage1 \
854
+ libxext6 \
855
+ libxfixes3 \
856
+ libxi6 \
857
+ libxrandr2 \
858
+ libxrender1 \
859
+ libappindicator1 \
860
+ lsb-release \
861
+ xdg-utils
862
+ ```