@powersync/node 0.0.0-dev-20250318143512
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +47 -0
- package/download_core.js +46 -0
- package/lib/db/AsyncDatabase.d.ts +16 -0
- package/lib/db/AsyncDatabase.js +1 -0
- package/lib/db/BetterSQLite3DBAdapter.d.ts +30 -0
- package/lib/db/BetterSQLite3DBAdapter.js +211 -0
- package/lib/db/PowerSyncDatabase.d.ts +24 -0
- package/lib/db/PowerSyncDatabase.js +46 -0
- package/lib/db/RemoteConnection.d.ts +22 -0
- package/lib/db/RemoteConnection.js +61 -0
- package/lib/db/SqliteWorker.d.ts +1 -0
- package/lib/db/SqliteWorker.js +99 -0
- package/lib/index.d.ts +2 -0
- package/lib/index.js +3 -0
- package/lib/libpowersync.so +0 -0
- package/lib/sync/stream/NodeRemote.d.ts +10 -0
- package/lib/sync/stream/NodeRemote.js +32 -0
- package/lib/sync/stream/NodeStreamingSyncImplementation.d.ts +11 -0
- package/lib/sync/stream/NodeStreamingSyncImplementation.js +40 -0
- package/package.json +58 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
<p align="center">
|
|
2
|
+
<a href="https://www.powersync.com" target="_blank"><img src="https://github.com/powersync-ja/.github/assets/7372448/d2538c43-c1a0-4c47-9a76-41462dba484f"/></a>
|
|
3
|
+
</p>
|
|
4
|
+
|
|
5
|
+
# PowerSync SDK for Node.js
|
|
6
|
+
|
|
7
|
+
_[PowerSync](https://www.powersync.com) is a sync engine for building local-first apps with instantly-responsive UI/UX and simplified state transfer. Syncs between SQLite on the client-side and Postgres, MongoDB or MySQL on the server-side._
|
|
8
|
+
|
|
9
|
+
This package (`packages/node`) is the PowerSync SDK for Node.js clients. It is an extension of `packages/common`.
|
|
10
|
+
Using this package is not necessary for PowerSync on servers, see [our documentation](https://docs.powersync.com/installation/app-backend-setup) for more details on that.
|
|
11
|
+
|
|
12
|
+
See a summary of features [here](https://docs.powersync.com/client-sdk-references/node).
|
|
13
|
+
|
|
14
|
+
## Alpha Release
|
|
15
|
+
|
|
16
|
+
The `@powersync/node` package is currently in an Alpha release.
|
|
17
|
+
|
|
18
|
+
# Installation
|
|
19
|
+
|
|
20
|
+
## Install Package
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
npm install @powersync/node
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Both `@powersync/node` and the `better-sqlite3` packages have install scripts that need to run to compile
|
|
27
|
+
or download sqlite3 and PowerSync binaries.
|
|
28
|
+
|
|
29
|
+
# Getting Started
|
|
30
|
+
|
|
31
|
+
The [Node.js SDK reference](https://docs.powersync.com/client-sdk-references/node)
|
|
32
|
+
contains everything you need to know to get started implementing PowerSync in your project.
|
|
33
|
+
|
|
34
|
+
# Examples
|
|
35
|
+
|
|
36
|
+
A simple example using `@powersync/node` is available in the [`demos/example-node/`](../demos/example-node) directory.
|
|
37
|
+
|
|
38
|
+
# Found a bug or need help?
|
|
39
|
+
|
|
40
|
+
- Join our [Discord server](https://discord.gg/powersync) where you can browse topics from our community, ask questions, share feedback, or just say hello :)
|
|
41
|
+
- Please open a [GitHub issue](https://github.com/powersync-ja/powersync-js/issues) when you come across a bug.
|
|
42
|
+
- Have feedback or an idea? [Submit an idea](https://roadmap.powersync.com/tabs/5-roadmap/submit-idea) via our public roadmap or [schedule a chat](https://calendly.com/powersync-product/powersync-chat) with someone from our product team.
|
|
43
|
+
|
|
44
|
+
# Thanks
|
|
45
|
+
|
|
46
|
+
The PowerSync Node.js SDK relies on the work contributors and maintainers have put into the upstream better-sqlite3 package.
|
|
47
|
+
In particular, we'd like to thank [@spinda](https://github.com/spinda) for contributing support for update, commit and rollback hooks!
|
package/download_core.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// TODO: Make this a pre-publish hook and just bundle everything
|
|
2
|
+
import * as OS from 'node:os';
|
|
3
|
+
import * as fs from 'node:fs/promises';
|
|
4
|
+
import * as path from 'node:path';
|
|
5
|
+
import { Readable } from 'node:stream';
|
|
6
|
+
import { finished } from 'node:stream/promises';
|
|
7
|
+
import { exit } from 'node:process';
|
|
8
|
+
|
|
9
|
+
const version = '0.3.11';
|
|
10
|
+
|
|
11
|
+
const platform = OS.platform();
|
|
12
|
+
let destination;
|
|
13
|
+
let asset;
|
|
14
|
+
|
|
15
|
+
if (platform === 'win32') {
|
|
16
|
+
asset = 'powersync_x64.dll';
|
|
17
|
+
destination = 'powersync.dll';
|
|
18
|
+
} else if (platform === 'linux') {
|
|
19
|
+
asset = OS.arch() === 'x64' ? 'libpowersync_x64.so' : 'libpowersync_aarch64.so';
|
|
20
|
+
destination = 'libpowersync.so';
|
|
21
|
+
} else if (platform === 'darwin') {
|
|
22
|
+
asset = OS.arch() === 'x64' ? 'libpowersync_x64.dylib' : 'libpowersync_aarch64.dylib';
|
|
23
|
+
destination = 'libpowersync.dylib';
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const destinationPath = path.resolve('lib', destination);
|
|
27
|
+
try {
|
|
28
|
+
await fs.access(destinationPath);
|
|
29
|
+
exit(0);
|
|
30
|
+
} catch {}
|
|
31
|
+
|
|
32
|
+
const url = `https://github.com/powersync-ja/powersync-sqlite-core/releases/download/v${version}/${asset}`;
|
|
33
|
+
const response = await fetch(url);
|
|
34
|
+
if (response.status != 200) {
|
|
35
|
+
throw `Could not download ${url}`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
try {
|
|
39
|
+
await fs.access('lib');
|
|
40
|
+
} catch {
|
|
41
|
+
await fs.mkdir('lib');
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const file = await fs.open(destinationPath, 'w');
|
|
45
|
+
await finished(Readable.fromWeb(response.body).pipe(file.createWriteStream()));
|
|
46
|
+
await file.close();
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { QueryResult } from '@powersync/common';
|
|
2
|
+
export type ProxiedQueryResult = Omit<QueryResult, 'rows'> & {
|
|
3
|
+
rows?: {
|
|
4
|
+
_array: any[];
|
|
5
|
+
length: number;
|
|
6
|
+
};
|
|
7
|
+
};
|
|
8
|
+
export interface AsyncDatabaseOpener {
|
|
9
|
+
open(path: string, isWriter: boolean): Promise<AsyncDatabase>;
|
|
10
|
+
}
|
|
11
|
+
export interface AsyncDatabase {
|
|
12
|
+
execute: (query: string, params: any[]) => Promise<ProxiedQueryResult>;
|
|
13
|
+
executeBatch: (query: string, params: any[][]) => Promise<ProxiedQueryResult>;
|
|
14
|
+
close: () => Promise<void>;
|
|
15
|
+
collectCommittedUpdates: () => Promise<string[]>;
|
|
16
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { BaseObserver, DBAdapter, DBAdapterListener, LockContext, Transaction, DBLockOptions, QueryResult, SQLOpenOptions } from '@powersync/common';
|
|
2
|
+
export type BetterSQLite3LockContext = LockContext & {
|
|
3
|
+
executeBatch(query: string, params?: any[][]): Promise<QueryResult>;
|
|
4
|
+
};
|
|
5
|
+
export type BetterSQLite3Transaction = Transaction & BetterSQLite3LockContext;
|
|
6
|
+
/**
|
|
7
|
+
* Adapter for better-sqlite3
|
|
8
|
+
*/
|
|
9
|
+
export declare class BetterSQLite3DBAdapter extends BaseObserver<DBAdapterListener> implements DBAdapter {
|
|
10
|
+
private readonly options;
|
|
11
|
+
readonly name: string;
|
|
12
|
+
private readConnections;
|
|
13
|
+
private writeConnection;
|
|
14
|
+
private readonly readQueue;
|
|
15
|
+
private readonly writeQueue;
|
|
16
|
+
constructor(options: SQLOpenOptions);
|
|
17
|
+
initialize(): Promise<void>;
|
|
18
|
+
close(): Promise<void>;
|
|
19
|
+
readLock<T>(fn: (tx: BetterSQLite3LockContext) => Promise<T>, _options?: DBLockOptions | undefined): Promise<T>;
|
|
20
|
+
writeLock<T>(fn: (tx: BetterSQLite3LockContext) => Promise<T>, _options?: DBLockOptions | undefined): Promise<T>;
|
|
21
|
+
readTransaction<T>(fn: (tx: BetterSQLite3Transaction) => Promise<T>, _options?: DBLockOptions | undefined): Promise<T>;
|
|
22
|
+
writeTransaction<T>(fn: (tx: BetterSQLite3Transaction) => Promise<T>, _options?: DBLockOptions | undefined): Promise<T>;
|
|
23
|
+
private internalTransaction;
|
|
24
|
+
getAll<T>(sql: string, parameters?: any[]): Promise<T[]>;
|
|
25
|
+
getOptional<T>(sql: string, parameters?: any[]): Promise<T | null>;
|
|
26
|
+
get<T>(sql: string, parameters?: any[]): Promise<T>;
|
|
27
|
+
execute(query: string, params?: any[] | undefined): Promise<QueryResult>;
|
|
28
|
+
executeBatch(query: string, params?: any[][]): Promise<QueryResult>;
|
|
29
|
+
refreshSchema(): Promise<void>;
|
|
30
|
+
}
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
import * as path from 'node:path';
|
|
2
|
+
import { Worker } from 'node:worker_threads';
|
|
3
|
+
import * as Comlink from 'comlink';
|
|
4
|
+
import { BaseObserver } from '@powersync/common';
|
|
5
|
+
import { AsyncResource } from 'node:async_hooks';
|
|
6
|
+
import { RemoteConnection } from './RemoteConnection.js';
|
|
7
|
+
const READ_CONNECTIONS = 5;
|
|
8
|
+
/**
|
|
9
|
+
* Adapter for better-sqlite3
|
|
10
|
+
*/
|
|
11
|
+
export class BetterSQLite3DBAdapter extends BaseObserver {
|
|
12
|
+
options;
|
|
13
|
+
name;
|
|
14
|
+
readConnections;
|
|
15
|
+
writeConnection;
|
|
16
|
+
readQueue = [];
|
|
17
|
+
writeQueue = [];
|
|
18
|
+
constructor(options) {
|
|
19
|
+
super();
|
|
20
|
+
this.options = options;
|
|
21
|
+
this.name = options.dbFilename;
|
|
22
|
+
}
|
|
23
|
+
async initialize() {
|
|
24
|
+
let dbFilePath = this.options.dbFilename;
|
|
25
|
+
if (this.options.dbLocation !== undefined) {
|
|
26
|
+
dbFilePath = path.join(this.options.dbLocation, dbFilePath);
|
|
27
|
+
}
|
|
28
|
+
const openWorker = async (isWriter) => {
|
|
29
|
+
const worker = new Worker(new URL('./SqliteWorker.js', import.meta.url), { name: isWriter ? `write ${dbFilePath}` : `read ${dbFilePath}` });
|
|
30
|
+
const listeners = new WeakMap();
|
|
31
|
+
const comlink = Comlink.wrap({
|
|
32
|
+
postMessage: worker.postMessage.bind(worker),
|
|
33
|
+
addEventListener: (type, listener) => {
|
|
34
|
+
let resolved = 'handleEvent' in listener ? listener.handleEvent.bind(listener) : listener;
|
|
35
|
+
// Comlink wants message events, but the message event on workers in Node returns the data only.
|
|
36
|
+
if (type === 'message') {
|
|
37
|
+
const original = resolved;
|
|
38
|
+
resolved = (data) => {
|
|
39
|
+
original({ data });
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
listeners.set(listener, resolved);
|
|
43
|
+
worker.addListener(type, resolved);
|
|
44
|
+
},
|
|
45
|
+
removeEventListener: (type, listener) => {
|
|
46
|
+
const resolved = listeners.get(listener);
|
|
47
|
+
if (!resolved) {
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
worker.removeListener(type, resolved);
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
worker.once('error', (e) => {
|
|
54
|
+
console.error('Unexpected PowerSync database worker error', e);
|
|
55
|
+
});
|
|
56
|
+
const database = (await comlink.open(dbFilePath, isWriter));
|
|
57
|
+
return new RemoteConnection(worker, comlink, database);
|
|
58
|
+
};
|
|
59
|
+
// Open the writer first to avoid multiple threads enabling WAL concurrently (causing "database is locked" errors).
|
|
60
|
+
this.writeConnection = await openWorker(true);
|
|
61
|
+
const createWorkers = [];
|
|
62
|
+
for (let i = 0; i < READ_CONNECTIONS; i++) {
|
|
63
|
+
createWorkers.push(openWorker(false));
|
|
64
|
+
}
|
|
65
|
+
this.readConnections = await Promise.all(createWorkers);
|
|
66
|
+
}
|
|
67
|
+
async close() {
|
|
68
|
+
await this.writeConnection.close();
|
|
69
|
+
for (const connection of this.readConnections) {
|
|
70
|
+
await connection.close();
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
readLock(fn, _options) {
|
|
74
|
+
let resolveConnectionPromise;
|
|
75
|
+
const connectionPromise = new Promise((resolve, _reject) => {
|
|
76
|
+
resolveConnectionPromise = AsyncResource.bind(resolve);
|
|
77
|
+
});
|
|
78
|
+
const connection = this.readConnections.find((connection) => !connection.isBusy);
|
|
79
|
+
if (connection) {
|
|
80
|
+
connection.isBusy = true;
|
|
81
|
+
resolveConnectionPromise(connection);
|
|
82
|
+
}
|
|
83
|
+
else {
|
|
84
|
+
this.readQueue.push(resolveConnectionPromise);
|
|
85
|
+
}
|
|
86
|
+
return (async () => {
|
|
87
|
+
const connection = await connectionPromise;
|
|
88
|
+
try {
|
|
89
|
+
return await fn(connection);
|
|
90
|
+
}
|
|
91
|
+
finally {
|
|
92
|
+
const next = this.readQueue.shift();
|
|
93
|
+
if (next) {
|
|
94
|
+
next(connection);
|
|
95
|
+
}
|
|
96
|
+
else {
|
|
97
|
+
connection.isBusy = false;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
})();
|
|
101
|
+
}
|
|
102
|
+
writeLock(fn, _options) {
|
|
103
|
+
let resolveLockPromise;
|
|
104
|
+
const lockPromise = new Promise((resolve, _reject) => {
|
|
105
|
+
resolveLockPromise = AsyncResource.bind(resolve);
|
|
106
|
+
});
|
|
107
|
+
if (!this.writeConnection.isBusy) {
|
|
108
|
+
this.writeConnection.isBusy = true;
|
|
109
|
+
resolveLockPromise();
|
|
110
|
+
}
|
|
111
|
+
else {
|
|
112
|
+
this.writeQueue.push(resolveLockPromise);
|
|
113
|
+
}
|
|
114
|
+
return (async () => {
|
|
115
|
+
await lockPromise;
|
|
116
|
+
try {
|
|
117
|
+
try {
|
|
118
|
+
return await fn(this.writeConnection);
|
|
119
|
+
}
|
|
120
|
+
finally {
|
|
121
|
+
const updates = await this.writeConnection.database.collectCommittedUpdates();
|
|
122
|
+
if (updates.length > 0) {
|
|
123
|
+
const event = {
|
|
124
|
+
tables: updates,
|
|
125
|
+
groupedUpdates: {},
|
|
126
|
+
rawUpdates: []
|
|
127
|
+
};
|
|
128
|
+
this.iterateListeners((cb) => cb.tablesUpdated?.(event));
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
finally {
|
|
133
|
+
const next = this.writeQueue.shift();
|
|
134
|
+
if (next) {
|
|
135
|
+
next();
|
|
136
|
+
}
|
|
137
|
+
else {
|
|
138
|
+
this.writeConnection.isBusy = false;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
})();
|
|
142
|
+
}
|
|
143
|
+
readTransaction(fn, _options) {
|
|
144
|
+
return this.readLock((ctx) => this.internalTransaction(ctx, fn));
|
|
145
|
+
}
|
|
146
|
+
writeTransaction(fn, _options) {
|
|
147
|
+
return this.writeLock((ctx) => this.internalTransaction(ctx, fn));
|
|
148
|
+
}
|
|
149
|
+
async internalTransaction(connection, fn) {
|
|
150
|
+
let finalized = false;
|
|
151
|
+
const commit = async () => {
|
|
152
|
+
if (!finalized) {
|
|
153
|
+
finalized = true;
|
|
154
|
+
await connection.execute('COMMIT');
|
|
155
|
+
}
|
|
156
|
+
return { rowsAffected: 0 };
|
|
157
|
+
};
|
|
158
|
+
const rollback = async () => {
|
|
159
|
+
if (!finalized) {
|
|
160
|
+
finalized = true;
|
|
161
|
+
await connection.execute('ROLLBACK');
|
|
162
|
+
}
|
|
163
|
+
return { rowsAffected: 0 };
|
|
164
|
+
};
|
|
165
|
+
try {
|
|
166
|
+
await connection.execute('BEGIN');
|
|
167
|
+
const result = await fn({
|
|
168
|
+
execute: (query, params) => connection.execute(query, params),
|
|
169
|
+
executeBatch: (query, params) => connection.executeBatch(query, params),
|
|
170
|
+
get: (query, params) => connection.get(query, params),
|
|
171
|
+
getAll: (query, params) => connection.getAll(query, params),
|
|
172
|
+
getOptional: (query, params) => connection.getOptional(query, params),
|
|
173
|
+
commit,
|
|
174
|
+
rollback
|
|
175
|
+
});
|
|
176
|
+
await commit();
|
|
177
|
+
return result;
|
|
178
|
+
}
|
|
179
|
+
catch (ex) {
|
|
180
|
+
try {
|
|
181
|
+
await rollback();
|
|
182
|
+
}
|
|
183
|
+
catch (ex2) {
|
|
184
|
+
// In rare cases, a rollback may fail.
|
|
185
|
+
// Safe to ignore.
|
|
186
|
+
}
|
|
187
|
+
throw ex;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
getAll(sql, parameters) {
|
|
191
|
+
return this.readLock((ctx) => ctx.getAll(sql, parameters));
|
|
192
|
+
}
|
|
193
|
+
getOptional(sql, parameters) {
|
|
194
|
+
return this.readLock((ctx) => ctx.getOptional(sql, parameters));
|
|
195
|
+
}
|
|
196
|
+
get(sql, parameters) {
|
|
197
|
+
return this.readLock((ctx) => ctx.get(sql, parameters));
|
|
198
|
+
}
|
|
199
|
+
execute(query, params) {
|
|
200
|
+
return this.writeLock((ctx) => ctx.execute(query, params));
|
|
201
|
+
}
|
|
202
|
+
executeBatch(query, params) {
|
|
203
|
+
return this.writeTransaction((ctx) => ctx.executeBatch(query, params));
|
|
204
|
+
}
|
|
205
|
+
async refreshSchema() {
|
|
206
|
+
await this.writeConnection.refreshSchema();
|
|
207
|
+
for (const readConnection of this.readConnections) {
|
|
208
|
+
await readConnection.refreshSchema();
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { AbstractPowerSyncDatabase, AbstractStreamingSyncImplementation, BucketStorageAdapter, DBAdapter, PowerSyncBackendConnector, PowerSyncDatabaseOptionsWithSettings } from '@powersync/common';
|
|
2
|
+
/**
|
|
3
|
+
* A PowerSync database which provides SQLite functionality
|
|
4
|
+
* which is automatically synced.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* ```typescript
|
|
8
|
+
* export const db = new PowerSyncDatabase({
|
|
9
|
+
* schema: AppSchema,
|
|
10
|
+
* database: {
|
|
11
|
+
* dbFilename: 'example.db'
|
|
12
|
+
* }
|
|
13
|
+
* });
|
|
14
|
+
* ```
|
|
15
|
+
*/
|
|
16
|
+
export declare class PowerSyncDatabase extends AbstractPowerSyncDatabase {
|
|
17
|
+
_initialize(): Promise<void>;
|
|
18
|
+
/**
|
|
19
|
+
* Opens a DBAdapter using better-sqlite3 as the default SQLite open factory.
|
|
20
|
+
*/
|
|
21
|
+
protected openDBAdapter(options: PowerSyncDatabaseOptionsWithSettings): DBAdapter;
|
|
22
|
+
protected generateBucketStorageAdapter(): BucketStorageAdapter;
|
|
23
|
+
protected generateSyncStreamImplementation(connector: PowerSyncBackendConnector): AbstractStreamingSyncImplementation;
|
|
24
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { AbstractPowerSyncDatabase, SqliteBucketStorage } from '@powersync/common';
|
|
2
|
+
import { NodeRemote } from '../sync/stream/NodeRemote.js';
|
|
3
|
+
import { NodeStreamingSyncImplementation } from '../sync/stream/NodeStreamingSyncImplementation.js';
|
|
4
|
+
import { BetterSQLite3DBAdapter } from './BetterSQLite3DBAdapter.js';
|
|
5
|
+
/**
|
|
6
|
+
* A PowerSync database which provides SQLite functionality
|
|
7
|
+
* which is automatically synced.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```typescript
|
|
11
|
+
* export const db = new PowerSyncDatabase({
|
|
12
|
+
* schema: AppSchema,
|
|
13
|
+
* database: {
|
|
14
|
+
* dbFilename: 'example.db'
|
|
15
|
+
* }
|
|
16
|
+
* });
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
export class PowerSyncDatabase extends AbstractPowerSyncDatabase {
|
|
20
|
+
async _initialize() {
|
|
21
|
+
await this.database.initialize();
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Opens a DBAdapter using better-sqlite3 as the default SQLite open factory.
|
|
25
|
+
*/
|
|
26
|
+
openDBAdapter(options) {
|
|
27
|
+
return new BetterSQLite3DBAdapter(options.database);
|
|
28
|
+
}
|
|
29
|
+
generateBucketStorageAdapter() {
|
|
30
|
+
return new SqliteBucketStorage(this.database, AbstractPowerSyncDatabase.transactionMutex);
|
|
31
|
+
}
|
|
32
|
+
generateSyncStreamImplementation(connector) {
|
|
33
|
+
const remote = new NodeRemote(connector);
|
|
34
|
+
return new NodeStreamingSyncImplementation({
|
|
35
|
+
adapter: this.bucketStorageAdapter,
|
|
36
|
+
remote,
|
|
37
|
+
uploadCrud: async () => {
|
|
38
|
+
await this.waitForReady();
|
|
39
|
+
await connector.uploadData(this);
|
|
40
|
+
},
|
|
41
|
+
retryDelayMs: this.options.retryDelayMs,
|
|
42
|
+
crudUploadThrottleMs: this.options.crudUploadThrottleMs,
|
|
43
|
+
identifier: this.database.name
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { Worker } from 'node:worker_threads';
|
|
2
|
+
import { LockContext, QueryResult } from '@powersync/common';
|
|
3
|
+
import { Remote } from 'comlink';
|
|
4
|
+
import { AsyncDatabase, AsyncDatabaseOpener, ProxiedQueryResult } from './AsyncDatabase.js';
|
|
5
|
+
/**
|
|
6
|
+
* A PowerSync database connection implemented with RPC calls to a background worker.
|
|
7
|
+
*/
|
|
8
|
+
export declare class RemoteConnection implements LockContext {
|
|
9
|
+
isBusy: boolean;
|
|
10
|
+
private readonly worker;
|
|
11
|
+
private readonly comlink;
|
|
12
|
+
readonly database: Remote<AsyncDatabase>;
|
|
13
|
+
constructor(worker: Worker, comlink: Remote<AsyncDatabaseOpener>, database: Remote<AsyncDatabase>);
|
|
14
|
+
executeBatch(query: string, params?: any[][]): Promise<QueryResult>;
|
|
15
|
+
execute(query: string, params?: any[] | undefined): Promise<QueryResult>;
|
|
16
|
+
getAll<T>(sql: string, parameters?: any[]): Promise<T[]>;
|
|
17
|
+
getOptional<T>(sql: string, parameters?: any[]): Promise<T | null>;
|
|
18
|
+
get<T>(sql: string, parameters?: any[]): Promise<T>;
|
|
19
|
+
refreshSchema(): Promise<void>;
|
|
20
|
+
close(): Promise<void>;
|
|
21
|
+
static wrapQueryResult(result: ProxiedQueryResult): QueryResult;
|
|
22
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { releaseProxy } from 'comlink';
|
|
2
|
+
/**
|
|
3
|
+
* A PowerSync database connection implemented with RPC calls to a background worker.
|
|
4
|
+
*/
|
|
5
|
+
export class RemoteConnection {
|
|
6
|
+
isBusy = false;
|
|
7
|
+
worker;
|
|
8
|
+
comlink;
|
|
9
|
+
database;
|
|
10
|
+
constructor(worker, comlink, database) {
|
|
11
|
+
this.worker = worker;
|
|
12
|
+
this.comlink = comlink;
|
|
13
|
+
this.database = database;
|
|
14
|
+
}
|
|
15
|
+
async executeBatch(query, params = []) {
|
|
16
|
+
const result = await this.database.executeBatch(query, params ?? []);
|
|
17
|
+
return RemoteConnection.wrapQueryResult(result);
|
|
18
|
+
}
|
|
19
|
+
async execute(query, params) {
|
|
20
|
+
const result = await this.database.execute(query, params ?? []);
|
|
21
|
+
return RemoteConnection.wrapQueryResult(result);
|
|
22
|
+
}
|
|
23
|
+
async getAll(sql, parameters) {
|
|
24
|
+
const res = await this.execute(sql, parameters);
|
|
25
|
+
return res.rows?._array ?? [];
|
|
26
|
+
}
|
|
27
|
+
async getOptional(sql, parameters) {
|
|
28
|
+
const res = await this.execute(sql, parameters);
|
|
29
|
+
return res.rows?.item(0) ?? null;
|
|
30
|
+
}
|
|
31
|
+
async get(sql, parameters) {
|
|
32
|
+
const res = await this.execute(sql, parameters);
|
|
33
|
+
const first = res.rows?.item(0);
|
|
34
|
+
if (!first) {
|
|
35
|
+
throw new Error('Result set is empty');
|
|
36
|
+
}
|
|
37
|
+
return first;
|
|
38
|
+
}
|
|
39
|
+
async refreshSchema() {
|
|
40
|
+
await this.execute("pragma table_info('sqlite_master')");
|
|
41
|
+
}
|
|
42
|
+
async close() {
|
|
43
|
+
await this.database.close();
|
|
44
|
+
this.database[releaseProxy]();
|
|
45
|
+
this.comlink[releaseProxy]();
|
|
46
|
+
await this.worker.terminate();
|
|
47
|
+
}
|
|
48
|
+
static wrapQueryResult(result) {
|
|
49
|
+
let rows = undefined;
|
|
50
|
+
if (result.rows) {
|
|
51
|
+
rows = {
|
|
52
|
+
...result.rows,
|
|
53
|
+
item: (idx) => result.rows?._array[idx]
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
return {
|
|
57
|
+
...result,
|
|
58
|
+
rows
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import BetterSQLite3Database from '@powersync/better-sqlite3';
|
|
2
|
+
import * as Comlink from 'comlink';
|
|
3
|
+
import { parentPort, threadId } from 'node:worker_threads';
|
|
4
|
+
import OS from 'node:os';
|
|
5
|
+
import url from 'node:url';
|
|
6
|
+
class BlockingAsyncDatabase {
|
|
7
|
+
db;
|
|
8
|
+
uncommittedUpdatedTables = new Set();
|
|
9
|
+
committedUpdatedTables = new Set();
|
|
10
|
+
constructor(db) {
|
|
11
|
+
this.db = db;
|
|
12
|
+
db.function('node_thread_id', () => threadId);
|
|
13
|
+
}
|
|
14
|
+
collectCommittedUpdates() {
|
|
15
|
+
const resolved = Promise.resolve([...this.committedUpdatedTables]);
|
|
16
|
+
this.committedUpdatedTables.clear();
|
|
17
|
+
return resolved;
|
|
18
|
+
}
|
|
19
|
+
installUpdateHooks() {
|
|
20
|
+
this.db.updateHook((_op, _dbName, tableName, _rowid) => {
|
|
21
|
+
this.uncommittedUpdatedTables.add(tableName);
|
|
22
|
+
});
|
|
23
|
+
this.db.commitHook(() => {
|
|
24
|
+
for (const tableName of this.uncommittedUpdatedTables) {
|
|
25
|
+
this.committedUpdatedTables.add(tableName);
|
|
26
|
+
}
|
|
27
|
+
this.uncommittedUpdatedTables.clear();
|
|
28
|
+
return true;
|
|
29
|
+
});
|
|
30
|
+
this.db.rollbackHook(() => {
|
|
31
|
+
this.uncommittedUpdatedTables.clear();
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
async close() {
|
|
35
|
+
this.db.close();
|
|
36
|
+
}
|
|
37
|
+
async execute(query, params) {
|
|
38
|
+
const stmt = this.db.prepare(query);
|
|
39
|
+
if (stmt.reader) {
|
|
40
|
+
const rows = stmt.all(params);
|
|
41
|
+
return {
|
|
42
|
+
rowsAffected: 0,
|
|
43
|
+
rows: {
|
|
44
|
+
_array: rows,
|
|
45
|
+
length: rows.length
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
else {
|
|
50
|
+
const info = stmt.run(params);
|
|
51
|
+
return {
|
|
52
|
+
rowsAffected: info.changes,
|
|
53
|
+
insertId: Number(info.lastInsertRowid)
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
async executeBatch(query, params) {
|
|
58
|
+
params = params ?? [];
|
|
59
|
+
let rowsAffected = 0;
|
|
60
|
+
const stmt = this.db.prepare(query);
|
|
61
|
+
for (const paramSet of params) {
|
|
62
|
+
const info = stmt.run(paramSet);
|
|
63
|
+
rowsAffected += info.changes;
|
|
64
|
+
}
|
|
65
|
+
return { rowsAffected };
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
class BetterSqliteWorker {
|
|
69
|
+
async open(path, isWriter) {
|
|
70
|
+
const baseDB = new BetterSQLite3Database(path);
|
|
71
|
+
baseDB.pragma('journal_mode = WAL');
|
|
72
|
+
loadExtension(baseDB);
|
|
73
|
+
if (!isWriter) {
|
|
74
|
+
baseDB.pragma('query_only = true');
|
|
75
|
+
}
|
|
76
|
+
const asyncDb = new BlockingAsyncDatabase(baseDB);
|
|
77
|
+
asyncDb.installUpdateHooks();
|
|
78
|
+
return Comlink.proxy(asyncDb);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
const loadExtension = (db) => {
|
|
82
|
+
const platform = OS.platform();
|
|
83
|
+
let extensionPath;
|
|
84
|
+
if (platform === 'win32') {
|
|
85
|
+
extensionPath = 'powersync.dll';
|
|
86
|
+
}
|
|
87
|
+
else if (platform === 'linux') {
|
|
88
|
+
extensionPath = 'libpowersync.so';
|
|
89
|
+
}
|
|
90
|
+
else if (platform === 'darwin') {
|
|
91
|
+
extensionPath = 'libpowersync.dylib';
|
|
92
|
+
}
|
|
93
|
+
else {
|
|
94
|
+
throw 'Unknown platform, PowerSync for Node.js currently supports Windows, Linux and macOS.';
|
|
95
|
+
}
|
|
96
|
+
const resolved = url.fileURLToPath(new URL(`../${extensionPath}`, import.meta.url));
|
|
97
|
+
db.loadExtension(resolved, 'sqlite3_powersync_init');
|
|
98
|
+
};
|
|
99
|
+
Comlink.expose(new BetterSqliteWorker(), parentPort);
|
package/lib/index.d.ts
ADDED
package/lib/index.js
ADDED
|
Binary file
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { ILogger } from 'js-logger';
|
|
2
|
+
import { AbstractRemote, AbstractRemoteOptions, BSONImplementation, RemoteConnector } from '@powersync/common';
|
|
3
|
+
export declare const STREAMING_POST_TIMEOUT_MS = 30000;
|
|
4
|
+
export declare class NodeRemote extends AbstractRemote {
|
|
5
|
+
protected connector: RemoteConnector;
|
|
6
|
+
protected logger: ILogger;
|
|
7
|
+
constructor(connector: RemoteConnector, logger?: ILogger, options?: Partial<AbstractRemoteOptions>);
|
|
8
|
+
getUserAgent(): string;
|
|
9
|
+
getBSON(): Promise<BSONImplementation>;
|
|
10
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import * as os from 'node:os';
|
|
2
|
+
import { AbstractRemote, DEFAULT_REMOTE_LOGGER, FetchImplementationProvider } from '@powersync/common';
|
|
3
|
+
import { BSON } from 'bson';
|
|
4
|
+
export const STREAMING_POST_TIMEOUT_MS = 30_000;
|
|
5
|
+
class NodeFetchProvider extends FetchImplementationProvider {
|
|
6
|
+
getFetch() {
|
|
7
|
+
return fetch.bind(globalThis);
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
export class NodeRemote extends AbstractRemote {
|
|
11
|
+
connector;
|
|
12
|
+
logger;
|
|
13
|
+
constructor(connector, logger = DEFAULT_REMOTE_LOGGER, options) {
|
|
14
|
+
super(connector, logger, {
|
|
15
|
+
...(options ?? {}),
|
|
16
|
+
fetchImplementation: options?.fetchImplementation ?? new NodeFetchProvider()
|
|
17
|
+
});
|
|
18
|
+
this.connector = connector;
|
|
19
|
+
this.logger = logger;
|
|
20
|
+
}
|
|
21
|
+
getUserAgent() {
|
|
22
|
+
return [
|
|
23
|
+
super.getUserAgent(),
|
|
24
|
+
`powersync-node`,
|
|
25
|
+
`node/${process.versions.node}`,
|
|
26
|
+
`${os.platform()}/${os.release()}`
|
|
27
|
+
].join(' ');
|
|
28
|
+
}
|
|
29
|
+
async getBSON() {
|
|
30
|
+
return BSON;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { AbstractStreamingSyncImplementation, AbstractStreamingSyncImplementationOptions, LockOptions } from '@powersync/common';
|
|
2
|
+
import Lock from 'async-lock';
|
|
3
|
+
export declare class NodeStreamingSyncImplementation extends AbstractStreamingSyncImplementation {
|
|
4
|
+
locks: Lock;
|
|
5
|
+
constructor(options: AbstractStreamingSyncImplementationOptions);
|
|
6
|
+
/**
|
|
7
|
+
* Configures global locks on sync process
|
|
8
|
+
*/
|
|
9
|
+
initLocks(): void;
|
|
10
|
+
obtainLock<T>(lockOptions: LockOptions<T>): Promise<T>;
|
|
11
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { AbstractStreamingSyncImplementation, LockType } from '@powersync/common';
|
|
2
|
+
import Lock from 'async-lock';
|
|
3
|
+
/**
|
|
4
|
+
* Global locks which prevent multiple instances from syncing
|
|
5
|
+
* concurrently.
|
|
6
|
+
*/
|
|
7
|
+
const LOCKS = new Map();
|
|
8
|
+
const lockTypes = new Set(Object.values(LockType));
|
|
9
|
+
export class NodeStreamingSyncImplementation extends AbstractStreamingSyncImplementation {
|
|
10
|
+
locks;
|
|
11
|
+
constructor(options) {
|
|
12
|
+
super(options);
|
|
13
|
+
this.initLocks();
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Configures global locks on sync process
|
|
17
|
+
*/
|
|
18
|
+
initLocks() {
|
|
19
|
+
const { identifier } = this.options;
|
|
20
|
+
if (identifier && LOCKS.has(identifier)) {
|
|
21
|
+
this.locks = LOCKS.get(identifier);
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
this.locks = new Lock();
|
|
25
|
+
if (identifier) {
|
|
26
|
+
LOCKS.set(identifier, this.locks);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
obtainLock(lockOptions) {
|
|
30
|
+
if (!lockTypes.has(lockOptions.type)) {
|
|
31
|
+
throw new Error(`Lock type ${lockOptions.type} not found`);
|
|
32
|
+
}
|
|
33
|
+
return this.locks.acquire(lockOptions.type, async () => {
|
|
34
|
+
if (lockOptions.signal?.aborted) {
|
|
35
|
+
throw new Error('Aborted');
|
|
36
|
+
}
|
|
37
|
+
return lockOptions.callback();
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@powersync/node",
|
|
3
|
+
"version": "0.0.0-dev-20250318143512",
|
|
4
|
+
"publishConfig": {
|
|
5
|
+
"registry": "https://registry.npmjs.org/",
|
|
6
|
+
"access": "public"
|
|
7
|
+
},
|
|
8
|
+
"description": "PowerSync Node.js SDK. Sync Postgres, MongoDB or MySQL with SQLite in your Node.js app",
|
|
9
|
+
"main": "./lib/index.js",
|
|
10
|
+
"module": "./lib/index.js",
|
|
11
|
+
"types": "./lib/index.d.ts",
|
|
12
|
+
"files": [
|
|
13
|
+
"lib",
|
|
14
|
+
"dist",
|
|
15
|
+
"download_core.js"
|
|
16
|
+
],
|
|
17
|
+
"type": "module",
|
|
18
|
+
"repository": {
|
|
19
|
+
"type": "git",
|
|
20
|
+
"url": "git+https://github.com/powersync-ja/powersync-js.git"
|
|
21
|
+
},
|
|
22
|
+
"author": "JOURNEYAPPS",
|
|
23
|
+
"license": "Apache-2.0",
|
|
24
|
+
"bugs": {
|
|
25
|
+
"url": "https://github.com/powersync-ja/powersync-js/issues"
|
|
26
|
+
},
|
|
27
|
+
"homepage": "https://docs.powersync.com/",
|
|
28
|
+
"peerDependencies": {
|
|
29
|
+
"@powersync/common": "^1.22.0",
|
|
30
|
+
"@powersync/better-sqlite3": "^0.1.0"
|
|
31
|
+
},
|
|
32
|
+
"dependencies": {
|
|
33
|
+
"async-lock": "^1.4.0",
|
|
34
|
+
"bson": "^6.6.0",
|
|
35
|
+
"comlink": "^4.4.2",
|
|
36
|
+
"@powersync/common": "1.25.0"
|
|
37
|
+
},
|
|
38
|
+
"devDependencies": {
|
|
39
|
+
"@types/async-lock": "^1.4.0",
|
|
40
|
+
"typescript": "^5.5.3",
|
|
41
|
+
"vitest": "^3.0.5"
|
|
42
|
+
},
|
|
43
|
+
"keywords": [
|
|
44
|
+
"data sync",
|
|
45
|
+
"offline-first",
|
|
46
|
+
"sqlite",
|
|
47
|
+
"real-time data stream",
|
|
48
|
+
"live data"
|
|
49
|
+
],
|
|
50
|
+
"scripts": {
|
|
51
|
+
"install": "node download_core.js",
|
|
52
|
+
"build": "tsc -b",
|
|
53
|
+
"build:prod": "tsc -b --sourceMap false",
|
|
54
|
+
"clean": "rm -rf lib dist tsconfig.tsbuildinfo dist",
|
|
55
|
+
"watch": "tsc -b -w",
|
|
56
|
+
"test": "vitest"
|
|
57
|
+
}
|
|
58
|
+
}
|