cno-bedrock 0.0.4 → 0.1.0

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,831 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ # [cno-sha2-256.js](src/cno-sha2-256.js)
4
+ > `cno-sha2-256`: Micropackage: an implementation-agnostic module for getting a SHA2-256 hash digest for a Node Buffer.
5
+
6
+ Author: Anadian
7
+
8
+ Code license: MIT
9
+ ```
10
+ Copyright 2024 Anadian
11
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this
12
+ software and associated documentation files (the "Software"), to deal in the Software
13
+ without restriction, including without limitation the rights to use, copy, modify,
14
+ merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
15
+ permit persons to whom the Software is furnished to do so, subject to the following
16
+ conditions:
17
+ The above copyright notice and this permission notice shall be included in all copies
18
+ or substantial portions of the Software.
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
20
+ INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
21
+ PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
22
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
23
+ CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
24
+ OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25
+ ```
26
+ Documentation License: [![Creative Commons License](https://i.creativecommons.org/l/by-sa/4.0/88x31.png)](http://creativecommons.org/licenses/by-sa/4.0/)
27
+ > The source-code comments and documentation are written in [GitHub Flavored Markdown](https://github.github.com/gfm/).
28
+
29
+ */
30
+
31
+ //# Dependencies
32
+ //## Internal
33
+ import deriveOptions from './cno-options.js';
34
+ import { inspThis } from './cno-utility.js';
35
+ //## Standard
36
+ import CryptoNS from 'node:crypto';
37
+ import FSNS from 'node:fs/promises';
38
+ //import TypesNS from 'node:util/types';
39
+ //## External
40
+ import * as NanoID from 'nanoid';
41
+ //# Constants
42
+ const FILENAME = 'cno-sha2-256.js';
43
+ const MULTIHASH_PREFIX = Buffer.from( [ 0x12, 0x20 ] );
44
+ //## Errors
45
+
46
+ //# Global Variables
47
+ /**## Functions*/
48
+ function getNowString(){
49
+ var datetime = new Date();
50
+ return datetime.toISOString();
51
+ }
52
+ /**
53
+ ### addSHA256PrefixToBuffer
54
+ > Adds the [MultiHash](https://multiformats.io/multihash/) prefix to the start of the digest buffer.
55
+
56
+ #### Parametres
57
+ | name | type | description |
58
+ | --- | --- | --- |
59
+ | buffer | buffer | The buffer to wich prepend `MULTIHASH_PREFIX`. |
60
+
61
+ #### Returns
62
+ | type | description |
63
+ | --- | --- |
64
+ | Buffer | A NodeJS Buffer of the hash digest prefixed with the MultiHash identifier code. |
65
+
66
+ #### History
67
+ | version | change |
68
+ | --- | --- |
69
+ | 0.0.1 | WIP |
70
+ */
71
+ function addSHA256PrefixToBuffer( buffer ){
72
+ const FUNCTION_NAME = 'addSHA256PrefixToBuffer';
73
+ // Variables
74
+ //var arguments_array = Array.from(arguments);
75
+ var _return = null;
76
+ //var return_error = null;
77
+ //this?.logger?.log({file: FILENAME, function: FUNCTION_NAME, level: 'debug', message: `received: ${arguments_array}`});
78
+ // Parametre checks
79
+ // Function
80
+ _return = Buffer.concat( [ MULTIHASH_PREFIX, buffer ] );
81
+ // Return
82
+ this?.logger?.log({file: FILENAME, function: FUNCTION_NAME, level: 'debug', message: `returned: ${_return}`});
83
+ return _return;
84
+ } // addSHA256PrefixToBuffer
85
+ /**
86
+ ### removeSHA256PrefixFromBuffer
87
+ > Removes the MultiHash SHA2-256 identification bytes from the start of the given buffer.
88
+
89
+ #### Parametres
90
+ | name | type | description |
91
+ | --- | --- | --- |
92
+ | buffer | object | The buffer. |
93
+
94
+ #### Returns
95
+ | type | description |
96
+ | --- | --- |
97
+ | Buffer | A buffer without the MultiHash prefix. |
98
+
99
+ #### History
100
+ | version | change |
101
+ | --- | --- |
102
+ | 0.0.1 | WIP |
103
+ */
104
+ function removeSHA256PrefixFromBuffer( buffer ){
105
+ const FUNCTION_NAME = 'removeSHA256PrefixFromBuffer';
106
+ // Variables
107
+ //var arguments_array = Array.from(arguments);
108
+ var _return = null;
109
+ //this?.logger?.log({file: FILENAME, function: FUNCTION_NAME, level: 'debug', message: `received: ${arguments_array}`});
110
+ // Parametre checks
111
+ // Function
112
+ _return = buffer.subarray( 2 );
113
+ // Return
114
+ this?.logger?.log({file: FILENAME, function: FUNCTION_NAME, level: 'debug', message: `returned: ${_return}`});
115
+ return _return;
116
+ } // removeSHA256PrefixFromBuffer
117
+ /**
118
+ ### addReadStreamToFilehandle
119
+ > Attaches a read stream to the filehandle which will be automatically destroyed when the file closes.
120
+
121
+ #### Parametres
122
+ | name | type | description |
123
+ | --- | --- | --- |
124
+ | input_options | object | Run-time options. \[default: {}\] |
125
+
126
+ ##### `options` Properties
127
+ | name | type | default | description |
128
+ | --- | --- | --- | --- |
129
+ | noop | boolean | false | Skip primary functionality. |
130
+ | noDefaults | boolean | false | Don't apply static default options. |
131
+ | noDynamic | boolean | false | Don't apply dynamic default options. |
132
+ | filehandle | [FileHandle](https://nodejs.org/docs/latest/api/fs.html#class-filehandle) | undefined | The filehandle for which to create a new read stream and attach it to the main filehandle. |
133
+
134
+ #### Returns
135
+ | type | description |
136
+ | --- | --- |
137
+ | [FileHandle](https://nodejs.org/docs/latest/api/fs.html#class-filehandle) | Filehandle with the read stream added via the `filehandle.managedReadStreams` array property. |
138
+
139
+ #### Throws
140
+ | code | type | condition |
141
+ | --- | --- | --- |
142
+ | 'ERR_INVALID_ARG_TYPE' | TypeError | Thrown if a given argument isn't of the correct type. |
143
+
144
+ #### History
145
+ | version | change |
146
+ | --- | --- |
147
+ | 0.0.1 | WIP |
148
+ */
149
+ function addReadStreamToFilehandle( input_options = {} ){
150
+ const FUNCTION_NAME = 'addReadStreamToFilehandle';
151
+ const DEFAULT_OPTIONS = {
152
+ noop: false, // Skip primary functionality.
153
+ noDefaults: false, // Don't apply static default options.
154
+ noDynamic: false, // Don't apply dynamic default options.
155
+ filehandle: undefined // The filehandle for which to create a new read stream and attach it to the main filehandle.
156
+ };// Variables
157
+ var arguments_array = Array.from(arguments);
158
+ var _return = null;
159
+ var return_error = null;
160
+ var options = {};
161
+ this?.logger?.log({file: FILENAME, function: FUNCTION_NAME, level: 'debug', message: `received: ${arguments_array}`});
162
+ // Parametre checks
163
+ if( typeof(input_options) !== 'object' ){
164
+ return_error = new TypeError('Param "input_options" is not of type object.');
165
+ return_error.code = 'ERR_INVALID_ARG_TYPE';
166
+ throw return_error;
167
+ }
168
+
169
+ // Options
170
+ if( input_options.noDefaults !== true ){
171
+ options = Object.assign( options, DEFAULT_OPTIONS, input_options );
172
+ } else{
173
+ options = Object.assign( options, input_options );
174
+ }
175
+ if( options.noop !== true ){
176
+ // Function
177
+ if( options.filehandle != null && typeof(options.filehandle) === 'object' ){
178
+ if( Array.isArray(options.filehandle?.managedReadStreams) == false ){
179
+ options.filehandle.managedReadStreams = [];
180
+ options.filehandle.on( 'close', () => {
181
+ for( var i = 0; i < options.filehandle.managedReadStreams.length; i++ ){
182
+ options.filehandle.managedReadStreams[i].destroy( null, () => {
183
+ this?.logger?.log({file: FILENAME, function: FUNCTION_NAME, level: 'debug', message: `stream#${options.filehandle.managedReadStreams[i].uid} destroy()`});
184
+ } );
185
+ }
186
+ } );
187
+ }
188
+ var temp_read_stream = options.filehandle.createReadStream( { autoClose: false, start: 0 } );
189
+ temp_read_stream.uid = NanoID.nanoid();
190
+ temp_read_stream.createdAt = getNowString();
191
+
192
+ _return = ( options.filehandle.managedReadStreams.push( temp_read_stream ) - 1 );
193
+ } else{
194
+ return_error = new TypeError('Invalid option property: "filehandle" must be an instance of NodeJS\'s FileHandle class.');
195
+ return_error.code = 'ERR_INVALID_ARG_VALUE';
196
+ throw return_error;
197
+ }
198
+ } // noop
199
+ // Return
200
+ this?.logger?.log({file: FILENAME, function: FUNCTION_NAME, level: 'debug', message: `returned: ${_return}`});
201
+ return _return;
202
+ } // addReadStreamToFilehandle
203
+
204
+ /**
205
+ ### getSHA2FromU8A
206
+ > A pure javascript implementation of the SHA2 suite.
207
+
208
+ #### Parametres
209
+ | name | type | description |
210
+ | --- | --- | --- |
211
+ | input_options | object | Run-time options. \[default: {}\] |
212
+
213
+ ##### `options` Properties
214
+ | name | type | default | description |
215
+ | noop | boolean | false | Skip primary functionality. |
216
+ | noDefaults | boolean | false | Don't apply static default options. |
217
+ | noDynamic | boolean | false | Don't apply dynamic default options. |
218
+ | message | Uint8Array | null | The message or data, as a `Uint8Array`, to be cryptographically hashed and digested. |
219
+ | bits | number | 256 | The digest size in bits; valid values are: 224, 256, 384, and 512. |
220
+
221
+ #### Returns
222
+ | type | description |
223
+ | --- | --- |
224
+ | Uint8Array | The SHA2 digest as a `Uint8Array`. |
225
+
226
+ #### Throws
227
+ | code | type | condition |
228
+ | --- | --- | --- |
229
+ | 'ERR_INVALID_ARG_TYPE' | TypeError | Thrown if a given argument isn't of the correct type. |
230
+
231
+ #### History
232
+ | version | change |
233
+ | --- | --- |
234
+ | 0.0.1 | WIP |
235
+ */
236
+ /* c8 ignore start */
237
+ /*function getSHA2FromU8A( input_options = {} ){
238
+ const FUNCTION_NAME = 'getSHA2FromU8A';
239
+ const DEFAULT_OPTIONS = {
240
+ noop: false, // Skip primary functionality.
241
+ noDefaults: false, // Don't apply static default options.
242
+ noDynamic: false, // Don't apply dynamic default options.
243
+ message: null, // The message or data, as a `Uint8Array`, to be cryptographically hashed and digested.
244
+ bits: 256, // The digest size in bits; valid values are: 224, 256, 384, and 512.
245
+ };//Variables
246
+ var arguments_array = Array.from(arguments);
247
+ var _return = null;
248
+ var return_error = null;
249
+ var options = {};
250
+ this?.logger?.log({file: FILENAME, function: FUNCTION_NAME, level: 'debug', message: `received: ${arguments_array}`});
251
+ //Parametre checks
252
+ if( typeof(input_options) !== 'object' ){
253
+ return_error = new TypeError('Param "input_options" is not of type object.');
254
+ return_error.code = 'ERR_INVALID_ARG_TYPE';
255
+ throw return_error;
256
+ }
257
+
258
+ // Options
259
+ if( input_options.noDefaults !== true ){
260
+ options = Object.assign( options, DEFAULT_OPTIONS, input_options );
261
+ } else{
262
+ options = Object.assign( options, input_options )
263
+ }
264
+ if( options.noop !== true ){
265
+ // Function
266
+ } // noop
267
+ //Return
268
+ this?.logger?.log({file: FILENAME, function: FUNCTION_NAME, level: 'debug', message: `returned: ${_return}`});
269
+ return _return;
270
+ } // getSHA2FromU8A */
271
+ /* c8 ignore stop */
272
+
273
+ /**
274
+ ### getSHA256FromBufferSync
275
+ > Returns a Node Buffer containing the SHA2-256 digest of the given buffer.
276
+
277
+ #### Parametres
278
+ | name | type | description |
279
+ | --- | --- | --- |
280
+ | input_options | object | Run-time options. \[default: {}\] |
281
+
282
+ ##### `options` Properties
283
+ | name | type | default | description |
284
+ | noop | boolean | false | Skip primary functionality. |
285
+ | noDefaults | boolean | false | Don't apply static default options. |
286
+ | noDynamic | boolean | false | Don't apply dynamic default options. |
287
+ | buffer | Buffer | null | A NodeJS Buffer to be hash-digested. |
288
+ | prefix | boolean | false | Whether to prefix the resultant Buffer with a [MultiHash](https://multiformats.io/multihash/) code. |
289
+
290
+ #### Returns
291
+ | type | description |
292
+ | --- | --- |
293
+ | Buffer | A NodeJS Buffer containing the SHA2-256 hash digest. |
294
+
295
+ #### Throws
296
+ | code | type | condition |
297
+ | --- | --- | --- |
298
+ | 'ERR_INVALID_ARG_TYPE' | TypeError | Thrown if a given argument isn't of the correct type. |
299
+
300
+ #### History
301
+ | version | change |
302
+ | --- | --- |
303
+ | 0.0.1 | WIP |
304
+ */
305
+ function getSHA256FromBufferSync( input_options = {} ){
306
+ const FUNCTION_NAME = 'getSHA256FromBufferSync';
307
+ const DEFAULT_OPTIONS = {
308
+ noop: false, // Skip primary functionality.
309
+ noDefaults: false, // Don't apply static default options.
310
+ noDynamic: false, // Don't apply dynamic default options.
311
+ buffer: null, // A NodeJS Buffer to be hash-digested.
312
+ prefix: false, // Whether to prefix the resultant Buffer with a [MultiHash](https://multiformats.io/multihash/) code.
313
+ };
314
+ // Variables
315
+ var arguments_array = Array.from(arguments);
316
+ var _return = null;
317
+ var return_error = null;
318
+ var options = {};
319
+ var buffer = null;
320
+ this?.logger?.log({file: FILENAME, function: FUNCTION_NAME, level: 'debug', message: `received: ${arguments_array}`});
321
+ // Parametre checks
322
+ if( typeof(input_options) !== 'object' ){
323
+ return_error = new TypeError('Param "input_options" is not of type object.');
324
+ return_error.code = 'ERR_INVALID_ARG_TYPE';
325
+ throw return_error;
326
+ }
327
+
328
+ // Options
329
+ if( input_options.noDefaults !== true ){
330
+ options = Object.assign( options, DEFAULT_OPTIONS, input_options );
331
+ } else{
332
+ options = Object.assign( options, input_options );
333
+ }
334
+ if( options.noop !== true ){
335
+ // Function
336
+ var hasher = CryptoNS.createHash( 'sha256' );
337
+ if( Buffer.isBuffer( options.buffer ) === true ){
338
+ buffer = options.buffer;
339
+ } else{
340
+ buffer = Buffer.from( options.buffer );
341
+ }
342
+ hasher.update( buffer );
343
+ if( options.prefix === true ){
344
+ _return = addSHA256PrefixToBuffer( hasher.digest() );
345
+ } else{
346
+ _return = hasher.digest();
347
+ }
348
+ } // noop
349
+ // Return
350
+ this?.logger?.log({file: FILENAME, function: FUNCTION_NAME, level: 'debug', message: `returned: ${_return}`});
351
+ return _return;
352
+ } // getSHA256FromBufferSync
353
+ /**
354
+ ### getSHA256FromBuffer
355
+ > Returns a promise which resolves to the SHA2-256 hash digest, as a Node buffer, of the given buffer.
356
+
357
+ #### Parametres
358
+ | name | type | description |
359
+ | --- | --- | --- |
360
+ | buffer | Buffer | The buffer to be hashed. |
361
+
362
+ #### Returns
363
+ | type | description |
364
+ | --- | --- |
365
+ | Promise | A promise which resolves to a SHA2-256 hash digest as a Node buffer. |
366
+
367
+ #### Throws
368
+ | code | type | condition |
369
+ | --- | --- | --- |
370
+ | 'ERR_INVALID_ARG_TYPE' | TypeError | Thrown if a given argument isn't of the correct type. |
371
+
372
+ #### History
373
+ | version | change |
374
+ | --- | --- |
375
+ | 0.0.1 | WIP |
376
+ */
377
+ function getSHA256FromBuffer( buffer ){
378
+ const FUNCTION_NAME = 'getSHA256FromBuffer';
379
+ // Variables
380
+ //var arguments_array = Array.from(arguments);
381
+ var _return = null;
382
+ var return_error = null;
383
+ //this?.logger?.log({file: FILENAME, function: FUNCTION_NAME, level: 'debug', message: `received: ${arguments_array}`});
384
+ // Parametre checks
385
+ if( Buffer.isBuffer(buffer) !== true ){
386
+ return_error = new TypeError('Param "buffer" is not of type Buffer.');
387
+ return_error.code = 'ERR_INVALID_ARG_TYPE';
388
+ throw return_error;
389
+ }
390
+ // Function
391
+ var hasher = CryptoNS.createHash( 'sha256' );
392
+ hasher.update( buffer );
393
+ _return = Promise.resolve( hasher.digest() );
394
+ // Return
395
+ this?.logger?.log({file: FILENAME, function: FUNCTION_NAME, level: 'debug', message: `returned: ${_return}`});
396
+ return _return;
397
+ } // getSHA256FromBuffer
398
+ /**
399
+ ### getSHA256FromString
400
+ > Returns a promise which resolves to the SHA2-256 hash digest of the given string.
401
+
402
+ #### Parametres
403
+ | name | type | description |
404
+ | --- | --- | --- |
405
+ | string | string | The string to hash. |
406
+
407
+ #### Returns
408
+ | type | description |
409
+ | --- | --- |
410
+ | Promise | A promise which resolves to the hash digest as a Node Buffer. |
411
+
412
+ #### Throws
413
+ | code | type | condition |
414
+ | --- | --- | --- |
415
+ | 'ERR_INVALID_ARG_TYPE' | TypeError | Thrown if a given argument isn't of the correct type. |
416
+
417
+ #### History
418
+ | version | change |
419
+ | --- | --- |
420
+ | 0.0.1 | WIP |
421
+ */
422
+ function getSHA256FromString( string ){
423
+ const FUNCTION_NAME = 'getSHA256FromString';
424
+ // Variables
425
+ //var arguments_array = Array.from(arguments);
426
+ var _return = null;
427
+ var return_error = null;
428
+ //this?.logger?.log({file: FILENAME, function: FUNCTION_NAME, level: 'debug', message: `received: ${arguments_array}`});
429
+ // Parametre checks
430
+ if( typeof(string) !== 'string' ){
431
+ return_error = new TypeError('Param "string" is not of type string.');
432
+ return_error.code = 'ERR_INVALID_ARG_TYPE';
433
+ throw return_error;
434
+ }
435
+
436
+ // Function
437
+ _return = getSHA256FromBuffer( Buffer.from( string, 'utf8' ) );
438
+ // Return
439
+ this?.logger?.log({file: FILENAME, function: FUNCTION_NAME, level: 'debug', message: `returned: ${_return}`});
440
+ return _return;
441
+ } // getSHA256FromString
442
+
443
+
444
+ //function promiseExecutor( resolveFunction, rejectFunction ){
445
+ // console.log( 'this: %o resolveFunction: %o rejectFunction: %o', this, resolveFunction, rejectFunction );
446
+ // var fail_func = function( reason_string ){
447
+ // rejectFunction( reason_string );
448
+ // };
449
+ // var timeout = setTimeout( fail_func.bind( null, 'Stream timed out.' ), 10000 );
450
+ // var hasher = CryptoNS.createHash('sha256');
451
+ // this.on( 'data', ( data_buffer ) => {
452
+ // console.error('onData: %d', data_buffer.length);
453
+ // hasher.update( data_buffer );
454
+ // } );
455
+ // this.on( 'end', () => {
456
+ // console.error('onEnd');
457
+ // clearTimeout( timeout );
458
+ // resolveFunction( hasher.digest() );
459
+ // } );
460
+ //}
461
+ /**
462
+ ### getSHA256FromStream
463
+ > Directly, asynchronously, gets a SHA2-256 hash digest as a Node Buffer from a Node stream.
464
+
465
+ #### Parametres
466
+ | name | type | description |
467
+ | --- | --- | --- |
468
+ | stream | stream.Readable | The Readable Stream to whose data is to be hashed. |
469
+
470
+ #### Returns
471
+ | type | description |
472
+ | --- | --- |
473
+ | Promise | A promise which resolves to the SHA2-256 hash digest as a Node buffer. |
474
+
475
+ #### History
476
+ | version | change |
477
+ | --- | --- |
478
+ | 0.1.1 | Finally working. |
479
+ | 0.0.1 | WIP |
480
+ */
481
+ function getSHA256FromStream( stream, input_options = null ){
482
+ const FUNCTION_NAME = 'getSHA256FromStream';
483
+ // Variables
484
+ var _return = null;
485
+ //var return_error = null;
486
+ //this?.logger?.log({file: FILENAME, function: FUNCTION_NAME, level: 'debug', message: `received: ${arguments_array}`});
487
+ // Parametre checks
488
+ // Function
489
+ const options = deriveOptions.call( this, input_options );
490
+ options.logFunction( `${FUNCTION_NAME} received stream=${inspThis.call( stream )} options=${inspThis.call( options )}` );
491
+ _return = new Promise( ( resolveFunction, rejectFunction ) => {
492
+ var hasher = CryptoNS.createHash('sha256');
493
+ var digest_buffer = null;
494
+ var timeout = setTimeout( () => {
495
+ options.logFunction( `onTimeout timeout=${timeout} resolveFunction=${resolveFunction} rejectFunction=${rejectFunction} digest_buffer=${digest_buffer?.toString( 'hex' )}` );
496
+ rejectFunction('Stream timedout.');
497
+ }, 10000 );
498
+ stream.on( 'data', ( data_buffer ) => {
499
+ options?.logFunction( `onData: ${data_buffer.length}` );
500
+ hasher.update( data_buffer );
501
+ } );
502
+ stream.on( 'end', () => {
503
+ digest_buffer = hasher.digest();
504
+ options.logFunction( `onEnd timeout=${timeout} resolveFunction=${resolveFunction} digest_buffer=${digest_buffer.toString( 'hex' )}` );
505
+ clearTimeout( timeout );
506
+ resolveFunction( digest_buffer );
507
+ } );
508
+ stream.on( 'close', () => {
509
+ options.logFunction( `onClose timeout=${timeout} resolveFunction=${resolveFunction} rejectFunction=${rejectFunction} digest_buffer=${digest_buffer?.toString( 'hex' )}` );
510
+ clearTimeout( timeout );
511
+ if( digest_buffer != null ){
512
+ resolveFunction( digest_buffer );
513
+ } else{
514
+ rejectFunction( 'Closed before end.' );
515
+ }
516
+ } );
517
+ } );
518
+ // Return
519
+ this?.logger?.log({file: FILENAME, function: FUNCTION_NAME, level: 'debug', message: `returned: ${_return}`});
520
+ return _return;
521
+ } // getSHA256FromStream
522
+ /**
523
+ ### getSHA256FromFilehandle
524
+ > Gets a SHA2-256 hash digest for a given filehandle.
525
+
526
+ #### Parametres
527
+ | name | type | description |
528
+ | --- | --- | --- |
529
+ | filehandle | object | The filehandle. |
530
+
531
+ #### Returns
532
+ | type | description |
533
+ | --- | --- |
534
+ | Promise | A promise which resolves to a Node buffer of the hash digest. |
535
+
536
+ #### History
537
+ | version | change |
538
+ | --- | --- |
539
+ | 0.0.1 | WIP |
540
+ */
541
+ function getSHA256FromFilehandle( filehandle, input_options = null ){
542
+ const FUNCTION_NAME = 'getSHA256FromFilehandle';
543
+ // Variables
544
+ //var arguments_array = Array.from(arguments);
545
+ var _return = null;
546
+ var return_error = null;
547
+ //`console.log( 'file: %s function: %s level: %s message: received: %o', FILENAME, FUNCTION_NAME, 'debug', filehandle );
548
+ // Parametre checks
549
+ /*if( typeof(filehandle) !== 'object' ){
550
+ return_error = new TypeError('Param "filehandle" is not of type object.');
551
+ return_error.code = 'ERR_INVALID_ARG_TYPE';
552
+ throw return_error;
553
+ }*/
554
+
555
+ const options = deriveOptions.call( this, input_options );
556
+ options.logFunction( `${FUNCTION_NAME} received filehandle=${inspThis.call( filehandle )} options=${inspThis.call( options )}` );
557
+ // Function
558
+ _return = new Promise( ( resolveFunction, rejectFunction ) => {
559
+ var read_stream = filehandle.createReadStream( { autoClose: false, start: 0 } );
560
+ _return = getSHA256FromStream( read_stream, options ).then(
561
+ ( digest_buffer ) => {
562
+ options?.logFunction( `getSHA256FromStream resolved with digest_buffer=${digest_buffer.toString( 'hex' )}` );
563
+ resolveFunction( digest_buffer );
564
+ },
565
+ ( error ) => {
566
+ return_error = new Error( `getSHA256FromStream rejected with error: ${error}` );
567
+ return_error.cause = error;
568
+ rejectFunction( return_error );
569
+ }
570
+ );
571
+ filehandle.on( 'close', () => {
572
+ options.logFunction( `onClose filehandle=${filehandle} read_stream=${read_stream}` );
573
+ read_stream.destroy();
574
+ rejectFunction( 'Filehandle closed' );
575
+ } );
576
+ } );
577
+
578
+ // read_stream.on( 'close', () => {
579
+ // console.error( 'stream on close.' );
580
+ // } );
581
+ // var index = addReadStreamToFilehandle( { filehandle: filehandle } );
582
+ // _return = getSHA256FromStream( filehandle.managedReadStreams[index] ).then(
583
+ // ( sha256_buffer ) => {
584
+ // console.log( 'Before destroying read stream: filehandle: %o', filehandle );
585
+ // /* read_stream.destroy( null, () => { // closes filehandle
586
+ // console.log( 'In stream.destroy callback.' );
587
+ // } ); */
588
+ // console.log( 'After destroying read stream: filehandle: %o', filehandle );
589
+ // return sha256_buffer;
590
+ // }
591
+ // );
592
+ // Return
593
+ this?.logger?.log({file: FILENAME, function: FUNCTION_NAME, level: 'debug', message: `returned: ${_return}`});
594
+ return _return;
595
+ } // getSHA256FromFilehandle
596
+ /**
597
+ ### getSHA256FromFilePath
598
+ > Returns a SHA2-256 hash digest for the file at the given path.
599
+
600
+ #### Parametres
601
+ | name | type | description |
602
+ | --- | --- | --- |
603
+ | path | string | The path of the file to hash. |
604
+
605
+ #### Returns
606
+ | type | description |
607
+ | --- | --- |
608
+ | Promise | A promise which resolves to the hash digest as a Node Buffer. |
609
+
610
+ #### Throws
611
+ | code | type | condition |
612
+ | --- | --- | --- |
613
+ | 'ERR_INVALID_ARG_TYPE' | TypeError | Thrown if a given argument isn't of the correct type. |
614
+
615
+ #### History
616
+ | version | change |
617
+ | --- | --- |
618
+ | 0.0.1 | WIP |
619
+ */
620
+ function getSHA256FromFilePath( path, input_options = null ){
621
+ const FUNCTION_NAME = 'getSHA256FromFilePath';
622
+ // Variables
623
+ //var arguments_array = Array.from(arguments);
624
+ var _return = null
625
+ var return_error = null;
626
+ //this?.logger?.log({file: FILENAME, function: FUNCTION_NAME, level: 'debug', message: `received: ${arguments_array}`});
627
+ // Parametre checks
628
+ // if( typeof(path) !== 'string' ){
629
+ // return_error = new TypeError('Param "path" is not of type string.');
630
+ // return_error.code = 'ERR_INVALID_ARG_TYPE';
631
+ // throw return_error;
632
+ // }
633
+ const options = deriveOptions.call( this, input_options );
634
+ options.logFunction( `${FUNCTION_NAME} received path=${inspThis.call( path )} options=${inspThis.call( options )}` );
635
+ // Function
636
+ _return = FSNS.open( path ).then(
637
+ ( filehandle ) => {
638
+ _return = getSHA256FromFilehandle( filehandle, options ).then(
639
+ null,
640
+ ( error ) => {
641
+ return_error = new Error( `getSHA256FromFilehandle rejected with error: ${error}` );
642
+ return_error.cause = error;
643
+ throw return_error;
644
+ }
645
+ ).finally(
646
+ () => filehandle.close().then( null, () => {} )
647
+ );
648
+ return _return;
649
+ },
650
+ ( error ) => {
651
+ return_error = new Error( `For path='${path}': FSNS.open rejected with error: ${error}` );
652
+ return_error.cause = error;
653
+ throw return_error;
654
+ }
655
+ );
656
+ // Return
657
+ this?.logger?.log({file: FILENAME, function: FUNCTION_NAME, level: 'debug', message: `returned: ${_return}`});
658
+ return _return;
659
+ } // getSHA256FromFilePath
660
+
661
+ /**
662
+ ### getSHA256FromOptions
663
+ > Gets a SHA2-256 digest of the stream's content when it closes.
664
+
665
+ #### Parametres
666
+ | name | type | description |
667
+ | --- | --- | --- |
668
+ | input_options | object | Run-time options. \[default: null\] |
669
+
670
+ ##### `options` Properties
671
+ | name | type | default | description |
672
+ | noop | boolean | false | Skip primary functionality. |
673
+ | noDefaults | boolean | false | Don't apply static default options. |
674
+ | noDynamic | boolean | false | Don't apply dynamic default options. |
675
+ | prefix | boolean | false | Whether to prefix the resultant buffer with the [MultiHash](https://multiformats.io/multihash/) prefix code.
676
+ | buffer | [Buffer](https://nodejs.org/api/buffer.html#class-buffer) | null | A buffer to hash; if this is specified the following input options will be ignored. |
677
+ | stream | [stream.Readable](https://nodejs.org/api/stream.html#class-streamreadable) | null | A NodeJS Readable Stream to be hashed; ignored if `options.buffer` is specified. |
678
+ | filehandle | [FileHandle](https://nodejs.org/api/fs.html#class-filehandle) | null | A NodeJS filehandle to be hashed; ignored if `options.buffer` or `options.stream` are specified. |
679
+ | path | string | '' | A filesystem path to a file to be hashed; only used if none of the previous input options are used. |
680
+
681
+ #### Returns
682
+ | type | description |
683
+ | --- | --- |
684
+ | Promise | A promise which resolves with the SHA2-256 digest of the stream's data when the stream closes. |
685
+
686
+ #### Throws
687
+ | code | type | condition |
688
+ | --- | --- | --- |
689
+ | 'ERR_INVALID_ARG_TYPE' | TypeError | Thrown if a given argument isn't of the correct type. |
690
+ | 'ERR_INVALID_ARG_VALUE' | Error | Thrown if none of the input options are specified. |
691
+
692
+ #### History
693
+ | version | change |
694
+ | --- | --- |
695
+ | 0.0.1 | WIP |
696
+ */
697
+ function getSHA256FromOptions( input_options = null ){
698
+ const FUNCTION_NAME = 'getSHA256FromOptions';
699
+ const DEFAULT_OPTIONS = {
700
+ prefix: false,
701
+ buffer: undefined,
702
+ string: undefined,
703
+ stream: undefined, // A NodeJS Readable Stream to be hashed.
704
+ filehandle: undefined,
705
+ path: undefined
706
+ };// Variables
707
+ //var arguments_array = Array.from(arguments);
708
+ var _return = null;
709
+ var return_error = null;
710
+ //this?.logger?.log({file: FILENAME, function: FUNCTION_NAME, level: 'debug', message: `received: ${arguments_array}`});
711
+ // Parametre checks
712
+ if( typeof(input_options) !== 'object' ){
713
+ return_error = new TypeError('Param "input_options" is not of type object.');
714
+ return_error.code = 'ERR_INVALID_ARG_TYPE';
715
+ throw return_error;
716
+ }
717
+
718
+ // Options
719
+ const options = deriveOptions.call( this, input_options, DEFAULT_OPTIONS );
720
+ if( options.noop !== true ){
721
+ // Function
722
+ options.logFunction('input: buffer %d; string %d; stream %d; filehandle %d; path %d', options.buffer != undefined, options.string != undefined, options.stream != undefined, options.filehandle != undefined, options.path != undefined );
723
+ if( options.buffer ){
724
+ if( Buffer.isBuffer( options.buffer ) ){
725
+ _return = getSHA256FromBuffer( options.buffer );
726
+ } else{
727
+ return_error = new TypeError('"options.buffer" is not a buffer.');
728
+ return_error.code = 'ERR_INVALID_ARG_TYPE';
729
+ throw return_error;
730
+ }
731
+ } else if( options.string != undefined ){
732
+ if( typeof(options.string) === 'string' ){
733
+ _return = getSHA256FromString( options.string );
734
+ } else{
735
+ return_error = new TypeError(`"options.string" is not a string.`);
736
+ return_error.code = 'ERR_INVALID_ARG_TYPE';
737
+ throw return_error;
738
+ }
739
+ } else if( options.stream ){
740
+ options.logFunction('stream');
741
+ _return = getSHA256FromStream( options.stream );
742
+ } else if( options.filehandle ){
743
+ /*const condition = ( options.filehandle instanceof FSNS.FileHandle );
744
+ console.log( 'condition: %d', condition );
745
+ if( options.filehandle instanceof FSNS.FileHandle ){*/
746
+ _return = getSHA256FromFilehandle( options.filehandle );
747
+ /*} else{
748
+ return_error = new TypeError('"options.filehandle" is not a FileHandle.');
749
+ return_error.code = 'ERR_INVALID_ARG_TYPE';
750
+ throw return_error;
751
+ }*/
752
+ } else if( options.path ){
753
+ options.logFunction( `path: ${options.path}` );
754
+ if( typeof(options.path) === 'string' ){
755
+ _return = getSHA256FromFilePath( options.path );
756
+ } else{
757
+ return_error = new TypeError('"options.path" is not a path.');
758
+ return_error.code = 'ERR_INVALID_ARG_TYPE';
759
+ throw return_error;
760
+ }
761
+ } else{
762
+ options.logFunction('no input');
763
+ return_error = new Error('No input option specified.');
764
+ return_error.code = 'ERR_INVALID_ARG_VALUE';
765
+ throw return_error;
766
+ }
767
+ if( options.prefix === true ){
768
+ _return = _return.then(
769
+ ( digest_buffer ) => {
770
+ return addSHA256PrefixToBuffer( digest_buffer );
771
+ },
772
+ null
773
+ );
774
+ }
775
+ } // noop
776
+ // Return
777
+ this?.logger?.log({file: FILENAME, function: FUNCTION_NAME, level: 'debug', message: `returned: ${_return}`});
778
+ return _return;
779
+ } // getSHA256FromOptions
780
+
781
+ const NAMESPACE = {};
782
+ Object.defineProperties( NAMESPACE, {
783
+ MULTIHASH_PREFIX: {
784
+ value: MULTIHASH_PREFIX,
785
+ enumerable: true
786
+ },
787
+ addSHA256PrefixToBuffer: {
788
+ value: addSHA256PrefixToBuffer,
789
+ enumerable: true
790
+ },
791
+ removeSHA256PrefixFromBuffer: {
792
+ value: removeSHA256PrefixFromBuffer,
793
+ enumerable: true
794
+ },
795
+ addReadStreamToFilehandle: {
796
+ value: addReadStreamToFilehandle,
797
+ enumerable: true
798
+ },
799
+ getSHA256FromBufferSync: {
800
+ value: getSHA256FromBufferSync,
801
+ enumerable: true
802
+ },
803
+ getSHA256FromBuffer: {
804
+ value: getSHA256FromBuffer,
805
+ enumerable: true
806
+ },
807
+ getSHA256FromString: {
808
+ value: getSHA256FromString,
809
+ enumerable: true
810
+ },
811
+ getSHA256FromStream: {
812
+ value: getSHA256FromStream,
813
+ enumerable: true
814
+ },
815
+ getSHA256FromFilehandle: {
816
+ value: getSHA256FromFilehandle,
817
+ enumerable: true
818
+ },
819
+ getSHA256FromFilePath: {
820
+ value: getSHA256FromFilePath,
821
+ enumerable: true
822
+ },
823
+ getSHA256FromOptions: {
824
+ value: getSHA256FromOptions,
825
+ enumerable: true
826
+ }
827
+ } );
828
+ export { NAMESPACE as default, getSHA256FromBufferSync, addSHA256PrefixToBuffer, removeSHA256PrefixFromBuffer, addReadStreamToFilehandle, getSHA256FromBuffer, getSHA256FromString, getSHA256FromStream, getSHA256FromFilehandle, getSHA256FromFilePath, getSHA256FromOptions };
829
+
830
+ // cno-sha2-256.js EOF
831
+