event-storage 1.2.0 → 1.3.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.
@@ -130,7 +130,7 @@ class ReadablePartition extends events.EventEmitter {
130
130
  const metadata = metadataBuffer.toString('utf8').trim();
131
131
  try {
132
132
  this.metadata = JSON.parse(metadata);
133
- this.metadata.epoch = this.metadata.epoch /* istanbul ignore next */|| NES_EPOCH.getTime();
133
+ this.metadata.epoch = this.metadata.epoch /* c8 ignore next */|| NES_EPOCH.getTime();
134
134
  } catch (e) {
135
135
  throw new Error('Invalid metadata.');
136
136
  }
@@ -373,13 +373,13 @@ class ReadablePartition extends events.EventEmitter {
373
373
  */
374
374
  readDocumentBefore(position) {
375
375
  const docPos = this.findDocumentPositionBefore(position);
376
- /* istanbul ignore if */
376
+ /* c8 ignore next */
377
377
  if (docPos === false || docPos < 0) return null;
378
378
  const reader = this.prepareReadBufferBackwards(Math.min(docPos + (this.readBuffer.byteLength >> 1), this.size));
379
- /* istanbul ignore if */
379
+ /* c8 ignore next */
380
380
  if (!reader.buffer) return null;
381
381
  const cursor = docPos - this.readBufferPos;
382
- /* istanbul ignore if */
382
+ /* c8 ignore next */
383
383
  if (cursor < 0 || cursor + DOCUMENT_HEADER_SIZE > reader.length) return null;
384
384
  const header = this.readDocumentHeader(reader.buffer, cursor, docPos);
385
385
  return { header, position: docPos };
@@ -436,7 +436,7 @@ class ReadablePartition extends events.EventEmitter {
436
436
 
437
437
  const header = {};
438
438
  const data = this.readFrom(position, 0, header);
439
- /* istanbul ignore if */
439
+ /* c8 ignore next 3 */
440
440
  if (data === false) {
441
441
  return null;
442
442
  }
@@ -178,7 +178,7 @@ class WritablePartition extends ReadablePartition {
178
178
  */
179
179
  writeDocumentHeader(buffer, offset, dataSize, sequenceNumber = null, time64 = null) {
180
180
  ({ sequenceNumber, time64 } = this.normalizeWriteMetadata(sequenceNumber, time64));
181
- /* istanbul ignore if */
181
+ /* c8 ignore next */
182
182
  assert(time64 >= 0, 'Time may not be negative!');
183
183
 
184
184
  buffer.writeUInt32BE(dataSize, offset);
@@ -91,7 +91,7 @@ class ReadOnlyStorage extends ReadableStorage {
91
91
  return;
92
92
  }
93
93
  const entries = index.range(prevLength + 1, newLength);
94
- /* istanbul ignore if */
94
+ /* c8 ignore next 3 */
95
95
  if (entries === false) {
96
96
  return;
97
97
  }
@@ -1,16 +1,16 @@
1
1
  import fs from 'fs';
2
2
  import path from 'path';
3
3
  import events from 'events';
4
- import Partition, { ReadOnly as ReadOnlyPartition } from '../Partition.js';
5
- import Index, { ReadOnly as ReadOnlyIndex } from '../Index.js';
4
+ import { ReadOnly as ReadOnlyPartition } from '../Partition.js';
5
+ import { ReadOnly as ReadOnlyIndex } from '../Index.js';
6
6
  import { assert, wrapAndCheck, iterate, kWayMerge } from '../utils/util.js';
7
7
  import { scanForFiles } from '../utils/fsUtil.js';
8
8
  import { createHmac, matches, buildMetadataForMatcher } from '../utils/metadataUtil.js';
9
+ import { normalizeNamedCtorArgs } from '../utils/apiHelpers.js';
9
10
  import IndexMatcher from '../IndexMatcher.js';
10
11
  import PartitionPool from '../PartitionPool.js';
11
12
 
12
13
  const DEFAULT_READ_BUFFER_SIZE = 4 * 1024;
13
- const NDJSON_NEWLINE = Buffer.from('\n');
14
14
 
15
15
  /**
16
16
  * Default ordered list of document property paths used as discriminant keys when
@@ -60,10 +60,7 @@ class ReadableStorage extends events.EventEmitter {
60
60
  */
61
61
  constructor(storageName = 'storage', config = {}) {
62
62
  super();
63
- if (typeof storageName !== 'string') {
64
- config = storageName;
65
- storageName = undefined;
66
- }
63
+ ({ name: storageName, options: config } = normalizeNamedCtorArgs(storageName, config));
67
64
 
68
65
  this.storageFile = storageName || 'storage';
69
66
  const defaults = {
@@ -158,7 +155,7 @@ class ReadableStorage extends events.EventEmitter {
158
155
  const partition = this.createPartition(file, this.partitionConfig);
159
156
  this.partitions.add(partition.id, partition);
160
157
  }, (partErr) => {
161
- /* istanbul ignore if */
158
+ /* c8 ignore next */
162
159
  if (partErr) throw partErr;
163
160
 
164
161
  // Scan was cancelled by close() between the two scan phases.
@@ -173,7 +170,7 @@ class ReadableStorage extends events.EventEmitter {
173
170
  this.emit('index-created', name);
174
171
  }, (indexErr) => {
175
172
  // The directory could disappear between existsSync and readdir (e.g. test cleanup).
176
- /* istanbul ignore if */
173
+ /* c8 ignore next */
177
174
  if (indexErr && indexErr.code !== 'ENOENT') throw indexErr;
178
175
  done();
179
176
  });
@@ -481,7 +478,7 @@ class ReadableStorage extends events.EventEmitter {
481
478
  * @param {boolean} [noIndex=false] When true, bypasses the index and iterates partitions directly.
482
479
  */
483
480
  forEachDocument(iterationHandler, noIndex = false) {
484
- /* istanbul ignore if */
481
+ /* c8 ignore next 3 */
485
482
  if (typeof iterationHandler !== 'function') {
486
483
  return;
487
484
  }
@@ -512,7 +509,7 @@ class ReadableStorage extends events.EventEmitter {
512
509
  * @param {object} [matchDocument] If supplied, only indexes the document matches on will be iterated.
513
510
  */
514
511
  forEachSecondaryIndex(iterationHandler, matchDocument) {
515
- /* istanbul ignore if */
512
+ /* c8 ignore next 3 */
516
513
  if (typeof iterationHandler !== 'function') {
517
514
  return;
518
515
  }
@@ -537,7 +534,7 @@ class ReadableStorage extends events.EventEmitter {
537
534
  * @param {function(ReadablePartition)} iterationHandler
538
535
  */
539
536
  forEachPartition(iterationHandler) {
540
- /* istanbul ignore if */
537
+ /* c8 ignore next 3 */
541
538
  if (typeof iterationHandler !== 'function') {
542
539
  return;
543
540
  }
@@ -6,6 +6,7 @@ import ReadableStorage from './ReadableStorage.js';
6
6
  import { assert } from '../utils/util.js';
7
7
  import { ensureDirectory } from '../utils/fsUtil.js';
8
8
  import { matches, buildMetadataForMatcher, buildMatcherFromMetadata } from '../utils/metadataUtil.js';
9
+ import { normalizeNamedCtorArgs } from '../utils/apiHelpers.js';
9
10
 
10
11
  const DEFAULT_WRITE_BUFFER_SIZE = 16 * 1024;
11
12
 
@@ -44,10 +45,7 @@ class WritableStorage extends ReadableStorage {
44
45
  * @param {number} [config.lock] One of LOCK_* constants that defines how an existing lock should be handled.
45
46
  */
46
47
  constructor(storageName = 'storage', config = {}) {
47
- if (typeof storageName !== 'string') {
48
- config = storageName;
49
- storageName = undefined;
50
- }
48
+ ({ name: storageName, options: config } = normalizeNamedCtorArgs(storageName, config));
51
49
  const defaults = {
52
50
  partitioner: (document, number) => '',
53
51
  writeBufferSize: DEFAULT_WRITE_BUFFER_SIZE,
@@ -100,7 +98,7 @@ class WritableStorage extends ReadableStorage {
100
98
  */
101
99
  forEachWritableSecondaryIndex(iterationHandler, matchDocument) {
102
100
  this.forEachSecondaryIndex((index, name) => {
103
- /* istanbul ignore if */
101
+ /* c8 ignore next */
104
102
  if (!(index instanceof WritableIndex)) return;
105
103
  const wasOpen = index.isOpen();
106
104
  if (!wasOpen) index.open();
@@ -123,7 +121,7 @@ class WritableStorage extends ReadableStorage {
123
121
  this.forEachPartition(partition => {
124
122
  partition.open();
125
123
  const last = partition.readLast();
126
- /* istanbul ignore if */
124
+ /* c8 ignore next */
127
125
  if (!last) return;
128
126
  const { header: { sequenceNumber, dataSize }, position } = last;
129
127
  if (position + partition.documentWriteSize(dataSize) > partition.size) {
@@ -165,7 +163,7 @@ class WritableStorage extends ReadableStorage {
165
163
  // Truncate all indexes to the torn-write boundary.
166
164
  this.index.open();
167
165
  this.index.truncate(lastValidSequenceNumber);
168
- /* istanbul ignore next */
166
+ /* c8 ignore next */
169
167
  this.forEachWritableSecondaryIndex(index => {
170
168
  index.truncate(index.find(lastValidSequenceNumber));
171
169
  });
@@ -231,7 +229,7 @@ class WritableStorage extends ReadableStorage {
231
229
  fs.mkdirSync(this.lockFile);
232
230
  this.locked = true;
233
231
  } catch (e) {
234
- /* istanbul ignore if */
232
+ /* c8 ignore next */
235
233
  assert(e.code === 'EEXIST', `Error creating lock for storage ${this.storageFile}: ` + e.message)
236
234
 
237
235
  throw new StorageLockedError(`Storage ${this.storageFile} is locked by another process`);
@@ -290,7 +288,7 @@ class WritableStorage extends ReadableStorage {
290
288
  const entry = new WritableIndexEntry(this.index.length + 1, position, size, partitionId);
291
289
  this.index.add(entry, (indexPosition) => {
292
290
  this.emit('wrote', document, entry, indexPosition);
293
- /* istanbul ignore if */
291
+ /* c8 ignore next 3 */
294
292
  if (typeof callback === 'function') {
295
293
  return callback(indexPosition);
296
294
  }
@@ -509,9 +507,8 @@ class WritableStorage extends ReadableStorage {
509
507
  2) truncate all partitions accordingly
510
508
  3) truncate/rewrite all indexes
511
509
  */
512
- if (!this.index.isOpen()) {
513
- this.index.open();
514
- }
510
+ this.index.open();
511
+
515
512
  if (after < 0) {
516
513
  after += this.index.length;
517
514
  }
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Normalize commit overloads into a single argument object.
3
+ *
4
+ * @param {object|object[]} events Event or event list.
5
+ * @param {number|object|function} expectedVersion Expected version, CommitCondition, or already metadata/callback.
6
+ * @param {object|function} metadata Commit metadata or callback.
7
+ * @param {function} callback Completion callback.
8
+ * @param {number} ExpectedVersionAny Fallback value for "any" expectedVersion.
9
+ * @param {Function} CommitConditionClass Class used for CommitCondition checks.
10
+ * @returns {{events: object[], expectedVersion: number|object, metadata: object, callback: function}} Normalized commit arguments.
11
+ */
12
+ function fixCommitArgumentTypes(events, expectedVersion, metadata, callback, ExpectedVersionAny, CommitConditionClass) {
13
+ if (!(events instanceof Array)) {
14
+ events = [events];
15
+ }
16
+ if (typeof expectedVersion !== 'number' && !(expectedVersion instanceof CommitConditionClass)) {
17
+ callback = metadata;
18
+ metadata = expectedVersion;
19
+ expectedVersion = ExpectedVersionAny;
20
+ }
21
+ if (typeof metadata !== 'object') {
22
+ callback = metadata;
23
+ metadata = {};
24
+ }
25
+ if (typeof callback !== 'function') {
26
+ callback = () => {};
27
+ }
28
+ return { events, expectedVersion, metadata, callback };
29
+ }
30
+
31
+ /**
32
+ * Derive the stream name from an index name.
33
+ *
34
+ * @param {string} indexName Index file/index name.
35
+ * @returns {string} Corresponding stream name.
36
+ */
37
+ function parseStreamFromIndexName(indexName) {
38
+ if (indexName === '_all') {
39
+ return '_all';
40
+ }
41
+ if (indexName.startsWith('stream-')) {
42
+ return indexName.slice(7);
43
+ }
44
+ return indexName;
45
+ }
46
+
47
+ /**
48
+ * Support predicate/raw shorthand (`predicate=true`).
49
+ *
50
+ * @param {object|function|boolean|null} predicate Filter predicate or raw shorthand.
51
+ * @param {boolean} raw Raw flag from the call signature.
52
+ * @returns {{predicate: object|function|null, raw: boolean}} Normalized predicate/raw pair.
53
+ */
54
+ function normalizePredicateRaw(predicate, raw) {
55
+ if (typeof predicate === 'boolean' && raw === false) {
56
+ return { predicate: null, raw: predicate };
57
+ }
58
+ return { predicate, raw };
59
+ }
60
+
61
+ /**
62
+ * Support constructor overloads with optional `name`.
63
+ *
64
+ * @param {string|object} name Name or already the options object.
65
+ * @param {object} options Options object when `name` is provided.
66
+ * @param {string|undefined} [fallbackName=undefined] Fallback name when no explicit `name` is passed.
67
+ * @returns {{name: string|undefined, options: object}} Normalized name/options pair.
68
+ */
69
+ function normalizeNamedCtorArgs(name, options, fallbackName = undefined) {
70
+ if (typeof name !== 'string') {
71
+ return { name: fallbackName, options: name };
72
+ }
73
+ return { name, options };
74
+ }
75
+
76
+ /**
77
+ * Normalize negative revisions relative to stream length.
78
+ *
79
+ * @param {number} version Requested revision.
80
+ * @param {number} length Current stream length.
81
+ * @returns {number} Resolved revision.
82
+ */
83
+ function normalizeRevision(version, length) {
84
+ return version < 0 ? version + length + 1 : version;
85
+ }
86
+
87
+ /**
88
+ * Clamp and normalize maxRevision, including negative values.
89
+ *
90
+ * @param {number} length Current stream length.
91
+ * @param {number} maxRevision Requested max revision.
92
+ * @returns {number} Effective max revision in valid range.
93
+ */
94
+ function normalizeMaxRevision(length, maxRevision) {
95
+ return Math.min(length, maxRevision < 0 ? length + maxRevision + 1 : maxRevision);
96
+ }
97
+
98
+ /**
99
+ * Support the consumer overload where the first argument is a numeric start offset.
100
+ *
101
+ * @param {object|number} initialState Initial state or numeric start offset.
102
+ * @param {number} startFrom Start offset from the call signature.
103
+ * @returns {{initialState: object, startFrom: number}} Normalized consumer initialization values.
104
+ */
105
+ function normalizeConsumerStateArgs(initialState, startFrom) {
106
+ if (typeof initialState === 'number') {
107
+ return { initialState: {}, startFrom: initialState };
108
+ }
109
+ return { initialState, startFrom };
110
+ }
111
+
112
+ export {
113
+ fixCommitArgumentTypes,
114
+ parseStreamFromIndexName,
115
+ normalizePredicateRaw,
116
+ normalizeNamedCtorArgs,
117
+ normalizeRevision,
118
+ normalizeMaxRevision,
119
+ normalizeConsumerStateArgs
120
+ };
121
+
122
+
123
+
@@ -0,0 +1,19 @@
1
+ const emittedDeprecationWarnings = new Set();
2
+
3
+ /**
4
+ * Emit a deprecation warning only once per warning code.
5
+ *
6
+ * @param {string} code Unique warning code.
7
+ * @param {string} message Warning message.
8
+ * @returns {void}
9
+ */
10
+ function emitDeprecationWarningOnce(code, message) {
11
+ if (emittedDeprecationWarnings.has(code)) {
12
+ return;
13
+ }
14
+ emittedDeprecationWarnings.add(code);
15
+ process.emitWarning(message, 'DeprecationWarning', code);
16
+ }
17
+
18
+ export { emitDeprecationWarningOnce };
19
+
@@ -4,8 +4,8 @@ import { mkdirpSync } from 'mkdirp';
4
4
 
5
5
  /**
6
6
  * Ensure that the given directory exists.
7
- * @param {string} dirName
8
- * @return {boolean} true if the directory existed already
7
+ * @param {string} dirName Target directory.
8
+ * @returns {boolean} True when the directory already existed.
9
9
  */
10
10
  function ensureDirectory(dirName) {
11
11
  if (!fs.existsSync(dirName)) {
@@ -21,9 +21,10 @@ function ensureDirectory(dirName) {
21
21
  /**
22
22
  * Invoke `onEach` if `relativePath` matches `regexPattern`, passing the first capture group or the full match.
23
23
  *
24
- * @param {string} relativePath
25
- * @param {RegExp} regexPattern
26
- * @param {function(string)} onEach
24
+ * @param {string} relativePath Relative file path.
25
+ * @param {RegExp} regexPattern Regex used for path matching.
26
+ * @param {function(string): void} onEach Callback invoked per match.
27
+ * @returns {void}
27
28
  */
28
29
  function visitMatchingPath(relativePath, regexPattern, onEach) {
29
30
  const match = relativePath.match(regexPattern);
@@ -35,11 +36,11 @@ function visitMatchingPath(relativePath, regexPattern, onEach) {
35
36
  /**
36
37
  * Classify `entries` into matching files (visited via `onEach`) and subdirectory names (returned).
37
38
  *
38
- * @param {fs.Dirent[]} entries
39
- * @param {string} relativePrefix
40
- * @param {RegExp} regexPattern
41
- * @param {function(string)} onEach
42
- * @returns {string[]} names of subdirectory entries
39
+ * @param {fs.Dirent[]} entries Directory entries from one level.
40
+ * @param {string} relativePrefix Relative prefix for child entries.
41
+ * @param {RegExp} regexPattern Regex for file paths.
42
+ * @param {function(string): void} onEach Callback for matching files.
43
+ * @returns {string[]} Names of subdirectory entries.
43
44
  */
44
45
  function classifyEntries(entries, relativePrefix, regexPattern, onEach) {
45
46
  const subdirs = [];
@@ -56,12 +57,13 @@ function classifyEntries(entries, relativePrefix, regexPattern, onEach) {
56
57
  /**
57
58
  * Sequentially scan each name in `subdirs`, calling `done` when all are complete or on first error.
58
59
  *
59
- * @param {string[]} subdirs
60
- * @param {string} dir
61
- * @param {string} relativePrefix
62
- * @param {RegExp} regexPattern
63
- * @param {function(string)} onEach
64
- * @param {function(Error?)} done
60
+ * @param {string[]} subdirs Subdirectory names.
61
+ * @param {string} dir Absolute parent path.
62
+ * @param {string} relativePrefix Relative prefix used during recursion.
63
+ * @param {RegExp} regexPattern Regex for file paths.
64
+ * @param {function(string): void} onEach Callback for matching files.
65
+ * @param {function(Error=): void} done Completion callback.
66
+ * @returns {void}
65
67
  */
66
68
  function scanSubdirs(subdirs, dir, relativePrefix, regexPattern, onEach, done) {
67
69
  let i = 0;
@@ -79,17 +81,18 @@ function scanSubdirs(subdirs, dir, relativePrefix, regexPattern, onEach, done) {
79
81
  /**
80
82
  * Asynchronously scan one directory level, then recurse into subdirectories sequentially.
81
83
  *
82
- * @param {string} dir
83
- * @param {string} relativePrefix
84
- * @param {boolean} isRoot
85
- * @param {RegExp} regexPattern
86
- * @param {function(string)} onEach
87
- * @param {function(Error?)} done
84
+ * @param {string} dir Absolute directory path.
85
+ * @param {string} relativePrefix Relative prefix for match paths.
86
+ * @param {boolean} isRoot True for the initial call.
87
+ * @param {RegExp} regexPattern Regex for file paths.
88
+ * @param {function(string): void} onEach Callback for matching files.
89
+ * @param {function(Error=): void} done Completion callback.
90
+ * @returns {void}
88
91
  */
89
92
  function scanDir(dir, relativePrefix, isRoot, regexPattern, onEach, done) {
90
93
  fs.readdir(dir, { withFileTypes: true }, (err, entries) => {
91
94
  if (err) {
92
- /* istanbul ignore next */
95
+ /* c8 ignore next */
93
96
  if (!isRoot && err.code === 'ENOENT') return done(null);
94
97
  return done(err);
95
98
  }
@@ -112,6 +115,7 @@ function scanDir(dir, relativePrefix, isRoot, regexPattern, onEach, done) {
112
115
  * @param {RegExp} regexPattern The pattern to match relative file paths against.
113
116
  * @param {function(string)} onEach Called with the first capturing group (or full match) for each matching path.
114
117
  * @param {function(Error?)} onDone Called when the scan is complete, or with an error if one occurred.
118
+ * @returns {void}
115
119
  */
116
120
  function scanForFiles(directory, regexPattern, onEach, onDone) {
117
121
  scanDir(directory, '', true, regexPattern, onEach, onDone);