@asaidimu/utils-database 1.1.1 → 2.0.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
@@ -16,7 +16,7 @@ A flexible, schema-driven document database layer for browser and Node.js with b
16
16
  - [Basic CRUD](#basic-crud)
17
17
  - [Transactions](#transactions)
18
18
  - [Migrations](#migrations)
19
- - [Events & Telemetry](#events--telemetry)
19
+ - [Events & Telemetry](#events-telemetry)
20
20
  - [Pagination & Filtering](#pagination--filtering)
21
21
  - [Project Architecture](#project-architecture)
22
22
  - [Development & Contributing](#development--contributing)
@@ -60,7 +60,7 @@ npm install @asaidimu/utils-database
60
60
  This package has the following peer dependencies – you need to install them manually:
61
61
 
62
62
  ```bash
63
- npm install @asaidimu/anansi @asaidimu/events
63
+ npm install @asaidimu/anansi
64
64
  ```
65
65
 
66
66
  ### Basic Configuration
@@ -356,7 +356,6 @@ This project is licensed under the **MIT License**. See the [LICENSE](https://gi
356
356
 
357
357
  Built with ❤️ using:
358
358
  - [`@asaidimu/anansi`](https://github.com/asaidimu/anansi) – schema validation and migrations.
359
- - [`@asaidimu/events`](https://github.com/asaidimu/events) – type‑safe event bus.
360
359
  - [`@standard-schema/spec`](https://github.com/standard-schema/standard-schema) – Standard Schema interoperability.
361
360
  - [`uuid`](https://github.com/uuidjs/uuid) – for v7 UUIDs.
362
361
  - [`fake-indexeddb`](https://github.com/dumbmatter/fakeIndexedDB) – testing support.
package/index.d.mts CHANGED
@@ -1,6 +1,5 @@
1
1
  import { QueryFilter, PaginationOptions } from '@asaidimu/query';
2
2
  import { IndexDefinition, SchemaDefinition, SchemaChange, DataTransform, PredicateMap } from '@asaidimu/anansi';
3
- import { EventBus } from '@asaidimu/events';
4
3
  import { StandardSchemaV1 } from '@standard-schema/spec';
5
4
 
6
5
  /**
@@ -728,6 +727,59 @@ declare const createIndexedDbStore: <T extends Record<string, any>>(config: Stor
728
727
 
729
728
  declare function DatabaseConnection(config: Omit<DatabaseConfig, "keyPath">, createStore: <T extends Record<string, any>>(config: StoreConfig, indexes: IndexDefinition[]) => Store<T>): Promise<Database>;
730
729
 
730
+ /**
731
+ * Interface defining the shape of the EventBus.
732
+ * @template TEventMap - A record mapping event names to their respective payload types.
733
+ */
734
+ interface EventBus<TEventMap extends Record<string, any>> {
735
+ /**
736
+ * Subscribes to a specific event by name.
737
+ * @param eventName - The name of the event to subscribe to.
738
+ * @param callback - The function to call when the event is emitted.
739
+ * @returns A function to unsubscribe from the event.
740
+ */
741
+ subscribe: <TEventName extends keyof TEventMap>(eventName: TEventName, callback: (payload: TEventMap[TEventName]) => void) => () => void;
742
+ /**
743
+ * Subscribes to an event and automatically unsubscribes after it fires once.
744
+ * @param eventName - The name of the event to subscribe to.
745
+ * @param callback - The function to call when the event is emitted.
746
+ * @returns A function to cancel the one-shot subscription before it fires.
747
+ */
748
+ once: <TEventName extends keyof TEventMap>(eventName: TEventName, callback: (payload: TEventMap[TEventName]) => void) => () => void;
749
+ /**
750
+ * Emits an event with a payload to all subscribed listeners.
751
+ * @param event - An object containing the event name and payload.
752
+ */
753
+ emit: <TEventName extends keyof TEventMap>(event: {
754
+ name: TEventName;
755
+ payload: TEventMap[TEventName];
756
+ }) => void;
757
+ /**
758
+ * Retrieves metrics about event bus usage.
759
+ * @returns An object containing various metrics.
760
+ */
761
+ metrics: () => EventMetrics;
762
+ /**
763
+ * Clears all subscriptions and resets metrics.
764
+ * After calling clear(), the bus is fully reset and can be reused —
765
+ * cross-tab communication is re-established if it was previously enabled.
766
+ */
767
+ clear: () => void;
768
+ }
769
+ /**
770
+ * Interface defining the metrics tracked by the EventBus.
771
+ */
772
+ interface EventMetrics {
773
+ /** Total number of events emitted (both sync and deferred paths). */
774
+ totalEvents: number;
775
+ /** Number of active subscriptions across all event names. */
776
+ activeSubscriptions: number;
777
+ /** Map of event names to their emission counts. */
778
+ eventCounts: Map<string, number>;
779
+ /** Average duration of event dispatch in milliseconds. */
780
+ averageEmitDuration: number;
781
+ }
782
+
731
783
  interface MiddlewareContext {
732
784
  collection?: string;
733
785
  documentId?: string;
@@ -789,4 +841,51 @@ declare function openCollection<T extends Record<string, any>>({ collection: sch
789
841
  validate: boolean;
790
842
  }): Promise<Collection<T>>;
791
843
 
792
- export { type BufferedOperation, type Collection, type CollectionEvent, type CollectionEventType, type CollectionMigrationOptions, ConnectionManager, type CursorCallback, type CursorCallbackResult, type CursorPaginationOptions, DEFAULT_KEYPATH, type Database, type DatabaseConfig, DatabaseConnection, type DatabaseEvent, type DatabaseEventType, type Document, type DocumentEvent, type DocumentEventType, IndexedDBStore, type Store, type StoreConfig, type StoreKeyRange, type TelemetryEvent, type TelemetryEventType, createDocument, createEphemeralStore, createIndexedDbStore, openCollection };
844
+ /**
845
+ * Error types for Database operations.
846
+ */
847
+ declare enum DatabaseErrorType {
848
+ /** The schema does not exist. */
849
+ SCHEMA_NOT_FOUND = "SCHEMA_NOT_FOUND",
850
+ /** The schema already exists. */
851
+ SCHEMA_ALREADY_EXISTS = "SCHEMA_ALREADY_EXISTS",
852
+ /** The schema name is invalid. */
853
+ INVALID_SCHEMA_NAME = "INVALID_SCHEMA_NAME",
854
+ /** The schema definition is invalid. */
855
+ INVALID_SCHEMA_DEFINITION = "INVALID_SCHEMA_DEFINITION",
856
+ /** The database subscription failed. */
857
+ SUBSCRIPTION_FAILED = "SUBSCRIPTION_FAILED",
858
+ /** The database operation failed due to an internal error. */
859
+ INTERNAL_ERROR = "INTERNAL_ERROR",
860
+ /** Data being entered into a collection does not satisfy its schema definition. */
861
+ INVALID_DATA = "INVALID_DATA",
862
+ /** Optimistic Concurrency Control version mismatches */
863
+ CONFLICT = "CONFLICT",
864
+ /** For retryable store locks */
865
+ TRANSIENT_ERROR = "TRANSIENT_ERROR",
866
+ TRANSACTION_FAILED = "TRANSACTION_FAILED",
867
+ CONNECTION_FAILED = "CONNECTION_FAILED",
868
+ INVALID_OPERATION = "INVALID_OPERATION"
869
+ }
870
+ /**
871
+ * Error class for Database operations.
872
+ */
873
+ declare class DatabaseError extends Error {
874
+ /**
875
+ * The type of error that occurred.
876
+ */
877
+ type: DatabaseErrorType;
878
+ /**
879
+ * The schema associated with the error, if applicable.
880
+ */
881
+ schema?: SchemaDefinition;
882
+ /**
883
+ * Constructs a new DatabaseErrorClass instance.
884
+ * @param type - The type of error that occurred.
885
+ * @param message - A human-readable message describing the error.
886
+ * @param schema - The schema associated with the error, if applicable.
887
+ */
888
+ constructor(type: DatabaseErrorType, message: string, schema?: SchemaDefinition, cause?: unknown);
889
+ }
890
+
891
+ export { type BufferedOperation, type Collection, type CollectionEvent, type CollectionEventType, type CollectionMigrationOptions, ConnectionManager, type CursorCallback, type CursorCallbackResult, type CursorPaginationOptions, DEFAULT_KEYPATH, type Database, type DatabaseConfig, DatabaseConnection, DatabaseError, DatabaseErrorType, type DatabaseEvent, type DatabaseEventType, type Document, type DocumentEvent, type DocumentEventType, IndexedDBStore, type Store, type StoreConfig, type StoreKeyRange, type TelemetryEvent, type TelemetryEventType, createDocument, createEphemeralStore, createIndexedDbStore, openCollection };
package/index.d.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  import { QueryFilter, PaginationOptions } from '@asaidimu/query';
2
2
  import { IndexDefinition, SchemaDefinition, SchemaChange, DataTransform, PredicateMap } from '@asaidimu/anansi';
3
- import { EventBus } from '@asaidimu/events';
4
3
  import { StandardSchemaV1 } from '@standard-schema/spec';
5
4
 
6
5
  /**
@@ -728,6 +727,59 @@ declare const createIndexedDbStore: <T extends Record<string, any>>(config: Stor
728
727
 
729
728
  declare function DatabaseConnection(config: Omit<DatabaseConfig, "keyPath">, createStore: <T extends Record<string, any>>(config: StoreConfig, indexes: IndexDefinition[]) => Store<T>): Promise<Database>;
730
729
 
730
+ /**
731
+ * Interface defining the shape of the EventBus.
732
+ * @template TEventMap - A record mapping event names to their respective payload types.
733
+ */
734
+ interface EventBus<TEventMap extends Record<string, any>> {
735
+ /**
736
+ * Subscribes to a specific event by name.
737
+ * @param eventName - The name of the event to subscribe to.
738
+ * @param callback - The function to call when the event is emitted.
739
+ * @returns A function to unsubscribe from the event.
740
+ */
741
+ subscribe: <TEventName extends keyof TEventMap>(eventName: TEventName, callback: (payload: TEventMap[TEventName]) => void) => () => void;
742
+ /**
743
+ * Subscribes to an event and automatically unsubscribes after it fires once.
744
+ * @param eventName - The name of the event to subscribe to.
745
+ * @param callback - The function to call when the event is emitted.
746
+ * @returns A function to cancel the one-shot subscription before it fires.
747
+ */
748
+ once: <TEventName extends keyof TEventMap>(eventName: TEventName, callback: (payload: TEventMap[TEventName]) => void) => () => void;
749
+ /**
750
+ * Emits an event with a payload to all subscribed listeners.
751
+ * @param event - An object containing the event name and payload.
752
+ */
753
+ emit: <TEventName extends keyof TEventMap>(event: {
754
+ name: TEventName;
755
+ payload: TEventMap[TEventName];
756
+ }) => void;
757
+ /**
758
+ * Retrieves metrics about event bus usage.
759
+ * @returns An object containing various metrics.
760
+ */
761
+ metrics: () => EventMetrics;
762
+ /**
763
+ * Clears all subscriptions and resets metrics.
764
+ * After calling clear(), the bus is fully reset and can be reused —
765
+ * cross-tab communication is re-established if it was previously enabled.
766
+ */
767
+ clear: () => void;
768
+ }
769
+ /**
770
+ * Interface defining the metrics tracked by the EventBus.
771
+ */
772
+ interface EventMetrics {
773
+ /** Total number of events emitted (both sync and deferred paths). */
774
+ totalEvents: number;
775
+ /** Number of active subscriptions across all event names. */
776
+ activeSubscriptions: number;
777
+ /** Map of event names to their emission counts. */
778
+ eventCounts: Map<string, number>;
779
+ /** Average duration of event dispatch in milliseconds. */
780
+ averageEmitDuration: number;
781
+ }
782
+
731
783
  interface MiddlewareContext {
732
784
  collection?: string;
733
785
  documentId?: string;
@@ -789,4 +841,51 @@ declare function openCollection<T extends Record<string, any>>({ collection: sch
789
841
  validate: boolean;
790
842
  }): Promise<Collection<T>>;
791
843
 
792
- export { type BufferedOperation, type Collection, type CollectionEvent, type CollectionEventType, type CollectionMigrationOptions, ConnectionManager, type CursorCallback, type CursorCallbackResult, type CursorPaginationOptions, DEFAULT_KEYPATH, type Database, type DatabaseConfig, DatabaseConnection, type DatabaseEvent, type DatabaseEventType, type Document, type DocumentEvent, type DocumentEventType, IndexedDBStore, type Store, type StoreConfig, type StoreKeyRange, type TelemetryEvent, type TelemetryEventType, createDocument, createEphemeralStore, createIndexedDbStore, openCollection };
844
+ /**
845
+ * Error types for Database operations.
846
+ */
847
+ declare enum DatabaseErrorType {
848
+ /** The schema does not exist. */
849
+ SCHEMA_NOT_FOUND = "SCHEMA_NOT_FOUND",
850
+ /** The schema already exists. */
851
+ SCHEMA_ALREADY_EXISTS = "SCHEMA_ALREADY_EXISTS",
852
+ /** The schema name is invalid. */
853
+ INVALID_SCHEMA_NAME = "INVALID_SCHEMA_NAME",
854
+ /** The schema definition is invalid. */
855
+ INVALID_SCHEMA_DEFINITION = "INVALID_SCHEMA_DEFINITION",
856
+ /** The database subscription failed. */
857
+ SUBSCRIPTION_FAILED = "SUBSCRIPTION_FAILED",
858
+ /** The database operation failed due to an internal error. */
859
+ INTERNAL_ERROR = "INTERNAL_ERROR",
860
+ /** Data being entered into a collection does not satisfy its schema definition. */
861
+ INVALID_DATA = "INVALID_DATA",
862
+ /** Optimistic Concurrency Control version mismatches */
863
+ CONFLICT = "CONFLICT",
864
+ /** For retryable store locks */
865
+ TRANSIENT_ERROR = "TRANSIENT_ERROR",
866
+ TRANSACTION_FAILED = "TRANSACTION_FAILED",
867
+ CONNECTION_FAILED = "CONNECTION_FAILED",
868
+ INVALID_OPERATION = "INVALID_OPERATION"
869
+ }
870
+ /**
871
+ * Error class for Database operations.
872
+ */
873
+ declare class DatabaseError extends Error {
874
+ /**
875
+ * The type of error that occurred.
876
+ */
877
+ type: DatabaseErrorType;
878
+ /**
879
+ * The schema associated with the error, if applicable.
880
+ */
881
+ schema?: SchemaDefinition;
882
+ /**
883
+ * Constructs a new DatabaseErrorClass instance.
884
+ * @param type - The type of error that occurred.
885
+ * @param message - A human-readable message describing the error.
886
+ * @param schema - The schema associated with the error, if applicable.
887
+ */
888
+ constructor(type: DatabaseErrorType, message: string, schema?: SchemaDefinition, cause?: unknown);
889
+ }
890
+
891
+ export { type BufferedOperation, type Collection, type CollectionEvent, type CollectionEventType, type CollectionMigrationOptions, ConnectionManager, type CursorCallback, type CursorCallbackResult, type CursorPaginationOptions, DEFAULT_KEYPATH, type Database, type DatabaseConfig, DatabaseConnection, DatabaseError, DatabaseErrorType, type DatabaseEvent, type DatabaseEventType, type Document, type DocumentEvent, type DocumentEventType, IndexedDBStore, type Store, type StoreConfig, type StoreKeyRange, type TelemetryEvent, type TelemetryEventType, createDocument, createEphemeralStore, createIndexedDbStore, openCollection };