node-red-contrib-prib-functions 0.22.0 → 0.23.3

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 (38) hide show
  1. package/README.md +142 -92
  2. package/lib/AlphaBeta.js +32 -0
  3. package/lib/GraphDB.js +40 -9
  4. package/lib/MinMax.js +17 -0
  5. package/lib/Tree.js +64 -0
  6. package/lib/common.js +128 -0
  7. package/lib/objectExtensions.js +213 -80
  8. package/lib/timeDimension.js +36 -0
  9. package/lib/typedInput.js +77 -0
  10. package/matrix/matrixNode.html +2 -1
  11. package/package.json +15 -13
  12. package/test/00-objectExtensions.js +192 -1
  13. package/test/02-graphdb.js +46 -0
  14. package/test/data/.config.nodes.json +3 -3
  15. package/test/data/.config.nodes.json.backup +3 -3
  16. package/test/data/.config.users.json +3 -2
  17. package/test/data/.config.users.json.backup +3 -2
  18. package/test/data/.flow.json.backup +3875 -472
  19. package/test/data/flow.json +3874 -471
  20. package/test/data/package-lock.json +11 -11
  21. package/test/data/shares/.config.nodes.json +589 -0
  22. package/test/data/shares/.config.runtime.json +4 -0
  23. package/test/data/shares/.config.runtime.json.backup +3 -0
  24. package/test/data/shares/.config.users.json +32 -0
  25. package/test/data/shares/.config.users.json.backup +29 -0
  26. package/test/data/shares/.flow.json.backup +230 -0
  27. package/test/data/shares/.flow_cred.json.backup +3 -0
  28. package/test/data/shares/flow.json +267 -0
  29. package/test/data/shares/flow_cred.json +3 -0
  30. package/test/data/shares/package.json +6 -0
  31. package/test/data/shares/settings.js +544 -0
  32. package/testing/test.js +63 -29
  33. package/transform/transform.html +185 -20
  34. package/transform/transform.js +272 -265
  35. package/transform/xlsx2.js +74 -0
  36. package/visual/shapes/base..js +1 -0
  37. package/visual/visual.js +0 -0
  38. package/visual/visualNode.js +45 -0
@@ -0,0 +1,544 @@
1
+ /**
2
+ * This is the default settings file provided by Node-RED.
3
+ *
4
+ * It can contain any valid JavaScript code that will get run when Node-RED
5
+ * is started.
6
+ *
7
+ * Lines that start with // are commented out.
8
+ * Each entry should be separated from the entries above and below by a comma ','
9
+ *
10
+ * For more information about individual settings, refer to the documentation:
11
+ * https://nodered.org/docs/user-guide/runtime/configuration
12
+ *
13
+ * The settings are split into the following sections:
14
+ * - Flow File and User Directory Settings
15
+ * - Security
16
+ * - Server Settings
17
+ * - Runtime Settings
18
+ * - Editor Settings
19
+ * - Node Settings
20
+ *
21
+ **/
22
+
23
+ module.exports = {
24
+
25
+ /*******************************************************************************
26
+ * Flow File and User Directory Settings
27
+ * - flowFile
28
+ * - credentialSecret
29
+ * - flowFilePretty
30
+ * - userDir
31
+ * - nodesDir
32
+ ******************************************************************************/
33
+
34
+ /** The file containing the flows. If not set, defaults to flows_<hostname>.json **/
35
+ flowFile: 'flows.json',
36
+
37
+ /** By default, credentials are encrypted in storage using a generated key. To
38
+ * specify your own secret, set the following property.
39
+ * If you want to disable encryption of credentials, set this property to false.
40
+ * Note: once you set this property, do not change it - doing so will prevent
41
+ * node-red from being able to decrypt your existing credentials and they will be
42
+ * lost.
43
+ */
44
+ //credentialSecret: "a-secret-key",
45
+
46
+ /** By default, the flow JSON will be formatted over multiple lines making
47
+ * it easier to compare changes when using version control.
48
+ * To disable pretty-printing of the JSON set the following property to false.
49
+ */
50
+ flowFilePretty: true,
51
+
52
+ /** By default, all user data is stored in a directory called `.node-red` under
53
+ * the user's home directory. To use a different location, the following
54
+ * property can be used
55
+ */
56
+ //userDir: '/home/nol/.node-red/',
57
+
58
+ /** Node-RED scans the `nodes` directory in the userDir to find local node files.
59
+ * The following property can be used to specify an additional directory to scan.
60
+ */
61
+ nodesDir: './',
62
+ // nodesDir: '~/Desktop/node-red-contrib-prib-functions/',
63
+ // nodesDir: '/home/peter/Desktop/node-red-contrib-prib-functions/',
64
+
65
+ /*******************************************************************************
66
+ * Security
67
+ * - adminAuth
68
+ * - https
69
+ * - httpsRefreshInterval
70
+ * - requireHttps
71
+ * - httpNodeAuth
72
+ * - httpStaticAuth
73
+ ******************************************************************************/
74
+
75
+ /** To password protect the Node-RED editor and admin API, the following
76
+ * property can be used. See http://nodered.org/docs/security.html for details.
77
+ */
78
+ //adminAuth: {
79
+ // type: "credentials",
80
+ // users: [{
81
+ // username: "admin",
82
+ // password: "$2a$08$zZWtXTja0fB1pzD4sHCMyOCMYz2Z6dNbM6tl8sJogENOMcxWV9DN.",
83
+ // permissions: "*"
84
+ // }]
85
+ //},
86
+
87
+ /** The following property can be used to enable HTTPS
88
+ * This property can be either an object, containing both a (private) key
89
+ * and a (public) certificate, or a function that returns such an object.
90
+ * See http://nodejs.org/api/https.html#https_https_createserver_options_requestlistener
91
+ * for details of its contents.
92
+ */
93
+
94
+ /** Option 1: static object */
95
+ //https: {
96
+ // key: require("fs").readFileSync('privkey.pem'),
97
+ // cert: require("fs").readFileSync('cert.pem')
98
+ //},
99
+
100
+ /** Option 2: function that returns the HTTP configuration object */
101
+ // https: function() {
102
+ // // This function should return the options object, or a Promise
103
+ // // that resolves to the options object
104
+ // return {
105
+ // key: require("fs").readFileSync('privkey.pem'),
106
+ // cert: require("fs").readFileSync('cert.pem')
107
+ // }
108
+ // },
109
+
110
+ /** If the `https` setting is a function, the following setting can be used
111
+ * to set how often, in hours, the function will be called. That can be used
112
+ * to refresh any certificates.
113
+ */
114
+ //httpsRefreshInterval : 12,
115
+
116
+ /** The following property can be used to cause insecure HTTP connections to
117
+ * be redirected to HTTPS.
118
+ */
119
+ //requireHttps: true,
120
+
121
+ /** To password protect the node-defined HTTP endpoints (httpNodeRoot),
122
+ * including node-red-dashboard, or the static content (httpStatic), the
123
+ * following properties can be used.
124
+ * The `pass` field is a bcrypt hash of the password.
125
+ * See http://nodered.org/docs/security.html#generating-the-password-hash
126
+ */
127
+ //httpNodeAuth: {user:"user",pass:"$2a$08$zZWtXTja0fB1pzD4sHCMyOCMYz2Z6dNbM6tl8sJogENOMcxWV9DN."},
128
+ //httpStaticAuth: {user:"user",pass:"$2a$08$zZWtXTja0fB1pzD4sHCMyOCMYz2Z6dNbM6tl8sJogENOMcxWV9DN."},
129
+
130
+ /*******************************************************************************
131
+ * Server Settings
132
+ * - uiPort
133
+ * - uiHost
134
+ * - apiMaxLength
135
+ * - httpServerOptions
136
+ * - httpAdminRoot
137
+ * - httpAdminMiddleware
138
+ * - httpNodeRoot
139
+ * - httpNodeCors
140
+ * - httpNodeMiddleware
141
+ * - httpStatic
142
+ * - httpStaticRoot
143
+ ******************************************************************************/
144
+
145
+ /** the tcp port that the Node-RED web server is listening on */
146
+ uiPort: process.env.PORT || 1880,
147
+
148
+ /** By default, the Node-RED UI accepts connections on all IPv4 interfaces.
149
+ * To listen on all IPv6 addresses, set uiHost to "::",
150
+ * The following property can be used to listen on a specific interface. For
151
+ * example, the following would only allow connections from the local machine.
152
+ */
153
+ //uiHost: "127.0.0.1",
154
+
155
+ /** The maximum size of HTTP request that will be accepted by the runtime api.
156
+ * Default: 5mb
157
+ */
158
+ //apiMaxLength: '5mb',
159
+
160
+ /** The following property can be used to pass custom options to the Express.js
161
+ * server used by Node-RED. For a full list of available options, refer
162
+ * to http://expressjs.com/en/api.html#app.settings.table
163
+ */
164
+ //httpServerOptions: { },
165
+
166
+ /** By default, the Node-RED UI is available at http://localhost:1880/
167
+ * The following property can be used to specify a different root path.
168
+ * If set to false, this is disabled.
169
+ */
170
+ //httpAdminRoot: '/admin',
171
+
172
+ /** The following property can be used to add a custom middleware function
173
+ * in front of all admin http routes. For example, to set custom http
174
+ * headers. It can be a single function or an array of middleware functions.
175
+ */
176
+ // httpAdminMiddleware: function(req,res,next) {
177
+ // // Set the X-Frame-Options header to limit where the editor
178
+ // // can be embedded
179
+ // //res.set('X-Frame-Options', 'sameorigin');
180
+ // next();
181
+ // },
182
+
183
+
184
+ /** Some nodes, such as HTTP In, can be used to listen for incoming http requests.
185
+ * By default, these are served relative to '/'. The following property
186
+ * can be used to specifiy a different root path. If set to false, this is
187
+ * disabled.
188
+ */
189
+ //httpNodeRoot: '/red-nodes',
190
+
191
+ /** The following property can be used to configure cross-origin resource sharing
192
+ * in the HTTP nodes.
193
+ * See https://github.com/troygoode/node-cors#configuration-options for
194
+ * details on its contents. The following is a basic permissive set of options:
195
+ */
196
+ //httpNodeCors: {
197
+ // origin: "*",
198
+ // methods: "GET,PUT,POST,DELETE"
199
+ //},
200
+
201
+ /** If you need to set an http proxy please set an environment variable
202
+ * called http_proxy (or HTTP_PROXY) outside of Node-RED in the operating system.
203
+ * For example - http_proxy=http://myproxy.com:8080
204
+ * (Setting it here will have no effect)
205
+ * You may also specify no_proxy (or NO_PROXY) to supply a comma separated
206
+ * list of domains to not proxy, eg - no_proxy=.acme.co,.acme.co.uk
207
+ */
208
+
209
+ /** The following property can be used to add a custom middleware function
210
+ * in front of all http in nodes. This allows custom authentication to be
211
+ * applied to all http in nodes, or any other sort of common request processing.
212
+ * It can be a single function or an array of middleware functions.
213
+ */
214
+ //httpNodeMiddleware: function(req,res,next) {
215
+ // // Handle/reject the request, or pass it on to the http in node by calling next();
216
+ // // Optionally skip our rawBodyParser by setting this to true;
217
+ // //req.skipRawBodyParser = true;
218
+ // next();
219
+ //},
220
+
221
+ /** When httpAdminRoot is used to move the UI to a different root path, the
222
+ * following property can be used to identify a directory of static content
223
+ * that should be served at http://localhost:1880/.
224
+ * When httpStaticRoot is set differently to httpAdminRoot, there is no need
225
+ * to move httpAdminRoot
226
+ */
227
+ //httpStatic: '/home/nol/node-red-static/', //single static source
228
+ /* OR multiple static sources can be created using an array of objects... */
229
+ //httpStatic: [
230
+ // {path: '/home/nol/pics/', root: "/img/"},
231
+ // {path: '/home/nol/reports/', root: "/doc/"},
232
+ //],
233
+
234
+ /**
235
+ * All static routes will be appended to httpStaticRoot
236
+ * e.g. if httpStatic = "/home/nol/docs" and httpStaticRoot = "/static/"
237
+ * then "/home/nol/docs" will be served at "/static/"
238
+ * e.g. if httpStatic = [{path: '/home/nol/pics/', root: "/img/"}]
239
+ * and httpStaticRoot = "/static/"
240
+ * then "/home/nol/pics/" will be served at "/static/img/"
241
+ */
242
+ //httpStaticRoot: '/static/',
243
+
244
+ /*******************************************************************************
245
+ * Runtime Settings
246
+ * - lang
247
+ * - runtimeState
248
+ * - diagnostics
249
+ * - logging
250
+ * - contextStorage
251
+ * - exportGlobalContextKeys
252
+ * - externalModules
253
+ ******************************************************************************/
254
+
255
+ /** Uncomment the following to run node-red in your preferred language.
256
+ * Available languages include: en-US (default), ja, de, zh-CN, zh-TW, ru, ko
257
+ * Some languages are more complete than others.
258
+ */
259
+ // lang: "de",
260
+
261
+ /** Configure diagnostics options
262
+ * - enabled: When `enabled` is `true` (or unset), diagnostics data will
263
+ * be available at http://localhost:1880/diagnostics
264
+ * - ui: When `ui` is `true` (or unset), the action `show-system-info` will
265
+ * be available to logged in users of node-red editor
266
+ */
267
+ diagnostics: {
268
+ /** enable or disable diagnostics endpoint. Must be set to `false` to disable */
269
+ enabled: true,
270
+ /** enable or disable diagnostics display in the node-red editor. Must be set to `false` to disable */
271
+ ui: true,
272
+ },
273
+ /** Configure runtimeState options
274
+ * - enabled: When `enabled` is `true` flows runtime can be Started/Stoped
275
+ * by POSTing to available at http://localhost:1880/flows/state
276
+ * - ui: When `ui` is `true`, the action `core:start-flows` and
277
+ * `core:stop-flows` will be available to logged in users of node-red editor
278
+ * Also, the deploy menu (when set to default) will show a stop or start button
279
+ */
280
+ runtimeState: {
281
+ /** enable or disable flows/state endpoint. Must be set to `false` to disable */
282
+ enabled: false,
283
+ /** show or hide runtime stop/start options in the node-red editor. Must be set to `false` to hide */
284
+ ui: false,
285
+ },
286
+ /** Configure the logging output */
287
+ logging: {
288
+ /** Only console logging is currently supported */
289
+ console: {
290
+ /** Level of logging to be recorded. Options are:
291
+ * fatal - only those errors which make the application unusable should be recorded
292
+ * error - record errors which are deemed fatal for a particular request + fatal errors
293
+ * warn - record problems which are non fatal + errors + fatal errors
294
+ * info - record information about the general running of the application + warn + error + fatal errors
295
+ * debug - record information which is more verbose than info + info + warn + error + fatal errors
296
+ * trace - record very detailed logging + debug + info + warn + error + fatal errors
297
+ * off - turn off all logging (doesn't affect metrics or audit)
298
+ */
299
+ level: "info",
300
+ /** Whether or not to include metric events in the log output */
301
+ metrics: false,
302
+ /** Whether or not to include audit events in the log output */
303
+ audit: false
304
+ }
305
+ },
306
+
307
+ /** Context Storage
308
+ * The following property can be used to enable context storage. The configuration
309
+ * provided here will enable file-based context that flushes to disk every 30 seconds.
310
+ * Refer to the documentation for further options: https://nodered.org/docs/api/context/
311
+ */
312
+ //contextStorage: {
313
+ // default: {
314
+ // module:"localfilesystem"
315
+ // },
316
+ //},
317
+
318
+ /** `global.keys()` returns a list of all properties set in global context.
319
+ * This allows them to be displayed in the Context Sidebar within the editor.
320
+ * In some circumstances it is not desirable to expose them to the editor. The
321
+ * following property can be used to hide any property set in `functionGlobalContext`
322
+ * from being list by `global.keys()`.
323
+ * By default, the property is set to false to avoid accidental exposure of
324
+ * their values. Setting this to true will cause the keys to be listed.
325
+ */
326
+ exportGlobalContextKeys: false,
327
+
328
+ /** Configure how the runtime will handle external npm modules.
329
+ * This covers:
330
+ * - whether the editor will allow new node modules to be installed
331
+ * - whether nodes, such as the Function node are allowed to have their
332
+ * own dynamically configured dependencies.
333
+ * The allow/denyList options can be used to limit what modules the runtime
334
+ * will install/load. It can use '*' as a wildcard that matches anything.
335
+ */
336
+ externalModules: {
337
+ // autoInstall: false, /** Whether the runtime will attempt to automatically install missing modules */
338
+ // autoInstallRetry: 30, /** Interval, in seconds, between reinstall attempts */
339
+ // palette: { /** Configuration for the Palette Manager */
340
+ // allowInstall: true, /** Enable the Palette Manager in the editor */
341
+ // allowUpdate: true, /** Allow modules to be updated in the Palette Manager */
342
+ // allowUpload: true, /** Allow module tgz files to be uploaded and installed */
343
+ // allowList: ['*'],
344
+ // denyList: [],
345
+ // allowUpdateList: ['*'],
346
+ // denyUpdateList: []
347
+ // },
348
+ // modules: { /** Configuration for node-specified modules */
349
+ // allowInstall: true,
350
+ // allowList: [],
351
+ // denyList: []
352
+ // }
353
+ },
354
+
355
+
356
+ /*******************************************************************************
357
+ * Editor Settings
358
+ * - disableEditor
359
+ * - editorTheme
360
+ ******************************************************************************/
361
+
362
+ /** The following property can be used to disable the editor. The admin API
363
+ * is not affected by this option. To disable both the editor and the admin
364
+ * API, use either the httpRoot or httpAdminRoot properties
365
+ */
366
+ //disableEditor: false,
367
+
368
+ /** Customising the editor
369
+ * See https://nodered.org/docs/user-guide/runtime/configuration#editor-themes
370
+ * for all available options.
371
+ */
372
+ editorTheme: {
373
+ /** The following property can be used to set a custom theme for the editor.
374
+ * See https://github.com/node-red-contrib-themes/theme-collection for
375
+ * a collection of themes to chose from.
376
+ */
377
+ //theme: "",
378
+
379
+ /** To disable the 'Welcome to Node-RED' tour that is displayed the first
380
+ * time you access the editor for each release of Node-RED, set this to false
381
+ */
382
+ //tours: false,
383
+
384
+ palette: {
385
+ /** The following property can be used to order the categories in the editor
386
+ * palette. If a node's category is not in the list, the category will get
387
+ * added to the end of the palette.
388
+ * If not set, the following default order is used:
389
+ */
390
+ //categories: ['subflows', 'common', 'function', 'network', 'sequence', 'parser', 'storage'],
391
+ },
392
+
393
+ projects: {
394
+ /** To enable the Projects feature, set this value to true */
395
+ enabled: false,
396
+ workflow: {
397
+ /** Set the default projects workflow mode.
398
+ * - manual - you must manually commit changes
399
+ * - auto - changes are automatically committed
400
+ * This can be overridden per-user from the 'Git config'
401
+ * section of 'User Settings' within the editor
402
+ */
403
+ mode: "manual"
404
+ }
405
+ },
406
+
407
+ codeEditor: {
408
+ /** Select the text editor component used by the editor.
409
+ * As of Node-RED V3, this defaults to "monaco", but can be set to "ace" if desired
410
+ */
411
+ lib: "monaco",
412
+ options: {
413
+ /** The follow options only apply if the editor is set to "monaco"
414
+ *
415
+ * theme - must match the file name of a theme in
416
+ * packages/node_modules/@node-red/editor-client/src/vendor/monaco/dist/theme
417
+ * e.g. "tomorrow-night", "upstream-sunburst", "github", "my-theme"
418
+ */
419
+ // theme: "vs",
420
+ /** other overrides can be set e.g. fontSize, fontFamily, fontLigatures etc.
421
+ * for the full list, see https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.IStandaloneEditorConstructionOptions.html
422
+ */
423
+ //fontSize: 14,
424
+ //fontFamily: "Cascadia Code, Fira Code, Consolas, 'Courier New', monospace",
425
+ //fontLigatures: true,
426
+ }
427
+ }
428
+ },
429
+
430
+ /*******************************************************************************
431
+ * Node Settings
432
+ * - fileWorkingDirectory
433
+ * - functionGlobalContext
434
+ * - functionExternalModules
435
+ * - nodeMessageBufferMaxLength
436
+ * - ui (for use with Node-RED Dashboard)
437
+ * - debugUseColors
438
+ * - debugMaxLength
439
+ * - execMaxBufferSize
440
+ * - httpRequestTimeout
441
+ * - mqttReconnectTime
442
+ * - serialReconnectTime
443
+ * - socketReconnectTime
444
+ * - socketTimeout
445
+ * - tcpMsgQueueSize
446
+ * - inboundWebSocketTimeout
447
+ * - tlsConfigDisableLocalFiles
448
+ * - webSocketNodeVerifyClient
449
+ ******************************************************************************/
450
+
451
+ /** The working directory to handle relative file paths from within the File nodes
452
+ * defaults to the working directory of the Node-RED process.
453
+ */
454
+ //fileWorkingDirectory: "",
455
+
456
+ /** Allow the Function node to load additional npm modules directly */
457
+ functionExternalModules: true,
458
+
459
+ /** The following property can be used to set predefined values in Global Context.
460
+ * This allows extra node modules to be made available with in Function node.
461
+ * For example, the following:
462
+ * functionGlobalContext: { os:require('os') }
463
+ * will allow the `os` module to be accessed in a Function node using:
464
+ * global.get("os")
465
+ */
466
+ functionGlobalContext: {
467
+ // os:require('os'),
468
+ },
469
+
470
+ /** The maximum number of messages nodes will buffer internally as part of their
471
+ * operation. This applies across a range of nodes that operate on message sequences.
472
+ * defaults to no limit. A value of 0 also means no limit is applied.
473
+ */
474
+ //nodeMessageBufferMaxLength: 0,
475
+
476
+ /** If you installed the optional node-red-dashboard you can set it's path
477
+ * relative to httpNodeRoot
478
+ * Other optional properties include
479
+ * readOnly:{boolean},
480
+ * middleware:{function or array}, (req,res,next) - http middleware
481
+ * ioMiddleware:{function or array}, (socket,next) - socket.io middleware
482
+ */
483
+ //ui: { path: "ui" },
484
+
485
+ /** Colourise the console output of the debug node */
486
+ //debugUseColors: true,
487
+
488
+ /** The maximum length, in characters, of any message sent to the debug sidebar tab */
489
+ debugMaxLength: 1000,
490
+
491
+ /** Maximum buffer size for the exec node. Defaults to 10Mb */
492
+ //execMaxBufferSize: 10000000,
493
+
494
+ /** Timeout in milliseconds for HTTP request connections. Defaults to 120s */
495
+ //httpRequestTimeout: 120000,
496
+
497
+ /** Retry time in milliseconds for MQTT connections */
498
+ mqttReconnectTime: 15000,
499
+
500
+ /** Retry time in milliseconds for Serial port connections */
501
+ serialReconnectTime: 15000,
502
+
503
+ /** Retry time in milliseconds for TCP socket connections */
504
+ //socketReconnectTime: 10000,
505
+
506
+ /** Timeout in milliseconds for TCP server socket connections. Defaults to no timeout */
507
+ //socketTimeout: 120000,
508
+
509
+ /** Maximum number of messages to wait in queue while attempting to connect to TCP socket
510
+ * defaults to 1000
511
+ */
512
+ //tcpMsgQueueSize: 2000,
513
+
514
+ /** Timeout in milliseconds for inbound WebSocket connections that do not
515
+ * match any configured node. Defaults to 5000
516
+ */
517
+ //inboundWebSocketTimeout: 5000,
518
+
519
+ /** To disable the option for using local files for storing keys and
520
+ * certificates in the TLS configuration node, set this to true.
521
+ */
522
+ //tlsConfigDisableLocalFiles: true,
523
+
524
+ /** The following property can be used to verify websocket connection attempts.
525
+ * This allows, for example, the HTTP request headers to be checked to ensure
526
+ * they include valid authentication information.
527
+ */
528
+ //webSocketNodeVerifyClient: function(info) {
529
+ // /** 'info' has three properties:
530
+ // * - origin : the value in the Origin header
531
+ // * - req : the HTTP request
532
+ // * - secure : true if req.connection.authorized or req.connection.encrypted is set
533
+ // *
534
+ // * The function should return true if the connection should be accepted, false otherwise.
535
+ // *
536
+ // * Alternatively, if this function is defined to accept a second argument, callback,
537
+ // * it can be used to verify the client asynchronously.
538
+ // * The callback takes three arguments:
539
+ // * - result : boolean, whether to accept the connection or not
540
+ // * - code : if result is false, the HTTP error status to return
541
+ // * - reason: if result is false, the HTTP reason string to return
542
+ // */
543
+ //},
544
+ }
package/testing/test.js CHANGED
@@ -1,4 +1,5 @@
1
1
  const logger = new (require("node-red-contrib-logger"))("test").sendInfo("Copyright 2020 Jaroslav Peter Prib");
2
+ const assert = require('node:assert')
2
3
 
3
4
  if(String.prototype.escapeSpecialChars)
4
5
  logger.warn("String.prototype.escapeSpecialChars already defined");
@@ -23,31 +24,62 @@ function escapeSpecialChars(s){
23
24
  }
24
25
  }
25
26
  function setError(msg,node,err) {
26
- msg._test.error=err;
27
- node.error(err);
28
- node.status({fill:"red",shape:"ring",text:"error"});
29
- node.send([null,msg]);
27
+ msg._test.error=err
28
+ node.error(err)
29
+ node.status({fill:"red",shape:"ring",text:"error"})
30
+ node.send([null,msg])
31
+ }
32
+ function assertObjects(obj1,obj2,errorFactor,callEquals=()=>true,callNotEquals=()=>false) {
33
+ try{
34
+ node.assert(obj1,obj2).then(callEquals)
35
+ } catch(ex) {
36
+ logger.error(ex.message);
37
+ callNotEquals(ex.message)
38
+ }
39
+ /*
40
+ assert.deepStrictEqual(actual, expected[, message])
41
+ assert.deepEqual(actual, expected[, message])
42
+ assert.notDeepEqual(actual, expected[, message])
43
+ assert.partialDeepStrictEqual(actual, expected[, message])
44
+ assert.equal(actual, expected[, message])
45
+ assert.notEqual(actual, expected[, message])
46
+ assert.strictEqual(actual, expected[, message])
47
+ assert.notStrictEqual(actual, expected[, message])
48
+
49
+ assert.doesNotMatch(string, regexp[, message])
50
+ assert.match(string, regexp[, message])
51
+
52
+ assert.doesNotReject(asyncFn[, error][, message])
53
+ assert.doesNotThrow(fn[, error][, message])
54
+ assert.throws(fn[, error][, message])
55
+ assert.ifError(value)
56
+ assert.ok(value[, message])
57
+ assert.rejects(asyncFn[, error][, message])
58
+ */
30
59
  }
31
60
 
32
61
  function equalObjects(obj1,obj2,errorFactor,callEquals=()=>true,callNotEquals=()=>false) {
33
- if( obj1 === obj2 ) return callEquals();
34
- if(obj1 instanceof Buffer ) return Buffer.compare(obj1, obj2) === 0
35
- if( obj1 === Number.POSITIVE_INFINITY && obj2==="Infinity") return callEquals();
36
- if( obj1 === Number.NEGATIVE_INFINITY && obj2==="-Infinity") return callEquals();
37
- if( Number.isNaN(obj1) && obj2==="NaN") return callEquals();
38
- const obj1type=typeof obj1;
39
- if( obj1type != typeof obj2 ) return callNotEquals();
40
- if(errorFactor && obj1type=="number") return (Math.abs(obj2-obj1)/obj2)<errorFactor?callEquals():callNotEquals();
41
- if( !(obj1 instanceof Object) ) return callNotEquals();
42
- if( Object.keys(obj1).length !== Object.keys(obj2).length ) return callNotEquals();
43
- try{
44
- for(let key in obj1) {
45
- if( !equalObjects(obj1[key],obj2[key],errorFactor) ) return callNotEquals();
62
+ if(obj1 == obj2) return callEquals()
63
+ if(obj1 instanceof Buffer) return Buffer.compare(obj1, obj2) === 0?callEquals():callNotEquals("buffers not equal")
64
+ if(obj1 === Number.POSITIVE_INFINITY && obj2==="Infinity") return callEquals()
65
+ if(obj1 === Number.NEGATIVE_INFINITY && obj2==="-Infinity") return callEquals()
66
+ if(Number.isNaN(obj1) && obj2==="NaN") return callEquals()
67
+ const obj1type=typeof obj1
68
+ if(obj1type != typeof obj2) return callNotEquals("different data types, "+obj1type+" vs "+typeof obj2)
69
+ if(obj1type=="boolean") callNotEquals("boolean not equal")
70
+ if(errorFactor && obj1type=="number") return (Math.abs(obj2-obj1)/obj2)<errorFactor?callEquals():callNotEquals("number outside bounds")
71
+ if( !(obj1 instanceof Object) ) return callNotEquals("different object types")
72
+ const keys1=Object.keys(obj1).sort()
73
+ const keys2=Object.keys(obj2).sort()
74
+ if( keys1.length !== keys2.length ) return callNotEquals("different number of properties")
75
+ for(const key1 of keys1){
76
+ try{
77
+ if( !equalObjects(obj1[key1],obj2[key1],errorFactor,undefined,err=>{throw Error(err)}) ) return callNotEquals()
78
+ } catch(ex){
79
+ return callNotEquals(ex.message)
46
80
  }
47
- } catch(e) {
48
- return callNotEquals();
49
81
  }
50
- return callEquals();
82
+ return callEquals();
51
83
  }
52
84
 
53
85
  const testedOK=(node,msg)=>{
@@ -55,9 +87,10 @@ const testedOK=(node,msg)=>{
55
87
  delete msg._test;
56
88
  node.send([null,null,msg]);
57
89
  }
58
- const testedFailed=(node,msg)=>{
59
- msg._test.testedValue=node.getData(msg,node);
60
- setError(msg,node,"Test failed");
90
+ const testedFailed=(node,msg,err)=>{
91
+ msg._test.testedValue=node.getData(msg,node)
92
+ msg._test.errorDetails=err
93
+ setError(msg,node,"Test failed")
61
94
  }
62
95
 
63
96
  module.exports = function(RED) {
@@ -90,17 +123,18 @@ module.exports = function(RED) {
90
123
  node.on("input",function(msg) {
91
124
  if(msg._test) {
92
125
  try{
126
+ const testData=node.getData(msg,node)
93
127
  if(msg._test.id!==node.id) return setError(msg,node,"Sent by another test "+msg._test.id);
94
-
95
128
  if(node.isJSONata)
96
- return RED.util.evaluateJSONataExpression(node.resultExpression,msg,(err,data)=>{
97
- if(err) testedFailed(node,msg)
98
- else return data?testedOK(node,msg):testedFailed(node,msg)
129
+ return RED.util.evaluateJSONataExpression(node.resultExpression,testData,(err,data)=>{
130
+ if(err) return testedFailed(node,msg,err)
131
+ if(data==null) testedFailed(node,msg,"no data, expecting boolean")
132
+ return data==true ? testedOK(node,msg) : testedFailed(node,msg,"jsonata not true")
99
133
  })
100
134
 
101
- node.equalObjects(node.getData(msg,node),msg._test.result,node.errorFactor,
135
+ node.equalObjects(testData,msg._test.result,node.errorFactor,
102
136
  ()=>testedOK(node,msg),
103
- ()=>testedFailed(node,msg)
137
+ err=>testedFailed(node,msg,"equal object test failure "+err)
104
138
  );
105
139
 
106
140
  } catch(ex){