@powersync/diagnostics 0.0.1

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 (52) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +115 -0
  3. package/lib/src/agent.d.ts +32 -0
  4. package/lib/src/agent.js +77 -0
  5. package/lib/src/agent.js.map +1 -0
  6. package/lib/src/client.d.ts +7 -0
  7. package/lib/src/client.js +29 -0
  8. package/lib/src/client.js.map +1 -0
  9. package/lib/src/constants.d.ts +13 -0
  10. package/lib/src/constants.js +14 -0
  11. package/lib/src/constants.js.map +1 -0
  12. package/lib/src/definition.d.ts +10 -0
  13. package/lib/src/definition.js +406 -0
  14. package/lib/src/definition.js.map +1 -0
  15. package/lib/src/index.d.ts +4 -0
  16. package/lib/src/index.js +6 -0
  17. package/lib/src/index.js.map +1 -0
  18. package/lib/src/js-agent.d.ts +63 -0
  19. package/lib/src/js-agent.js +295 -0
  20. package/lib/src/js-agent.js.map +1 -0
  21. package/lib/src/node.d.ts +58 -0
  22. package/lib/src/node.js +38 -0
  23. package/lib/src/node.js.map +1 -0
  24. package/lib/src/page.d.ts +5 -0
  25. package/lib/src/page.js +50 -0
  26. package/lib/src/page.js.map +1 -0
  27. package/lib/src/rpc-types.d.ts +39 -0
  28. package/lib/src/rpc-types.js +2 -0
  29. package/lib/src/rpc-types.js.map +1 -0
  30. package/lib/src/sync-state.d.ts +4 -0
  31. package/lib/src/sync-state.js +53 -0
  32. package/lib/src/sync-state.js.map +1 -0
  33. package/lib/src/vite-static.d.ts +18 -0
  34. package/lib/src/vite-static.js +67 -0
  35. package/lib/src/vite-static.js.map +1 -0
  36. package/lib/src/vite.d.ts +21 -0
  37. package/lib/src/vite.js +42 -0
  38. package/lib/src/vite.js.map +1 -0
  39. package/lib/tsconfig.tsbuildinfo +1 -0
  40. package/package.json +94 -0
  41. package/src/agent.ts +115 -0
  42. package/src/client.ts +36 -0
  43. package/src/constants.ts +15 -0
  44. package/src/definition.ts +486 -0
  45. package/src/index.ts +7 -0
  46. package/src/js-agent.ts +373 -0
  47. package/src/node.ts +86 -0
  48. package/src/page.ts +61 -0
  49. package/src/rpc-types.ts +51 -0
  50. package/src/sync-state.ts +61 -0
  51. package/src/vite-static.ts +83 -0
  52. package/src/vite.ts +48 -0
@@ -0,0 +1,373 @@
1
+ import type {
2
+ CommonPowerSyncDatabase,
3
+ LogRecord as SdkLogRecord,
4
+ PowerSyncBackendConnector,
5
+ SyncOptions,
6
+ SyncStatus,
7
+ SyncStreamSubscription
8
+ } from '@powersync/common';
9
+ import type {
10
+ ActionRequest,
11
+ BucketState,
12
+ CoreDiagnosticsEvent,
13
+ DiagnosticsEvent,
14
+ LogRecord,
15
+ ProtocolInfo,
16
+ QueryParams,
17
+ QueryResult,
18
+ SchemaPayload,
19
+ SdkIntegration,
20
+ StreamActionArgs,
21
+ SyncState,
22
+ Unsubscribe,
23
+ UploadQueueState
24
+ } from '@powersync/diagnostics-core';
25
+ import { toStreamStates, toSyncState } from './sync-state.js';
26
+
27
+ /** Delivers the SQLite core's diagnostics events to the agent. How they arrive is runtime-specific. */
28
+ export interface CoreEventSource {
29
+ onEvent(handler: (event: CoreDiagnosticsEvent) => void): Unsubscribe;
30
+ dispose(): void;
31
+ }
32
+
33
+ /**
34
+ * Read access to the live connection. The connector and options are not on the database's public
35
+ * interface, so the code that installs the agent (which can see the concrete database) hands them in.
36
+ */
37
+ export interface ConnectionAccess {
38
+ getConnector(): PowerSyncBackendConnector | null;
39
+ getConnectionOptions(): SyncOptions | null;
40
+ }
41
+
42
+ export interface JsAgentOptions {
43
+ /** A label for the SDK behind this agent, e.g. `@powersync/web`. */
44
+ sdk?: string;
45
+ /** Debounce for re-reading bucket stats after internal-table changes. */
46
+ bucketThrottleMs?: number;
47
+ /** Core diagnostics events (per-bucket `target_count`). Omit when core diagnostics are off. */
48
+ coreEvents?: CoreEventSource;
49
+ /** Read access to the live connection; omit if the runtime cannot expose it. */
50
+ connection?: ConnectionAccess;
51
+ }
52
+
53
+ /**
54
+ * The JavaScript `SdkIntegration`: runs next to a live PowerSync database and answers the protocol
55
+ * from it. Every status change is pushed as mapped state; requests are answered by querying the
56
+ * live client. Hosts reach it through a bridge or call it directly when they share the page.
57
+ */
58
+ export class JsAgent implements SdkIntegration {
59
+ private handlers = new Set<(event: DiagnosticsEvent) => void>();
60
+ private disposers: Array<() => void> = [];
61
+ private started = false;
62
+ /** Debug subscriptions created through `action`, keyed by name + params, so they can be released. */
63
+ private streamHandles = new Map<string, SyncStreamSubscription>();
64
+ // Retained so reconnect / clear work after a disconnect, when the connection no longer exposes them.
65
+ private lastConnector: PowerSyncBackendConnector | null = null;
66
+ private lastConnectionOptions: SyncOptions | null = null;
67
+ // Per-bucket total operation counts from the core diagnostics stream (not stored in ps_buckets).
68
+ private bucketTargets = new Map<string, number>();
69
+
70
+ constructor(
71
+ private db: CommonPowerSyncDatabase,
72
+ private options: JsAgentOptions = {}
73
+ ) {}
74
+
75
+ // --- SdkIntegration ---
76
+
77
+ async runQuery({ sql, params }: QueryParams): Promise<QueryResult> {
78
+ const records = await this.db.getAll<Record<string, unknown>>(sql, params);
79
+ const columns = records.length > 0 ? Object.keys(records[0]) : [];
80
+ return { columns, rows: records.map((record) => columns.map((column) => record[column])) };
81
+ }
82
+
83
+ async getSchema(): Promise<SchemaPayload> {
84
+ // The core payload: what the client already sends to `powersync_replace_schema`.
85
+ return this.db.schema.toJSON() as SchemaPayload;
86
+ }
87
+
88
+ async getInfo(): Promise<ProtocolInfo> {
89
+ const connection = this.options.connection;
90
+
91
+ let endpoint: string | null = null;
92
+ let token: string | null = null;
93
+ try {
94
+ const credentials = await connection?.getConnector()?.fetchCredentials();
95
+ endpoint = credentials?.endpoint ?? null;
96
+ token = credentials?.token ?? null;
97
+ } catch {
98
+ // Credentials are unavailable before connect().
99
+ }
100
+
101
+ let clientId: string | null = null;
102
+ try {
103
+ clientId = await this.db.getClientId();
104
+ } catch {
105
+ // Non-fatal.
106
+ }
107
+
108
+ let sqliteCoreVersion: string | null = null;
109
+ try {
110
+ const [row] = await this.db.getAll<{ v: string }>('SELECT powersync_rs_version() AS v');
111
+ sqliteCoreVersion = row?.v ?? null;
112
+ } catch {
113
+ // Non-fatal.
114
+ }
115
+
116
+ const connectionOptions = connection?.getConnectionOptions() ?? null;
117
+ return {
118
+ endpoint,
119
+ token,
120
+ clientId,
121
+ connectionMethod: connectionOptions?.connectionMethod ?? null,
122
+ params: connectionOptions?.params ?? null,
123
+ connected: this.db.currentStatus?.connected ?? false,
124
+ sqliteCoreVersion,
125
+ sdk: this.options.sdk ?? null
126
+ };
127
+ }
128
+
129
+ async observeEvents(handler: (event: DiagnosticsEvent) => void): Promise<Unsubscribe> {
130
+ this.handlers.add(handler);
131
+ this.start();
132
+ // A late subscriber receives the present state at once.
133
+ this.replay(handler);
134
+ return () => {
135
+ this.handlers.delete(handler);
136
+ };
137
+ }
138
+
139
+ async action(request: ActionRequest): Promise<void> {
140
+ switch (request.action) {
141
+ case 'disconnect':
142
+ await this.db.disconnect();
143
+ break;
144
+ case 'clearData':
145
+ await this.db.disconnectAndClear();
146
+ await this.reconnect();
147
+ break;
148
+ case 'reconnect':
149
+ await this.db.disconnect();
150
+ await this.reconnect();
151
+ break;
152
+ case 'requestCheckpoint': {
153
+ // Confirms the client is caught up right now. Needs `checkpointMode: 'requests'` on connect.
154
+ const checkpoint = await this.db.requestCheckpoint();
155
+ await checkpoint.waitForSync({ signal: AbortSignal.timeout(120_000) });
156
+ break;
157
+ }
158
+ case 'subscribeStream': {
159
+ const { name, params, ttl, priority } = request.args as StreamActionArgs;
160
+ // TTL defaults to 0 so a forgotten debug subscription is evicted as soon as it is released.
161
+ const handle = await this.db.syncStream(name, params).subscribe({ ttl: ttl ?? 0, priority });
162
+ this.streamHandles.set(streamKey(name, params), handle);
163
+ break;
164
+ }
165
+ case 'unsubscribeStream': {
166
+ const { name, params } = request.args as StreamActionArgs;
167
+ const key = streamKey(name, params);
168
+ this.streamHandles.get(key)?.unsubscribe();
169
+ this.streamHandles.delete(key);
170
+ break;
171
+ }
172
+ }
173
+ }
174
+
175
+ async close(): Promise<void> {
176
+ for (const handle of this.streamHandles.values()) {
177
+ handle.unsubscribe();
178
+ }
179
+ this.streamHandles.clear();
180
+ for (const dispose of this.disposers) {
181
+ dispose();
182
+ }
183
+ this.disposers = [];
184
+ this.handlers.clear();
185
+ this.started = false;
186
+ }
187
+
188
+ // --- push bridge ---
189
+
190
+ private start(): void {
191
+ if (this.started) {
192
+ return;
193
+ }
194
+ this.started = true;
195
+
196
+ this.disposers.push(
197
+ this.db.registerListener({
198
+ statusChanged: (status: SyncStatus) => {
199
+ this.captureConnection();
200
+ this.pushStatus(status);
201
+ void this.pushUploadQueue();
202
+ void this.pushBuckets();
203
+ }
204
+ })
205
+ );
206
+ this.captureConnection();
207
+
208
+ if (this.options.coreEvents) {
209
+ const source = this.options.coreEvents;
210
+ this.disposers.push(source.onEvent((event) => this.handleCoreEvent(event)));
211
+ this.disposers.push(() => source.dispose());
212
+ }
213
+
214
+ this.captureLogs();
215
+
216
+ // Re-read bucket stats and the upload queue when internal tables change, so a local write shows up
217
+ // before the sync status moves.
218
+ this.disposers.push(
219
+ this.db.onChangeWithCallback(
220
+ {
221
+ onChange: () => {
222
+ void this.pushBuckets();
223
+ void this.pushUploadQueue();
224
+ }
225
+ },
226
+ { tables: ['ps_buckets', 'ps_oplog', 'ps_crud'], throttleMs: this.options.bucketThrottleMs ?? 300 }
227
+ )
228
+ );
229
+ }
230
+
231
+ private replay(handler: (event: DiagnosticsEvent) => void): void {
232
+ const status = this.db.currentStatus;
233
+ handler({ type: 'status', payload: toSyncState(status) });
234
+ handler({ type: 'streams', payload: toStreamStates(status) });
235
+ void this.readUploadQueue()
236
+ .then((payload) => handler({ type: 'uploadQueue', payload }))
237
+ .catch(() => {});
238
+ void this.readBuckets()
239
+ .then((payload) => handler({ type: 'buckets', payload }))
240
+ .catch(() => {});
241
+ }
242
+
243
+ private emit(event: DiagnosticsEvent): void {
244
+ for (const handler of this.handlers) {
245
+ try {
246
+ handler(event);
247
+ } catch {
248
+ // One failing subscriber must not break the others.
249
+ }
250
+ }
251
+ }
252
+
253
+ private pushStatus(status: SyncStatus): void {
254
+ this.emit({ type: 'status', payload: toSyncState(status) });
255
+ this.emit({ type: 'streams', payload: toStreamStates(status) });
256
+ }
257
+
258
+ private async readUploadQueue(): Promise<UploadQueueState> {
259
+ const stats = await this.db.getUploadQueueStats(true);
260
+ return { count: stats.count, size: stats.size ?? null };
261
+ }
262
+
263
+ private async pushUploadQueue(): Promise<void> {
264
+ try {
265
+ this.emit({ type: 'uploadQueue', payload: await this.readUploadQueue() });
266
+ } catch {
267
+ // Non-fatal: queue stats are best-effort.
268
+ }
269
+ }
270
+
271
+ private async pushBuckets(): Promise<void> {
272
+ try {
273
+ this.emit({ type: 'buckets', payload: await this.readBuckets() });
274
+ } catch {
275
+ // Non-fatal: the diagnostic tables may not exist yet.
276
+ }
277
+ }
278
+
279
+ private async readBuckets(): Promise<BucketState[]> {
280
+ const downloading = this.db.currentStatus?.downloading ?? false;
281
+ const withSize =
282
+ 'SELECT name, count_at_last + count_since_last AS ops, downloaded_size AS size, last_op FROM ps_buckets ORDER BY name';
283
+ const withoutSize = 'SELECT name, count_at_last + count_since_last AS ops, last_op FROM ps_buckets ORDER BY name';
284
+
285
+ let rows: Record<string, unknown>[];
286
+ try {
287
+ rows = await this.db.getAll(withSize);
288
+ } catch {
289
+ // `downloaded_size` is absent on older cores.
290
+ rows = await this.db.getAll(withoutSize);
291
+ }
292
+
293
+ return rows.map((row) => {
294
+ const name = String(row.name);
295
+ return {
296
+ name,
297
+ downloadedOperations: Number(row.ops) || 0,
298
+ totalOperations: this.bucketTargets.get(name) ?? null,
299
+ downloadedSize: row.size == null ? null : Number(row.size),
300
+ lastOp: row.last_op == null ? null : String(row.last_op),
301
+ downloading
302
+ };
303
+ });
304
+ }
305
+
306
+ /** Wraps `db.logger.log` so every SDK log record is forwarded; restored on close. */
307
+ private captureLogs(): void {
308
+ const logger = this.db.logger;
309
+ if (!logger || typeof logger.log !== 'function') {
310
+ return;
311
+ }
312
+ const original = logger.log.bind(logger);
313
+ logger.log = (record) => {
314
+ original(record);
315
+ try {
316
+ this.pushLog(record);
317
+ } catch {
318
+ // Never let diagnostics break the app's logging.
319
+ }
320
+ };
321
+ this.disposers.push(() => {
322
+ logger.log = original;
323
+ });
324
+ }
325
+
326
+ private pushLog(record: SdkLogRecord): void {
327
+ const entry: LogRecord = {
328
+ timestamp: Date.now(),
329
+ level: logLevelName(record.level),
330
+ message: record.message,
331
+ args: record.error == null ? undefined : [record.error instanceof Error ? record.error.message : record.error]
332
+ };
333
+ this.emit({ type: 'newLogs', payload: [entry] });
334
+ }
335
+
336
+ private handleCoreEvent(event: CoreDiagnosticsEvent): void {
337
+ this.emit({ type: 'core', payload: event });
338
+ if ('BucketStateChange' in event) {
339
+ for (const bucket of event.BucketStateChange.changes) {
340
+ this.bucketTargets.set(bucket.name, bucket.progress.target_count);
341
+ }
342
+ void this.pushBuckets();
343
+ }
344
+ }
345
+
346
+ private captureConnection(): void {
347
+ const connection = this.options.connection;
348
+ const connector = connection?.getConnector() ?? null;
349
+ if (connector) {
350
+ this.lastConnector = connector;
351
+ this.lastConnectionOptions = connection?.getConnectionOptions() ?? null;
352
+ }
353
+ }
354
+
355
+ private async reconnect(): Promise<void> {
356
+ if (this.lastConnector) {
357
+ await this.db.connect(this.lastConnector, this.lastConnectionOptions ?? undefined);
358
+ }
359
+ }
360
+ }
361
+
362
+ function streamKey(name: string, params?: Record<string, unknown>): string {
363
+ return `${name}|${JSON.stringify(params ?? null)}`;
364
+ }
365
+
366
+ /** Maps a numeric SDK log level to its name. */
367
+ function logLevelName(level: number): string {
368
+ if (level >= 50) return 'error';
369
+ if (level >= 40) return 'warn';
370
+ if (level >= 30) return 'info';
371
+ if (level >= 20) return 'debug';
372
+ return 'trace';
373
+ }
package/src/node.ts ADDED
@@ -0,0 +1,86 @@
1
+ /**
2
+ * PowerSync DevTools for a node app: the database lives in this process, so this process hosts the
3
+ * dev server itself. Opens the diagnostics UI on a local port and exposes the MCP tools at `/__mcp`.
4
+ */
5
+ import type { McpSetting } from 'devframe';
6
+ import { createDevServer } from 'devframe/adapters/dev';
7
+ import { buildOtpAuthUrl } from 'devframe/node/auth';
8
+ import { createIntegration, type DiagnosableDatabase } from './agent.js';
9
+ import { definition, registerIntegration } from './definition.js';
10
+
11
+ export interface EnableDiagnosticsOptions {
12
+ /**
13
+ * Port for the DevTools window. By default the OS picks a free port, so other websites cannot
14
+ * probe a known one. @default random
15
+ */
16
+ port?: number;
17
+ /** Bind host. @default 'localhost' */
18
+ host?: string;
19
+ /**
20
+ * Gate the window behind a code printed in the terminal, together with a link that carries it, so
21
+ * opening the link is enough. `false` trusts every local browser. @default true
22
+ */
23
+ auth?: boolean;
24
+ /** Open the browser once the server is up. @default false */
25
+ open?: boolean;
26
+ /** A label for the SDK, shown in the UI. @default '@powersync/node' */
27
+ sdk?: string;
28
+ /** The source id shown in the UI. @default 'node-1' */
29
+ id?: string;
30
+ /**
31
+ * The MCP endpoint at `<url>/__mcp`. By default it mounts once the tools exist and accepts only
32
+ * requests with a loopback `Origin` header; a request without one gets `403`. Pass
33
+ * `{ allowedOrigins: false }` for an MCP client that sends no `Origin` header, `false` to leave
34
+ * the endpoint off, or `{ authorization }` to require a bearer token. @default 'auto'
35
+ */
36
+ mcp?: McpSetting;
37
+ }
38
+
39
+ export interface DiagnosticsServer {
40
+ /** Where the UI is, e.g. `http://localhost:51234`. The base for `<url>/__mcp`. */
41
+ url: string;
42
+ /**
43
+ * The link to open in the browser. With `auth` on, it carries a one-time code (valid for five
44
+ * minutes, for one browser), so opening it trusts the browser. With `auth: false`, it equals `url`.
45
+ */
46
+ signInUrl: string;
47
+ /** Stops serving and detaches the database. */
48
+ close(): Promise<void>;
49
+ }
50
+
51
+ /**
52
+ * Serves live diagnostics for `db` from this process. Development only: call it behind your own
53
+ * environment check.
54
+ *
55
+ * @example
56
+ * ```ts
57
+ * const db = new PowerSyncDatabase({ ... });
58
+ * if (process.env.NODE_ENV !== 'production') {
59
+ * const devtools = await enablePowerSyncDiagnostics(db);
60
+ * console.log(`PowerSync DevTools: ${devtools.signInUrl}`);
61
+ * }
62
+ * ```
63
+ */
64
+ export async function enablePowerSyncDiagnostics(
65
+ db: DiagnosableDatabase,
66
+ options: EnableDiagnosticsOptions = {}
67
+ ): Promise<DiagnosticsServer> {
68
+ const sdk = options.sdk ?? '@powersync/node';
69
+ const detach = await registerIntegration(options.id ?? 'node-1', createIntegration(db, sdk), sdk);
70
+ const auth = options.auth ?? true;
71
+ const server = await createDevServer(definition, {
72
+ port: options.port ?? 0,
73
+ host: options.host,
74
+ auth,
75
+ openBrowser: options.open ?? false,
76
+ mcp: options.mcp ?? 'auto'
77
+ });
78
+ return {
79
+ url: server.origin,
80
+ signInUrl: auth ? buildOtpAuthUrl(server.origin) : server.origin,
81
+ async close() {
82
+ detach();
83
+ await server.close();
84
+ }
85
+ };
86
+ }
package/src/page.ts ADDED
@@ -0,0 +1,61 @@
1
+ /**
2
+ * The page side for hosts without a devframe hub: the app loads this module during development, and
3
+ * it serves the app's live database to any diagnostics UI iframe that asks over `postMessage`.
4
+ * Nuxt DevTools v3 uses it together with `./vite-static`. Nothing here reaches a production build:
5
+ * the host loads the module only in dev.
6
+ */
7
+ import {
8
+ PORT_MESSAGE,
9
+ REQUEST_PORT_MESSAGE,
10
+ exposeIntegration,
11
+ type SdkIntegration
12
+ } from '@powersync/diagnostics-core';
13
+ import { observeRegisteredDatabases } from '@powersync/web/devtools';
14
+ import { createIntegration } from './agent.js';
15
+
16
+ const SDK = '@powersync/web';
17
+
18
+ /**
19
+ * Serves the app's first live database to any iframe that asks. Call once per page.
20
+ * Returns a function that stops serving.
21
+ */
22
+ export function serveDiagnostics(): () => void {
23
+ let integration: SdkIntegration | null = null;
24
+ const stops = new Set<() => void>();
25
+
26
+ const stopObserving = observeRegisteredDatabases((databases) => {
27
+ const next = databases[0] ?? null;
28
+ // The database changed (opened, or the previous one closed): drop the old integration.
29
+ for (const stop of stops) stop();
30
+ stops.clear();
31
+ void integration?.close();
32
+ integration = next ? createIntegration(next, SDK) : null;
33
+ });
34
+
35
+ const onMessage = (event: MessageEvent) => {
36
+ if (event.data?.type !== REQUEST_PORT_MESSAGE) {
37
+ return;
38
+ }
39
+ if (!integration) {
40
+ return;
41
+ }
42
+ // One dedicated channel per asking iframe, so several docks can attach at once.
43
+ const channel = new MessageChannel();
44
+ stops.add(exposeIntegration(integration, channel.port1));
45
+ (event.source as Window | null)?.postMessage(
46
+ { type: PORT_MESSAGE },
47
+ { targetOrigin: event.origin, transfer: [channel.port2] }
48
+ );
49
+ };
50
+ window.addEventListener('message', onMessage);
51
+
52
+ return () => {
53
+ window.removeEventListener('message', onMessage);
54
+ stopObserving();
55
+ for (const stop of stops) stop();
56
+ void integration?.close();
57
+ };
58
+ }
59
+
60
+ // Loaded as a side-effect module: start serving as soon as the page loads it.
61
+ serveDiagnostics();
@@ -0,0 +1,51 @@
1
+ /**
2
+ * The RPC functions this package registers on both sides of a devframe connection, declared once so
3
+ * every `rpc.call` / `session.rpc.$call` is type-checked against the same contract. devframe types
4
+ * calls against these two registries; augmenting them is the documented way to add functions.
5
+ */
6
+ import type {
7
+ ActionRequest,
8
+ DiagnosticsEvent,
9
+ ProtocolInfo,
10
+ QueryParams,
11
+ QueryResult,
12
+ SchemaPayload,
13
+ SyncState,
14
+ UploadQueueState
15
+ } from '@powersync/diagnostics-core';
16
+
17
+ /** A database served through the node side. */
18
+ export interface SourceInfo {
19
+ id: string;
20
+ /** A label for the SDK behind it, e.g. `@powersync/web`. */
21
+ sdk: string | null;
22
+ }
23
+
24
+ declare module 'devframe/types' {
25
+ /** Functions the node side serves; called by the UI, by agents over MCP, and by pages announcing a database. */
26
+ interface DevframeRpcServerFunctions {
27
+ 'powersync:sources': () => SourceInfo[];
28
+ 'powersync:query': (params: QueryParams, sourceId?: string | null) => Promise<QueryResult>;
29
+ 'powersync:schema': (sourceId?: string | null) => Promise<SchemaPayload>;
30
+ 'powersync:info': (sourceId?: string | null) => Promise<ProtocolInfo>;
31
+ 'powersync:status': (sourceId?: string | null) => Promise<SyncState | null>;
32
+ 'powersync:upload-queue': (sourceId?: string | null) => Promise<UploadQueueState | null>;
33
+ 'powersync:action': (request: ActionRequest, sourceId?: string | null) => Promise<void>;
34
+ 'powersync:observe': (sourceId?: string | null) => void;
35
+ 'powersync:unobserve': () => void;
36
+ 'powersync:page-register': (sourceId: string, sdk: string | null) => void;
37
+ 'powersync:page-unregister': (sourceId: string) => void;
38
+ 'powersync:page-heartbeat': (sourceId: string) => void;
39
+ 'powersync:page-event': (sourceId: string, event: DiagnosticsEvent) => void;
40
+ }
41
+
42
+ /** Functions a connected page or app serves; called by the node side on the session that announced the database. */
43
+ interface DevframeRpcClientFunctions {
44
+ 'powersync:event': (sourceId: string, event: DiagnosticsEvent) => void;
45
+ 'powersync:sources-changed': (sources: SourceInfo[]) => void;
46
+ 'powersync:page-query': (sourceId: string, params: QueryParams) => Promise<QueryResult>;
47
+ 'powersync:page-schema': (sourceId: string) => Promise<SchemaPayload>;
48
+ 'powersync:page-info': (sourceId: string) => Promise<ProtocolInfo>;
49
+ 'powersync:page-action': (sourceId: string, request: ActionRequest) => Promise<void>;
50
+ }
51
+ }
@@ -0,0 +1,61 @@
1
+ import type { ProgressWithOperations, SyncPriorityStatus, SyncStatus, SyncStreamStatus } from '@powersync/common';
2
+ import type { PriorityState, ProgressState, StreamState, SyncState } from '@powersync/diagnostics-core';
3
+
4
+ /** Maps the SDK's live sync status onto the plain, serializable protocol shapes. */
5
+
6
+ function toProgress(progress: ProgressWithOperations | null | undefined): ProgressState | null {
7
+ if (!progress) {
8
+ return null;
9
+ }
10
+ return {
11
+ downloadedOperations: progress.downloadedOperations,
12
+ totalOperations: progress.totalOperations
13
+ };
14
+ }
15
+
16
+ function toEpoch(date: Date | null | undefined): number | null {
17
+ return date ? date.getTime() : null;
18
+ }
19
+
20
+ function errorText(error: { message?: string } | null | undefined): string | null {
21
+ return error ? String(error.message ?? error) : null;
22
+ }
23
+
24
+ export function toSyncState(status: SyncStatus): SyncState {
25
+ const priorities: PriorityState[] = (status.priorityStatusEntries ?? []).map((entry: SyncPriorityStatus) => ({
26
+ priority: entry.priority,
27
+ lastSyncedAt: toEpoch(entry.lastSyncedAt),
28
+ hasSynced: entry.hasSynced ?? null
29
+ }));
30
+
31
+ return {
32
+ connected: status.connected,
33
+ connecting: status.connecting,
34
+ downloading: status.downloading,
35
+ uploading: status.uploading,
36
+ hasSynced: status.hasSynced ?? null,
37
+ lastSyncedAt: toEpoch(status.lastSyncedAt),
38
+ downloadProgress: toProgress(status.downloadProgress),
39
+ priorities,
40
+ downloadError: errorText(status.downloadError),
41
+ uploadError: errorText(status.uploadError)
42
+ };
43
+ }
44
+
45
+ export function toStreamStates(status: SyncStatus): StreamState[] {
46
+ return (status.syncStreams ?? []).map((stream: SyncStreamStatus) => {
47
+ const subscription = stream.subscription;
48
+ return {
49
+ name: subscription.name,
50
+ priority: stream.priority,
51
+ active: subscription.active,
52
+ autoSubscribed: subscription.isDefault,
53
+ explicitlySubscribed: subscription.hasExplicitSubscription,
54
+ progress: toProgress(stream.progress),
55
+ params: subscription.parameters,
56
+ expiresAt: toEpoch(subscription.expiresAt),
57
+ hasSynced: subscription.hasSynced,
58
+ lastSyncedAt: toEpoch(subscription.lastSyncedAt)
59
+ };
60
+ });
61
+ }