@powersync/shared-internals 0.0.0-tmp.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 (153) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +5 -0
  3. package/dist/bundle.cjs +11787 -0
  4. package/dist/bundle.cjs.map +1 -0
  5. package/dist/bundle.mjs +11757 -0
  6. package/dist/bundle.mjs.map +1 -0
  7. package/dist/bundle.node.cjs +9418 -0
  8. package/dist/bundle.node.cjs.map +1 -0
  9. package/dist/bundle.node.mjs +9388 -0
  10. package/dist/bundle.node.mjs.map +1 -0
  11. package/dist/index.d.cts +1159 -0
  12. package/dist/websockets.mjs +7558 -0
  13. package/dist/websockets.mjs.map +1 -0
  14. package/dist/websockets.node.mjs +5189 -0
  15. package/dist/websockets.node.mjs.map +1 -0
  16. package/legacy/sync_protocol.d.ts +103 -0
  17. package/lib/client/BasePowerSyncDatabase.d.ts +147 -0
  18. package/lib/client/BasePowerSyncDatabase.js +622 -0
  19. package/lib/client/BasePowerSyncDatabase.js.map +1 -0
  20. package/lib/client/ConnectionManager.d.ts +116 -0
  21. package/lib/client/ConnectionManager.js +306 -0
  22. package/lib/client/ConnectionManager.js.map +1 -0
  23. package/lib/client/CustomQuery.d.ts +21 -0
  24. package/lib/client/CustomQuery.js +43 -0
  25. package/lib/client/CustomQuery.js.map +1 -0
  26. package/lib/client/sync/bucket/BucketStorageAdapter.d.ts +42 -0
  27. package/lib/client/sync/bucket/BucketStorageAdapter.js +23 -0
  28. package/lib/client/sync/bucket/BucketStorageAdapter.js.map +1 -0
  29. package/lib/client/sync/bucket/CrudEntry.d.ts +46 -0
  30. package/lib/client/sync/bucket/CrudEntry.js +60 -0
  31. package/lib/client/sync/bucket/CrudEntry.js.map +1 -0
  32. package/lib/client/sync/bucket/SqliteBucketStorage.d.ts +33 -0
  33. package/lib/client/sync/bucket/SqliteBucketStorage.js +166 -0
  34. package/lib/client/sync/bucket/SqliteBucketStorage.js.map +1 -0
  35. package/lib/client/sync/options.d.ts +9 -0
  36. package/lib/client/sync/options.js +16 -0
  37. package/lib/client/sync/options.js.map +1 -0
  38. package/lib/client/sync/stream/AbstractRemote.d.ts +125 -0
  39. package/lib/client/sync/stream/AbstractRemote.js +265 -0
  40. package/lib/client/sync/stream/AbstractRemote.js.map +1 -0
  41. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +138 -0
  42. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +611 -0
  43. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js.map +1 -0
  44. package/lib/client/sync/stream/WebSocketSupport.d.ts +26 -0
  45. package/lib/client/sync/stream/WebSocketSupport.js +198 -0
  46. package/lib/client/sync/stream/WebSocketSupport.js.map +1 -0
  47. package/lib/client/sync/stream/WebsocketClientTransport.d.ts +15 -0
  48. package/lib/client/sync/stream/WebsocketClientTransport.js +62 -0
  49. package/lib/client/sync/stream/WebsocketClientTransport.js.map +1 -0
  50. package/lib/client/sync/stream/core-instruction.d.ts +75 -0
  51. package/lib/client/sync/stream/core-instruction.js +4 -0
  52. package/lib/client/sync/stream/core-instruction.js.map +1 -0
  53. package/lib/client/triggers/MemoryTriggerClaimManager.d.ts +6 -0
  54. package/lib/client/triggers/MemoryTriggerClaimManager.js +21 -0
  55. package/lib/client/triggers/MemoryTriggerClaimManager.js.map +1 -0
  56. package/lib/client/triggers/TriggerManagerImpl.d.ts +68 -0
  57. package/lib/client/triggers/TriggerManagerImpl.js +415 -0
  58. package/lib/client/triggers/TriggerManagerImpl.js.map +1 -0
  59. package/lib/client/watched/AbstractQueryProcessor.d.ts +68 -0
  60. package/lib/client/watched/AbstractQueryProcessor.js +155 -0
  61. package/lib/client/watched/AbstractQueryProcessor.js.map +1 -0
  62. package/lib/client/watched/DifferentialQueryProcessor.d.ts +50 -0
  63. package/lib/client/watched/DifferentialQueryProcessor.js +174 -0
  64. package/lib/client/watched/DifferentialQueryProcessor.js.map +1 -0
  65. package/lib/client/watched/OnChangeQueryProcessor.d.ts +22 -0
  66. package/lib/client/watched/OnChangeQueryProcessor.js +80 -0
  67. package/lib/client/watched/OnChangeQueryProcessor.js.map +1 -0
  68. package/lib/client/watched/WatchedQuery.d.ts +9 -0
  69. package/lib/client/watched/WatchedQuery.js +12 -0
  70. package/lib/client/watched/WatchedQuery.js.map +1 -0
  71. package/lib/constants.d.ts +5 -0
  72. package/lib/constants.js +6 -0
  73. package/lib/constants.js.map +1 -0
  74. package/lib/db/ConnectionClosedError.d.ts +12 -0
  75. package/lib/db/ConnectionClosedError.js +23 -0
  76. package/lib/db/ConnectionClosedError.js.map +1 -0
  77. package/lib/db/crud/SyncProgress.d.ts +10 -0
  78. package/lib/db/crud/SyncProgress.js +33 -0
  79. package/lib/db/crud/SyncProgress.js.map +1 -0
  80. package/lib/db/crud/SyncStatus.d.ts +48 -0
  81. package/lib/db/crud/SyncStatus.js +178 -0
  82. package/lib/db/crud/SyncStatus.js.map +1 -0
  83. package/lib/db/openDatabase.d.ts +7 -0
  84. package/lib/db/openDatabase.js +22 -0
  85. package/lib/db/openDatabase.js.map +1 -0
  86. package/lib/index.d.ts +22 -0
  87. package/lib/index.js +22 -0
  88. package/lib/index.js.map +1 -0
  89. package/lib/utils/AbortOperation.d.ts +11 -0
  90. package/lib/utils/AbortOperation.js +21 -0
  91. package/lib/utils/AbortOperation.js.map +1 -0
  92. package/lib/utils/ControlledExecutor.d.ts +31 -0
  93. package/lib/utils/ControlledExecutor.js +54 -0
  94. package/lib/utils/ControlledExecutor.js.map +1 -0
  95. package/lib/utils/MetaBaseObserver.d.ts +11 -0
  96. package/lib/utils/MetaBaseObserver.js +51 -0
  97. package/lib/utils/MetaBaseObserver.js.map +1 -0
  98. package/lib/utils/async.d.ts +46 -0
  99. package/lib/utils/async.js +147 -0
  100. package/lib/utils/async.js.map +1 -0
  101. package/lib/utils/compatibility.d.ts +8 -0
  102. package/lib/utils/compatibility.js +9 -0
  103. package/lib/utils/compatibility.js.map +1 -0
  104. package/lib/utils/mutex.d.ts +42 -0
  105. package/lib/utils/mutex.js +150 -0
  106. package/lib/utils/mutex.js.map +1 -0
  107. package/lib/utils/parseQuery.d.ts +12 -0
  108. package/lib/utils/parseQuery.js +20 -0
  109. package/lib/utils/parseQuery.js.map +1 -0
  110. package/lib/utils/queue.d.ts +16 -0
  111. package/lib/utils/queue.js +42 -0
  112. package/lib/utils/queue.js.map +1 -0
  113. package/lib/utils/stream_transform.d.ts +41 -0
  114. package/lib/utils/stream_transform.js +211 -0
  115. package/lib/utils/stream_transform.js.map +1 -0
  116. package/lib/version.d.ts +1 -0
  117. package/lib/version.js +4 -0
  118. package/lib/version.js.map +1 -0
  119. package/package.json +65 -0
  120. package/src/client/BasePowerSyncDatabase.ts +853 -0
  121. package/src/client/ConnectionManager.ts +419 -0
  122. package/src/client/CustomQuery.ts +60 -0
  123. package/src/client/sync/bucket/BucketStorageAdapter.ts +51 -0
  124. package/src/client/sync/bucket/CrudEntry.ts +116 -0
  125. package/src/client/sync/bucket/SqliteBucketStorage.ts +213 -0
  126. package/src/client/sync/options.ts +24 -0
  127. package/src/client/sync/stream/AbstractRemote.ts +369 -0
  128. package/src/client/sync/stream/AbstractStreamingSyncImplementation.ts +795 -0
  129. package/src/client/sync/stream/WebSocketSupport.ts +259 -0
  130. package/src/client/sync/stream/WebsocketClientTransport.ts +82 -0
  131. package/src/client/sync/stream/core-instruction.ts +78 -0
  132. package/src/client/triggers/MemoryTriggerClaimManager.ts +25 -0
  133. package/src/client/triggers/TriggerManagerImpl.ts +538 -0
  134. package/src/client/watched/AbstractQueryProcessor.ts +231 -0
  135. package/src/client/watched/DifferentialQueryProcessor.ts +226 -0
  136. package/src/client/watched/OnChangeQueryProcessor.ts +108 -0
  137. package/src/client/watched/WatchedQuery.ts +14 -0
  138. package/src/constants.ts +6 -0
  139. package/src/db/ConnectionClosedError.ts +25 -0
  140. package/src/db/crud/SyncProgress.ts +39 -0
  141. package/src/db/crud/SyncStatus.ts +234 -0
  142. package/src/db/openDatabase.ts +23 -0
  143. package/src/index.ts +24 -0
  144. package/src/utils/AbortOperation.ts +19 -0
  145. package/src/utils/ControlledExecutor.ts +78 -0
  146. package/src/utils/MetaBaseObserver.ts +65 -0
  147. package/src/utils/async.ts +185 -0
  148. package/src/utils/compatibility.ts +9 -0
  149. package/src/utils/mutex.ts +186 -0
  150. package/src/utils/parseQuery.ts +31 -0
  151. package/src/utils/queue.ts +48 -0
  152. package/src/utils/stream_transform.ts +260 -0
  153. package/src/version.ts +3 -0
@@ -0,0 +1,213 @@
1
+ import {
2
+ BaseObserver,
3
+ LogLevels,
4
+ PowerSyncLogger,
5
+ DBAdapter,
6
+ Transaction,
7
+ CrudEntry,
8
+ CrudBatch
9
+ } from '@powersync/common';
10
+
11
+ import {
12
+ BucketStorageAdapter,
13
+ BucketStorageListener,
14
+ PowerSyncControlCommand,
15
+ PSInternalTable
16
+ } from './BucketStorageAdapter.js';
17
+ import { CrudEntryImpl, CrudEntryJSON } from './CrudEntry.js';
18
+ import { MAX_OP_ID } from '../../../constants.js';
19
+
20
+ /**
21
+ * @internal
22
+ */
23
+ export class SqliteBucketStorage extends BaseObserver<BucketStorageListener> implements BucketStorageAdapter {
24
+ public tableNames: Set<string>;
25
+ private updateListener: () => void;
26
+ private _clientId?: Promise<string>;
27
+
28
+ constructor(
29
+ private db: DBAdapter,
30
+ private logger: PowerSyncLogger
31
+ ) {
32
+ super();
33
+ this.tableNames = new Set();
34
+ this.updateListener = db.registerListener({
35
+ tablesUpdated: ({ tables }) => {
36
+ if (tables.includes(PSInternalTable.CRUD)) {
37
+ this.iterateListeners((l) => l.crudUpdate?.());
38
+ }
39
+ }
40
+ });
41
+ }
42
+
43
+ async init() {
44
+ const existingTableRows = await this.db.getAll<{ name: string }>(
45
+ `SELECT name FROM sqlite_master WHERE type='table' AND name GLOB 'ps_data_*'`
46
+ );
47
+ for (const row of existingTableRows ?? []) {
48
+ this.tableNames.add(row.name);
49
+ }
50
+ }
51
+
52
+ async dispose() {
53
+ this.updateListener?.();
54
+ }
55
+
56
+ async _getClientId() {
57
+ const row = await this.db.get<{ client_id: string }>('SELECT powersync_client_id() as client_id');
58
+ return row['client_id'];
59
+ }
60
+
61
+ getClientId() {
62
+ if (this._clientId == null) {
63
+ this._clientId = this._getClientId();
64
+ }
65
+ return this._clientId!;
66
+ }
67
+
68
+ getMaxOpId() {
69
+ return MAX_OP_ID;
70
+ }
71
+
72
+ async updateLocalTarget(cb: () => Promise<string>): Promise<boolean> {
73
+ const rs1 = await this.db.getAll(
74
+ "SELECT target_op FROM ps_buckets WHERE name = '$local' AND target_op = CAST(? as INTEGER)",
75
+ [MAX_OP_ID]
76
+ );
77
+ if (!rs1.length) {
78
+ // Nothing to update
79
+ return false;
80
+ }
81
+ const rs = await this.db.getOptional<{ seq: number }>(
82
+ "SELECT seq FROM main.sqlite_sequence WHERE name = 'ps_crud'"
83
+ );
84
+ if (!rs) {
85
+ // Nothing to update
86
+ return false;
87
+ }
88
+
89
+ const seqBefore = rs.seq;
90
+
91
+ const opId = await cb();
92
+
93
+ return this.writeTransaction(async (tx) => {
94
+ const anyData = await tx.execute('SELECT 1 FROM ps_crud LIMIT 1');
95
+ if (anyData.rows?.length) {
96
+ // if isNotEmpty
97
+ this.logger.log({
98
+ level: LogLevels.debug,
99
+ message: `New data uploaded since write checkpoint ${opId} - need new write checkpoint`
100
+ });
101
+ return false;
102
+ }
103
+
104
+ const { seq: seqAfter } = await tx.get<{ seq: number }>(
105
+ "SELECT seq FROM main.sqlite_sequence WHERE name = 'ps_crud'"
106
+ );
107
+
108
+ if (seqAfter != seqBefore) {
109
+ this.logger.log({
110
+ level: LogLevels.debug,
111
+ message: `New data uploaded since write checpoint ${opId} - need new write checkpoint (sequence updated)`
112
+ });
113
+
114
+ // New crud data may have been uploaded since we got the checkpoint. Abort.
115
+ return false;
116
+ }
117
+
118
+ this.logger.log({
119
+ level: LogLevels.debug,
120
+ message: `Updating target write checkpoint to ${opId}`
121
+ });
122
+ await tx.execute("UPDATE ps_buckets SET target_op = CAST(? as INTEGER) WHERE name='$local'", [opId]);
123
+ return true;
124
+ });
125
+ }
126
+
127
+ async nextCrudItem(): Promise<CrudEntry | undefined> {
128
+ const next = await this.db.getOptional<CrudEntryJSON>('SELECT * FROM ps_crud ORDER BY id ASC LIMIT 1');
129
+ if (!next) {
130
+ return;
131
+ }
132
+ return CrudEntryImpl.fromRow(next);
133
+ }
134
+
135
+ async hasCrud(): Promise<boolean> {
136
+ const anyData = await this.db.getOptional('SELECT 1 FROM ps_crud LIMIT 1');
137
+ return !!anyData;
138
+ }
139
+
140
+ /**
141
+ * Get a batch of objects to send to the server.
142
+ * When the objects are successfully sent to the server, call .complete()
143
+ */
144
+ async getCrudBatch(limit: number = 100): Promise<CrudBatch | null> {
145
+ if (!(await this.hasCrud())) {
146
+ return null;
147
+ }
148
+
149
+ const crudResult = await this.db.getAll<CrudEntryJSON>('SELECT * FROM ps_crud ORDER BY id ASC LIMIT ?', [limit]);
150
+
151
+ const all: CrudEntry[] = [];
152
+ for (const row of crudResult) {
153
+ all.push(CrudEntryImpl.fromRow(row));
154
+ }
155
+
156
+ if (all.length === 0) {
157
+ return null;
158
+ }
159
+
160
+ const last = all[all.length - 1];
161
+ return {
162
+ crud: all,
163
+ haveMore: true,
164
+ complete: async (writeCheckpoint?: string) => {
165
+ return this.writeTransaction(async (tx) => {
166
+ await tx.execute('DELETE FROM ps_crud WHERE id <= ?', [last.clientId]);
167
+ if (writeCheckpoint) {
168
+ const crudResult = await tx.execute('SELECT 1 FROM ps_crud LIMIT 1');
169
+ if (crudResult.rows?.length) {
170
+ await tx.execute("UPDATE ps_buckets SET target_op = CAST(? as INTEGER) WHERE name='$local'", [
171
+ writeCheckpoint
172
+ ]);
173
+ }
174
+ } else {
175
+ await tx.execute("UPDATE ps_buckets SET target_op = CAST(? as INTEGER) WHERE name='$local'", [
176
+ this.getMaxOpId()
177
+ ]);
178
+ }
179
+ });
180
+ }
181
+ };
182
+ }
183
+
184
+ async writeTransaction<T>(callback: (tx: Transaction) => Promise<T>, options?: { timeoutMs: number }): Promise<T> {
185
+ return this.db.writeTransaction(callback, options);
186
+ }
187
+
188
+ async control(op: PowerSyncControlCommand, payload: string | Uint8Array | ArrayBuffer | null): Promise<string> {
189
+ return await this.writeTransaction(async (tx) => {
190
+ const { rawRows } = await tx.executeRaw('SELECT powersync_control(?, ?)', [op, payload]);
191
+ return rawRows[0][0] as string;
192
+ });
193
+ }
194
+
195
+ async hasMigratedSubkeys(): Promise<boolean> {
196
+ const { r } = await this.db.get<{ r: number }>('SELECT EXISTS(SELECT * FROM ps_kv WHERE key = ?) as r', [
197
+ SqliteBucketStorage._subkeyMigrationKey
198
+ ]);
199
+ return r != 0;
200
+ }
201
+
202
+ async migrateToFixedSubkeys(): Promise<void> {
203
+ await this.writeTransaction(async (tx) => {
204
+ await tx.execute('UPDATE ps_oplog SET key = powersync_remove_duplicate_key_encoding(key);');
205
+ await tx.execute('INSERT OR REPLACE INTO ps_kv (key, value) VALUES (?, ?);', [
206
+ SqliteBucketStorage._subkeyMigrationKey,
207
+ '1'
208
+ ]);
209
+ });
210
+ }
211
+
212
+ static _subkeyMigrationKey = 'powersync_js_migrated_subkeys';
213
+ }
@@ -0,0 +1,24 @@
1
+ import { FetchStrategy, SyncOptions, SyncStreamConnectionMethod } from '@powersync/common';
2
+
3
+ /**
4
+ * @internal
5
+ */
6
+ export type ResolvedSyncOptions = Required<SyncOptions>;
7
+
8
+ /**
9
+ * @internal
10
+ */
11
+ export function resolveSyncOptions(
12
+ options: SyncOptions,
13
+ defaultConnectionMethod: SyncStreamConnectionMethod
14
+ ): ResolvedSyncOptions {
15
+ return {
16
+ appMetadata: options.appMetadata ?? {},
17
+ connectionMethod: options.connectionMethod ?? defaultConnectionMethod,
18
+ fetchStrategy: options.fetchStrategy ?? FetchStrategy.Buffered,
19
+ params: options.params ?? {},
20
+ includeDefaultStreams: options.includeDefaultStreams ?? true,
21
+ retryDelayMs: options.retryDelayMs ?? 5000,
22
+ crudUploadThrottleMs: options.crudUploadThrottleMs ?? 1000
23
+ };
24
+ }
@@ -0,0 +1,369 @@
1
+ import { type fetch } from 'cross-fetch';
2
+ import { FetchStrategy, PowerSyncCredentials, LogLevels, PowerSyncLogger } from '@powersync/common';
3
+
4
+ import { AbortOperation } from '../../../utils/AbortOperation.js';
5
+ import {
6
+ doneResult,
7
+ extractBsonObjects,
8
+ extractJsonLines,
9
+ SimpleAsyncIterator
10
+ } from '../../../utils/stream_transform.js';
11
+ import { WebSocketSupport, WebSocketSyncStreamPlatform } from './WebSocketSupport.js';
12
+ import { EventQueue } from '../../../utils/async.js';
13
+ import { POWERSYNC_JS_VERSION } from '../../../version.js';
14
+
15
+ /**
16
+ * @internal
17
+ */
18
+ export type RemoteConnector = {
19
+ fetchCredentials: () => Promise<PowerSyncCredentials | null>;
20
+ invalidateCredentials?: () => void;
21
+ };
22
+
23
+ const POWERSYNC_TRAILING_SLASH_MATCH = /\/+$/;
24
+
25
+ const webSocketPlatform: WebSocketSyncStreamPlatform = {
26
+ LogLevels,
27
+ EventQueue,
28
+ AbortOperation
29
+ };
30
+
31
+ /**
32
+ * @internal
33
+ */
34
+ export type SyncStreamOptions = {
35
+ path: string;
36
+ data: unknown;
37
+ abortSignal: AbortSignal;
38
+ };
39
+
40
+ /**
41
+ * @internal
42
+ */
43
+ export type FetchImplementation = typeof fetch;
44
+
45
+ export function lazyFetchImplementation(getFetch: () => FetchImplementation): FetchImplementation {
46
+ let resolved: FetchImplementation;
47
+
48
+ return (request) => {
49
+ const fetch = (resolved ??= getFetch());
50
+ return fetch(request);
51
+ };
52
+ }
53
+
54
+ export interface FetchOptions {
55
+ resource: string;
56
+ request: RequestInit;
57
+ expectStreamingResponse: boolean;
58
+ }
59
+
60
+ /**
61
+ * @internal
62
+ */
63
+ export interface SocketSyncStreamOptions {
64
+ path: string;
65
+ fetchStrategy: FetchStrategy;
66
+ abortSignal: AbortSignal;
67
+ data: unknown;
68
+ }
69
+
70
+ export interface PreparedRequest {
71
+ url: string;
72
+ headers: Record<string, string>;
73
+ userAgent: string;
74
+ path: string;
75
+ }
76
+
77
+ /**
78
+ * @internal
79
+ */
80
+ export abstract class AbstractRemote {
81
+ protected credentials: PowerSyncCredentials | null = null;
82
+
83
+ constructor(
84
+ protected connector: RemoteConnector,
85
+ readonly logger: PowerSyncLogger
86
+ ) {}
87
+
88
+ /**
89
+ * Sends a request using a suitable `fetch` implementation for the current platform.
90
+ */
91
+ protected abstract fetch(options: FetchOptions): Promise<Response>;
92
+
93
+ /**
94
+ * Get credentials currently cached, or fetch new credentials if none are
95
+ * available.
96
+ *
97
+ * These credentials may have expired already.
98
+ */
99
+ async getCredentials(): Promise<PowerSyncCredentials | null> {
100
+ if (this.credentials) {
101
+ return this.credentials;
102
+ }
103
+
104
+ return this.prefetchCredentials();
105
+ }
106
+
107
+ /**
108
+ * Fetch a new set of credentials and cache it.
109
+ *
110
+ * Until this call succeeds, `getCredentials` will still return the
111
+ * old credentials.
112
+ *
113
+ * This may be called before the current credentials have expired.
114
+ */
115
+ async prefetchCredentials() {
116
+ this.credentials = await this.fetchCredentials();
117
+
118
+ return this.credentials;
119
+ }
120
+
121
+ /**
122
+ * Get credentials for PowerSync.
123
+ *
124
+ * This should always fetch a fresh set of credentials - don't use cached
125
+ * values.
126
+ */
127
+ async fetchCredentials() {
128
+ const credentials = await this.connector.fetchCredentials();
129
+ if (credentials?.endpoint.match(POWERSYNC_TRAILING_SLASH_MATCH)) {
130
+ throw new Error(
131
+ `A trailing forward slash "/" was found in the fetchCredentials endpoint: "${credentials.endpoint}". Remove the trailing forward slash "/" to fix this error.`
132
+ );
133
+ }
134
+
135
+ return credentials;
136
+ }
137
+
138
+ /***
139
+ * Immediately invalidate credentials.
140
+ *
141
+ * This may be called when the current credentials have expired.
142
+ */
143
+ invalidateCredentials() {
144
+ this.credentials = null;
145
+ this.connector.invalidateCredentials?.();
146
+ }
147
+
148
+ getUserAgent() {
149
+ return `powersync-js/${POWERSYNC_JS_VERSION}`;
150
+ }
151
+
152
+ protected async buildRequest(path: string): Promise<PreparedRequest> {
153
+ const credentials = await this.getCredentials();
154
+ if (credentials != null && (credentials.endpoint == null || credentials.endpoint == '')) {
155
+ throw new Error('PowerSync endpoint not configured');
156
+ } else if (credentials?.token == null || credentials?.token == '') {
157
+ const error: any = new Error(`Not signed in`);
158
+ error.status = 401;
159
+ throw error;
160
+ }
161
+
162
+ const userAgent = this.getUserAgent();
163
+
164
+ return {
165
+ url: credentials.endpoint + path,
166
+ headers: {
167
+ 'content-type': 'application/json',
168
+ Authorization: `Token ${credentials.token}`,
169
+ 'x-user-agent': userAgent
170
+ },
171
+ userAgent,
172
+ path
173
+ };
174
+ }
175
+
176
+ async get(path: string, headers?: Record<string, string>): Promise<any> {
177
+ const request = await this.buildRequest(path);
178
+ const res = await this.fetch({
179
+ resource: request.url,
180
+ request: {
181
+ method: 'GET',
182
+ headers: {
183
+ ...headers,
184
+ ...request.headers
185
+ }
186
+ },
187
+ expectStreamingResponse: false
188
+ });
189
+
190
+ if (res.status === 401) {
191
+ this.invalidateCredentials();
192
+ }
193
+
194
+ if (!res.ok) {
195
+ throw new Error(`Received ${res.status} - ${res.statusText} when getting from ${path}: ${await res.text()}}`);
196
+ }
197
+
198
+ return res.json();
199
+ }
200
+
201
+ /**
202
+ * @returns A text decoder decoding UTF-8. This is a method to allow patching it for Hermes which doesn't support the
203
+ * builtin, without forcing us to bundle a polyfill with `@powersync/common`.
204
+ */
205
+ createTextDecoder(): TextDecoder {
206
+ return new TextDecoder();
207
+ }
208
+
209
+ createSocket(url: string): WebSocket {
210
+ return new WebSocket(url);
211
+ }
212
+
213
+ /**
214
+ * Loads `@powersync/shared-internals/websockets`.
215
+ *
216
+ * We prefer to load that as a lazy module with a dynamic `import()` expressions on most platforms. An exception is
217
+ * React Native, where WebSocket support is preferred and we want to load this directly.
218
+ */
219
+ protected abstract loadWebSocketSupport(platform: WebSocketSyncStreamPlatform): Promise<WebSocketSupport>;
220
+
221
+ /**
222
+ * Returns a data stream of sync line data, fetched via RSocket-over-WebSocket.
223
+ *
224
+ * The only mechanism to abort the returned stream is to use the abort signal in {@link SocketSyncStreamOptions}.
225
+ */
226
+ async socketStreamRaw(options: SocketSyncStreamOptions): Promise<SimpleAsyncIterator<Uint8Array>> {
227
+ const support = await this.loadWebSocketSupport(webSocketPlatform);
228
+
229
+ const request = await this.buildRequest(options.path);
230
+ request.url = request.url.replace(/^https?:\/\//, function (match) {
231
+ return match === 'https://' ? 'wss://' : 'ws://';
232
+ });
233
+ const { fetchStrategy = FetchStrategy.Buffered, abortSignal, data } = options;
234
+
235
+ return await support.webSocketSyncStream({
236
+ remote: this,
237
+ buffered: fetchStrategy == FetchStrategy.Buffered,
238
+ abortSignal,
239
+ requestPayload: data,
240
+ request
241
+ });
242
+ }
243
+
244
+ /**
245
+ * Posts a `/sync/stream` request, asserts that it completes successfully and returns the streaming response as an
246
+ * async iterator of byte blobs.
247
+ *
248
+ * To cancel the async iterator, use the abort signal from {@link SyncStreamOptions} passed to this method.
249
+ */
250
+ protected async fetchStreamRaw(
251
+ options: SyncStreamOptions
252
+ ): Promise<{ isBson: boolean; stream: SimpleAsyncIterator<Uint8Array> }> {
253
+ const { data, path, abortSignal } = options;
254
+ const request = await this.buildRequest(path);
255
+
256
+ /**
257
+ * This abort controller will abort pending fetch requests.
258
+ * If the request has resolved, it will be used to close the readable stream.
259
+ * Which will cancel the network request.
260
+ *
261
+ * This nested controller is required since:
262
+ * Aborting the active fetch request while it is being consumed seems to throw
263
+ * an unhandled exception on the window level.
264
+ */
265
+ if (abortSignal.aborted) {
266
+ throw new AbortOperation('Abort request received before making fetchStreamRaw request');
267
+ }
268
+
269
+ const controller = new AbortController();
270
+ let reader: ReadableStreamDefaultReader<Uint8Array> | null = null;
271
+ abortSignal.addEventListener('abort', () => {
272
+ const reason =
273
+ abortSignal.reason ??
274
+ new AbortOperation('Cancelling network request before it resolves. Abort signal has been received.');
275
+
276
+ if (reader == null) {
277
+ // Only abort via the abort controller if the request has not resolved yet
278
+ controller.abort(reason);
279
+ } else {
280
+ reader.cancel(reason).catch(() => {
281
+ // Cancelling the reader might rethrow an exception we would have handled by throwing in next(). So we can
282
+ // ignore it here.
283
+ });
284
+ }
285
+ });
286
+
287
+ let res: Response;
288
+ let responseIsBson = false;
289
+ try {
290
+ const ndJson = 'application/x-ndjson';
291
+ const bson = 'application/vnd.powersync.bson-stream';
292
+
293
+ res = await this.fetch({
294
+ resource: request.url,
295
+ request: {
296
+ method: 'POST',
297
+ headers: {
298
+ ...request.headers,
299
+ accept: `${bson};q=0.9,${ndJson};q=0.8`
300
+ },
301
+ body: JSON.stringify(data),
302
+ signal: controller.signal,
303
+ cache: 'no-store'
304
+ },
305
+ expectStreamingResponse: true
306
+ });
307
+
308
+ if (!res.ok || !res.body) {
309
+ const text = await res.text();
310
+ const error: any = new Error(`HTTP ${res.statusText}: ${text}`);
311
+ error.status = res.status;
312
+
313
+ this.logger.log({
314
+ level: LogLevels.error,
315
+ message: `Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`,
316
+ error
317
+ });
318
+ throw error;
319
+ }
320
+
321
+ const contentType = res.headers.get('content-type');
322
+ responseIsBson = contentType == bson;
323
+ } catch (ex: any) {
324
+ if (ex.name == 'AbortError') {
325
+ throw new AbortOperation(`Pending fetch request to ${request.url} has been aborted.`);
326
+ }
327
+ throw ex;
328
+ }
329
+
330
+ reader = res.body.getReader();
331
+
332
+ const stream: SimpleAsyncIterator<Uint8Array> = {
333
+ next: async () => {
334
+ if (controller.signal.aborted) {
335
+ return doneResult;
336
+ }
337
+
338
+ try {
339
+ return await reader.read();
340
+ } catch (ex) {
341
+ if (controller.signal.aborted) {
342
+ // .read() completes with an error if we cancel the reader, which we do to disconnect. So this is just
343
+ // things working as intended, we can return a done event and consider the exception handled.
344
+ return doneResult;
345
+ }
346
+
347
+ throw ex;
348
+ }
349
+ }
350
+ };
351
+
352
+ return { isBson: responseIsBson, stream };
353
+ }
354
+
355
+ /**
356
+ * Posts a `/sync/stream` request.
357
+ *
358
+ * Depending on the `Content-Type` of the response, this returns strings for sync lines or encoded BSON documents as
359
+ * `Uint8Array`s.
360
+ */
361
+ async fetchStream(options: SyncStreamOptions): Promise<SimpleAsyncIterator<Uint8Array | string>> {
362
+ const { isBson, stream } = await this.fetchStreamRaw(options);
363
+ if (isBson) {
364
+ return extractBsonObjects(stream);
365
+ } else {
366
+ return extractJsonLines(stream, this.createTextDecoder());
367
+ }
368
+ }
369
+ }