@powersync/common 0.0.0-dev-20250715104704 → 0.0.0-dev-20250722092404

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 (34) hide show
  1. package/dist/bundle.cjs +5 -5
  2. package/dist/bundle.mjs +3 -3
  3. package/lib/client/AbstractPowerSyncDatabase.d.ts +58 -8
  4. package/lib/client/AbstractPowerSyncDatabase.js +100 -36
  5. package/lib/client/CustomQuery.d.ts +25 -0
  6. package/lib/client/CustomQuery.js +41 -0
  7. package/lib/client/Query.d.ts +97 -0
  8. package/lib/client/Query.js +1 -0
  9. package/lib/client/sync/bucket/BucketStorageAdapter.d.ts +2 -2
  10. package/lib/client/sync/bucket/SqliteBucketStorage.js +14 -14
  11. package/lib/client/sync/stream/AbstractRemote.js +31 -19
  12. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +5 -5
  13. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +30 -12
  14. package/lib/client/watched/GetAllQuery.d.ts +32 -0
  15. package/lib/client/watched/GetAllQuery.js +24 -0
  16. package/lib/client/watched/WatchedQuery.d.ts +93 -0
  17. package/lib/client/watched/WatchedQuery.js +12 -0
  18. package/lib/client/watched/processors/AbstractQueryProcessor.d.ts +67 -0
  19. package/lib/client/watched/processors/AbstractQueryProcessor.js +136 -0
  20. package/lib/client/watched/processors/DifferentialQueryProcessor.d.ts +121 -0
  21. package/lib/client/watched/processors/DifferentialQueryProcessor.js +164 -0
  22. package/lib/client/watched/processors/OnChangeQueryProcessor.d.ts +33 -0
  23. package/lib/client/watched/processors/OnChangeQueryProcessor.js +74 -0
  24. package/lib/client/watched/processors/comparators.d.ts +30 -0
  25. package/lib/client/watched/processors/comparators.js +34 -0
  26. package/lib/db/schema/RawTable.d.ts +4 -0
  27. package/lib/db/schema/RawTable.js +4 -0
  28. package/lib/index.d.ts +7 -1
  29. package/lib/index.js +7 -1
  30. package/lib/utils/BaseObserver.d.ts +3 -4
  31. package/lib/utils/BaseObserver.js +3 -0
  32. package/lib/utils/MetaBaseObserver.d.ts +29 -0
  33. package/lib/utils/MetaBaseObserver.js +50 -0
  34. package/package.json +1 -1
@@ -0,0 +1,121 @@
1
+ import { WatchCompatibleQuery, WatchedQuery, WatchedQueryListener, WatchedQueryOptions } from '../WatchedQuery.js';
2
+ import { AbstractQueryProcessor, AbstractQueryProcessorOptions, LinkQueryOptions } from './AbstractQueryProcessor.js';
3
+ /**
4
+ * Represents an updated row in a differential watched query.
5
+ * It contains both the current and previous state of the row.
6
+ */
7
+ export interface WatchedQueryRowDifferential<RowType> {
8
+ readonly current: RowType;
9
+ readonly previous: RowType;
10
+ }
11
+ /**
12
+ * Represents the result of a watched query that has been diffed.
13
+ * {@link DifferentialWatchedQueryState#diff} is of the {@link WatchedQueryDifferential} form.
14
+ */
15
+ export interface WatchedQueryDifferential<RowType> {
16
+ readonly added: ReadonlyArray<Readonly<RowType>>;
17
+ /**
18
+ * The entire current result set.
19
+ * Array item object references are preserved between updates if the item is unchanged.
20
+ *
21
+ * e.g. In the query
22
+ * ```sql
23
+ * SELECT name, make FROM assets ORDER BY make ASC;
24
+ * ```
25
+ *
26
+ * If a previous result set contains an item (A) `{name: 'pc', make: 'Cool PC'}` and
27
+ * an update has been made which adds another item (B) to the result set (the item A is unchanged) - then
28
+ * the updated result set will be contain the same object reference, to item A, as the previous result set.
29
+ * This is regardless of the item A's position in the updated result set.
30
+ */
31
+ readonly all: ReadonlyArray<Readonly<RowType>>;
32
+ readonly removed: ReadonlyArray<Readonly<RowType>>;
33
+ readonly updated: ReadonlyArray<WatchedQueryRowDifferential<Readonly<RowType>>>;
34
+ readonly unchanged: ReadonlyArray<Readonly<RowType>>;
35
+ }
36
+ /**
37
+ * Comparator for differentially watched queries which keys and compares items in the result set.
38
+ */
39
+ export interface DifferentialWatchedQueryComparator<RowType> {
40
+ /**
41
+ * Unique identifier for the item.
42
+ */
43
+ keyBy: (item: RowType) => string;
44
+ /**
45
+ * Generates a key for comparing items with matching identifiers.
46
+ */
47
+ compareBy: (item: RowType) => string;
48
+ }
49
+ /**
50
+ * Options for building a differential watched query with the {@link Query} builder.
51
+ */
52
+ export interface DifferentialWatchedQueryOptions<RowType> extends WatchedQueryOptions {
53
+ /**
54
+ * Initial result data which is presented while the initial loading is executing.
55
+ */
56
+ placeholderData?: RowType[];
57
+ /**
58
+ * Comparator used to identify and compare items in the result set.
59
+ * If not provided, the default comparator will be used which keys items by their `id` property if available,
60
+ * otherwise it uses JSON stringification of the entire item for keying and comparison.
61
+ * @defaultValue {@link DEFAULT_DIFFERENTIAL_WATCHED_QUERY_COMPARATOR}
62
+ */
63
+ comparator?: DifferentialWatchedQueryComparator<RowType>;
64
+ }
65
+ /**
66
+ * Settings for differential incremental watched queries using.
67
+ */
68
+ export interface DifferentialWatchedQuerySettings<RowType> extends DifferentialWatchedQueryOptions<RowType> {
69
+ /**
70
+ * The query here must return an array of items that can be differentiated.
71
+ */
72
+ query: WatchCompatibleQuery<RowType[]>;
73
+ }
74
+ export interface DifferentialWatchedQueryListener<RowType> extends WatchedQueryListener<ReadonlyArray<Readonly<RowType>>> {
75
+ onDiff?: (diff: WatchedQueryDifferential<RowType>) => void | Promise<void>;
76
+ }
77
+ export type DifferentialWatchedQuery<RowType> = WatchedQuery<ReadonlyArray<Readonly<RowType>>, DifferentialWatchedQuerySettings<RowType>, DifferentialWatchedQueryListener<RowType>>;
78
+ /**
79
+ * @internal
80
+ */
81
+ export interface DifferentialQueryProcessorOptions<RowType> extends AbstractQueryProcessorOptions<RowType[], DifferentialWatchedQuerySettings<RowType>> {
82
+ comparator?: DifferentialWatchedQueryComparator<RowType>;
83
+ }
84
+ type DataHashMap<RowType> = Map<string, {
85
+ hash: string;
86
+ item: RowType;
87
+ }>;
88
+ /**
89
+ * An empty differential result set.
90
+ * This is used as the initial state for differential incrementally watched queries.
91
+ */
92
+ export declare const EMPTY_DIFFERENTIAL: {
93
+ added: never[];
94
+ all: never[];
95
+ removed: never[];
96
+ updated: never[];
97
+ unchanged: never[];
98
+ };
99
+ /**
100
+ * Default implementation of the {@link DifferentialWatchedQueryComparator} for watched queries.
101
+ * It keys items by their `id` property if available, alternatively it uses JSON stringification
102
+ * of the entire item for the key and comparison.
103
+ */
104
+ export declare const DEFAULT_DIFFERENTIAL_WATCHED_QUERY_COMPARATOR: DifferentialWatchedQueryComparator<any>;
105
+ /**
106
+ * Uses the PowerSync onChange event to trigger watched queries.
107
+ * Results are emitted on every change of the relevant tables.
108
+ * @internal
109
+ */
110
+ export declare class DifferentialQueryProcessor<RowType> extends AbstractQueryProcessor<ReadonlyArray<Readonly<RowType>>, DifferentialWatchedQuerySettings<RowType>> implements DifferentialWatchedQuery<RowType> {
111
+ protected options: DifferentialQueryProcessorOptions<RowType>;
112
+ protected comparator: DifferentialWatchedQueryComparator<RowType>;
113
+ constructor(options: DifferentialQueryProcessorOptions<RowType>);
114
+ protected differentiate(current: RowType[], previousMap: DataHashMap<RowType>): {
115
+ diff: WatchedQueryDifferential<RowType>;
116
+ map: DataHashMap<RowType>;
117
+ hasChanged: boolean;
118
+ };
119
+ protected linkQuery(options: LinkQueryOptions<WatchedQueryDifferential<RowType>>): Promise<void>;
120
+ }
121
+ export {};
@@ -0,0 +1,164 @@
1
+ import { AbstractQueryProcessor } from './AbstractQueryProcessor.js';
2
+ /**
3
+ * An empty differential result set.
4
+ * This is used as the initial state for differential incrementally watched queries.
5
+ */
6
+ export const EMPTY_DIFFERENTIAL = {
7
+ added: [],
8
+ all: [],
9
+ removed: [],
10
+ updated: [],
11
+ unchanged: []
12
+ };
13
+ /**
14
+ * Default implementation of the {@link DifferentialWatchedQueryComparator} for watched queries.
15
+ * It keys items by their `id` property if available, alternatively it uses JSON stringification
16
+ * of the entire item for the key and comparison.
17
+ */
18
+ export const DEFAULT_DIFFERENTIAL_WATCHED_QUERY_COMPARATOR = {
19
+ keyBy: (item) => {
20
+ if (item && typeof item == 'object' && typeof item['id'] == 'string') {
21
+ return item['id'];
22
+ }
23
+ return JSON.stringify(item);
24
+ },
25
+ compareBy: (item) => JSON.stringify(item)
26
+ };
27
+ /**
28
+ * Uses the PowerSync onChange event to trigger watched queries.
29
+ * Results are emitted on every change of the relevant tables.
30
+ * @internal
31
+ */
32
+ export class DifferentialQueryProcessor extends AbstractQueryProcessor {
33
+ options;
34
+ comparator;
35
+ constructor(options) {
36
+ super(options);
37
+ this.options = options;
38
+ this.comparator = options.comparator ?? DEFAULT_DIFFERENTIAL_WATCHED_QUERY_COMPARATOR;
39
+ }
40
+ /*
41
+ * @returns If the sets are equal
42
+ */
43
+ differentiate(current, previousMap) {
44
+ const { keyBy, compareBy } = this.comparator;
45
+ let hasChanged = false;
46
+ const currentMap = new Map();
47
+ const removedTracker = new Set(previousMap.keys());
48
+ // Allow mutating to populate the data temporarily.
49
+ const diff = {
50
+ all: [],
51
+ added: [],
52
+ removed: [],
53
+ updated: [],
54
+ unchanged: []
55
+ };
56
+ /**
57
+ * Looping over the current result set array is important to preserve
58
+ * the ordering of the result set.
59
+ * We can replace items in the current array with previous object references if they are equal.
60
+ */
61
+ for (const item of current) {
62
+ const key = keyBy(item);
63
+ const hash = compareBy(item);
64
+ currentMap.set(key, { hash, item });
65
+ const previousItem = previousMap.get(key);
66
+ if (!previousItem) {
67
+ // New item
68
+ hasChanged = true;
69
+ diff.added.push(item);
70
+ diff.all.push(item);
71
+ }
72
+ else {
73
+ // Existing item
74
+ if (hash == previousItem.hash) {
75
+ diff.unchanged.push(previousItem.item);
76
+ // Use the previous object reference
77
+ diff.all.push(previousItem.item);
78
+ // update the map to preserve the reference
79
+ currentMap.set(key, previousItem);
80
+ }
81
+ else {
82
+ hasChanged = true;
83
+ diff.updated.push({ current: item, previous: previousItem.item });
84
+ // Use the new reference
85
+ diff.all.push(item);
86
+ }
87
+ }
88
+ // The item is present, we don't consider it removed
89
+ removedTracker.delete(key);
90
+ }
91
+ diff.removed = Array.from(removedTracker).map((key) => previousMap.get(key).item);
92
+ hasChanged = hasChanged || diff.removed.length > 0;
93
+ return {
94
+ diff,
95
+ hasChanged,
96
+ map: currentMap
97
+ };
98
+ }
99
+ async linkQuery(options) {
100
+ const { db, watchOptions } = this.options;
101
+ const { abortSignal } = options;
102
+ const compiledQuery = watchOptions.query.compile();
103
+ const tables = await db.resolveTables(compiledQuery.sql, compiledQuery.parameters);
104
+ let currentMap = new Map();
105
+ // populate the currentMap from the placeholder data
106
+ this.state.data.forEach((item) => {
107
+ currentMap.set(this.comparator.keyBy(item), {
108
+ hash: this.comparator.compareBy(item),
109
+ item
110
+ });
111
+ });
112
+ db.onChangeWithCallback({
113
+ onChange: async () => {
114
+ if (this.closed) {
115
+ return;
116
+ }
117
+ // This fires for each change of the relevant tables
118
+ try {
119
+ if (this.reportFetching && !this.state.isFetching) {
120
+ await this.updateState({ isFetching: true });
121
+ }
122
+ const partialStateUpdate = {};
123
+ // Always run the query if an underlying table has changed
124
+ const result = await watchOptions.query.execute({
125
+ sql: compiledQuery.sql,
126
+ // Allows casting from ReadOnlyArray[unknown] to Array<unknown>
127
+ // This allows simpler compatibility with PowerSync queries
128
+ parameters: [...compiledQuery.parameters],
129
+ db: this.options.db
130
+ });
131
+ if (this.reportFetching) {
132
+ partialStateUpdate.isFetching = false;
133
+ }
134
+ if (this.state.isLoading) {
135
+ partialStateUpdate.isLoading = false;
136
+ }
137
+ const { diff, hasChanged, map } = this.differentiate(result, currentMap);
138
+ // Update for future comparisons
139
+ currentMap = map;
140
+ if (hasChanged) {
141
+ await this.iterateAsyncListenersWithError((l) => l.onDiff?.(diff));
142
+ Object.assign(partialStateUpdate, {
143
+ data: diff.all
144
+ });
145
+ }
146
+ if (Object.keys(partialStateUpdate).length > 0) {
147
+ await this.updateState(partialStateUpdate);
148
+ }
149
+ }
150
+ catch (error) {
151
+ await this.updateState({ error });
152
+ }
153
+ },
154
+ onError: async (error) => {
155
+ await this.updateState({ error });
156
+ }
157
+ }, {
158
+ signal: abortSignal,
159
+ tables,
160
+ throttleMs: watchOptions.throttleMs,
161
+ triggerImmediate: true // used to emit the initial state
162
+ });
163
+ }
164
+ }
@@ -0,0 +1,33 @@
1
+ import { WatchCompatibleQuery, WatchedQuery, WatchedQueryOptions } from '../WatchedQuery.js';
2
+ import { AbstractQueryProcessor, AbstractQueryProcessorOptions, LinkQueryOptions } from './AbstractQueryProcessor.js';
3
+ import { WatchedQueryComparator } from './comparators.js';
4
+ /**
5
+ * Settings for {@link WatchedQuery} instances created via {@link Query#watch}.
6
+ */
7
+ export interface WatchedQuerySettings<DataType> extends WatchedQueryOptions {
8
+ query: WatchCompatibleQuery<DataType>;
9
+ }
10
+ /**
11
+ * {@link WatchedQuery} returned from {@link Query#watch}.
12
+ */
13
+ export type StandardWatchedQuery<DataType> = WatchedQuery<DataType, WatchedQuerySettings<DataType>>;
14
+ /**
15
+ * @internal
16
+ */
17
+ export interface OnChangeQueryProcessorOptions<Data> extends AbstractQueryProcessorOptions<Data, WatchedQuerySettings<Data>> {
18
+ comparator?: WatchedQueryComparator<Data>;
19
+ }
20
+ /**
21
+ * Uses the PowerSync onChange event to trigger watched queries.
22
+ * Results are emitted on every change of the relevant tables.
23
+ * @internal
24
+ */
25
+ export declare class OnChangeQueryProcessor<Data> extends AbstractQueryProcessor<Data, WatchedQuerySettings<Data>> {
26
+ protected options: OnChangeQueryProcessorOptions<Data>;
27
+ constructor(options: OnChangeQueryProcessorOptions<Data>);
28
+ /**
29
+ * @returns If the sets are equal
30
+ */
31
+ protected checkEquality(current: Data, previous: Data): boolean;
32
+ protected linkQuery(options: LinkQueryOptions<Data>): Promise<void>;
33
+ }
@@ -0,0 +1,74 @@
1
+ import { AbstractQueryProcessor } from './AbstractQueryProcessor.js';
2
+ /**
3
+ * Uses the PowerSync onChange event to trigger watched queries.
4
+ * Results are emitted on every change of the relevant tables.
5
+ * @internal
6
+ */
7
+ export class OnChangeQueryProcessor extends AbstractQueryProcessor {
8
+ options;
9
+ constructor(options) {
10
+ super(options);
11
+ this.options = options;
12
+ }
13
+ /**
14
+ * @returns If the sets are equal
15
+ */
16
+ checkEquality(current, previous) {
17
+ // Use the provided comparator if available. Assume values are unique if not available.
18
+ return this.options.comparator?.checkEquality?.(current, previous) ?? false;
19
+ }
20
+ async linkQuery(options) {
21
+ const { db, watchOptions } = this.options;
22
+ const { abortSignal } = options;
23
+ const compiledQuery = watchOptions.query.compile();
24
+ const tables = await db.resolveTables(compiledQuery.sql, compiledQuery.parameters);
25
+ db.onChangeWithCallback({
26
+ onChange: async () => {
27
+ if (this.closed) {
28
+ return;
29
+ }
30
+ // This fires for each change of the relevant tables
31
+ try {
32
+ if (this.reportFetching && !this.state.isFetching) {
33
+ await this.updateState({ isFetching: true });
34
+ }
35
+ const partialStateUpdate = {};
36
+ // Always run the query if an underlying table has changed
37
+ const result = await watchOptions.query.execute({
38
+ sql: compiledQuery.sql,
39
+ // Allows casting from ReadOnlyArray[unknown] to Array<unknown>
40
+ // This allows simpler compatibility with PowerSync queries
41
+ parameters: [...compiledQuery.parameters],
42
+ db: this.options.db
43
+ });
44
+ if (this.reportFetching) {
45
+ partialStateUpdate.isFetching = false;
46
+ }
47
+ if (this.state.isLoading) {
48
+ partialStateUpdate.isLoading = false;
49
+ }
50
+ // Check if the result has changed
51
+ if (!this.checkEquality(result, this.state.data)) {
52
+ Object.assign(partialStateUpdate, {
53
+ data: result
54
+ });
55
+ }
56
+ if (Object.keys(partialStateUpdate).length > 0) {
57
+ await this.updateState(partialStateUpdate);
58
+ }
59
+ }
60
+ catch (error) {
61
+ await this.updateState({ error });
62
+ }
63
+ },
64
+ onError: async (error) => {
65
+ await this.updateState({ error });
66
+ }
67
+ }, {
68
+ signal: abortSignal,
69
+ tables,
70
+ throttleMs: watchOptions.throttleMs,
71
+ triggerImmediate: true // used to emit the initial state
72
+ });
73
+ }
74
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * A basic comparator for incrementally watched queries. This performs a single comparison which
3
+ * determines if the result set has changed. The {@link WatchedQuery} will only emit the new result
4
+ * if a change has been detected.
5
+ */
6
+ export interface WatchedQueryComparator<Data> {
7
+ checkEquality: (current: Data, previous: Data) => boolean;
8
+ }
9
+ /**
10
+ * Options for {@link ArrayComparator}
11
+ */
12
+ export type ArrayComparatorOptions<ItemType> = {
13
+ /**
14
+ * Returns a string to uniquely identify an item in the array.
15
+ */
16
+ compareBy: (item: ItemType) => string;
17
+ };
18
+ /**
19
+ * An efficient comparator for {@link WatchedQuery} created with {@link Query#watch}. This has the ability to determine if a query
20
+ * result has changes without necessarily processing all items in the result.
21
+ */
22
+ export declare class ArrayComparator<ItemType> implements WatchedQueryComparator<ItemType[]> {
23
+ protected options: ArrayComparatorOptions<ItemType>;
24
+ constructor(options: ArrayComparatorOptions<ItemType>);
25
+ checkEquality(current: ItemType[], previous: ItemType[]): boolean;
26
+ }
27
+ /**
28
+ * Watched query comparator that always reports changed result sets.
29
+ */
30
+ export declare const FalsyComparator: WatchedQueryComparator<unknown>;
@@ -0,0 +1,34 @@
1
+ /**
2
+ * An efficient comparator for {@link WatchedQuery} created with {@link Query#watch}. This has the ability to determine if a query
3
+ * result has changes without necessarily processing all items in the result.
4
+ */
5
+ export class ArrayComparator {
6
+ options;
7
+ constructor(options) {
8
+ this.options = options;
9
+ }
10
+ checkEquality(current, previous) {
11
+ if (current.length === 0 && previous.length === 0) {
12
+ return true;
13
+ }
14
+ if (current.length !== previous.length) {
15
+ return false;
16
+ }
17
+ const { compareBy } = this.options;
18
+ // At this point the lengths are equal
19
+ for (let i = 0; i < current.length; i++) {
20
+ const currentItem = compareBy(current[i]);
21
+ const previousItem = compareBy(previous[i]);
22
+ if (currentItem !== previousItem) {
23
+ return false;
24
+ }
25
+ }
26
+ return true;
27
+ }
28
+ }
29
+ /**
30
+ * Watched query comparator that always reports changed result sets.
31
+ */
32
+ export const FalsyComparator = {
33
+ checkEquality: () => false // Default comparator that always returns false
34
+ };
@@ -37,6 +37,10 @@ export type PendingStatement = {
37
37
  * Since raw tables are not backed by JSON, running complex queries on them may be more efficient. Further, they allow
38
38
  * using client-side table and column constraints.
39
39
  *
40
+ * To collect local writes to raw tables with PowerSync, custom triggers are required. See
41
+ * {@link https://docs.powersync.com/usage/use-case-examples/raw-tables the documentation} for details and an example on
42
+ * using raw tables.
43
+ *
40
44
  * Note that raw tables are only supported when using the new `SyncClientImplementation.rust` sync client.
41
45
  *
42
46
  * @experimental Please note that this feature is experimental at the moment, and not covered by PowerSync semver or
@@ -4,6 +4,10 @@
4
4
  * Since raw tables are not backed by JSON, running complex queries on them may be more efficient. Further, they allow
5
5
  * using client-side table and column constraints.
6
6
  *
7
+ * To collect local writes to raw tables with PowerSync, custom triggers are required. See
8
+ * {@link https://docs.powersync.com/usage/use-case-examples/raw-tables the documentation} for details and an example on
9
+ * using raw tables.
10
+ *
7
11
  * Note that raw tables are only supported when using the new `SyncClientImplementation.rust` sync client.
8
12
  *
9
13
  * @experimental Please note that this feature is experimental at the moment, and not covered by PowerSync semver or
package/lib/index.d.ts CHANGED
@@ -29,9 +29,15 @@ export * from './db/schema/IndexedColumn.js';
29
29
  export * from './db/schema/Schema.js';
30
30
  export * from './db/schema/Table.js';
31
31
  export * from './db/schema/TableV2.js';
32
+ export * from './client/Query.js';
33
+ export * from './client/watched/GetAllQuery.js';
34
+ export * from './client/watched/processors/AbstractQueryProcessor.js';
35
+ export * from './client/watched/processors/comparators.js';
36
+ export * from './client/watched/processors/DifferentialQueryProcessor.js';
37
+ export * from './client/watched/processors/OnChangeQueryProcessor.js';
38
+ export * from './client/watched/WatchedQuery.js';
32
39
  export * from './utils/AbortOperation.js';
33
40
  export * from './utils/BaseObserver.js';
34
- export * from './utils/ControlledExecutor.js';
35
41
  export * from './utils/DataStream.js';
36
42
  export * from './utils/Logger.js';
37
43
  export * from './utils/parseQuery.js';
package/lib/index.js CHANGED
@@ -29,9 +29,15 @@ export * from './db/schema/IndexedColumn.js';
29
29
  export * from './db/schema/Schema.js';
30
30
  export * from './db/schema/Table.js';
31
31
  export * from './db/schema/TableV2.js';
32
+ export * from './client/Query.js';
33
+ export * from './client/watched/GetAllQuery.js';
34
+ export * from './client/watched/processors/AbstractQueryProcessor.js';
35
+ export * from './client/watched/processors/comparators.js';
36
+ export * from './client/watched/processors/DifferentialQueryProcessor.js';
37
+ export * from './client/watched/processors/OnChangeQueryProcessor.js';
38
+ export * from './client/watched/WatchedQuery.js';
32
39
  export * from './utils/AbortOperation.js';
33
40
  export * from './utils/BaseObserver.js';
34
- export * from './utils/ControlledExecutor.js';
35
41
  export * from './utils/DataStream.js';
36
42
  export * from './utils/Logger.js';
37
43
  export * from './utils/parseQuery.js';
@@ -1,15 +1,14 @@
1
1
  export interface Disposable {
2
- dispose: () => Promise<void>;
2
+ dispose: () => Promise<void> | void;
3
3
  }
4
+ export type BaseListener = Record<string, ((...event: any) => any) | undefined>;
4
5
  export interface BaseObserverInterface<T extends BaseListener> {
5
6
  registerListener(listener: Partial<T>): () => void;
6
7
  }
7
- export type BaseListener = {
8
- [key: string]: ((...event: any) => any) | undefined;
9
- };
10
8
  export declare class BaseObserver<T extends BaseListener = BaseListener> implements BaseObserverInterface<T> {
11
9
  protected listeners: Set<Partial<T>>;
12
10
  constructor();
11
+ dispose(): void;
13
12
  /**
14
13
  * Register a listener for updates to the PowerSync client.
15
14
  */
@@ -1,6 +1,9 @@
1
1
  export class BaseObserver {
2
2
  listeners = new Set();
3
3
  constructor() { }
4
+ dispose() {
5
+ this.listeners.clear();
6
+ }
4
7
  /**
5
8
  * Register a listener for updates to the PowerSync client.
6
9
  */
@@ -0,0 +1,29 @@
1
+ import { BaseListener, BaseObserver, BaseObserverInterface } from './BaseObserver.js';
2
+ /**
3
+ * Represents the counts of listeners for each event type in a BaseListener.
4
+ */
5
+ export type ListenerCounts<Listener extends BaseListener> = Partial<Record<keyof Listener, number>> & {
6
+ total: number;
7
+ };
8
+ /**
9
+ * Meta listener which reports the counts of listeners for each event type.
10
+ */
11
+ export interface MetaListener<ParentListener extends BaseListener> extends BaseListener {
12
+ listenersChanged?: (counts: ListenerCounts<ParentListener>) => void;
13
+ }
14
+ export interface ListenerMetaManager<Listener extends BaseListener> extends BaseObserverInterface<MetaListener<Listener>> {
15
+ counts: ListenerCounts<Listener>;
16
+ }
17
+ export interface MetaBaseObserverInterface<Listener extends BaseListener> extends BaseObserverInterface<Listener> {
18
+ listenerMeta: ListenerMetaManager<Listener>;
19
+ }
20
+ /**
21
+ * A BaseObserver that tracks the counts of listeners for each event type.
22
+ */
23
+ export declare class MetaBaseObserver<Listener extends BaseListener> extends BaseObserver<Listener> implements MetaBaseObserverInterface<Listener> {
24
+ protected get listenerCounts(): ListenerCounts<Listener>;
25
+ get listenerMeta(): ListenerMetaManager<Listener>;
26
+ protected metaListener: BaseObserver<MetaListener<Listener>>;
27
+ constructor();
28
+ registerListener(listener: Partial<Listener>): () => void;
29
+ }
@@ -0,0 +1,50 @@
1
+ import { BaseObserver } from './BaseObserver.js';
2
+ /**
3
+ * A BaseObserver that tracks the counts of listeners for each event type.
4
+ */
5
+ export class MetaBaseObserver extends BaseObserver {
6
+ get listenerCounts() {
7
+ const counts = {};
8
+ let total = 0;
9
+ for (const listener of this.listeners) {
10
+ for (const key in listener) {
11
+ if (listener[key]) {
12
+ counts[key] = (counts[key] ?? 0) + 1;
13
+ total++;
14
+ }
15
+ }
16
+ }
17
+ return {
18
+ ...counts,
19
+ total
20
+ };
21
+ }
22
+ get listenerMeta() {
23
+ return {
24
+ counts: this.listenerCounts,
25
+ // Allows registering a meta listener that will be notified of changes in listener counts
26
+ registerListener: (listener) => {
27
+ return this.metaListener.registerListener(listener);
28
+ }
29
+ };
30
+ }
31
+ metaListener;
32
+ constructor() {
33
+ super();
34
+ this.metaListener = new BaseObserver();
35
+ }
36
+ registerListener(listener) {
37
+ const dispose = super.registerListener(listener);
38
+ const updatedCount = this.listenerCounts;
39
+ this.metaListener.iterateListeners((l) => {
40
+ l.listenersChanged?.(updatedCount);
41
+ });
42
+ return () => {
43
+ dispose();
44
+ const updatedCount = this.listenerCounts;
45
+ this.metaListener.iterateListeners((l) => {
46
+ l.listenersChanged?.(updatedCount);
47
+ });
48
+ };
49
+ }
50
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@powersync/common",
3
- "version": "0.0.0-dev-20250715104704",
3
+ "version": "0.0.0-dev-20250722092404",
4
4
  "publishConfig": {
5
5
  "registry": "https://registry.npmjs.org/",
6
6
  "access": "public"