@signaldb/core 1.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.
Files changed (102) hide show
  1. package/README.md +68 -0
  2. package/dist/.vite/manifest.json +222 -0
  3. package/dist/AutoFetchCollection.d.ts +60 -0
  4. package/dist/Collection/Cursor.d.ts +112 -0
  5. package/dist/Collection/Observer.d.ts +61 -0
  6. package/dist/Collection/createIndex.d.ts +15 -0
  7. package/dist/Collection/getIndexInfo.d.ts +41 -0
  8. package/dist/Collection/index.d.ts +235 -0
  9. package/dist/Collection/types.d.ts +25 -0
  10. package/dist/ReplicatedCollection.d.ts +60 -0
  11. package/dist/createIndexProvider.d.ts +8 -0
  12. package/dist/createMemoryAdapter.d.ts +7 -0
  13. package/dist/createReactivityAdapter.d.ts +8 -0
  14. package/dist/index.cjs.js +24 -0
  15. package/dist/index.cjs10.js +8 -0
  16. package/dist/index.cjs11.js +5 -0
  17. package/dist/index.cjs12.js +37 -0
  18. package/dist/index.cjs13.js +26 -0
  19. package/dist/index.cjs14.js +7 -0
  20. package/dist/index.cjs15.js +43 -0
  21. package/dist/index.cjs16.js +13 -0
  22. package/dist/index.cjs17.js +20 -0
  23. package/dist/index.cjs18.js +247 -0
  24. package/dist/index.cjs19.js +71 -0
  25. package/dist/index.cjs2.js +631 -0
  26. package/dist/index.cjs20.js +80 -0
  27. package/dist/index.cjs21.js +10 -0
  28. package/dist/index.cjs22.js +27 -0
  29. package/dist/index.cjs23.js +137 -0
  30. package/dist/index.cjs24.js +18 -0
  31. package/dist/index.cjs25.js +7 -0
  32. package/dist/index.cjs26.js +19 -0
  33. package/dist/index.cjs27.js +24 -0
  34. package/dist/index.cjs28.js +42 -0
  35. package/dist/index.cjs29.js +29 -0
  36. package/dist/index.cjs3.js +165 -0
  37. package/dist/index.cjs30.js +9 -0
  38. package/dist/index.cjs4.js +70 -0
  39. package/dist/index.cjs5.js +5 -0
  40. package/dist/index.cjs6.js +5 -0
  41. package/dist/index.cjs7.js +5 -0
  42. package/dist/index.cjs8.js +5 -0
  43. package/dist/index.cjs9.js +30 -0
  44. package/dist/index.d.ts +16 -0
  45. package/dist/index.mjs +24 -0
  46. package/dist/index10.mjs +9 -0
  47. package/dist/index11.mjs +6 -0
  48. package/dist/index12.mjs +37 -0
  49. package/dist/index13.mjs +27 -0
  50. package/dist/index14.mjs +8 -0
  51. package/dist/index15.mjs +43 -0
  52. package/dist/index16.mjs +14 -0
  53. package/dist/index17.mjs +21 -0
  54. package/dist/index18.mjs +247 -0
  55. package/dist/index19.mjs +71 -0
  56. package/dist/index2.mjs +632 -0
  57. package/dist/index20.mjs +80 -0
  58. package/dist/index21.mjs +11 -0
  59. package/dist/index22.mjs +28 -0
  60. package/dist/index23.mjs +138 -0
  61. package/dist/index24.mjs +18 -0
  62. package/dist/index25.mjs +8 -0
  63. package/dist/index26.mjs +20 -0
  64. package/dist/index27.mjs +25 -0
  65. package/dist/index28.mjs +43 -0
  66. package/dist/index29.mjs +30 -0
  67. package/dist/index3.mjs +166 -0
  68. package/dist/index30.mjs +10 -0
  69. package/dist/index4.mjs +70 -0
  70. package/dist/index5.mjs +6 -0
  71. package/dist/index6.mjs +6 -0
  72. package/dist/index7.mjs +6 -0
  73. package/dist/index8.mjs +6 -0
  74. package/dist/index9.mjs +31 -0
  75. package/dist/persistence/combinePersistenceAdapters.d.ts +32 -0
  76. package/dist/persistence/createPersistenceAdapter.d.ts +9 -0
  77. package/dist/types/Dependency.d.ts +4 -0
  78. package/dist/types/EventEmitter.d.ts +25 -0
  79. package/dist/types/IndexProvider.d.ts +19 -0
  80. package/dist/types/MemoryAdapter.d.ts +15 -0
  81. package/dist/types/Modifier.d.ts +39 -0
  82. package/dist/types/PersistenceAdapter.d.ts +20 -0
  83. package/dist/types/ReactivityAdapter.d.ts +6 -0
  84. package/dist/types/Selector.d.ts +47 -0
  85. package/dist/types/Signal.d.ts +4 -0
  86. package/dist/utils/compact.d.ts +9 -0
  87. package/dist/utils/createSignal.d.ts +14 -0
  88. package/dist/utils/deepClone.d.ts +17 -0
  89. package/dist/utils/get.d.ts +9 -0
  90. package/dist/utils/getMatchingKeys.d.ts +14 -0
  91. package/dist/utils/intersection.d.ts +9 -0
  92. package/dist/utils/isEqual.d.ts +14 -0
  93. package/dist/utils/isFieldExpression.d.ts +11 -0
  94. package/dist/utils/match.d.ts +12 -0
  95. package/dist/utils/modify.d.ts +14 -0
  96. package/dist/utils/project.d.ts +15 -0
  97. package/dist/utils/randomId.d.ts +7 -0
  98. package/dist/utils/serializeValue.d.ts +12 -0
  99. package/dist/utils/set.d.ts +13 -0
  100. package/dist/utils/sortItems.d.ts +12 -0
  101. package/dist/utils/uniqueBy.d.ts +10 -0
  102. package/package.json +58 -0
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
3
+ const index = require("./index.cjs2.js");
4
+ const combinePersistenceAdapters = require("./index.cjs4.js");
5
+ const createPersistenceAdapter = require("./index.cjs7.js");
6
+ const createSignal = require("./index.cjs17.js");
7
+ function createReplicationAdapter(options) {
8
+ return createPersistenceAdapter({
9
+ async register(onChange) {
10
+ if (!options.registerRemoteChange)
11
+ return;
12
+ await options.registerRemoteChange(onChange);
13
+ },
14
+ load: () => options.pull(),
15
+ save: (items, changes) => {
16
+ if (!options.push)
17
+ throw new Error("Pushing is not configured for this collection. Try to pass a `push` function to the collection options.");
18
+ return options.push(changes, items);
19
+ }
20
+ });
21
+ }
22
+ class ReplicatedCollection extends index.default {
23
+ /**
24
+ * Creates a new instance of the `ReplicatedCollection` class.
25
+ * Sets up the replication adapter, combining it with an optional persistence adapter, and
26
+ * initializes signals for tracking remote pull and push operations.
27
+ * @param options - The configuration options for the replicated collection.
28
+ * @param options.pull - A function to fetch data from the remote source.
29
+ * @param options.push - An optional function to send changes and items to the remote source.
30
+ * @param options.registerRemoteChange - An optional function to register a listener for remote changes.
31
+ * @param options.persistence - An optional persistence adapter to combine with replication.
32
+ * @param options.reactivity - A reactivity adapter for observing changes in the collection.
33
+ * @param options.transform - A transformation function to apply to items when retrieving them.
34
+ * @param options.indices - An array of index providers for optimized querying.
35
+ * @param options.enableDebugMode - A boolean to enable or disable debug mode.
36
+ */
37
+ constructor(options) {
38
+ var _a, _b;
39
+ const replicationAdapter = createReplicationAdapter({
40
+ registerRemoteChange: options.registerRemoteChange,
41
+ pull: async () => {
42
+ this.isPullingRemoteSignal.set(true);
43
+ try {
44
+ return await options.pull();
45
+ } finally {
46
+ this.isPullingRemoteSignal.set(false);
47
+ }
48
+ },
49
+ push: options.push ? async (changes, items) => {
50
+ if (!options.push)
51
+ throw new Error("Pushing is not configured for this collection. Try to pass a `push` function to the collection options.");
52
+ this.isPushingRemoteSignal.set(true);
53
+ try {
54
+ await options.push(changes, items);
55
+ } finally {
56
+ this.isPushingRemoteSignal.set(false);
57
+ }
58
+ } : void 0
59
+ });
60
+ const persistenceAdapter = (options === null || options === void 0 ? void 0 : options.persistence) ? combinePersistenceAdapters.default(replicationAdapter, options.persistence) : replicationAdapter;
61
+ super(Object.assign(Object.assign({}, options), { persistence: persistenceAdapter }));
62
+ this.isPullingRemoteSignal = createSignal((_a = options.reactivity) === null || _a === void 0 ? void 0 : _a.create(), false);
63
+ this.isPushingRemoteSignal = createSignal((_b = options.reactivity) === null || _b === void 0 ? void 0 : _b.create(), false);
64
+ }
65
+ /**
66
+ * Checks whether the collection is currently performing any loading operation,
67
+ * including pulling or pushing data from/to the remote source, or standard
68
+ * persistence adapter operations.
69
+ * ⚡️ this function is reactive!
70
+ * @returns A boolean indicating if the collection is currently loading or synchronizing.
71
+ */
72
+ isLoading() {
73
+ const isPullingRemote = this.isPullingRemoteSignal.get();
74
+ const isPushingRemote = this.isPushingRemoteSignal.get();
75
+ const isLoading = super.isLoading();
76
+ return isPullingRemote || isPushingRemote || isLoading;
77
+ }
78
+ }
79
+ exports.createReplicationAdapter = createReplicationAdapter;
80
+ exports.default = ReplicatedCollection;
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ const fastSort = require("fast-sort");
3
+ const get = require("./index.cjs26.js");
4
+ function sortItems(items, sortFields) {
5
+ return fastSort.sort(items).by(Object.entries(sortFields).map(([key, value]) => {
6
+ const order = value === 1 ? "asc" : "desc";
7
+ return { [order]: (i) => get(i, key) };
8
+ }));
9
+ }
10
+ module.exports = sortItems;
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ const get = require("./index.cjs26.js");
3
+ const set = require("./index.cjs29.js");
4
+ function project(item, fields) {
5
+ const allFieldsDeactivated = Object.values(fields).every((value) => value === 0);
6
+ if (allFieldsDeactivated) {
7
+ const result2 = Object.assign({}, item);
8
+ Object.keys(fields).forEach((key) => {
9
+ const fieldValue = get(item, key);
10
+ if (fieldValue === void 0)
11
+ return;
12
+ set(result2, key, void 0, true);
13
+ });
14
+ return result2;
15
+ }
16
+ const result = {};
17
+ Object.entries(fields).forEach(([key, value]) => {
18
+ const fieldValue = get(item, key);
19
+ if (fieldValue === void 0)
20
+ return;
21
+ if (fieldValue == null && value !== 1)
22
+ return;
23
+ set(result, key, value === 1 ? fieldValue : void 0);
24
+ });
25
+ return result;
26
+ }
27
+ module.exports = project;
@@ -0,0 +1,137 @@
1
+ "use strict";
2
+ const isEqual = require("./index.cjs9.js");
3
+ const uniqueBy = require("./index.cjs30.js");
4
+ class Observer {
5
+ /**
6
+ * Creates a new instance of the `Observer` class.
7
+ * Sets up event bindings and initializes the callbacks for tracking changes in a collection.
8
+ * @param bindEvents - A function to bind external events to the observer. Must return a cleanup function to unbind those events.
9
+ */
10
+ constructor(bindEvents) {
11
+ this.previousItems = [];
12
+ this.callbacks = {
13
+ added: [],
14
+ addedBefore: [],
15
+ changed: [],
16
+ changedField: [],
17
+ movedBefore: [],
18
+ removed: []
19
+ };
20
+ this.unbindEvents = bindEvents();
21
+ }
22
+ call(event, ...args) {
23
+ this.callbacks[event].forEach(({ callback, options }) => {
24
+ if (!options.skipInitial || !options.isInitial) {
25
+ callback(...args);
26
+ }
27
+ });
28
+ }
29
+ hasCallbacks(events) {
30
+ return events.some((event) => this.callbacks[event].length > 0);
31
+ }
32
+ /**
33
+ * Determines if the observer has no active callbacks registered for any events.
34
+ * @returns A boolean indicating whether the observer is empty (i.e., no callbacks are registered).
35
+ */
36
+ isEmpty() {
37
+ return !this.hasCallbacks([
38
+ "added",
39
+ "addedBefore",
40
+ "changed",
41
+ "changedField",
42
+ "movedBefore",
43
+ "removed"
44
+ ]);
45
+ }
46
+ /**
47
+ * Compares the previous state of items with the new state and triggers the appropriate callbacks
48
+ * for events such as added, removed, changed, or moved items.
49
+ * @param newItems - The new list of items to compare against the previous state.
50
+ */
51
+ runChecks(newItems) {
52
+ const oldItemsMap = new Map(this.previousItems.map((item, index) => [
53
+ item.id,
54
+ { item, index, beforeItem: this.previousItems[index + 1] || null }
55
+ ]));
56
+ const newItemsMap = new Map(newItems.map((item, index) => [
57
+ item.id,
58
+ { item, index, beforeItem: newItems[index + 1] || null }
59
+ ]));
60
+ if (this.hasCallbacks(["changed", "changedField", "movedBefore", "removed"])) {
61
+ oldItemsMap.forEach(({ item: oldItem, index, beforeItem: oldBeforeItem }) => {
62
+ var _a;
63
+ const newItem = newItemsMap.get(oldItem.id);
64
+ if (newItem) {
65
+ if (this.hasCallbacks(["changed", "changedField"])) {
66
+ if (!isEqual(newItem.item, oldItem)) {
67
+ this.call("changed", newItem.item);
68
+ if (this.hasCallbacks(["changedField"])) {
69
+ const keys = uniqueBy([
70
+ ...Object.keys(newItem.item),
71
+ ...Object.keys(oldItem)
72
+ ], (value) => value);
73
+ keys.forEach((key) => {
74
+ if (isEqual(newItem.item[key], oldItem[key]))
75
+ return;
76
+ this.call("changedField", newItem.item, key, oldItem[key], newItem.item[key]);
77
+ });
78
+ }
79
+ }
80
+ }
81
+ if (newItem.index !== index && ((_a = newItem.beforeItem) === null || _a === void 0 ? void 0 : _a.id) !== (oldBeforeItem === null || oldBeforeItem === void 0 ? void 0 : oldBeforeItem.id)) {
82
+ this.call("movedBefore", newItem.item, newItem.beforeItem);
83
+ }
84
+ } else {
85
+ this.call("removed", oldItem);
86
+ }
87
+ });
88
+ }
89
+ if (this.hasCallbacks(["added", "addedBefore"])) {
90
+ newItems.forEach((newItem, index) => {
91
+ const oldItem = oldItemsMap.get(newItem.id);
92
+ if (oldItem)
93
+ return;
94
+ this.call("added", newItem);
95
+ this.call("addedBefore", newItem, newItems[index + 1] || null);
96
+ });
97
+ }
98
+ this.previousItems = newItems;
99
+ Object.keys(this.callbacks).forEach((key) => {
100
+ const event = key;
101
+ const callbacks = this.callbacks[event];
102
+ this.callbacks[event] = callbacks.map((callback) => Object.assign(Object.assign({}, callback), { options: Object.assign(Object.assign({}, callback.options), { isInitial: false }) }));
103
+ });
104
+ }
105
+ /**
106
+ * Stops the observer by unbinding all events and cleaning up resources.
107
+ */
108
+ stop() {
109
+ this.unbindEvents();
110
+ }
111
+ /**
112
+ * Registers callbacks for specific events to observe changes in the collection.
113
+ * @param callbacks - An object containing the callbacks for various events (e.g., 'added', 'removed').
114
+ * @param skipInitial - A boolean indicating whether to skip invoking the callbacks for the initial state of the collection.
115
+ */
116
+ addCallbacks(callbacks, skipInitial = false) {
117
+ Object.keys(callbacks).forEach((key) => {
118
+ const typedKey = key;
119
+ this.callbacks[typedKey].push({
120
+ callback: callbacks[typedKey],
121
+ options: { skipInitial, isInitial: true }
122
+ });
123
+ });
124
+ }
125
+ /**
126
+ * Removes the specified callbacks for specific events, unregistering them from the observer.
127
+ * @param callbacks - An object containing the callbacks to be removed for various events.
128
+ */
129
+ removeCallbacks(callbacks) {
130
+ Object.keys(callbacks).forEach((key) => {
131
+ const typedKey = key;
132
+ const index = this.callbacks[typedKey].findIndex(({ callback }) => callback === callbacks[typedKey]);
133
+ this.callbacks[typedKey].splice(index, 1);
134
+ });
135
+ }
136
+ }
137
+ module.exports = Observer;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ function __rest(s, e) {
4
+ var t = {};
5
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
6
+ t[p] = s[p];
7
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
8
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
9
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
10
+ t[p[i]] = s[p[i]];
11
+ }
12
+ return t;
13
+ }
14
+ typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
15
+ var e = new Error(message);
16
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
17
+ };
18
+ exports.__rest = __rest;
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ function intersection(...arrays) {
3
+ if (arrays.length === 0)
4
+ return [];
5
+ return [...new Set(arrays.reduce((a, b) => a.filter((c) => b.includes(c))))];
6
+ }
7
+ module.exports = intersection;
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ function get(value, path) {
3
+ const segments = path.split(/[.[\]]/g);
4
+ if (segments[0] === "")
5
+ segments.shift();
6
+ if (segments[segments.length - 1] === "")
7
+ segments.pop();
8
+ let current = value;
9
+ for (let i = 0; i < segments.length; i += 1) {
10
+ const key = segments[i];
11
+ if (current == null || key.trim() === "")
12
+ return void 0;
13
+ current = current[key];
14
+ }
15
+ if (current === void 0)
16
+ return void 0;
17
+ return current;
18
+ }
19
+ module.exports = get;
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ const isFieldExpression = require("./index.cjs28.js");
3
+ const serializeValue = require("./index.cjs16.js");
4
+ function getMatchingKeys(field, selector) {
5
+ if (selector[field] instanceof RegExp)
6
+ return null;
7
+ if (selector[field] != null) {
8
+ if (isFieldExpression(selector[field])) {
9
+ const is$in = isFieldExpression(selector[field]) && Array.isArray(selector[field].$in) && selector[field].$in.length;
10
+ if (is$in) {
11
+ const optimizedSelector = Object.assign(Object.assign({}, selector), { [field]: Object.assign({}, selector[field]) });
12
+ delete optimizedSelector[field].$in;
13
+ if (Object.keys(optimizedSelector[field]).length === 0) {
14
+ delete optimizedSelector[field];
15
+ }
16
+ return selector[field].$in.map(serializeValue);
17
+ }
18
+ return null;
19
+ }
20
+ return [serializeValue(selector[field])];
21
+ }
22
+ return null;
23
+ }
24
+ module.exports = getMatchingKeys;
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ const expressionKeys = [
3
+ "$eq",
4
+ "$gt",
5
+ "$gte",
6
+ "$lt",
7
+ "$lte",
8
+ "$in",
9
+ "$nin",
10
+ "$ne",
11
+ "$exists",
12
+ "$not",
13
+ "$expr",
14
+ "$jsonSchema",
15
+ "$mod",
16
+ "$regex",
17
+ "$options",
18
+ "$text",
19
+ "$where",
20
+ "$all",
21
+ "$elemMatch",
22
+ "$size",
23
+ "$bitsAllClear",
24
+ "$bitsAllSet",
25
+ "$bitsAnyClear",
26
+ "$bitsAnySet"
27
+ ];
28
+ function isFieldExpression(expression) {
29
+ if (typeof expression !== "object" || expression == null) {
30
+ return false;
31
+ }
32
+ const keys = Object.keys(expression);
33
+ if (keys.length === 0) {
34
+ return false;
35
+ }
36
+ const hasInvalidKeys = keys.some((key) => !expressionKeys.includes(key));
37
+ if (hasInvalidKeys)
38
+ return false;
39
+ const hasValidKeys = keys.every((key) => expressionKeys.includes(key));
40
+ return hasValidKeys;
41
+ }
42
+ module.exports = isFieldExpression;
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ function set(obj, path, value, deleteIfUndefined = false) {
3
+ if (obj == null)
4
+ return obj;
5
+ const segments = path.split(/[.[\]]/g);
6
+ if (segments[0] === "")
7
+ segments.shift();
8
+ if (segments[segments.length - 1] === "")
9
+ segments.pop();
10
+ const apply = (node) => {
11
+ if (segments.length > 1) {
12
+ const key = segments.shift();
13
+ const nextIsNum = !Number.isNaN(parseInt(segments[0], 10));
14
+ if (node[key] === void 0) {
15
+ node[key] = nextIsNum ? [] : {};
16
+ }
17
+ apply(node[key]);
18
+ } else {
19
+ if (deleteIfUndefined && value === void 0) {
20
+ delete node[segments[0]];
21
+ return;
22
+ }
23
+ node[segments[0]] = value;
24
+ }
25
+ };
26
+ apply(obj);
27
+ return obj;
28
+ }
29
+ module.exports = set;
@@ -0,0 +1,165 @@
1
+ "use strict";
2
+ const ReplicatedCollection = require("./index.cjs20.js");
3
+ const createSignal = require("./index.cjs17.js");
4
+ class AutoFetchCollection extends ReplicatedCollection.default {
5
+ /**
6
+ * @param options {Object} - Options for the collection.
7
+ * @param options.fetchQueryItems {Function} - A function that fetches items from the server. It takes the selector as an argument and returns a promise that resolves to an object with an `items` property.
8
+ * @param options.purgeDelay {Number} - The delay in milliseconds before purging an item from the cache.
9
+ */
10
+ constructor(options) {
11
+ var _a, _b, _c, _d;
12
+ let triggerRemoteChange;
13
+ super(Object.assign(Object.assign({}, options), { pull: () => Promise.resolve({
14
+ items: [...this.itemsCache.values()].reduce((memo, items) => {
15
+ const newItems = [...memo];
16
+ items.forEach((item) => {
17
+ const index = newItems.findIndex((i) => i.id === item.id);
18
+ if (index === -1) {
19
+ newItems.push(item);
20
+ return;
21
+ }
22
+ newItems[index] = this.mergeItems(newItems[index], item);
23
+ });
24
+ return newItems;
25
+ }, [])
26
+ }), registerRemoteChange: async (onChange) => {
27
+ triggerRemoteChange = onChange;
28
+ return Promise.resolve();
29
+ } }));
30
+ this.activeObservers = /* @__PURE__ */ new Map();
31
+ this.observerTimeouts = /* @__PURE__ */ new Map();
32
+ this.idQueryCache = /* @__PURE__ */ new Map();
33
+ this.itemsCache = /* @__PURE__ */ new Map();
34
+ this.triggerReload = null;
35
+ this.reactivityAdapter = null;
36
+ this.loadingSignals = /* @__PURE__ */ new Map();
37
+ this.mergeItems = (_a = options.mergeItems) !== null && _a !== void 0 ? _a : (itemA, itemB) => Object.assign(Object.assign({}, itemA), itemB);
38
+ this.purgeDelay = (_b = options.purgeDelay) !== null && _b !== void 0 ? _b : 1e4;
39
+ this.isFetchingSignal = createSignal((_c = options.reactivity) === null || _c === void 0 ? void 0 : _c.create(), false);
40
+ if (!triggerRemoteChange)
41
+ throw new Error("No triggerRemoteChange method found. Looks like your persistence adapter was not registered");
42
+ this.triggerReload = triggerRemoteChange;
43
+ this.reactivityAdapter = (_d = options.reactivity) !== null && _d !== void 0 ? _d : null;
44
+ this.fetchQueryItems = options.fetchQueryItems;
45
+ this.on("observer.created", (selector) => this.handleObserverCreation(selector !== null && selector !== void 0 ? selector : {}));
46
+ this.on("observer.disposed", (selector) => setTimeout(() => this.handleObserverDisposal(selector !== null && selector !== void 0 ? selector : {}), 100));
47
+ if (options.registerRemoteChange) {
48
+ void options.registerRemoteChange(() => this.forceRefetch());
49
+ }
50
+ }
51
+ /**
52
+ * Registers a query manually that items should be fetched for it
53
+ * @param selector {Object} Selector of the query
54
+ */
55
+ registerQuery(selector) {
56
+ this.handleObserverCreation(selector);
57
+ }
58
+ /**
59
+ * Unregisters a query manually that items are not fetched anymore for it
60
+ * @param selector {Object} Selector of the query
61
+ */
62
+ unregisterQuery(selector) {
63
+ this.handleObserverDisposal(selector);
64
+ }
65
+ // eslint-disable-next-line class-methods-use-this
66
+ getKeyForSelector(selector) {
67
+ return JSON.stringify(selector);
68
+ }
69
+ async forceRefetch() {
70
+ return Promise.all([...this.activeObservers.values()].map(({ selector }) => this.fetchSelector(selector))).then(() => {
71
+ });
72
+ }
73
+ fetchSelector(selector) {
74
+ this.isFetchingSignal.set(true);
75
+ return this.fetchQueryItems(selector).then((response) => {
76
+ if (!response.items)
77
+ throw new Error("AutoFetchCollection currently only works with a full item response");
78
+ this.itemsCache.set(this.getKeyForSelector(selector), response.items);
79
+ response.items.forEach((item) => {
80
+ var _a;
81
+ const queries = (_a = this.idQueryCache.get(item.id)) !== null && _a !== void 0 ? _a : [];
82
+ queries.push(selector);
83
+ this.idQueryCache.set(item.id, queries);
84
+ });
85
+ this.setLoading(selector, true);
86
+ this.once("persistence.received", () => {
87
+ this.setLoading(selector, false);
88
+ });
89
+ if (!this.triggerReload)
90
+ throw new Error("No triggerReload method found. Looks like your persistence adapter was not registered");
91
+ void this.triggerReload();
92
+ }).catch((error) => {
93
+ this.emit("persistence.error", error);
94
+ }).finally(() => {
95
+ this.isFetchingSignal.set(false);
96
+ });
97
+ }
98
+ handleObserverCreation(selector) {
99
+ var _a, _b;
100
+ const activeObservers = (_b = (_a = this.activeObservers.get(this.getKeyForSelector(selector))) === null || _a === void 0 ? void 0 : _a.count) !== null && _b !== void 0 ? _b : 0;
101
+ this.activeObservers.set(this.getKeyForSelector(selector), {
102
+ selector,
103
+ count: activeObservers + 1
104
+ });
105
+ const timeout = this.observerTimeouts.get(this.getKeyForSelector(selector));
106
+ if (timeout)
107
+ clearTimeout(timeout);
108
+ if (activeObservers === 0)
109
+ void this.fetchSelector(selector);
110
+ }
111
+ handleObserverDisposal(selector) {
112
+ var _a, _b;
113
+ const currentObservers = (_b = (_a = this.activeObservers.get(this.getKeyForSelector(selector))) === null || _a === void 0 ? void 0 : _a.count) !== null && _b !== void 0 ? _b : 0;
114
+ const activeObservers = currentObservers - 1;
115
+ if (activeObservers > 0) {
116
+ this.activeObservers.set(this.getKeyForSelector(selector), {
117
+ selector,
118
+ count: activeObservers
119
+ });
120
+ return;
121
+ }
122
+ const timeout = this.observerTimeouts.get(this.getKeyForSelector(selector));
123
+ if (timeout)
124
+ clearTimeout(timeout);
125
+ const removeObserver = () => {
126
+ this.activeObservers.delete(this.getKeyForSelector(selector));
127
+ this.itemsCache.delete(this.getKeyForSelector(selector));
128
+ if (!this.triggerReload)
129
+ throw new Error("No triggerReload method found. Looks like your persistence adapter was not registered");
130
+ void this.triggerReload();
131
+ };
132
+ if (this.purgeDelay === 0) {
133
+ removeObserver();
134
+ return;
135
+ }
136
+ this.observerTimeouts.set(this.getKeyForSelector(selector), setTimeout(removeObserver, this.purgeDelay));
137
+ }
138
+ ensureSignal(selector) {
139
+ if (!this.reactivityAdapter)
140
+ throw new Error("No reactivity adapter found");
141
+ if (!this.loadingSignals.has(this.getKeyForSelector(selector))) {
142
+ this.loadingSignals.set(this.getKeyForSelector(selector), createSignal(this.reactivityAdapter.create(), false));
143
+ }
144
+ return this.loadingSignals.get(this.getKeyForSelector(selector));
145
+ }
146
+ setLoading(selector, value) {
147
+ const signal = this.ensureSignal(selector);
148
+ signal.set(value);
149
+ }
150
+ /**
151
+ * Indicates wether a query is currently been loaded
152
+ * ⚡️ this function is reactive!
153
+ * @param selector {Object} Selector of the query
154
+ * @returns The loading state
155
+ */
156
+ isLoading(selector) {
157
+ const isPushing = this.isPushing();
158
+ if (!selector) {
159
+ return this.isFetchingSignal.get() || isPushing;
160
+ }
161
+ const signal = this.ensureSignal(selector);
162
+ return signal.get() || isPushing;
163
+ }
164
+ }
165
+ module.exports = AutoFetchCollection;
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ function uniqueBy(arr, fn) {
3
+ const set = /* @__PURE__ */ new Set();
4
+ return arr.filter((el) => {
5
+ const value = typeof fn === "function" ? fn(el) : el[fn];
6
+ return !set.has(value) && set.add(value);
7
+ });
8
+ }
9
+ module.exports = uniqueBy;
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+ Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
3
+ const createPersistenceAdapter = require("./index.cjs7.js");
4
+ function createTemporaryFallbackExecutor(firstResolvingPromiseFn, secondResolvingPromiseFn, options) {
5
+ var _a;
6
+ const cacheTimeout = (_a = options === null || options === void 0 ? void 0 : options.cacheTimeout) !== null && _a !== void 0 ? _a : 0;
7
+ let isResolved = false;
8
+ let resolvedValue = null;
9
+ let timeout = null;
10
+ let secondaryPromise = null;
11
+ return (...args) => {
12
+ if (secondaryPromise == null) {
13
+ if (timeout) {
14
+ clearTimeout(timeout);
15
+ timeout = null;
16
+ }
17
+ secondaryPromise = secondResolvingPromiseFn(...args).then((result) => {
18
+ if (cacheTimeout > 0) {
19
+ timeout = setTimeout(() => {
20
+ isResolved = false;
21
+ resolvedValue = null;
22
+ secondaryPromise = null;
23
+ }, cacheTimeout);
24
+ }
25
+ isResolved = true;
26
+ resolvedValue = result;
27
+ if (options === null || options === void 0 ? void 0 : options.onResolve)
28
+ options.onResolve(resolvedValue);
29
+ return result;
30
+ });
31
+ } else if (isResolved) {
32
+ return secondaryPromise;
33
+ }
34
+ return firstResolvingPromiseFn(...args);
35
+ };
36
+ }
37
+ function combinePersistenceAdapters(slowAdapter, fastAdapter) {
38
+ let handleChange = null;
39
+ const readExecutor = createTemporaryFallbackExecutor(() => fastAdapter.load(), () => slowAdapter.load(), {
40
+ cacheTimeout: 100,
41
+ onResolve: (result) => {
42
+ var _a, _b, _c;
43
+ if (handleChange)
44
+ void handleChange();
45
+ void fastAdapter.save(result.items || [], {
46
+ added: ((_a = result.changes) === null || _a === void 0 ? void 0 : _a.added) || [],
47
+ modified: ((_b = result.changes) === null || _b === void 0 ? void 0 : _b.modified) || [],
48
+ removed: ((_c = result.changes) === null || _c === void 0 ? void 0 : _c.removed) || []
49
+ });
50
+ }
51
+ });
52
+ return createPersistenceAdapter({
53
+ async register(onChange) {
54
+ handleChange = onChange;
55
+ await Promise.all([slowAdapter.register(onChange), fastAdapter.register(onChange)]);
56
+ },
57
+ async load() {
58
+ const promise = readExecutor();
59
+ return promise;
60
+ },
61
+ async save(items, changes) {
62
+ await Promise.all([
63
+ fastAdapter.save(items, changes),
64
+ slowAdapter.save(items, changes)
65
+ ]);
66
+ }
67
+ });
68
+ }
69
+ exports.createTemporaryFallbackExecutor = createTemporaryFallbackExecutor;
70
+ exports.default = combinePersistenceAdapters;
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ function createIndexProvider(definition) {
3
+ return definition;
4
+ }
5
+ module.exports = createIndexProvider;
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ function createMemoryAdapter(definition) {
3
+ return definition;
4
+ }
5
+ module.exports = createMemoryAdapter;
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ function createPersistenceAdapter(definition) {
3
+ return definition;
4
+ }
5
+ module.exports = createPersistenceAdapter;
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ function createReactivityAdapter(definition) {
3
+ return definition;
4
+ }
5
+ module.exports = createReactivityAdapter;