@routier/core 0.0.4 → 0.0.6

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.
@@ -320,39 +320,6 @@ function forEach(expression, callback) {
320
320
  }
321
321
 
322
322
 
323
- }),
324
- "./src/performance/index.ts":
325
- /*!**********************************!*\
326
- !*** ./src/performance/index.ts ***!
327
- \**********************************/
328
- (function (__unused_webpack_module, __webpack_exports__, __webpack_require__) {
329
- __webpack_require__.r(__webpack_exports__);
330
- __webpack_require__.d(__webpack_exports__, {
331
- measure: () => (measure),
332
- now: () => (now)
333
- });
334
- const measurements = {};
335
- const now = () => {
336
- if (typeof performance !== 'undefined' && performance.now) {
337
- // Browser or modern Node.js
338
- return performance.now();
339
- }
340
- // Fallback for older environments
341
- return Date.now();
342
- };
343
- const measure = {
344
- start: (name) => {
345
- measurements[name] = now();
346
- },
347
- end: (name) => {
348
- const start = measurements[name];
349
- delete measurements[name];
350
- const delta = now() - start;
351
- console.log(`[ROUTIER] - Performance: ${name} took ${delta}`);
352
- }
353
- };
354
-
355
-
356
323
  }),
357
324
  "./src/pipeline/TrampolinePipeline.ts":
358
325
  /*!********************************************!*\
@@ -465,8 +432,8 @@ class TrampolinePipeline {
465
432
  this._hasErrored = true;
466
433
  }
467
434
  currentStep = null; // Stop the loop
468
- // We don't call `done` here because an error occurred.
469
- // The application should handle the uncaught exception if desired.
435
+ // Call done with the error to properly notify the caller
436
+ queueMicrotask(() => done(currentData, trampolineError));
470
437
  break; // Explicitly break loop on error
471
438
  }
472
439
  }
@@ -593,8 +560,8 @@ class AsyncPipeline {
593
560
  this._hasErrored = true;
594
561
  }
595
562
  currentStep = null; // Stop the loop
596
- // We don't call `done` here because an error occurred.
597
- // The application should handle the uncaught exception if desired.
563
+ // Call done with the error to properly notify the caller
564
+ queueMicrotask(() => done(_results__WEBPACK_IMPORTED_MODULE_0__.Result.error(trampolineError)));
598
565
  break; // Explicitly break loop on error
599
566
  }
600
567
  }
@@ -628,112 +595,88 @@ class AsyncPipeline {
628
595
  */
629
596
  class WorkPipeline {
630
597
  unitsOfWork = [];
631
- _hasErrored = false; // Flag to prevent calling done on error
632
598
  filter(done) {
633
- this._hasErrored = false; // Reset error flag on new execution
634
- if (this.unitsOfWork.length === 0) {
599
+ const units = this.unitsOfWork;
600
+ const unitsLength = units.length;
601
+ // Fast path for empty pipeline
602
+ if (unitsLength === 0) {
635
603
  queueMicrotask(() => done(_results__WEBPACK_IMPORTED_MODULE_0__.Result.success()));
636
604
  return;
637
605
  }
638
- let index = 0;
639
- let isRunning = false; // Guard against overlapping trampoline calls
606
+ // Fast path for single work unit
607
+ if (unitsLength === 1) {
608
+ try {
609
+ units[0]((result) => {
610
+ queueMicrotask(() => done(result));
611
+ });
612
+ }
613
+ catch (error) {
614
+ done(_results__WEBPACK_IMPORTED_MODULE_0__.Result.error(error));
615
+ }
616
+ return;
617
+ }
618
+ let isRunning = false;
619
+ let hasErrored = false;
640
620
  try {
641
- // --- Revised Completion Logic --- (Moved up for clarity)
642
- const finalStepSentinel = () => {
643
- // Only call done if no error has occurred
644
- if (!this._hasErrored) {
645
- queueMicrotask(() => done(_results__WEBPACK_IMPORTED_MODULE_0__.Result.success()));
646
- }
647
- return null; // Stop the trampoline
648
- };
649
- const createStepRevised = (idx) => {
621
+ const createStep = (idx) => {
650
622
  return () => {
651
- if (this._hasErrored)
652
- return null; // Stop if an error occurred elsewhere
653
- if (idx >= this.unitsOfWork.length) {
654
- return finalStepSentinel(); // Execute the dedicated final step
623
+ if (hasErrored)
624
+ return null;
625
+ if (idx >= unitsLength) {
626
+ if (!hasErrored) {
627
+ queueMicrotask(() => done(_results__WEBPACK_IMPORTED_MODULE_0__.Result.success()));
628
+ }
629
+ return null;
655
630
  }
656
- const processor = this.unitsOfWork[idx];
657
- // Initialize syncCallbackResult to null to satisfy StepResult type
658
- let syncCallbackResult = null;
631
+ const processor = units[idx];
632
+ let syncResult = null;
659
633
  let calledSync = false;
660
634
  try {
661
635
  processor((result) => {
662
- // --- Error Handling ---
663
636
  if (result.ok === _results__WEBPACK_IMPORTED_MODULE_0__.Result.ERROR) {
664
- console.error(`Error reported by AsyncPipeline at index ${idx}:`, result.error);
665
- this._hasErrored = true; // Set flag
666
- // Throw the error to be caught by outer try...catch blocks
637
+ hasErrored = true;
667
638
  throw result.error;
668
639
  }
669
- // --- /Error Handling ---
670
- // If no error, proceed as before
671
- index = idx + 1; // Update index for the next step
672
- const nextStep = createStepRevised(index); // Use updated index
640
+ const nextStep = createStep(idx + 1);
673
641
  if (isRunning) {
674
- // Callback was synchronous
675
- syncCallbackResult = nextStep; // Store next step function
642
+ syncResult = nextStep;
676
643
  calledSync = true;
677
644
  }
678
645
  else {
679
- // Callback was asynchronous, restart trampoline
680
646
  trampoline(nextStep);
681
647
  }
682
648
  });
683
649
  }
684
650
  catch (error) {
685
- if (!this._hasErrored) { // Check flag to avoid double logging if error was from callback
686
- console.error(`Error thrown by processor at index ${idx} or its callback:`, error);
687
- this._hasErrored = true;
688
- }
689
- // Rethrow to be caught by the trampoline's catch block
651
+ hasErrored = true;
690
652
  throw error;
691
653
  }
692
- if (calledSync) {
693
- // Return the next step function for the sync loop
694
- return syncCallbackResult;
695
- }
696
- else {
697
- // Pause trampoline for async, loop will stop as step returns null
698
- return null;
699
- }
654
+ return calledSync ? syncResult : null;
700
655
  };
701
656
  };
702
- // The trampoline loop
703
657
  const trampoline = (step) => {
704
- if (isRunning) {
658
+ if (isRunning)
705
659
  return;
706
- }
707
660
  isRunning = true;
708
661
  let currentStep = step;
709
- while (typeof currentStep === 'function') {
662
+ while (currentStep) {
710
663
  try {
711
- // Stop immediately if an error was flagged elsewhere
712
- if (this._hasErrored) {
664
+ if (hasErrored) {
713
665
  currentStep = null;
714
666
  break;
715
667
  }
716
- currentStep = currentStep(); // Execute step, get next step or null
668
+ currentStep = currentStep();
717
669
  }
718
- catch (trampolineError) {
719
- // Catch errors propagated from step execution (processor or callback errors)
720
- if (!this._hasErrored) { // Avoid double logging
721
- console.error("Error during trampoline step execution:", trampolineError);
722
- this._hasErrored = true;
723
- }
724
- currentStep = null; // Stop the loop
725
- // We don't call `done` here because an error occurred.
726
- // The application should handle the uncaught exception if desired.
727
- break; // Explicitly break loop on error
670
+ catch (error) {
671
+ hasErrored = true;
672
+ currentStep = null;
673
+ queueMicrotask(() => done(_results__WEBPACK_IMPORTED_MODULE_0__.Result.error(error)));
674
+ break;
728
675
  }
729
676
  }
730
- // Loop ends when currentStep is null or loop is broken by error
731
677
  isRunning = false;
732
- // Completion check is now handled by finalStepSentinel ensuring `done` isn't called on error.
733
678
  };
734
- // --- Start the process ---
735
- index = 0; // Reset index
736
- trampoline(createStepRevised(0)); // Start with the revised step creator
679
+ trampoline(createStep(0));
737
680
  }
738
681
  catch (error) {
739
682
  done(_results__WEBPACK_IMPORTED_MODULE_0__.Result.error(error));
@@ -755,10 +698,10 @@ __webpack_require__.r(__webpack_exports__);
755
698
  __webpack_require__.d(__webpack_exports__, {
756
699
  EphemeralDataPlugin: () => (EphemeralDataPlugin)
757
700
  });
758
- /* ESM import */var _assertions__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../assertions */ "./src/assertions/index.ts");
701
+ /* ESM import */var _assertions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../assertions */ "./src/assertions/index.ts");
759
702
  /* ESM import */var _pipeline__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../pipeline */ "./src/pipeline/TrampolinePipeline.ts");
760
703
  /* ESM import */var ___WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! . */ "./src/plugins/translators/JsonTranslator.ts");
761
- /* ESM import */var _results__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../results */ "./src/results/Result.ts");
704
+ /* ESM import */var _results__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../results */ "./src/results/Result.ts");
762
705
 
763
706
 
764
707
 
@@ -770,470 +713,104 @@ class EphemeralDataPlugin {
770
713
  }
771
714
  bulkPersist(event, done) {
772
715
  try {
773
- const pipeline = new _pipeline__WEBPACK_IMPORTED_MODULE_0__.WorkPipeline();
774
716
  const bulkPersistResult = event.operation.toResult();
717
+ const schemas = event.schemas;
718
+ const pipeline = new _pipeline__WEBPACK_IMPORTED_MODULE_0__.WorkPipeline();
719
+ let hasWork = false;
775
720
  for (const [schemaId, changes] of event.operation) {
721
+ const { adds, hasItems, removes, updates } = changes;
722
+ if (!hasItems) {
723
+ continue;
724
+ }
725
+ hasWork = true;
726
+ const result = bulkPersistResult.get(schemaId);
727
+ const schema = schemas.get(schemaId);
728
+ (0,_assertions__WEBPACK_IMPORTED_MODULE_1__.assertIsNotNull)(schema);
776
729
  pipeline.pipe((d) => {
777
730
  try {
778
- const { adds, hasItems, removes, updates } = changes;
779
- if (hasItems === false) {
780
- d(_results__WEBPACK_IMPORTED_MODULE_1__.Result.success());
781
- return;
782
- }
783
- const result = bulkPersistResult.get(schemaId);
784
- const schema = event.schemas.get(schemaId);
785
- (0,_assertions__WEBPACK_IMPORTED_MODULE_2__.assertIsNotNull)(schema);
786
731
  const collection = this.resolveCollection(schema);
787
732
  collection.load(readResult => {
788
- if (readResult.ok === _results__WEBPACK_IMPORTED_MODULE_1__.Result.ERROR) {
733
+ if (readResult.ok === _results__WEBPACK_IMPORTED_MODULE_2__.Result.ERROR) {
789
734
  d(readResult);
790
735
  return;
791
736
  }
792
- for (let i = 0, length = adds.length; i < length; i++) {
793
- collection.add(adds[i]);
794
- result.adds.push(adds[i]);
737
+ const addsLength = adds.length;
738
+ const updatesLength = updates.length;
739
+ const removesLength = removes.length;
740
+ result.adds = new Array(addsLength);
741
+ result.updates = new Array(updatesLength);
742
+ result.removes = new Array(removesLength);
743
+ for (let j = 0; j < addsLength; j++) {
744
+ const item = adds[j];
745
+ collection.add(item);
746
+ result.adds[j] = item;
795
747
  }
796
- for (let i = 0, length = updates.length; i < length; i++) {
797
- collection.update(updates[i].entity);
798
- result.updates.push(updates[i].entity);
748
+ for (let j = 0; j < updatesLength; j++) {
749
+ const item = updates[j].entity;
750
+ collection.update(item);
751
+ result.updates[j] = item;
799
752
  }
800
- for (let i = 0, length = removes.length; i < length; i++) {
801
- collection.remove(removes[i]);
802
- result.removes.push(removes[i]);
753
+ for (let j = 0; j < removesLength; j++) {
754
+ collection.remove(removes[j]);
755
+ result.removes[j] = removes[j];
803
756
  }
804
757
  collection.save(saveResult => {
805
- if (saveResult.ok === _results__WEBPACK_IMPORTED_MODULE_1__.Result.ERROR) {
758
+ if (saveResult.ok === _results__WEBPACK_IMPORTED_MODULE_2__.Result.ERROR) {
806
759
  d(saveResult);
807
760
  return;
808
761
  }
809
- d(_results__WEBPACK_IMPORTED_MODULE_1__.Result.success());
762
+ d(_results__WEBPACK_IMPORTED_MODULE_2__.Result.success());
810
763
  });
811
764
  });
812
765
  }
813
766
  catch (e) {
814
- d(_results__WEBPACK_IMPORTED_MODULE_1__.Result.error(e));
767
+ d(_results__WEBPACK_IMPORTED_MODULE_2__.Result.error(e));
815
768
  }
816
769
  });
817
770
  }
818
- let successCount = 0;
819
- pipeline.filter((asyncResult) => {
820
- if (asyncResult.ok !== _results__WEBPACK_IMPORTED_MODULE_1__.PluginEventResult.SUCCESS) {
821
- if (successCount === 0) {
822
- done(_results__WEBPACK_IMPORTED_MODULE_1__.PluginEventResult.error(event.id, asyncResult.error));
823
- return;
824
- }
825
- done(_results__WEBPACK_IMPORTED_MODULE_1__.PluginEventResult.partial(event.id, bulkPersistResult, asyncResult.error));
771
+ if (!hasWork) {
772
+ done(_results__WEBPACK_IMPORTED_MODULE_2__.PluginEventResult.success(event.id, bulkPersistResult));
773
+ return;
774
+ }
775
+ pipeline.filter((result) => {
776
+ if (result.ok === _results__WEBPACK_IMPORTED_MODULE_2__.Result.ERROR) {
777
+ done(_results__WEBPACK_IMPORTED_MODULE_2__.PluginEventResult.error(event.id, result.error));
826
778
  return;
827
779
  }
828
- successCount++;
829
- done(_results__WEBPACK_IMPORTED_MODULE_1__.PluginEventResult.success(event.id, bulkPersistResult));
780
+ done(_results__WEBPACK_IMPORTED_MODULE_2__.PluginEventResult.success(event.id, bulkPersistResult));
830
781
  });
831
782
  }
832
783
  catch (e) {
833
- done(_results__WEBPACK_IMPORTED_MODULE_1__.PluginEventResult.error(event.id, e));
784
+ done(_results__WEBPACK_IMPORTED_MODULE_2__.PluginEventResult.error(event.id, e));
834
785
  }
835
786
  }
836
787
  query(event, done) {
837
788
  try {
838
- const { operation } = event;
789
+ const operation = event.operation;
790
+ const schema = operation.schema;
839
791
  const translator = new ___WEBPACK_IMPORTED_MODULE_3__.JsonTranslator(operation);
840
- const collection = this.resolveCollection(operation.schema);
841
- // translate if we are doing any operations like count/sum/min/max/skip/take
792
+ const collection = this.resolveCollection(schema);
842
793
  collection.load(r => {
843
- if (r.ok === _results__WEBPACK_IMPORTED_MODULE_1__.Result.ERROR) {
844
- done(_results__WEBPACK_IMPORTED_MODULE_1__.PluginEventResult.error(event.id, r.error));
794
+ if (r.ok === _results__WEBPACK_IMPORTED_MODULE_2__.Result.ERROR) {
795
+ done(_results__WEBPACK_IMPORTED_MODULE_2__.PluginEventResult.error(event.id, r.error));
845
796
  return;
846
797
  }
847
- const cloned = [];
848
- for (let i = 0, length = collection.records.length; i < length; i++) {
849
- cloned.push(event.operation.schema.clone(collection.records[i]));
798
+ const records = collection.records;
799
+ const length = records.length;
800
+ const cloned = new Array(length);
801
+ for (let i = 0; i < length; i++) {
802
+ cloned[i] = schema.clone(records[i]);
850
803
  }
851
- const translated = translator.translate(cloned);
852
- done(_results__WEBPACK_IMPORTED_MODULE_1__.PluginEventResult.success(event.id, translated));
804
+ done(_results__WEBPACK_IMPORTED_MODULE_2__.PluginEventResult.success(event.id, translator.translate(cloned)));
853
805
  });
854
806
  }
855
807
  catch (e) {
856
- done(_results__WEBPACK_IMPORTED_MODULE_1__.PluginEventResult.error(event.id, e));
857
- }
858
- }
859
- }
860
-
861
-
862
- }),
863
- "./src/plugins/capabilities/DbPluginCapability.ts":
864
- /*!********************************************************!*\
865
- !*** ./src/plugins/capabilities/DbPluginCapability.ts ***!
866
- \********************************************************/
867
- (function (__unused_webpack_module, __webpack_exports__, __webpack_require__) {
868
- __webpack_require__.r(__webpack_exports__);
869
- __webpack_require__.d(__webpack_exports__, {
870
- DbPluginCapability: () => (DbPluginCapability)
871
- });
872
- /**
873
- * Extends plugin functionality through hooks and event handlers without
874
- * changing the plugin's type (mixin). Essential for maintaining type safety
875
- * in routier's core systems.
876
- */
877
- class DbPluginCapability {
878
- events = {};
879
- add(name, callback) {
880
- this.resolve(name);
881
- switch (name) {
882
- case "queryStart":
883
- this.events["query"].before = callback;
884
- break;
885
- case "queryComplete":
886
- this.events["query"].after = callback;
887
- break;
888
- case "destroyStart":
889
- this.events["destroy"].before = callback;
890
- break;
891
- case "destroyComplete":
892
- this.events["destroy"].after = callback;
893
- break;
894
- case "bulkPersistStart":
895
- this.events["bulkPersist"].before = callback;
896
- break;
897
- case "bulkPersistComplete":
898
- this.events["bulkPersist"].after = callback;
899
- break;
900
- }
901
- return this;
902
- }
903
- resolve(name) {
904
- switch (name) {
905
- case "queryStart":
906
- case "queryComplete":
907
- if (!this.events["query"]) {
908
- this.events["query"] = {};
909
- }
910
- return;
911
- case "destroyStart":
912
- case "destroyComplete":
913
- if (!this.events["destroy"]) {
914
- this.events["destroy"] = {};
915
- }
916
- return;
917
- case "bulkPersistStart":
918
- case "bulkPersistComplete":
919
- if (!this.events["bulkPersist"]) {
920
- this.events["bulkPersist"] = {};
921
- }
922
- return;
923
- default:
924
- throw new Error("Exhaustive check");
925
- }
926
- }
927
- apply(plugin) {
928
- const methodWrappers = [
929
- { method: 'query', events: this.events.query },
930
- { method: 'destroy', events: this.events.destroy },
931
- { method: 'bulkPersist', events: this.events.bulkPersist }
932
- ];
933
- // apply the mixins
934
- for (let i = 0, length = methodWrappers.length; i < length; i++) {
935
- const { events, method } = methodWrappers[i];
936
- if (events?.before || events?.after) {
937
- const original = plugin[method].bind(plugin);
938
- plugin[method] = ((event, done) => {
939
- events.before?.(event, done);
940
- if (events.after) {
941
- return original(event, (result) => {
942
- events.after(result);
943
- done(result);
944
- });
945
- }
946
- return original(event, done);
947
- });
948
- }
949
- }
950
- }
951
- }
952
-
953
-
954
- }),
955
- "./src/plugins/capabilities/index.ts":
956
- /*!*******************************************!*\
957
- !*** ./src/plugins/capabilities/index.ts ***!
958
- \*******************************************/
959
- (function (__unused_webpack_module, __webpack_exports__, __webpack_require__) {
960
- __webpack_require__.r(__webpack_exports__);
961
- __webpack_require__.d(__webpack_exports__, {
962
- DbPluginCapability: () => (/* reexport safe */ _DbPluginCapability__WEBPACK_IMPORTED_MODULE_0__.DbPluginCapability),
963
- DbPluginLoggingCapability: () => (/* reexport safe */ _logging__WEBPACK_IMPORTED_MODULE_1__.DbPluginLoggingCapability)
964
- });
965
- /* ESM import */var _DbPluginCapability__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./DbPluginCapability */ "./src/plugins/capabilities/DbPluginCapability.ts");
966
- /* ESM import */var _logging__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./logging */ "./src/plugins/capabilities/logging/index.ts");
967
-
968
-
969
-
970
-
971
- }),
972
- "./src/plugins/capabilities/logging/DbPluginLoggingCapability.ts":
973
- /*!***********************************************************************!*\
974
- !*** ./src/plugins/capabilities/logging/DbPluginLoggingCapability.ts ***!
975
- \***********************************************************************/
976
- (function (__unused_webpack_module, __webpack_exports__, __webpack_require__) {
977
- __webpack_require__.r(__webpack_exports__);
978
- __webpack_require__.d(__webpack_exports__, {
979
- DbPluginLoggingCapability: () => (DbPluginLoggingCapability)
980
- });
981
- /* ESM import */var _DbPluginCapability__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../DbPluginCapability */ "./src/plugins/capabilities/DbPluginCapability.ts");
982
- /* ESM import */var _performance__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../performance */ "./src/performance/index.ts");
983
-
984
-
985
- class DbPluginLoggingCapability {
986
- logStyle = 'redux';
987
- maxLogEntries = 100;
988
- logHistory = [];
989
- queryPerformance = new Map();
990
- constructor(options) {
991
- this.logStyle = options?.logStyle ?? 'redux';
992
- this.maxLogEntries = options?.maxLogEntries ?? 100;
993
- }
994
- apply(plugin) {
995
- const baseCapability = new _DbPluginCapability__WEBPACK_IMPORTED_MODULE_0__.DbPluginCapability();
996
- const pluginName = plugin.constructor.name;
997
- // Query logging
998
- baseCapability
999
- .add("queryStart", (event) => {
1000
- this.logReduxAction('QUERY_REQUEST', event.id, {
1001
- plugin: pluginName,
1002
- collection: event.operation.schema.collectionName,
1003
- schemaId: event.operation.schema.id,
1004
- changeTracking: event.operation.changeTracking
1005
- }, {
1006
- timestamp: new Date().toISOString(),
1007
- options: this.extractQueryOptions(event.operation)
1008
- });
1009
- this.addToHistory('QUERY_REQUEST', event);
1010
- this.queryPerformance.set(event.id, (0,_performance__WEBPACK_IMPORTED_MODULE_1__.now)());
1011
- })
1012
- .add("queryComplete", (result) => {
1013
- const start = this.queryPerformance.get(result.id);
1014
- this.queryPerformance.delete(result.id);
1015
- const end = (0,_performance__WEBPACK_IMPORTED_MODULE_1__.now)();
1016
- const duration = start == null ? -1 : end - start;
1017
- const performance = this.getPerformanceIndicator(duration);
1018
- if (result.ok === 'success') {
1019
- this.logReduxAction('QUERY_SUCCESS', result.id, {
1020
- plugin: pluginName,
1021
- resultCount: this.getResultCount(result.data),
1022
- resultType: this.getResultType(result.data)
1023
- }, {
1024
- duration: `${duration.toFixed(4)}ms`,
1025
- performance: performance.label,
1026
- timestamp: new Date().toISOString()
1027
- });
1028
- }
1029
- else {
1030
- this.logReduxAction('QUERY_ERROR', result.id, {
1031
- plugin: pluginName,
1032
- error: result.error?.message || result.error,
1033
- isCritical: false
1034
- }, {
1035
- duration: `${duration.toFixed(4)}ms`,
1036
- performance: performance.label,
1037
- timestamp: new Date().toISOString()
1038
- });
1039
- }
1040
- this.addToHistory('QUERY_RESULT', { result, duration });
1041
- });
1042
- // Bulk operations logging
1043
- baseCapability
1044
- .add("bulkPersistStart", (event) => {
1045
- const totalOperations = event.operation.aggregate.size;
1046
- this.logReduxAction('BULK_OPERATIONS_REQUEST', event.id, {
1047
- plugin: pluginName,
1048
- totalOperations,
1049
- schemaCount: event.schemas.size,
1050
- operations: this.extractBulkOperations(event.operation)
1051
- }, {
1052
- timestamp: new Date().toISOString()
1053
- });
1054
- this.addToHistory('BULK_OPERATIONS_REQUEST', event);
1055
- this.queryPerformance.set(event.id, (0,_performance__WEBPACK_IMPORTED_MODULE_1__.now)());
1056
- })
1057
- .add("bulkPersistComplete", (result) => {
1058
- const start = this.queryPerformance.get(result.id);
1059
- this.queryPerformance.delete(result.id);
1060
- const end = (0,_performance__WEBPACK_IMPORTED_MODULE_1__.now)();
1061
- const duration = start == null ? -1 : end - start;
1062
- const performance = this.getPerformanceIndicator(duration);
1063
- if (result.ok === 'success') {
1064
- this.logReduxAction('BULK_OPERATIONS_SUCCESS', result.id, {
1065
- plugin: pluginName,
1066
- completedOperations: this.countCompletedOperations(result.data),
1067
- schemaCount: result.data.size
1068
- }, {
1069
- duration: `${duration.toFixed(4)}ms`,
1070
- performance: performance.label,
1071
- timestamp: new Date().toISOString()
1072
- });
1073
- }
1074
- else {
1075
- this.logReduxAction('BULK_OPERATIONS_ERROR', result.id, {
1076
- plugin: pluginName,
1077
- error: result.error?.message || result.error,
1078
- isCritical: false
1079
- }, {
1080
- duration: `${duration.toFixed(4)}ms`,
1081
- performance: performance.label,
1082
- timestamp: new Date().toISOString()
1083
- });
1084
- }
1085
- this.addToHistory('BULK_OPERATIONS_RESULT', { result, duration });
1086
- });
1087
- // Destroy logging
1088
- baseCapability
1089
- .add("destroyStart", (event) => {
1090
- this.logReduxAction('DESTROY_REQUEST', event.id, {
1091
- plugin: pluginName,
1092
- schemaCount: event.schemas.size
1093
- }, {
1094
- timestamp: new Date().toISOString()
1095
- });
1096
- this.addToHistory('DESTROY_REQUEST', event);
1097
- this.queryPerformance.set(event.id, (0,_performance__WEBPACK_IMPORTED_MODULE_1__.now)());
1098
- })
1099
- .add("destroyComplete", (result) => {
1100
- const start = this.queryPerformance.get(result.id);
1101
- this.queryPerformance.delete(result.id);
1102
- const end = (0,_performance__WEBPACK_IMPORTED_MODULE_1__.now)();
1103
- const duration = start == null ? -1 : end - start;
1104
- const performance = this.getPerformanceIndicator(duration);
1105
- if (result.ok === 'success') {
1106
- this.logReduxAction('DESTROY_SUCCESS', result.id, {
1107
- plugin: pluginName
1108
- }, {
1109
- duration: `${duration.toFixed(4)}ms`,
1110
- performance: performance.label,
1111
- timestamp: new Date().toISOString()
1112
- });
1113
- }
1114
- else {
1115
- this.logReduxAction('DESTROY_ERROR', result.id, {
1116
- plugin: pluginName,
1117
- error: result.error?.message || result.error
1118
- }, {
1119
- duration: `${duration.toFixed(4)}ms`,
1120
- performance: performance.label,
1121
- timestamp: new Date().toISOString()
1122
- });
1123
- }
1124
- this.addToHistory('DESTROY_RESULT', { result, duration });
1125
- });
1126
- baseCapability.apply(plugin);
1127
- }
1128
- getPerformanceIndicator(duration) {
1129
- if (duration > 1000)
1130
- return { emoji: '🐌', color: '#ef4444', label: 'SLOW', level: 'error' };
1131
- if (duration > 500)
1132
- return { emoji: '🐢', color: '#f97316', label: 'MEDIUM', level: 'warning' };
1133
- if (duration > 100)
1134
- return { emoji: '⚡', color: '#eab308', label: 'FAST', level: 'info' };
1135
- return { emoji: '🚀', color: '#22c55e', label: 'INSTANT', level: 'success' };
1136
- }
1137
- logReduxAction(action, eventId, payload, meta) {
1138
- if (this.logStyle !== 'redux')
1139
- return;
1140
- const timestamp = new Date().toISOString();
1141
- console.groupCollapsed(`%c${action} %c@ ${timestamp}`, 'color: #3b82f6; font-weight: bold; font-size: 14px;', 'color: #6b7280; font-size: 12px;');
1142
- console.group('Action');
1143
- console.log('Type:', action);
1144
- console.log('Event ID:', eventId);
1145
- console.log('Timestamp:', timestamp);
1146
- console.groupEnd();
1147
- if (payload) {
1148
- console.group('Payload');
1149
- console.log(payload);
1150
- console.groupEnd();
1151
- }
1152
- if (meta) {
1153
- console.group('Meta');
1154
- console.log(meta);
1155
- console.groupEnd();
1156
- }
1157
- console.groupEnd();
1158
- }
1159
- extractQueryOptions(query) {
1160
- const options = {};
1161
- if (query.options) {
1162
- ['skip', 'take', 'sort', 'filter', 'map', 'distinct'].forEach(type => {
1163
- try {
1164
- const values = query.options.getValues(type);
1165
- if (values.length > 0)
1166
- options[type] = values;
1167
- }
1168
- catch (e) {
1169
- // Skip if option type not supported
1170
- }
1171
- });
1172
- }
1173
- return options;
1174
- }
1175
- getResultCount(result) {
1176
- if (Array.isArray(result))
1177
- return `${result.length} items`;
1178
- if (result !== null && typeof result === 'object')
1179
- return '1 object';
1180
- return '1 primitive';
1181
- }
1182
- getResultType(result) {
1183
- if (Array.isArray(result))
1184
- return 'array';
1185
- if (result !== null && typeof result === 'object')
1186
- return 'object';
1187
- return typeof result;
1188
- }
1189
- extractBulkOperations(operations) {
1190
- const aggregate = operations.aggregate;
1191
- return {
1192
- adds: aggregate.adds,
1193
- updates: aggregate.updates,
1194
- removes: aggregate.removes
1195
- };
1196
- }
1197
- countCompletedOperations(result) {
1198
- return result?.aggregate.size || 0;
1199
- }
1200
- addToHistory(type, data) {
1201
- this.logHistory.push({
1202
- type,
1203
- timestamp: Date.now(),
1204
- data
1205
- });
1206
- if (this.logHistory.length > this.maxLogEntries) {
1207
- this.logHistory = this.logHistory.slice(-this.maxLogEntries);
808
+ done(_results__WEBPACK_IMPORTED_MODULE_2__.PluginEventResult.error(event.id, e));
1208
809
  }
1209
810
  }
1210
- generateId() {
1211
- return Math.random().toString(36).substr(2, 9);
1212
- }
1213
- // Public methods for debugging
1214
- getLogHistory() {
1215
- return [...this.logHistory];
1216
- }
1217
- clearLogHistory() {
1218
- this.logHistory = [];
1219
- }
1220
811
  }
1221
812
 
1222
813
 
1223
- }),
1224
- "./src/plugins/capabilities/logging/index.ts":
1225
- /*!***************************************************!*\
1226
- !*** ./src/plugins/capabilities/logging/index.ts ***!
1227
- \***************************************************/
1228
- (function (__unused_webpack_module, __webpack_exports__, __webpack_require__) {
1229
- __webpack_require__.r(__webpack_exports__);
1230
- __webpack_require__.d(__webpack_exports__, {
1231
- DbPluginLoggingCapability: () => (/* reexport safe */ _DbPluginLoggingCapability__WEBPACK_IMPORTED_MODULE_0__.DbPluginLoggingCapability)
1232
- });
1233
- /* ESM import */var _DbPluginLoggingCapability__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./DbPluginLoggingCapability */ "./src/plugins/capabilities/logging/DbPluginLoggingCapability.ts");
1234
-
1235
-
1236
-
1237
814
  }),
1238
815
  "./src/plugins/query/Query.ts":
1239
816
  /*!************************************!*\
@@ -1488,8 +1065,10 @@ const getMemoryPluginCollectionSize = (plugin, schema) => {
1488
1065
  }
1489
1066
  throw new Error("Cannot get size of collection for MemoryPlugin, not an instance of MemoryPlugin");
1490
1067
  };
1491
- const WAS_OPTIMISTIC_DB_HYDRATED_KEY = "was-hydrated";
1492
- const cache = new Set();
1068
+ const HYDRATION_STATUS_PENDING = "hydration-pending";
1069
+ const HYDRATION_STATUS_ERROR = "hydration-error";
1070
+ const HYDRATION_STATUS_SUCCESS = "hydration-success";
1071
+ let hydrationStatus = "hydration-not-started";
1493
1072
  class OptimisticReplicationDbPlugin {
1494
1073
  plugins;
1495
1074
  constructor(plugins) {
@@ -1513,10 +1092,10 @@ class OptimisticReplicationDbPlugin {
1513
1092
  const readPlugin = this.plugins.read;
1514
1093
  const sourcePlugin = this.plugins.source;
1515
1094
  const collectionSize = getMemoryPluginCollectionSize(this.plugins.read, event.operation.schema);
1516
- if (collectionSize === 0 && cache.has(WAS_OPTIMISTIC_DB_HYDRATED_KEY) === false) {
1095
+ if (collectionSize === 0 && hydrationStatus === "hydration-not-started") {
1517
1096
  // Notify the cache that the db was hydrated right away
1518
- cache.add(WAS_OPTIMISTIC_DB_HYDRATED_KEY);
1519
- console.log('[ROUTIER] - Optimistic Query', cache);
1097
+ hydrationStatus = "hydration-pending";
1098
+ console.log('[ROUTIER] - Optimistic Query', hydrationStatus);
1520
1099
  // nothing is hydrated, let's try and hydrate before querying
1521
1100
  // Memory plugin might not be hydrated, lets hydrate it for the targeted schema only,
1522
1101
  // Other queries will do the same and hydrate if needed
@@ -1530,19 +1109,22 @@ class OptimisticReplicationDbPlugin {
1530
1109
  }, (sourceResult) => {
1531
1110
  if (sourceResult.ok === _results__WEBPACK_IMPORTED_MODULE_2__.Result.ERROR) {
1532
1111
  // Notify that hydration failed
1533
- cache.delete(WAS_OPTIMISTIC_DB_HYDRATED_KEY);
1112
+ hydrationStatus = "hydration-error";
1113
+ console.log("[ROUTIER] - Hydration Error - Source Query", sourceResult);
1534
1114
  done(sourceResult);
1535
1115
  return;
1536
1116
  }
1537
1117
  if (sourceResult == null || (Array.isArray(sourceResult.data) && sourceResult.data.length === 0)) {
1538
1118
  // Notify that hydration had no data
1539
- cache.delete(WAS_OPTIMISTIC_DB_HYDRATED_KEY);
1119
+ hydrationStatus = "hydration-error";
1120
+ console.log("[ROUTIER] - Hydration Error - No Data", sourceResult);
1540
1121
  done(sourceResult);
1541
1122
  return;
1542
1123
  }
1543
1124
  if (Array.isArray(sourceResult.data) === false) {
1544
1125
  // Notify that hydration failed
1545
- cache.delete(WAS_OPTIMISTIC_DB_HYDRATED_KEY);
1126
+ hydrationStatus = "hydration-error";
1127
+ console.log("[ROUTIER] - Hydration Error - Bad Result", sourceResult);
1546
1128
  done(_results__WEBPACK_IMPORTED_MODULE_2__.PluginEventResult.error(event.id, "Query result is not an array"));
1547
1129
  return;
1548
1130
  }
@@ -1558,10 +1140,12 @@ class OptimisticReplicationDbPlugin {
1558
1140
  }, (readPersistResult) => {
1559
1141
  if (readPersistResult.ok === _results__WEBPACK_IMPORTED_MODULE_2__.Result.ERROR) {
1560
1142
  // Notify that hydration failed
1561
- cache.delete(WAS_OPTIMISTIC_DB_HYDRATED_KEY);
1143
+ hydrationStatus = "hydration-error";
1144
+ console.log("[ROUTIER] - Hydration Error - Could Not Save", readPersistResult);
1562
1145
  done(readPersistResult);
1563
1146
  return;
1564
1147
  }
1148
+ hydrationStatus = "hydration-success";
1565
1149
  // requery the read plugin
1566
1150
  readPlugin.query(event, done);
1567
1151
  });
@@ -2349,23 +1933,19 @@ var __webpack_exports__ = {};
2349
1933
  __webpack_require__.r(__webpack_exports__);
2350
1934
  __webpack_require__.d(__webpack_exports__, {
2351
1935
  DataTranslator: () => (/* reexport safe */ _translators__WEBPACK_IMPORTED_MODULE_0__.DataTranslator),
2352
- DbPluginCapability: () => (/* reexport safe */ _capabilities__WEBPACK_IMPORTED_MODULE_1__.DbPluginCapability),
2353
- DbPluginLoggingCapability: () => (/* reexport safe */ _capabilities__WEBPACK_IMPORTED_MODULE_1__.DbPluginLoggingCapability),
2354
- EphemeralDataPlugin: () => (/* reexport safe */ _EphemeralDataPlugin__WEBPACK_IMPORTED_MODULE_4__.EphemeralDataPlugin),
1936
+ EphemeralDataPlugin: () => (/* reexport safe */ _EphemeralDataPlugin__WEBPACK_IMPORTED_MODULE_3__.EphemeralDataPlugin),
2355
1937
  JsonTranslator: () => (/* reexport safe */ _translators__WEBPACK_IMPORTED_MODULE_0__.JsonTranslator),
2356
- OptimisticReplicationDbPlugin: () => (/* reexport safe */ _replication__WEBPACK_IMPORTED_MODULE_2__.OptimisticReplicationDbPlugin),
2357
- Query: () => (/* reexport safe */ _query__WEBPACK_IMPORTED_MODULE_3__.Query),
2358
- QueryOptionsCollection: () => (/* reexport safe */ _query__WEBPACK_IMPORTED_MODULE_3__.QueryOptionsCollection),
2359
- QueryOrdering: () => (/* reexport safe */ _query__WEBPACK_IMPORTED_MODULE_3__.QueryOrdering),
2360
- ReplicationDbPlugin: () => (/* reexport safe */ _replication__WEBPACK_IMPORTED_MODULE_2__.ReplicationDbPlugin),
1938
+ OptimisticReplicationDbPlugin: () => (/* reexport safe */ _replication__WEBPACK_IMPORTED_MODULE_1__.OptimisticReplicationDbPlugin),
1939
+ Query: () => (/* reexport safe */ _query__WEBPACK_IMPORTED_MODULE_2__.Query),
1940
+ QueryOptionsCollection: () => (/* reexport safe */ _query__WEBPACK_IMPORTED_MODULE_2__.QueryOptionsCollection),
1941
+ QueryOrdering: () => (/* reexport safe */ _query__WEBPACK_IMPORTED_MODULE_2__.QueryOrdering),
1942
+ ReplicationDbPlugin: () => (/* reexport safe */ _replication__WEBPACK_IMPORTED_MODULE_1__.ReplicationDbPlugin),
2361
1943
  SqlTranslator: () => (/* reexport safe */ _translators__WEBPACK_IMPORTED_MODULE_0__.SqlTranslator)
2362
1944
  });
2363
1945
  /* ESM import */var _translators__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./translators */ "./src/plugins/translators/index.ts");
2364
- /* ESM import */var _capabilities__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./capabilities */ "./src/plugins/capabilities/index.ts");
2365
- /* ESM import */var _replication__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./replication */ "./src/plugins/replication/index.ts");
2366
- /* ESM import */var _query__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./query */ "./src/plugins/query/index.ts");
2367
- /* ESM import */var _EphemeralDataPlugin__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./EphemeralDataPlugin */ "./src/plugins/EphemeralDataPlugin.ts");
2368
-
1946
+ /* ESM import */var _replication__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./replication */ "./src/plugins/replication/index.ts");
1947
+ /* ESM import */var _query__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./query */ "./src/plugins/query/index.ts");
1948
+ /* ESM import */var _EphemeralDataPlugin__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./EphemeralDataPlugin */ "./src/plugins/EphemeralDataPlugin.ts");
2369
1949
 
2370
1950
 
2371
1951
 
@@ -2375,8 +1955,6 @@ __webpack_require__.d(__webpack_exports__, {
2375
1955
  })();
2376
1956
 
2377
1957
  var __webpack_exports__DataTranslator = __webpack_exports__.DataTranslator;
2378
- var __webpack_exports__DbPluginCapability = __webpack_exports__.DbPluginCapability;
2379
- var __webpack_exports__DbPluginLoggingCapability = __webpack_exports__.DbPluginLoggingCapability;
2380
1958
  var __webpack_exports__EphemeralDataPlugin = __webpack_exports__.EphemeralDataPlugin;
2381
1959
  var __webpack_exports__JsonTranslator = __webpack_exports__.JsonTranslator;
2382
1960
  var __webpack_exports__OptimisticReplicationDbPlugin = __webpack_exports__.OptimisticReplicationDbPlugin;
@@ -2385,6 +1963,6 @@ var __webpack_exports__QueryOptionsCollection = __webpack_exports__.QueryOptions
2385
1963
  var __webpack_exports__QueryOrdering = __webpack_exports__.QueryOrdering;
2386
1964
  var __webpack_exports__ReplicationDbPlugin = __webpack_exports__.ReplicationDbPlugin;
2387
1965
  var __webpack_exports__SqlTranslator = __webpack_exports__.SqlTranslator;
2388
- export { __webpack_exports__DataTranslator as DataTranslator, __webpack_exports__DbPluginCapability as DbPluginCapability, __webpack_exports__DbPluginLoggingCapability as DbPluginLoggingCapability, __webpack_exports__EphemeralDataPlugin as EphemeralDataPlugin, __webpack_exports__JsonTranslator as JsonTranslator, __webpack_exports__OptimisticReplicationDbPlugin as OptimisticReplicationDbPlugin, __webpack_exports__Query as Query, __webpack_exports__QueryOptionsCollection as QueryOptionsCollection, __webpack_exports__QueryOrdering as QueryOrdering, __webpack_exports__ReplicationDbPlugin as ReplicationDbPlugin, __webpack_exports__SqlTranslator as SqlTranslator };
1966
+ export { __webpack_exports__DataTranslator as DataTranslator, __webpack_exports__EphemeralDataPlugin as EphemeralDataPlugin, __webpack_exports__JsonTranslator as JsonTranslator, __webpack_exports__OptimisticReplicationDbPlugin as OptimisticReplicationDbPlugin, __webpack_exports__Query as Query, __webpack_exports__QueryOptionsCollection as QueryOptionsCollection, __webpack_exports__QueryOrdering as QueryOrdering, __webpack_exports__ReplicationDbPlugin as ReplicationDbPlugin, __webpack_exports__SqlTranslator as SqlTranslator };
2389
1967
 
2390
1968
  //# sourceMappingURL=index.js.map