@powersync/shared-internals 0.0.0-dev-20260917080037 → 0.0.0-dev-20261015114518
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/lib/client/BasePowerSyncDatabase.js +26 -17
- package/lib/client/BasePowerSyncDatabase.js.map +1 -1
- package/lib/client/ConnectionManager.d.ts +1 -0
- package/lib/client/ConnectionManager.js +7 -1
- package/lib/client/ConnectionManager.js.map +1 -1
- package/lib/client/sync/options.js +2 -1
- package/lib/client/sync/options.js.map +1 -1
- package/lib/client/sync/stream/AbstractRemote.d.ts +5 -5
- package/lib/client/sync/stream/AbstractRemote.js +11 -11
- package/lib/client/sync/stream/AbstractRemote.js.map +1 -1
- package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +9 -6
- package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +40 -12
- package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js.map +1 -1
- package/lib/client/sync/stream/core-instruction.d.ts +26 -1
- package/lib/client/sync/stream/core-instruction.js.map +1 -1
- package/lib/client/watched/AbstractQueryProcessor.js +6 -1
- package/lib/client/watched/AbstractQueryProcessor.js.map +1 -1
- package/lib/db/crud/SyncStatus.d.ts +2 -5
- package/lib/db/crud/SyncStatus.js +5 -18
- package/lib/db/crud/SyncStatus.js.map +1 -1
- package/lib/index.d.ts +2 -0
- package/lib/index.js +1 -0
- package/lib/index.js.map +1 -1
- package/lib/utils/error-serialization.d.ts +27 -0
- package/lib/utils/error-serialization.js +90 -0
- package/lib/utils/error-serialization.js.map +1 -0
- package/lib/version.d.ts +1 -1
- package/lib/version.js +1 -1
- package/package.json +3 -3
- package/src/client/BasePowerSyncDatabase.ts +23 -18
- package/src/client/ConnectionManager.ts +8 -1
- package/src/client/sync/options.ts +2 -1
- package/src/client/sync/stream/AbstractRemote.ts +12 -12
- package/src/client/sync/stream/AbstractStreamingSyncImplementation.ts +47 -20
- package/src/client/sync/stream/core-instruction.ts +24 -2
- package/src/client/watched/AbstractQueryProcessor.ts +7 -1
- package/src/db/crud/SyncStatus.ts +6 -19
- package/src/index.ts +2 -0
- package/src/utils/error-serialization.ts +116 -0
- package/src/version.ts +1 -1
|
@@ -20,6 +20,7 @@ export function resolveSyncOptions(
|
|
|
20
20
|
includeDefaultStreams: options.includeDefaultStreams ?? true,
|
|
21
21
|
retryDelayMs: options.retryDelayMs ?? 5000,
|
|
22
22
|
crudUploadThrottleMs: options.crudUploadThrottleMs ?? 1000,
|
|
23
|
-
checkpointMode: options.checkpointMode ?? 'legacy'
|
|
23
|
+
checkpointMode: options.checkpointMode ?? 'legacy',
|
|
24
|
+
diagnostics: options.diagnostics ?? false
|
|
24
25
|
};
|
|
25
26
|
}
|
|
@@ -16,7 +16,7 @@ import { POWERSYNC_JS_VERSION } from '../../../version.js';
|
|
|
16
16
|
* @internal
|
|
17
17
|
*/
|
|
18
18
|
export type RemoteConnector = {
|
|
19
|
-
fetchCredentials: () => Promise<PowerSyncCredentials | null>;
|
|
19
|
+
fetchCredentials: (signal?: AbortSignal) => Promise<PowerSyncCredentials | null>;
|
|
20
20
|
invalidateCredentials?: () => void;
|
|
21
21
|
};
|
|
22
22
|
|
|
@@ -96,12 +96,12 @@ export abstract class AbstractRemote {
|
|
|
96
96
|
*
|
|
97
97
|
* These credentials may have expired already.
|
|
98
98
|
*/
|
|
99
|
-
async getCredentials(): Promise<PowerSyncCredentials | null> {
|
|
99
|
+
async getCredentials(signal?: AbortSignal): Promise<PowerSyncCredentials | null> {
|
|
100
100
|
if (this.credentials) {
|
|
101
101
|
return this.credentials;
|
|
102
102
|
}
|
|
103
103
|
|
|
104
|
-
return this.prefetchCredentials();
|
|
104
|
+
return this.prefetchCredentials(signal);
|
|
105
105
|
}
|
|
106
106
|
|
|
107
107
|
/**
|
|
@@ -112,8 +112,8 @@ export abstract class AbstractRemote {
|
|
|
112
112
|
*
|
|
113
113
|
* This may be called before the current credentials have expired.
|
|
114
114
|
*/
|
|
115
|
-
async prefetchCredentials() {
|
|
116
|
-
this.credentials = await this.fetchCredentials();
|
|
115
|
+
async prefetchCredentials(signal?: AbortSignal) {
|
|
116
|
+
this.credentials = await this.fetchCredentials(signal);
|
|
117
117
|
|
|
118
118
|
return this.credentials;
|
|
119
119
|
}
|
|
@@ -124,8 +124,8 @@ export abstract class AbstractRemote {
|
|
|
124
124
|
* This should always fetch a fresh set of credentials - don't use cached
|
|
125
125
|
* values.
|
|
126
126
|
*/
|
|
127
|
-
async fetchCredentials() {
|
|
128
|
-
const credentials = await this.connector.fetchCredentials();
|
|
127
|
+
async fetchCredentials(signal?: AbortSignal) {
|
|
128
|
+
const credentials = await this.connector.fetchCredentials(signal);
|
|
129
129
|
if (credentials?.endpoint.match(POWERSYNC_TRAILING_SLASH_MATCH)) {
|
|
130
130
|
throw new Error(
|
|
131
131
|
`A trailing forward slash "/" was found in the fetchCredentials endpoint: "${credentials.endpoint}". Remove the trailing forward slash "/" to fix this error.`
|
|
@@ -149,8 +149,8 @@ export abstract class AbstractRemote {
|
|
|
149
149
|
return `powersync-js/${POWERSYNC_JS_VERSION}`;
|
|
150
150
|
}
|
|
151
151
|
|
|
152
|
-
protected async buildRequest(path: string): Promise<PreparedRequest> {
|
|
153
|
-
const credentials = await this.getCredentials();
|
|
152
|
+
protected async buildRequest(path: string, signal?: AbortSignal): Promise<PreparedRequest> {
|
|
153
|
+
const credentials = await this.getCredentials(signal);
|
|
154
154
|
if (credentials != null && (credentials.endpoint == null || credentials.endpoint == '')) {
|
|
155
155
|
throw new Error('PowerSync endpoint not configured');
|
|
156
156
|
} else if (credentials?.token == null || credentials?.token == '') {
|
|
@@ -186,7 +186,7 @@ export abstract class AbstractRemote {
|
|
|
186
186
|
body?: string;
|
|
187
187
|
signal?: AbortSignal;
|
|
188
188
|
}): Promise<any> {
|
|
189
|
-
const request = await this.buildRequest(path);
|
|
189
|
+
const request = await this.buildRequest(path, signal);
|
|
190
190
|
const res = await this.fetch({
|
|
191
191
|
resource: request.url,
|
|
192
192
|
request: {
|
|
@@ -240,7 +240,7 @@ export abstract class AbstractRemote {
|
|
|
240
240
|
async socketStreamRaw(options: SocketSyncStreamOptions): Promise<SimpleAsyncIterator<Uint8Array>> {
|
|
241
241
|
const support = await this.loadWebSocketSupport(webSocketPlatform);
|
|
242
242
|
|
|
243
|
-
const request = await this.buildRequest(options.path);
|
|
243
|
+
const request = await this.buildRequest(options.path, options.abortSignal);
|
|
244
244
|
request.url = request.url.replace(/^https?:\/\//, function (match) {
|
|
245
245
|
return match === 'https://' ? 'wss://' : 'ws://';
|
|
246
246
|
});
|
|
@@ -265,7 +265,7 @@ export abstract class AbstractRemote {
|
|
|
265
265
|
options: SyncStreamOptions
|
|
266
266
|
): Promise<{ isBson: boolean; stream: SimpleAsyncIterator<Uint8Array> }> {
|
|
267
267
|
const { data, path, abortSignal } = options;
|
|
268
|
-
const request = await this.buildRequest(path);
|
|
268
|
+
const request = await this.buildRequest(path, abortSignal);
|
|
269
269
|
|
|
270
270
|
/**
|
|
271
271
|
* This abort controller will abort pending fetch requests.
|
|
@@ -18,7 +18,8 @@ import {
|
|
|
18
18
|
CoreSyncStatus,
|
|
19
19
|
Instruction,
|
|
20
20
|
NonInterruptingInstruction,
|
|
21
|
-
isInterruptingInstruction
|
|
21
|
+
isInterruptingInstruction,
|
|
22
|
+
DiagnosticsEvent
|
|
22
23
|
} from './core-instruction.js';
|
|
23
24
|
import {
|
|
24
25
|
doneResult,
|
|
@@ -58,11 +59,9 @@ export interface AbstractStreamingSyncImplementationOptions {
|
|
|
58
59
|
adapter: BucketStorageAdapter;
|
|
59
60
|
subscriptions: SubscribedStream[];
|
|
60
61
|
/**
|
|
61
|
-
* Uploads pending CRUD data
|
|
62
|
-
*
|
|
63
|
-
*
|
|
64
|
-
* boundary (such as the web shared worker calling into a tab) must stop waiting once it aborts: `disconnect()` awaits
|
|
65
|
-
* the sync loops, so a call that can never settle also prevents every subsequent `connect()` from resolving.
|
|
62
|
+
* Uploads pending CRUD data.
|
|
63
|
+
* Cross-context implementations must stop waiting when `signal` aborts
|
|
64
|
+
* on disconnect, allowing the sync loops to finish.
|
|
66
65
|
*/
|
|
67
66
|
uploadCrud: (signal?: AbortSignal) => Promise<void>;
|
|
68
67
|
/**
|
|
@@ -197,11 +196,17 @@ export abstract class AbstractStreamingSyncImplementation
|
|
|
197
196
|
this.crudUpdateListener = undefined;
|
|
198
197
|
}
|
|
199
198
|
|
|
199
|
+
/**
|
|
200
|
+
* Receives a core diagnostics event (emitted only when diagnostics are enabled on the sync stream).
|
|
201
|
+
* Does nothing here; an SDK with diagnostics tooling overrides it to hand the event on.
|
|
202
|
+
*/
|
|
203
|
+
protected emitDiagnostics(_event: DiagnosticsEvent): void {}
|
|
204
|
+
|
|
200
205
|
abstract obtainLock<T>(lockOptions: LockOptions<T>): Promise<T>;
|
|
201
206
|
|
|
202
207
|
private async requestNextCheckpointFromService(abort: AbortSignal): Promise<string> {
|
|
203
208
|
if (!(await this.checkpoints.waitForCheckpointRequestsReady(abort))) {
|
|
204
|
-
abort.
|
|
209
|
+
throw abort.reason;
|
|
205
210
|
}
|
|
206
211
|
|
|
207
212
|
const nextCheckpointRequestId = await this.options.adapter.readCheckpointRequestId('next');
|
|
@@ -335,22 +340,38 @@ The next upload iteration will be delayed.`
|
|
|
335
340
|
|
|
336
341
|
const controller = new AbortController();
|
|
337
342
|
this.abortController = controller;
|
|
343
|
+
const signal = controller.signal;
|
|
338
344
|
this.streamingSyncPromise = Promise.all([
|
|
339
|
-
this.crudUploadLoop(
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
345
|
+
this.crudUploadLoop(signal, options).catch((error) => {
|
|
346
|
+
// Requesting the crud lock when aborted will file, but that's not something worth logging.
|
|
347
|
+
if (signal.reason !== error) {
|
|
348
|
+
this.logger.log({ level: LogLevels.error, message: 'Error in crud upload loop', error });
|
|
349
|
+
}
|
|
350
|
+
}),
|
|
351
|
+
this.streamingSync(signal, options),
|
|
352
|
+
this.repostUnacknowledgedCheckpointRequests(signal, options)
|
|
344
353
|
]).finally(() => {
|
|
345
354
|
// These promises only complete when we want to disconnect. No further sync iteration can resume checkpoint
|
|
346
355
|
// requests, so fail any that are still pending.
|
|
347
356
|
this.checkpoints.disconnected();
|
|
348
357
|
});
|
|
349
358
|
|
|
350
|
-
// Return a promise that resolves when the connection status is updated to indicate that we're connected
|
|
359
|
+
// Return a promise that resolves when the connection status is updated to indicate that we're connected, or when
|
|
360
|
+
// this connection attempt is aborted (e.g. superseded by another connect() call) before that happens. We do this
|
|
351
361
|
// by waiting for connecting to be true and then false again.
|
|
352
362
|
return new Promise<void>((resolve) => {
|
|
353
363
|
let sawStartOfConnection = false;
|
|
364
|
+
let settled = false;
|
|
365
|
+
|
|
366
|
+
const finish = () => {
|
|
367
|
+
if (settled) {
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
settled = true;
|
|
371
|
+
disposer();
|
|
372
|
+
signal.removeEventListener('abort', finish);
|
|
373
|
+
resolve();
|
|
374
|
+
};
|
|
354
375
|
|
|
355
376
|
const disposer = this.registerListener({
|
|
356
377
|
statusChanged: (snapshot) => {
|
|
@@ -368,10 +389,13 @@ The next upload iteration will be delayed.`
|
|
|
368
389
|
return;
|
|
369
390
|
}
|
|
370
391
|
|
|
371
|
-
|
|
372
|
-
resolve();
|
|
392
|
+
finish();
|
|
373
393
|
}
|
|
374
394
|
});
|
|
395
|
+
|
|
396
|
+
// If this attempt is aborted (disconnected) before a `statusChanged` event ever fires - which can happen when
|
|
397
|
+
// the instance never got as far as reporting a connecting status - there's nothing left to wait for.
|
|
398
|
+
signal.addEventListener('abort', finish, { once: true });
|
|
375
399
|
});
|
|
376
400
|
}
|
|
377
401
|
|
|
@@ -470,9 +494,7 @@ The next upload iteration will be delayed.`
|
|
|
470
494
|
* The WebRemote should only abort pending fetch requests or close active Readable streams.
|
|
471
495
|
*/
|
|
472
496
|
|
|
473
|
-
//
|
|
474
|
-
// `ex instanceof AbortOperation`: an abort raised further down (such as a connector call that timed out) is a
|
|
475
|
-
// genuine failure that should be reported and retried with a delay.
|
|
497
|
+
// Check the disconnect signal: other aborts must still be reported and retried.
|
|
476
498
|
const stoppedOnRequest = signal.aborted;
|
|
477
499
|
|
|
478
500
|
if (stoppedOnRequest) {
|
|
@@ -491,8 +513,7 @@ The next upload iteration will be delayed.`
|
|
|
491
513
|
}
|
|
492
514
|
|
|
493
515
|
if (!stoppedOnRequest) {
|
|
494
|
-
//
|
|
495
|
-
// `downloadError` is only cleared by a completed sync, which can no longer happen once we have stopped.
|
|
516
|
+
// Don't record intentional disconnects as errors: they persist until a successful sync.
|
|
496
517
|
this.updateJsSyncState({ downloadError: ex as Error });
|
|
497
518
|
}
|
|
498
519
|
} finally {
|
|
@@ -718,6 +739,10 @@ The next upload iteration will be delayed.`
|
|
|
718
739
|
if (serializedSchema) {
|
|
719
740
|
options.schema = serializedSchema;
|
|
720
741
|
}
|
|
742
|
+
if (resolvedOptions.diagnostics) {
|
|
743
|
+
// An empty object enables the core's diagnostics event stream (Option<DiagnosticOptions>).
|
|
744
|
+
options.diagnostics = {};
|
|
745
|
+
}
|
|
721
746
|
|
|
722
747
|
return invokePowerSyncControl(PowerSyncControlCommand.START, JSON.stringify(options));
|
|
723
748
|
}
|
|
@@ -802,6 +827,8 @@ The next upload iteration will be delayed.`
|
|
|
802
827
|
// Not necessary on JS platforms.
|
|
803
828
|
} else if ('DidCompleteSync' in instruction) {
|
|
804
829
|
syncImplementation.updateJsSyncState({ downloadError: undefined });
|
|
830
|
+
} else if ('HandleDiagnostics' in instruction) {
|
|
831
|
+
syncImplementation.emitDiagnostics(instruction.HandleDiagnostics);
|
|
805
832
|
}
|
|
806
833
|
}
|
|
807
834
|
|
|
@@ -16,7 +16,29 @@ export type NonInterruptingInstruction =
|
|
|
16
16
|
| { UpdateSyncStatus: UpdateSyncStatus }
|
|
17
17
|
| { FetchCredentials: FetchCredentials }
|
|
18
18
|
| { FlushFileSystem: any }
|
|
19
|
-
| { DidCompleteSync: any }
|
|
19
|
+
| { DidCompleteSync: any }
|
|
20
|
+
| { HandleDiagnostics: DiagnosticsEvent };
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Emitted by the core extension when diagnostics are enabled on the sync stream (see
|
|
24
|
+
* {@link https://github.com/powersync-ja/powersync-sqlite-core/blob/main/crates/core/src/sync/diagnostics.rs diagnostics.rs}). Reports detailed
|
|
25
|
+
* per-bucket download state — including the per-bucket `target_count` that is otherwise internal to
|
|
26
|
+
* the core — and inferred column types as data is downloaded.
|
|
27
|
+
*/
|
|
28
|
+
export type DiagnosticsEvent =
|
|
29
|
+
| { BucketStateChange: { changes: BucketDownloadState[]; incremental: boolean } }
|
|
30
|
+
| { SchemaChange: ObservedSchemaColumn };
|
|
31
|
+
|
|
32
|
+
export interface BucketDownloadState {
|
|
33
|
+
name: string;
|
|
34
|
+
progress: BucketProgress;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface ObservedSchemaColumn {
|
|
38
|
+
table: string;
|
|
39
|
+
column: string;
|
|
40
|
+
value_type: 'Null' | 'String' | 'Integer' | 'Real';
|
|
41
|
+
}
|
|
20
42
|
|
|
21
43
|
export interface LogLine {
|
|
22
44
|
severity: 'DEBUG' | 'INFO' | 'WARNING';
|
|
@@ -56,7 +78,7 @@ export interface CoreStreamSubscription {
|
|
|
56
78
|
|
|
57
79
|
export interface SyncPriorityStatus {
|
|
58
80
|
priority: number;
|
|
59
|
-
last_synced_at: number |
|
|
81
|
+
last_synced_at: number | null;
|
|
60
82
|
has_synced: boolean | null;
|
|
61
83
|
}
|
|
62
84
|
|
|
@@ -174,11 +174,17 @@ export abstract class AbstractQueryProcessor<
|
|
|
174
174
|
}
|
|
175
175
|
});
|
|
176
176
|
|
|
177
|
-
|
|
177
|
+
const disposeListeners = () => {
|
|
178
178
|
disposeCloseListener();
|
|
179
179
|
disposeSchemaListener();
|
|
180
180
|
};
|
|
181
181
|
|
|
182
|
+
if (this._closed) {
|
|
183
|
+
disposeListeners();
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
this.disposeListeners = disposeListeners;
|
|
187
|
+
|
|
182
188
|
// Initial setup
|
|
183
189
|
await this.runWithReporting(async () => {
|
|
184
190
|
await this.updateSettingsInternal(this.options.watchOptions, signal);
|
|
@@ -9,6 +9,7 @@ import {
|
|
|
9
9
|
} from '@powersync/common';
|
|
10
10
|
import { CoreStreamSubscription, CoreSyncStatus } from '../../client/sync/stream/core-instruction.js';
|
|
11
11
|
import { SyncPriorityStatus as CoreSyncPriorityStatus } from '../../client/sync/stream/core-instruction.js';
|
|
12
|
+
import { SerializedRelayError, serializeErrorForRelay } from '../../utils/error-serialization.js';
|
|
12
13
|
import { SyncProgressImpl } from './SyncProgress.js';
|
|
13
14
|
import { FULL_SYNC_PRIORITY } from '../../constants.js';
|
|
14
15
|
|
|
@@ -156,26 +157,12 @@ export class SyncStatusSnapshot implements SyncStatus {
|
|
|
156
157
|
};
|
|
157
158
|
}
|
|
158
159
|
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
* This explicitly serializes errors in the SyncStatus.
|
|
162
|
-
*/
|
|
163
|
-
serializeError(error?: Error) {
|
|
160
|
+
// Must stay deterministic: isEqual() serializes both sides of a comparison.
|
|
161
|
+
serializeError(error?: Error): SerializedRelayError | undefined {
|
|
164
162
|
if (typeof error == 'undefined') {
|
|
165
163
|
return undefined;
|
|
166
164
|
}
|
|
167
|
-
|
|
168
|
-
name: error.name,
|
|
169
|
-
message: error.message,
|
|
170
|
-
stack: error.stack
|
|
171
|
-
};
|
|
172
|
-
// `Error.cause` can be any value (the spec types it as unknown). Preserve it
|
|
173
|
-
// so consumers reading uploadError/downloadError keep the failure context.
|
|
174
|
-
// Recurse for Error causes so the whole chain is flattened the same way.
|
|
175
|
-
if (typeof error.cause != 'undefined') {
|
|
176
|
-
serialized.cause = error.cause instanceof Error ? this.serializeError(error.cause) : error.cause;
|
|
177
|
-
}
|
|
178
|
-
return serialized;
|
|
165
|
+
return serializeErrorForRelay(error);
|
|
179
166
|
}
|
|
180
167
|
}
|
|
181
168
|
|
|
@@ -210,9 +197,9 @@ class SyncStreamStatusView implements SyncStreamStatus {
|
|
|
210
197
|
active: core.active,
|
|
211
198
|
isDefault: core.is_default,
|
|
212
199
|
hasExplicitSubscription: core.has_explicit_subscription,
|
|
213
|
-
expiresAt:
|
|
200
|
+
expiresAt: coreTimestampToDate(core.expires_at) ?? null,
|
|
214
201
|
hasSynced: core.last_synced_at != null,
|
|
215
|
-
lastSyncedAt:
|
|
202
|
+
lastSyncedAt: coreTimestampToDate(core.last_synced_at) ?? null
|
|
216
203
|
};
|
|
217
204
|
}
|
|
218
205
|
|
package/src/index.ts
CHANGED
|
@@ -18,6 +18,8 @@ export * from './client/watched/OnChangeQueryProcessor.js';
|
|
|
18
18
|
|
|
19
19
|
export * from './utils/AbortOperation.js';
|
|
20
20
|
export * from './utils/compatibility.js';
|
|
21
|
+
export { serializeErrorForRelay } from './utils/error-serialization.js';
|
|
22
|
+
export type { SerializedRelayError, ErrorRelayState } from './utils/error-serialization.js';
|
|
21
23
|
export * from './utils/ControlledExecutor.js';
|
|
22
24
|
export * from './utils/mutex.js';
|
|
23
25
|
export * from './utils/parseQuery.js';
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
// Clone-safe representation of errors crossing a worker boundary.
|
|
2
|
+
|
|
3
|
+
export const RELAY_ERROR_MARKER = '__powersyncError';
|
|
4
|
+
|
|
5
|
+
export type ErrorRelayState = 'serialized' | 'partial' | 'missing';
|
|
6
|
+
|
|
7
|
+
/** Structurally Error-like, but `instanceof Error` is false. */
|
|
8
|
+
export interface SerializedRelayError {
|
|
9
|
+
[RELAY_ERROR_MARKER]: true;
|
|
10
|
+
name: string;
|
|
11
|
+
message: string;
|
|
12
|
+
stack?: string;
|
|
13
|
+
/** SQLite errors, e.g. wa-sqlite's `SQLiteError`. */
|
|
14
|
+
code?: string | number;
|
|
15
|
+
/** HTTP/network error status, e.g. 401. */
|
|
16
|
+
status?: number;
|
|
17
|
+
cause?: SerializedRelayError | string;
|
|
18
|
+
state: ErrorRelayState;
|
|
19
|
+
relay?: { origin: string; sequence: number; errorState: ErrorRelayState; relayedAt: string };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const MAX_CAUSE_DEPTH = 5;
|
|
23
|
+
|
|
24
|
+
interface RelayContext {
|
|
25
|
+
lossy: boolean;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function isErrorLike(value: unknown): value is Error {
|
|
29
|
+
return (
|
|
30
|
+
typeof value === 'object' &&
|
|
31
|
+
value !== null &&
|
|
32
|
+
typeof (value as { name?: unknown }).name === 'string' &&
|
|
33
|
+
typeof (value as { message?: unknown }).message === 'string'
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function missing(reason: unknown): SerializedRelayError {
|
|
38
|
+
return {
|
|
39
|
+
[RELAY_ERROR_MARKER]: true,
|
|
40
|
+
name: 'PowerSyncMissingRejectionReason',
|
|
41
|
+
message: `No rejection reason was provided (${reason}).`,
|
|
42
|
+
state: 'missing'
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function serializeCause(value: unknown, depth: number, ctx: RelayContext): SerializedRelayError | string {
|
|
47
|
+
if (isErrorLike(value)) {
|
|
48
|
+
if (depth <= 0) {
|
|
49
|
+
ctx.lossy = true;
|
|
50
|
+
return '[Max depth reached]';
|
|
51
|
+
}
|
|
52
|
+
return serialize(value, depth, ctx);
|
|
53
|
+
}
|
|
54
|
+
if (value === null || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
|
|
55
|
+
return String(value);
|
|
56
|
+
}
|
|
57
|
+
ctx.lossy = true;
|
|
58
|
+
return `[Unserializable ${typeof value}]`;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function serialize(value: unknown, depth: number, ctx: RelayContext): SerializedRelayError {
|
|
62
|
+
if (isSerializedRelayError(value)) return value;
|
|
63
|
+
if (!isErrorLike(value)) return serializePlain(value);
|
|
64
|
+
|
|
65
|
+
const source = value as Error & { code?: unknown; status?: unknown; cause?: unknown };
|
|
66
|
+
const result: SerializedRelayError = {
|
|
67
|
+
[RELAY_ERROR_MARKER]: true,
|
|
68
|
+
name: source.name || 'Error',
|
|
69
|
+
message: source.message,
|
|
70
|
+
state: 'serialized'
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
const stack = source.stack;
|
|
74
|
+
if (typeof stack === 'string') result.stack = stack;
|
|
75
|
+
// Not standard Error fields, but wa-sqlite errors (code) and HTTP errors (status) carry them and consumers need them as context.
|
|
76
|
+
if (typeof source.code === 'string' || typeof source.code === 'number') result.code = source.code;
|
|
77
|
+
if (typeof source.status === 'number') result.status = source.status;
|
|
78
|
+
|
|
79
|
+
if (source.cause !== undefined) result.cause = serializeCause(source.cause, depth - 1, ctx);
|
|
80
|
+
|
|
81
|
+
if (ctx.lossy && result.state !== 'missing') result.state = 'partial';
|
|
82
|
+
return result;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Never stringifies an arbitrary object: it may hold credentials or a request payload. */
|
|
86
|
+
function serializePlain(value: unknown): SerializedRelayError {
|
|
87
|
+
const printable = typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean';
|
|
88
|
+
return {
|
|
89
|
+
[RELAY_ERROR_MARKER]: true,
|
|
90
|
+
name: typeof value === 'string' ? 'String' : 'Error',
|
|
91
|
+
message: printable ? String(value) : 'Non-Error rejection',
|
|
92
|
+
state: 'serialized'
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Serializes a caught value into a clone-safe shape. Never throws and never
|
|
98
|
+
* returns `undefined` — a missing rejection reason becomes `state: 'missing'`.
|
|
99
|
+
*/
|
|
100
|
+
export function serializeErrorForRelay(value: unknown): SerializedRelayError {
|
|
101
|
+
try {
|
|
102
|
+
if (value === undefined || value === null) return missing(value);
|
|
103
|
+
return serialize(value, MAX_CAUSE_DEPTH, { lossy: false });
|
|
104
|
+
} catch {
|
|
105
|
+
return {
|
|
106
|
+
[RELAY_ERROR_MARKER]: true,
|
|
107
|
+
name: 'Error',
|
|
108
|
+
message: 'Unable to serialize rejection reason',
|
|
109
|
+
state: 'partial'
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function isSerializedRelayError(value: unknown): value is SerializedRelayError {
|
|
115
|
+
return typeof value === 'object' && value !== null && (value as SerializedRelayError)[RELAY_ERROR_MARKER] === true;
|
|
116
|
+
}
|
package/src/version.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// Note: This file gets updated by tool/update_version.js script as part of the Changesets release workflow.
|
|
2
2
|
// The update happens in the changesets PR, before the package is built.
|
|
3
|
-
export const POWERSYNC_JS_VERSION = '1.
|
|
3
|
+
export const POWERSYNC_JS_VERSION = '1.3.1';
|