event-storage 1.3.4 → 1.4.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.
package/README.md CHANGED
@@ -35,6 +35,7 @@ npm install event-storage
35
35
  > **CommonJS / `require()` users:** version 1.0 is ESM-only. If your project uses `require()` and migrating to ESM is not an option, install the 0.x series (`npm install event-storage@0`) which is functionally equivalent and retains full CJS support.
36
36
 
37
37
 
38
+ ## Quick Start
38
39
 
39
40
  ```javascript
40
41
  import { EventStore } from 'event-storage';
@@ -55,14 +56,22 @@ eventstore.on('ready', () => {
55
56
  });
56
57
  ```
57
58
 
59
+ ## Common Usage at a Glance
60
+
61
+ - **Append events** with optimistic concurrency via `commit(stream, events, expectedVersion, cb)`.
62
+ - **Read streams** with `getEventStream()` and fluent options for revision/range/direction.
63
+ - **Run cross-stream queries** with `query(types, matcher)` and commit with its returned `condition` for DCB.
64
+ - **Build projections** with `fromStreams()` (joined streams) and `createStream()` for persistent filtered streams.
65
+ - **Consume reliably** with `createConsumer()` for durable at-least-once (or exactly-once with state) processing.
66
+
58
67
  ## Key Features
59
68
 
60
69
  | Feature | Summary |
61
70
  |---------|---------|
62
71
  | **Optimistic concurrency** | Pass `expectedVersion` to `commit()` to guarantee conflict-free writes. |
63
72
  | **Flexible stream reading** | Range queries, reverse iteration, and a fluent builder API. |
64
- | **Derived streams** | Filter or combine events into new read-only streams. |
65
- | **Object matchers** | Support nested equality, array values (OR semantics), and scalar operators like `$gt` / `$gte` / `$lt` / `$lte` / `$eq` / `$ne`, while still benefiting from O(1) discriminant routing on writes. |
73
+ | **Joined and derived streams** | Combine any number of streams with a nested OR/AND selector tree into one globally-ordered virtual stream; filter events into reusable derived projection streams. |
74
+ | **Object matchers** | Support nested equality, array values (OR semantics), scalar operators (`$gt` / `$gte` / `$lt` / `$lte` / `$eq` / `$ne`), plus array-containment operators (`$has` / `$hasAny`), while still benefiting from O(1) discriminant routing on writes. |
66
75
  | **DCB** | Configure `typeAccessor` to have per-type stream indexes maintained automatically, and use `query()` / `Condition` for fine-grained, query-scoped optimistic concurrency (Dynamic Consistency Boundaries). |
67
76
  | **Stream categories** | Name streams `<category>-<id>` and query the whole category at once. |
68
77
  | **Durable consumers** | At-least-once (and exactly-once with `setState`) event delivery with automatic position tracking. |
@@ -75,6 +84,28 @@ eventstore.on('ready', () => {
75
84
 
76
85
  ---
77
86
 
87
+ ## Joining Streams
88
+
89
+ Merge events from multiple streams in global insertion order with `fromStreams`. The selector tree alternates: OR at even depths, AND at odd depths:
90
+
91
+ ```javascript
92
+ // OR: all events from either stream, in insertion order
93
+ const joined = eventstore.fromStreams('view', ['orders', 'payments']);
94
+
95
+ // AND: only events indexed in both streams (intersection)
96
+ const matched = eventstore.fromStreams('view', [['customer-42', 'OrderPlaced']]);
97
+
98
+ // Nested — (stream-a AND stream-b) OR (stream-c AND stream-d)
99
+ const complex = eventstore.fromStreams('view', [
100
+ ['stream-a', 'stream-b'],
101
+ ['stream-c', 'stream-d']
102
+ ]);
103
+ ```
104
+
105
+ See [Event Streams](https://node-event-storage.readthedocs.io/en/latest/streams/) for the full selector algebra, categories, and derived projection streams.
106
+
107
+ ---
108
+
78
109
  ## DCB Example
79
110
 
80
111
  ```javascript
@@ -90,11 +121,18 @@ if (!hasOpenOrder) {
90
121
 
91
122
  ## Object Matcher Syntax
92
123
 
93
- Object matchers support nested equality, array values, and scalar operators like `$gt`, `$gte`, `$lt`, `$lte`, `$eq`, and `$ne`.
124
+ Object matchers support nested equality, array values, scalar operators (`$gt`, `$gte`, `$lt`, `$lte`, `$eq`, `$ne`), and array-containment operators (`$has`, `$hasAny`).
125
+
126
+ - Scalar operators can be combined on one field (AND semantics), e.g. `{ $gte: 100, $lt: 1000 }`.
127
+ - `$has` / `$hasAny` target array-valued fields and must be used on their own for that field.
128
+
129
+ For hot paths, reuse the same matcher object reference across calls when possible (instead of recreating equivalent objects each time) so matcher compilation and cache-based optimization paths can be reused.
94
130
 
95
131
  ```javascript
96
132
  { payload: { type: ['OrderPlaced', 'OrderCancelled'] } }
97
133
  { payload: { amount: { $gte: 100, $lt: 1000 } } }
134
+ { payload: { tags: { $has: 'featured' } } }
135
+ { payload: { tags: { $hasAny: ['featured', 'priority'] } } }
98
136
  ```
99
137
 
100
138
  ---
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "event-storage",
3
- "version": "1.3.4",
3
+ "version": "1.4.0",
4
4
  "type": "module",
5
5
  "description": "An optimized embedded event store for node.js",
6
6
  "keywords": [
@@ -63,7 +63,7 @@
63
63
  "mkdirp": "^3.0.1"
64
64
  },
65
65
  "devDependencies": {
66
- "c8": "^11.0.0",
66
+ "c8": "^12.0.0",
67
67
  "coveralls-next": "^6.0.1",
68
68
  "expect.js": "^0.3.1",
69
69
  "fs-extra": "^11.3.4",
package/src/EventStore.js CHANGED
@@ -6,10 +6,11 @@ import events from 'events';
6
6
  import Storage, { ReadOnly as ReadOnlyStorage, LOCK_THROW, LOCK_RECLAIM } from './Storage.js';
7
7
  import Index from './Index.js';
8
8
  import Consumer from './Consumer.js';
9
- import { assert, getPropertyAtPath } from './utils/util.js';
9
+ import { assert } from './utils/util.js';
10
10
  import { ensureDirectory, resolvePath, scanForFiles } from './utils/fsUtil.js';
11
- import { buildTypeMatcherFn } from './utils/metadataUtil.js';
12
11
  import { fixCommitArgumentTypes, parseStreamFromIndexName, normalizePredicateRaw } from './utils/apiHelpers.js';
12
+ import { normalizeSelector, buildStreamSource } from "./utils/indexUtil.js";
13
+ import { isDcbQuery, compileDcbQuery } from "./utils/dcbUtil.js";
13
14
 
14
15
  const ExpectedVersion = {
15
16
  Any: -1,
@@ -23,29 +24,46 @@ const DEFAULT_MATCHER_PROPERTIES = ['stream', 'payload.type'];
23
24
  const STREAM_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_]*(?:[\/:@~+=\-#.][A-Za-z0-9_]+)*$/;
24
25
  const STORAGE_HOOK_EVENTS = new Set(['preCommit', 'preRead']);
25
26
 
27
+
26
28
  class OptimisticConcurrencyError extends Error {}
27
29
 
30
+ /**
31
+ * @typedef {string | SelectorNode[]} SelectorNode
32
+ */
33
+
34
+ /**
35
+ * @typedef {object} QueryItem
36
+ * @property {string[]} [types] Event type names to match (OR within the group).
37
+ * @property {string[]} [tags] Tag values to match (each tag is ANDed with the others and with types).
38
+ */
39
+
40
+ /**
41
+ * @typedef {object} DcbQuery
42
+ * @property {QueryItem[]} items Non-empty array of query items combined with OR semantics at the top level.
43
+ */
44
+
28
45
  /**
29
46
  * An accept condition that captures the global event-log position at the time a {@link EventStore#query}
30
47
  * call was made. Pass it as the `expectedVersion` argument to {@link EventStore#commit} to enforce
31
48
  * DCB-style (Dynamic Consistency Boundary) optimistic concurrency: the commit is rejected only when
32
- * one or more events that match the original query (types + optional matcher) have been appended to
49
+ * one or more events that match the original query (selector + optional matcher) have been appended to
33
50
  * the store between the `query` call and the `commit` call.
34
51
  *
35
- * @property {string[]} types The event types included in the query.
52
+ * @property {SelectorNode[]|string} selector The normalized stream selector used in the query.
53
+ * @property {string[]} types Backwards-compatible alias for the leaf stream names of the selector.
36
54
  * @property {function(object, object): boolean|null} matcher An optional function `(payload, metadata) => boolean`
37
55
  * used to narrow the conflict check. When `null`, any new event of a listed type causes a conflict.
38
56
  * @property {number} noneMatchAfter The global store length (total event count) at the time the query was made.
39
57
  */
40
58
  class CommitCondition {
41
59
  /**
42
- * @param {string[]} types
60
+ * @param {SelectorNode[]|string} selector The (normalized) stream selector.
43
61
  * @param {(function(object, object): boolean)|object|null} [matcher]
44
- * @param {number} noneMatchAfter
45
- * @param {boolean} [raw=false]
62
+ * @param {number} noneMatchAfter
63
+ * @param {boolean} [raw=false]
46
64
  */
47
- constructor(types, matcher = null, noneMatchAfter, raw = false) {
48
- this.types = types;
65
+ constructor(selector, matcher = null, noneMatchAfter, raw = false) {
66
+ this.selector = selector;
49
67
  this.matcher = matcher;
50
68
  this.raw = raw;
51
69
  this.noneMatchAfter = noneMatchAfter;
@@ -66,9 +84,20 @@ class EventStore extends events.EventEmitter {
66
84
  * @param {string} [config.streamsDirectory] The directory where the streams should be stored. Default '{storageDirectory}/streams'.
67
85
  * @param {object} [config.storageConfig] Additional config options given to the storage backend. See `Storage`.
68
86
  * @param {boolean} [config.readOnly] If the storage should be mounted in read-only mode.
69
- * @param {string|function(object): string} [config.typeAccessor] Dot-notation path (e.g. `'type'`) or
70
- * function `(event) => string` identifying the event type. Enables type-based queries via
71
- * {@link EventStore#query} and ensures proper index routing for those queries.
87
+ * @param {Array<{path: string, nameBuilder: function(string): string}>} [config.streamSources] Generic
88
+ * stream-index definitions. Each entry specifies a dot-notation `path` into the event payload and a
89
+ * `nameBuilder(value) => streamName` function. On every {@link EventStore#commit} each entry is
90
+ * evaluated: scalar values are passed directly to `nameBuilder`; array values are iterated so each
91
+ * element produces its own stream. Non-string and empty values are skipped silently. The resulting
92
+ * stream names must satisfy the stream-name pattern. Each entry's `path` is automatically registered
93
+ * in `matcherProperties` for O(1) IndexMatcher routing.
94
+ * @param {string} [config.typeAccessor] Shorthand for a `streamSources` entry with `nameBuilder = v => v`.
95
+ * Dot-notation path to the event type field (e.g. `'type'`). Enables type-based
96
+ * {@link EventStore#query} selectors and {@link DcbQuery} `types` items.
97
+ * @param {string} [config.tagsAccessor] Shorthand for a `streamSources` entry with
98
+ * `nameBuilder = v => \`tags/${v}\``. Dot-notation path to an array field of tag values (e.g.
99
+ * `'tags'`). Enables tag-scoped {@link DcbQuery} `tags` items. Values are recommended to use `/`
100
+ * as a hierarchy separator (e.g. `'course/jdsj4'` → stream `tags/course/jdsj4`).
72
101
  * @param {object|function(string): object} [config.streamMetadata] A metadata object or a function `(streamName) => object`
73
102
  * that is called whenever a new stream partition is created. The returned object is stored once in the partition
74
103
  * file header and surfaced to `preCommit` / `preRead` hooks. Takes precedence only when
@@ -81,13 +110,26 @@ class EventStore extends events.EventEmitter {
81
110
  storeName = 'eventstore';
82
111
  }
83
112
 
84
- if (typeof config.typeAccessor === 'string' && config.typeAccessor) {
85
- const accessorPath = config.typeAccessor;
86
- this.typeAccessor = (event) => getPropertyAtPath(event, accessorPath);
87
- this.typeMatcherFn = buildTypeMatcherFn(accessorPath);
88
- } else {
89
- this.typeAccessor = typeof config.typeAccessor === 'function' ? config.typeAccessor : null;
90
- this.typeMatcherFn = null;
113
+ this.streamSources = [];
114
+ this.typeSource = null;
115
+ this.tagsSource = null;
116
+
117
+ if (config.typeAccessor) {
118
+ assert(typeof config.typeAccessor === 'string', 'typeAccessor must be a dot-notation string path (e.g. \'type\').');
119
+ this.typeSource = buildStreamSource(config.typeAccessor, (v) => v);
120
+ this.streamSources.push(this.typeSource);
121
+ }
122
+
123
+ if (config.tagsAccessor) {
124
+ assert(typeof config.tagsAccessor === 'string', 'tagsAccessor must be a dot-notation string path (e.g. \'tags\').');
125
+ this.tagsSource = buildStreamSource(config.tagsAccessor, (v) => `tags/${v}`);
126
+ this.streamSources.push(this.tagsSource);
127
+ }
128
+
129
+ for (const { path, nameBuilder } of config.streamSources ?? []) {
130
+ assert(typeof path === 'string' && path, 'Each streamSources entry must have a non-empty string path.');
131
+ assert(typeof nameBuilder === 'function', 'Each streamSources entry must have a nameBuilder function.');
132
+ this.streamSources.push(buildStreamSource(path, nameBuilder));
91
133
  }
92
134
 
93
135
  this.storageDirectory = resolvePath(config.storageDirectory || /* istanbul ignore next */ './data');
@@ -99,11 +141,10 @@ class EventStore extends events.EventEmitter {
99
141
  };
100
142
  const storageConfig = Object.assign(defaults, config.storageConfig);
101
143
 
102
- // When typeAccessor is a string path, ensure the corresponding full document path
103
- // (payload.<path>) is present in matcherProperties so the IndexMatcher discriminant
104
- // table can route type-stream lookups in O(1) on every write.
105
- if (this.typeMatcherFn) {
106
- const fullPath = `payload.${config.typeAccessor}`;
144
+ // Register each source's payload path in matcherProperties so the IndexMatcher
145
+ // discriminant table can route stream lookups in O(1) on every write.
146
+ for (const source of this.streamSources) {
147
+ const fullPath = `payload.${source.path}`;
107
148
  const currentProps = storageConfig.matcherProperties || DEFAULT_MATCHER_PROPERTIES;
108
149
  if (!currentProps.includes(fullPath)) {
109
150
  storageConfig.matcherProperties = [...currentProps, fullPath];
@@ -398,14 +439,13 @@ class EventStore extends events.EventEmitter {
398
439
  checkCondition(condition) {
399
440
  if (this.storage.length <= condition.noneMatchAfter) return; // no new events since condition was obtained
400
441
 
401
- const existingTypes = condition.types.filter(t => t in this.streams);
402
- if (existingTypes.length === 0) return;
442
+ const selector = condition.selector || condition.types;
403
443
 
404
444
  // Only events after condition.noneMatchAfter can be conflicts.
405
445
  // Pass the original matcher and raw flag so the stream filters at the source.
406
446
  const stream = this.fromStreams(
407
- '_check_' + condition.types.join('_'),
408
- existingTypes,
447
+ '_check_' + Date.now(),
448
+ selector,
409
449
  condition.noneMatchAfter + 1,
410
450
  -1,
411
451
  condition.matcher,
@@ -416,57 +456,30 @@ class EventStore extends events.EventEmitter {
416
456
  }
417
457
 
418
458
  /**
419
- * Ensure a dedicated type stream exists for each event's type, creating it if needed.
420
- * Must be called before the entity stream is created to guarantee correct index routing.
459
+ * Ensure a dedicated stream exists for each indexed property value across all stream sources.
460
+ * Must be called before the entity stream write so those indexes are never incomplete.
421
461
  *
422
462
  * @private
423
- * @param {Array<object>} events The events to process.
424
- */
425
- ensureTypeStreams(events) {
426
- if (!this.typeAccessor) return;
427
- for (const event of events) {
428
- const type = this.resolveValidatedTypeStreamName(event);
429
- if (type && !(type in this.streams)) {
430
- const matcher = this.typeMatcherFn
431
- ? this.typeMatcherFn(type)
432
- : (doc) => this.typeAccessor(doc.payload) === type;
433
- this.createEventStream(type, matcher, false);
434
- }
435
- }
436
- }
437
-
438
- /**
439
- * @private
440
- * @param {object} event
441
- * @returns {string|null}
442
- */
443
- resolveValidatedTypeStreamName(event) {
444
- const type = this.typeAccessor(event);
445
- if (type === undefined || type === null || type === '') {
446
- return null;
447
- }
448
- assert(typeof type === 'string', 'typeAccessor must return a string.');
449
- assert(STREAM_NAME_PATTERN.test(type), `typeAccessor must return a valid stream name. Got: "${type}"`);
450
- return type;
451
- }
452
-
453
- /**
454
- * @private
455
- * @param {string[]} types
456
- * @returns {string[]}
457
- */
458
- getExistingQueryTypes(types) {
459
- const queryTypes = [];
460
- for (const type of types) {
461
- if (type in this.streams) {
462
- queryTypes.push(type);
463
- continue;
464
- }
465
- if (!this.typeAccessor) {
466
- throw new Error(`Type stream "${type}" does not exist. Create it with createEventStream() first, or configure typeAccessor to have type streams created automatically on commit.`);
463
+ * @param {Array<object>} events
464
+ */
465
+ ensureStreams(events) {
466
+ if (this.streamSources.length === 0) return;
467
+ for (const { accessor, nameBuilder, matcherFn, path } of this.streamSources) {
468
+ for (const event of events) {
469
+ const raw = accessor(event);
470
+ const isArrayValue = Array.isArray(raw);
471
+ const values = isArrayValue ? raw : (raw != null && raw !== '' ? [raw] : []);
472
+ const buildMatcher = matcherFn(isArrayValue ? '$has' : undefined);
473
+ for (const value of values) {
474
+ if (typeof value !== 'string' || !value) continue;
475
+ const streamName = nameBuilder(value);
476
+ assert(STREAM_NAME_PATTERN.test(streamName), `Invalid stream name "${streamName}" derived from path "${path}".`);
477
+ if (!(streamName in this.streams)) {
478
+ this.createEventStream(streamName, buildMatcher(value), false);
479
+ }
480
+ }
467
481
  }
468
482
  }
469
- return queryTypes;
470
483
  }
471
484
 
472
485
  /**
@@ -504,9 +517,8 @@ class EventStore extends events.EventEmitter {
504
517
  expectedVersion = ExpectedVersion.Any;
505
518
  }
506
519
 
507
- // When typeAccessor is configured, ensure a dedicated type stream exists for each event
508
- // before the entity stream write so the type stream index is never incomplete.
509
- this.ensureTypeStreams(events);
520
+ // Ensure all indexed streams exist before the entity stream write so those indexes are never incomplete.
521
+ this.ensureStreams(events);
510
522
 
511
523
  if (!(streamName in this.streams)) {
512
524
  this.createEventStream(streamName, { stream: streamName }, false);
@@ -569,15 +581,12 @@ class EventStore extends events.EventEmitter {
569
581
  * belongs to one of the listed types and (when `matcher` is provided) also satisfies
570
582
  * `matcher(payload, metadata)`. Events written before the `query` call are never treated as conflicts.
571
583
  *
572
- * **Behaviour when a type stream does not exist:**
573
- * - Without `typeAccessor` configured: throws an error, because the store cannot guarantee that no
574
- * events of that type exist (the stream was never created). Create the stream explicitly first,
575
- * or configure `typeAccessor` to have streams created automatically on commit.
576
- * - With `typeAccessor` configured: treats the missing stream as empty (0-length). The stream will
577
- * be created automatically the first time an event of that type is committed.
584
+ * Missing stream references are treated as empty sets. In OR groups they have no effect;
585
+ * in AND groups they collapse that branch to an empty result.
578
586
  *
579
587
  * @api
580
- * @param {string[]} types A non-empty array of event-type names to query.
588
+ * @param {SelectorNode[]|object} selectorOrDcbQuery A non-empty selector array, or a {@link DcbQuery} object
589
+ * with an `items` property (compiled automatically to selector algebra).
581
590
  * @param {function|object|null} [matcher] Optional matcher used for stream pre-filtering.
582
591
  * In object mode, function predicates receive `(payload, metadata)`.
583
592
  * @param {number} [minRevision=1] The 1-based minimum global revision to include in the returned stream (inclusive).
@@ -585,17 +594,52 @@ class EventStore extends events.EventEmitter {
585
594
  * @returns {{ condition: CommitCondition, stream: EventStream }} An object with:
586
595
  * - `condition` — the {@link CommitCondition} to pass to {@link EventStore#commit}.
587
596
  * - `stream` — a read-only event stream containing all matching events.
588
- * @throws {Error} if `types` is not a non-empty array.
589
- * @throws {Error} if `typeAccessor` is not configured and any of the listed type streams do not exist.
590
- */
591
- query(types, matcher = null, minRevision = 1, raw = false) {
592
- assert(Array.isArray(types) && types.length > 0, 'Must specify a non-empty array of event types for query.');
593
- const queryTypes = this.getExistingQueryTypes(types);
594
- const condition = new CommitCondition(types, matcher, this.storage.length, raw);
595
- const stream = this.fromStreams('_query_' + types.join('_'), queryTypes, minRevision, -1, matcher, raw);
597
+ * Nested selector example (items=OR, per-item=AND, inner=OR):
598
+ * `[[courseTag, ['CourseCreated', 'CourseCapacityChanged']], [studentTag, ['StudentCreated']]]`
599
+ * @throws {Error} if `selector` is not a non-empty array.
600
+ */
601
+ query(selectorOrDcbQuery, matcher = null, minRevision = 1, raw = false) {
602
+ let selector = selectorOrDcbQuery;
603
+ if (isDcbQuery(selectorOrDcbQuery)) {
604
+ selector = compileDcbQuery(
605
+ selectorOrDcbQuery,
606
+ (type) => this.resolveTypeStream(type),
607
+ (tag) => this.resolveTagStream(tag)
608
+ );
609
+ }
610
+ assert(Array.isArray(selector) && selector.length > 0, 'Must specify a non-empty array of stream selectors for query.');
611
+ // Normalize the selector once here; both the condition and the stream use
612
+ // the normalized form. Wrap a string result (single-stream reduction) in
613
+ // an array so fromStreams always receives an array.
614
+ const normalized = normalizeSelector(selector);
615
+ const querySelector = Array.isArray(normalized) ? normalized : [normalized];
616
+ const condition = new CommitCondition(querySelector, matcher, this.storage.length, raw);
617
+ const stream = this.fromStreams('_query_' + Date.now(), querySelector, minRevision, -1, matcher, raw);
596
618
  return { stream, condition };
597
619
  }
598
620
 
621
+ /**
622
+ * @private
623
+ * @param {string} type
624
+ * @returns {string} Stream name for the given event type.
625
+ * @throws {Error} When typeAccessor is not configured.
626
+ */
627
+ resolveTypeStream(type) {
628
+ assert(this.typeSource !== null, 'DcbQuery references "types" but typeAccessor not configured.');
629
+ return this.typeSource.nameBuilder(type);
630
+ }
631
+
632
+ /**
633
+ * @private
634
+ * @param {string} tag
635
+ * @returns {string} Stream name for the given tag value.
636
+ * @throws {Error} When tagsAccessor is not configured.
637
+ */
638
+ resolveTagStream(tag) {
639
+ assert(this.tagsSource !== null, 'DcbQuery references "tags" but tagsAccessor not configured.');
640
+ return this.tagsSource.nameBuilder(tag);
641
+ }
642
+
599
643
  /**
600
644
  * Get an event stream for the given stream name within the revision boundaries.
601
645
  *
@@ -632,29 +676,23 @@ class EventStore extends events.EventEmitter {
632
676
  }
633
677
 
634
678
  /**
635
- * Create a virtual event stream from existing streams by joining them.
679
+ * Create a virtual event stream from existing streams.
680
+ *
681
+ * Uses selector algebra with alternating operator levels (depth 0 = OR, depth 1 = AND, ...).
636
682
  *
637
683
  * @param {string} streamName The (transient) name of the joined stream.
638
- * @param {Array<string>} streamNames An array of the stream names to join.
684
+ * @param {Array<string|Array<string>>} streamNames Stream selector input.
639
685
  * @param {number} [minRevision=1] The 1-based minimum revision to include in the events (inclusive).
640
686
  * @param {number} [maxRevision=-1] The 1-based maximum revision to include in the events (inclusive).
641
687
  * @param {function|object|null} [predicate] Optional matcher (see {@link EventStream}).
642
688
  * @param {boolean} [raw=false] If true, return NDJSON buffers.
643
- * @returns {EventStream} The joined event stream.
644
- * @throws {Error} if any of the streams doesn't exist.
689
+ * @returns {EventStream|JoinEventStream}
690
+ * @throws {Error} if any selected stream doesn't exist.
645
691
  */
646
692
  fromStreams(streamName, streamNames, minRevision = 1, maxRevision = -1, predicate = null, raw = false) {
647
693
  ({ predicate, raw } = normalizePredicateRaw(predicate, raw));
648
694
  assert(streamNames instanceof Array, 'Must specify an array of stream names.');
649
695
 
650
- if (streamNames.length === 0) {
651
- return new EventStream(streamName, this);
652
- }
653
-
654
- for (let stream of streamNames) {
655
- assert(stream in this.streams, `Stream "${stream}" does not exist.`);
656
- }
657
-
658
696
  return new JoinEventStream(streamName, streamNames, this, minRevision, maxRevision, predicate, raw);
659
697
  }
660
698
 
@@ -1,6 +1,38 @@
1
1
  import { getPropertyAtPath } from './utils/util.js';
2
2
  import { matches } from './utils/metadataUtil.js';
3
3
 
4
+ /**
5
+ * @param {any} value Candidate matcher value at a discriminant path.
6
+ * @param {string} operator Operator key to check for (e.g. `'$has'`).
7
+ * @returns {boolean} True when `value` is a plain object with exactly one key equal to `operator`
8
+ * and the operator value is non-null and non-undefined.
9
+ */
10
+ function isLoneOperator(value, operator) {
11
+ if (Array.isArray(value)) return false;
12
+ const keys = Object.keys(value);
13
+ if (keys.length !== 1 || keys[0] !== operator) return false;
14
+ const operand = value[operator];
15
+ return operand !== null && operand !== undefined;
16
+ }
17
+
18
+ /**
19
+ * @param {any} value Candidate matcher value at a discriminant path.
20
+ * @returns {boolean} True when `value` is `{ $has: scalar }` (lone $has with a non-object value).
21
+ */
22
+ function isLoneHasScalar(value) {
23
+ return isLoneOperator(value, '$has') && typeof value.$has !== 'object';
24
+ }
25
+
26
+ /**
27
+ * @param {any} value Candidate matcher value at a discriminant path.
28
+ * @returns {boolean} True when `value` is `{ $hasAny: [scalar, ...] }` (lone $hasAny with a non-empty scalar array).
29
+ */
30
+ function isLoneHasAnyArray(value) {
31
+ return isLoneOperator(value, '$hasAny') &&
32
+ Array.isArray(value.$hasAny) && value.$hasAny.length > 0 &&
33
+ value.$hasAny.every(v => v !== null && v !== undefined && typeof v !== 'object');
34
+ }
35
+
4
36
  /**
5
37
  * @typedef {object|function(object):boolean} Matcher
6
38
  */
@@ -143,7 +175,30 @@ class IndexMatcher {
143
175
 
144
176
  for (const propPath of this.properties) {
145
177
  const docValue = getPropertyAtPath(document, propPath);
146
- if (docValue === undefined || docValue === null || typeof docValue === 'object') {
178
+ if (docValue === undefined || docValue === null) {
179
+ continue;
180
+ }
181
+
182
+ if (Array.isArray(docValue)) {
183
+ // Multi-value document property: each array element is a potential discriminant.
184
+ // A dedup set prevents calling iterationHandler twice when two elements map to
185
+ // the same index (e.g. duplicate tags, or a single index registered for both).
186
+ const called = new Set();
187
+ for (const item of docValue) {
188
+ if (item === null || item === undefined || typeof item === 'object') continue;
189
+ const indexSet = this.table.get(propPath)?.get(String(item));
190
+ if (!indexSet) continue;
191
+ for (const indexName of indexSet) {
192
+ if (!called.has(indexName) && matches(document, this.matchers.get(indexName))) {
193
+ called.add(indexName);
194
+ iterationHandler(indexName);
195
+ }
196
+ }
197
+ }
198
+ continue;
199
+ }
200
+
201
+ if (typeof docValue === 'object') {
147
202
  continue;
148
203
  }
149
204
 
@@ -195,6 +250,16 @@ class IndexMatcher {
195
250
  value.every(v => v !== null && v !== undefined && typeof v !== 'object')) {
196
251
  return { propPath, values: value.map(String) };
197
252
  }
253
+ // Lone $has operator: array-containment matcher (e.g. tag streams). Treat the
254
+ // has-value as the discriminant so array-valued documents route in O(1).
255
+ if (isLoneHasScalar(value)) {
256
+ return { propPath, values: [String(value.$has)] };
257
+ }
258
+ // Lone $hasAny: register one matcher under each expected value so any of them
259
+ // can trigger O(1) routing when the document array contains that value.
260
+ if (isLoneHasAnyArray(value)) {
261
+ return { propPath, values: value.$hasAny.map(String) };
262
+ }
198
263
  }
199
264
  }
200
265
  return null;