@powersync/diagnostics 0.0.3 → 0.1.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 (40) hide show
  1. package/README.md +50 -2
  2. package/dist/devtools/assets/powersync-CHeJS2lE.js +184 -0
  3. package/dist/devtools/assets/powersync-lB_i3nJt.css +1 -0
  4. package/dist/devtools/powersync.html +24 -0
  5. package/dist/rozenite.json +14 -0
  6. package/lib/src/agent.d.ts +1 -1
  7. package/lib/src/agent.js +32 -4
  8. package/lib/src/agent.js.map +1 -1
  9. package/lib/src/definition.js +11 -17
  10. package/lib/src/definition.js.map +1 -1
  11. package/lib/src/js-agent.d.ts +1 -0
  12. package/lib/src/js-agent.js +16 -2
  13. package/lib/src/js-agent.js.map +1 -1
  14. package/lib/src/react-native/agent-tools.d.ts +3 -0
  15. package/lib/src/react-native/agent-tools.js +137 -0
  16. package/lib/src/react-native/agent-tools.js.map +1 -0
  17. package/lib/src/react-native/protocol.d.ts +22 -0
  18. package/lib/src/react-native/protocol.js +5 -0
  19. package/lib/src/react-native/protocol.js.map +1 -0
  20. package/lib/src/react-native/usePowerSyncDevTools.d.ts +7 -0
  21. package/lib/src/react-native/usePowerSyncDevTools.js +56 -0
  22. package/lib/src/react-native/usePowerSyncDevTools.js.map +1 -0
  23. package/lib/src/react-native.d.ts +7 -0
  24. package/lib/src/react-native.js +8 -0
  25. package/lib/src/react-native.js.map +1 -0
  26. package/lib/src/rpc-types.d.ts +1 -1
  27. package/lib/src/tools.d.ts +19 -0
  28. package/lib/src/tools.js +24 -0
  29. package/lib/src/tools.js.map +1 -0
  30. package/lib/tsconfig.tsbuildinfo +1 -1
  31. package/package.json +32 -9
  32. package/src/agent.ts +39 -4
  33. package/src/definition.ts +11 -17
  34. package/src/js-agent.ts +17 -2
  35. package/src/react-native/agent-tools.ts +148 -0
  36. package/src/react-native/protocol.ts +33 -0
  37. package/src/react-native/usePowerSyncDevTools.ts +59 -0
  38. package/src/react-native.ts +14 -0
  39. package/src/rpc-types.ts +1 -1
  40. package/src/tools.ts +35 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@powersync/diagnostics",
3
- "version": "0.0.3",
3
+ "version": "0.1.1",
4
4
  "description": "PowerSync DevTools: a devframe definition that serves live PowerSync diagnostics as a Vite DevTools dock, a node dev server, and MCP tools.",
5
5
  "type": "module",
6
6
  "main": "lib/src/index.js",
@@ -33,11 +33,16 @@
33
33
  "./agent": {
34
34
  "types": "./lib/src/agent.d.ts",
35
35
  "default": "./lib/src/agent.js"
36
+ },
37
+ "./react-native": {
38
+ "types": "./lib/src/react-native.d.ts",
39
+ "default": "./lib/src/react-native.js"
36
40
  }
37
41
  },
38
42
  "author": "PowerSync",
39
43
  "license": "Apache-2.0",
40
44
  "files": [
45
+ "dist",
41
46
  "lib",
42
47
  "src"
43
48
  ],
@@ -55,8 +60,11 @@
55
60
  "homepage": "https://docs.powersync.com",
56
61
  "peerDependencies": {
57
62
  "@powersync/common": "^2.5.0",
58
- "@powersync/web": "^2.6.0",
63
+ "@powersync/web": "^2.7.0",
64
+ "@rozenite/agent-bridge": "^2.5.0",
65
+ "@rozenite/plugin-bridge": "^2.5.0",
59
66
  "@vitejs/devtools-kit": ">=0.7.5",
67
+ "react": ">=18",
60
68
  "vite": ">=7.0.0"
61
69
  },
62
70
  "peerDependenciesMeta": {
@@ -66,6 +74,15 @@
66
74
  "@powersync/web": {
67
75
  "optional": true
68
76
  },
77
+ "@rozenite/agent-bridge": {
78
+ "optional": true
79
+ },
80
+ "@rozenite/plugin-bridge": {
81
+ "optional": true
82
+ },
83
+ "react": {
84
+ "optional": true
85
+ },
69
86
  "@vitejs/devtools-kit": {
70
87
  "optional": true
71
88
  },
@@ -77,23 +94,29 @@
77
94
  "@devframes/agentic": "^1.2.6",
78
95
  "devframe": "^1.2.6",
79
96
  "zod": "^4.6.5",
80
- "@powersync/diagnostics-core": "0.0.3",
81
- "@powersync/diagnostics-ui": "0.0.3"
97
+ "@powersync/diagnostics-core": "0.0.4",
98
+ "@powersync/diagnostics-ui": "0.0.5"
82
99
  },
83
100
  "devDependencies": {
84
101
  "@devframes/hub": "^1.2.6",
102
+ "@rozenite/agent-bridge": "^2.5.0",
103
+ "@rozenite/plugin-bridge": "^2.5.0",
85
104
  "@types/node": "^24.0.0",
105
+ "@types/react": "19.2.14",
86
106
  "@vitejs/devtools-kit": "^0.7.5",
107
+ "react": "19.3.0",
87
108
  "typescript": "^6.0.3",
88
109
  "vite": "^7.3.6",
110
+ "vue": "3.5.43",
89
111
  "@powersync/common": "2.5.0",
90
- "@powersync/shared-internals": "1.5.0",
91
- "@powersync/web": "2.6.0"
112
+ "@powersync/shared-internals": "1.6.0",
113
+ "@powersync/web": "2.7.0"
92
114
  },
93
115
  "scripts": {
94
- "build": "tsc -b",
95
- "build:prod": "tsc -b",
96
- "clean": "rm -rf lib tsconfig.tsbuildinfo",
116
+ "build": "tsc -b && pnpm build:rozenite",
117
+ "build:prod": "tsc -b && pnpm build:rozenite",
118
+ "build:rozenite": "tsc -p tsconfig.rozenite.json && vite build --config vite.rozenite.config.ts",
119
+ "clean": "rm -rf dist lib tsconfig.tsbuildinfo",
97
120
  "watch": "tsc --build -w"
98
121
  }
99
122
  }
package/src/agent.ts CHANGED
@@ -14,7 +14,9 @@ export type {
14
14
  ActionRequest,
15
15
  AttachIframeOptions,
16
16
  DiagnosticsEvent,
17
+ ProtocolInfo,
17
18
  SdkIntegration,
19
+ StreamDefinition,
18
20
  SyncState
19
21
  } from '@powersync/diagnostics-core';
20
22
 
@@ -41,11 +43,44 @@ class BroadcastCoreEvents implements CoreEventSource {
41
43
  }
42
44
  }
43
45
 
46
+ /** A database that hands core diagnostics events to listeners directly (React Native). */
47
+ interface DiagnosticsListenerDatabase {
48
+ registerDiagnosticsListener(listener: (event: CoreDiagnosticsEvent) => void): () => void;
49
+ }
50
+
51
+ function hasDiagnosticsListener(database: object): database is DiagnosticsListenerDatabase {
52
+ return typeof (database as Partial<DiagnosticsListenerDatabase>).registerDiagnosticsListener === 'function';
53
+ }
54
+
55
+ /** Consumes the core diagnostics events a database hands to its listeners. */
56
+ class ListenerCoreEvents implements CoreEventSource {
57
+ private removers = new Set<Unsubscribe>();
58
+
59
+ constructor(private readonly database: DiagnosticsListenerDatabase) {}
60
+
61
+ onEvent(handler: (event: CoreDiagnosticsEvent) => void): Unsubscribe {
62
+ const remove = this.database.registerDiagnosticsListener(handler);
63
+ this.removers.add(remove);
64
+ return () => {
65
+ this.removers.delete(remove);
66
+ remove();
67
+ };
68
+ }
69
+
70
+ dispose(): void {
71
+ for (const remove of this.removers) remove();
72
+ this.removers.clear();
73
+ }
74
+ }
75
+
76
+ function coreEventSource(database: object): CoreEventSource | undefined {
77
+ if (hasDiagnosticsListener(database)) return new ListenerCoreEvents(database);
78
+ if (typeof BroadcastChannel === 'function') return new BroadcastCoreEvents();
79
+ return undefined;
80
+ }
81
+
44
82
  /** Builds the JavaScript integration over a live database. The agent reads the connection from the database itself. */
45
83
  export function createIntegration(database: CommonPowerSyncDatabase, sdk: string): SdkIntegration {
46
84
  const db = database as BasePowerSyncDatabase;
47
- return new JsAgent(db, {
48
- sdk,
49
- coreEvents: typeof BroadcastChannel === 'function' ? new BroadcastCoreEvents() : undefined
50
- });
85
+ return new JsAgent(db, { sdk, coreEvents: coreEventSource(db) });
51
86
  }
package/src/definition.ts CHANGED
@@ -25,6 +25,7 @@ import type {
25
25
  } from '@powersync/diagnostics-core';
26
26
  import { DEVFRAME_ID, HEARTBEAT_MS, UI_ROUTE } from './constants.js';
27
27
  import type { SetupSdk, SourceInfo } from './rpc-types.js';
28
+ import { ACTION_NAMES, ARGUMENT_DESCRIPTIONS, TOOL_DESCRIPTIONS } from './tools.js';
28
29
 
29
30
  export type { SetupSdk, SourceInfo } from './rpc-types.js';
30
31
 
@@ -250,20 +251,13 @@ const sourceIdArg = z
250
251
  .describe('Id of the attached database, from powersync_sources. Null for the first one.');
251
252
  const queryParamsArg = z
252
253
  .object({
253
- sql: z.string().describe('SQL to run against the local SQLite database.'),
254
- params: z.array(z.unknown()).optional().describe('Positional parameters for `?` placeholders.')
254
+ sql: z.string().describe(ARGUMENT_DESCRIPTIONS.sql),
255
+ params: z.array(z.unknown()).optional().describe(ARGUMENT_DESCRIPTIONS.params)
255
256
  })
256
257
  .describe('The query.');
257
258
  const actionRequestArg = z
258
259
  .object({
259
- action: z.enum([
260
- 'reconnect',
261
- 'disconnect',
262
- 'clearData',
263
- 'requestCheckpoint',
264
- 'subscribeStream',
265
- 'unsubscribeStream'
266
- ]),
260
+ action: z.enum(ACTION_NAMES),
267
261
  args: z
268
262
  .object({
269
263
  name: z.string(),
@@ -272,7 +266,7 @@ const actionRequestArg = z
272
266
  priority: z.union([z.literal(0), z.literal(1), z.literal(2), z.literal(3)]).optional()
273
267
  })
274
268
  .optional()
275
- .describe('Stream name and options, for the stream actions only.')
269
+ .describe(ARGUMENT_DESCRIPTIONS.actionArgs)
276
270
  })
277
271
  .describe('The action to run.');
278
272
  const anyResult = z.unknown();
@@ -391,7 +385,7 @@ export const definition = defineDevframe({
391
385
  returns: anyResult,
392
386
  agent: {
393
387
  description:
394
- 'Run SQL against the attached PowerSync SQLite database. App tables are views; the sync client state is in the ps_* tables (ps_buckets, ps_oplog, ps_crud, ps_stream_subscriptions). Returns columns and rows. Arguments: arg0 = { sql, params? }, arg1 = database id or null for the first one.',
388
+ `${TOOL_DESCRIPTIONS.query} Arguments: arg0 = { sql, params? }, arg1 = database id or null for the first one.`,
395
389
  safety: 'action'
396
390
  },
397
391
  handler: (params, sourceId) => pickSource(sourceId).integration.runQuery(params as QueryParams)
@@ -406,7 +400,7 @@ export const definition = defineDevframe({
406
400
  returns: anyResult,
407
401
  agent: {
408
402
  description:
409
- 'The client schema as the PowerSync SQLite core receives it: tables, columns, indexes. Argument: arg0 = database id or null for the first one.'
403
+ `${TOOL_DESCRIPTIONS.schema} Argument: arg0 = database id or null for the first one.`
410
404
  },
411
405
  handler: (sourceId) => pickSource(sourceId).integration.getSchema()
412
406
  })
@@ -420,7 +414,7 @@ export const definition = defineDevframe({
420
414
  returns: anyResult,
421
415
  agent: {
422
416
  description:
423
- 'Connection info of the PowerSync client: endpoint, user id, client id, connection method, core version. Argument: arg0 = database id or null for the first one.'
417
+ `${TOOL_DESCRIPTIONS.info} Argument: arg0 = database id or null for the first one.`
424
418
  },
425
419
  handler: (sourceId) => pickSource(sourceId).integration.getInfo()
426
420
  })
@@ -434,7 +428,7 @@ export const definition = defineDevframe({
434
428
  returns: anyResult,
435
429
  agent: {
436
430
  description:
437
- 'The latest sync status the PowerSync client reported: connected, downloading, progress, last sync, errors. Null until it has reported. Argument: arg0 = database id or null for the first one.'
431
+ `${TOOL_DESCRIPTIONS.status} Argument: arg0 = database id or null for the first one.`
438
432
  },
439
433
  handler: async (sourceId) => latestSnapshot(sourceId, 'status')
440
434
  })
@@ -448,7 +442,7 @@ export const definition = defineDevframe({
448
442
  returns: anyResult,
449
443
  agent: {
450
444
  description:
451
- 'Pending local changes waiting to upload, as last reported: count and size. Null until reported. Argument: arg0 = database id or null for the first one.'
445
+ `${TOOL_DESCRIPTIONS['upload-queue']} Argument: arg0 = database id or null for the first one.`
452
446
  },
453
447
  handler: async (sourceId) => latestSnapshot(sourceId, 'uploadQueue')
454
448
  })
@@ -462,7 +456,7 @@ export const definition = defineDevframe({
462
456
  returns: anyResult,
463
457
  agent: {
464
458
  description:
465
- 'Run a control action on the PowerSync client: reconnect, disconnect, clearData (wipes local data and re-syncs), requestCheckpoint, subscribeStream, unsubscribeStream. Arguments: arg0 = { action, args? }, arg1 = database id or null for the first one.',
459
+ `${TOOL_DESCRIPTIONS.action} Arguments: arg0 = { action, args? }, arg1 = database id or null for the first one.`,
466
460
  safety: 'destructive'
467
461
  },
468
462
  handler: (request, sourceId) => pickSource(sourceId).integration.action(request as ActionRequest)
package/src/js-agent.ts CHANGED
@@ -23,6 +23,9 @@ import type {
23
23
  import { toStreamStates, toSyncState } from './sync-state.js';
24
24
  import type { BasePowerSyncDatabase, InternalConnector } from '@powersync/shared-internals';
25
25
 
26
+ /** SQL that only reads, so it can run on a read connection. */
27
+ const READ_STATEMENT = /^\s*(select|explain)\b/i;
28
+
26
29
  /** Delivers the SQLite core's diagnostics events to the agent. How they arrive is runtime-specific. */
27
30
  export interface CoreEventSource {
28
31
  onEvent(handler: (event: CoreDiagnosticsEvent) => void): Unsubscribe;
@@ -65,11 +68,19 @@ export class JsAgent implements SdkIntegration {
65
68
  // --- SdkIntegration ---
66
69
 
67
70
  async runQuery({ sql, params }: QueryParams): Promise<QueryResult> {
68
- const records = await this.db.getAll<Record<string, unknown>>(sql, params);
71
+ const records = await this.queryRecords(sql, params);
69
72
  const columns = records.length > 0 ? Object.keys(records[0]) : [];
70
73
  return { columns, rows: records.map((record) => columns.map((column) => record[column])) };
71
74
  }
72
75
 
76
+ // Node and React Native open their read connections read-only, so only plain reads go to one.
77
+ // Everything else (INSERT, UPDATE, DELETE, WITH, PRAGMA, …) runs on the write connection.
78
+ private async queryRecords(sql: string, params?: unknown[]): Promise<Record<string, unknown>[]> {
79
+ if (READ_STATEMENT.test(sql)) return this.db.getAll<Record<string, unknown>>(sql, params);
80
+ const result = await this.db.execute(sql, params);
81
+ return (result.rows?._array ?? []) as Record<string, unknown>[];
82
+ }
83
+
73
84
  async getSchema(): Promise<SchemaPayload> {
74
85
  // The core payload: what the client already sends to `powersync_replace_schema`.
75
86
  return this.db.schema.toJSON() as SchemaPayload;
@@ -148,7 +159,11 @@ export class JsAgent implements SdkIntegration {
148
159
  const { name, params, ttl, priority } = request.args as StreamActionArgs;
149
160
  // TTL defaults to 0 so a forgotten debug subscription is evicted as soon as it is released.
150
161
  const handle = await this.db.syncStream(name, params).subscribe({ ttl: ttl ?? 0, priority });
151
- this.streamHandles.set(streamKey(name, params), handle);
162
+ const key = streamKey(name, params);
163
+ // Subscribing again returns another handle. Releasing the old one after the new one holds the stream
164
+ // keeps a single handle, so Unsubscribe releases the subscription.
165
+ this.streamHandles.get(key)?.unsubscribe();
166
+ this.streamHandles.set(key, handle);
152
167
  break;
153
168
  }
154
169
  case 'unsubscribeStream': {
@@ -0,0 +1,148 @@
1
+ import { useEffect, useRef } from 'react';
2
+ import { useRozenitePluginAgentTool, type AgentTool } from '@rozenite/agent-bridge';
3
+ import type {
4
+ ActionRequest,
5
+ QueryParams,
6
+ SdkIntegration,
7
+ SyncState,
8
+ UploadQueueState
9
+ } from '@powersync/diagnostics-core';
10
+ import { ACTION_NAMES, ARGUMENT_DESCRIPTIONS, TOOL_DESCRIPTIONS } from '../tools.js';
11
+ import { PLUGIN_ID } from './protocol.js';
12
+
13
+ // The same tools the MCP endpoint offers on the web, for Rozenite's agent CLI and SDK.
14
+
15
+ const queryTool: AgentTool = {
16
+ name: 'query',
17
+ description: TOOL_DESCRIPTIONS.query,
18
+ inputSchema: {
19
+ type: 'object',
20
+ properties: {
21
+ sql: { type: 'string', description: ARGUMENT_DESCRIPTIONS.sql },
22
+ params: { type: 'array', description: ARGUMENT_DESCRIPTIONS.params }
23
+ },
24
+ required: ['sql']
25
+ }
26
+ };
27
+
28
+ const schemaTool: AgentTool = {
29
+ name: 'schema',
30
+ description: TOOL_DESCRIPTIONS.schema,
31
+ inputSchema: { type: 'object', properties: {} },
32
+ readOnly: true
33
+ };
34
+
35
+ const infoTool: AgentTool = {
36
+ name: 'info',
37
+ description: TOOL_DESCRIPTIONS.info,
38
+ inputSchema: { type: 'object', properties: {} },
39
+ readOnly: true
40
+ };
41
+
42
+ const statusTool: AgentTool = {
43
+ name: 'status',
44
+ description: TOOL_DESCRIPTIONS.status,
45
+ inputSchema: { type: 'object', properties: {} },
46
+ readOnly: true
47
+ };
48
+
49
+ const uploadQueueTool: AgentTool = {
50
+ name: 'upload-queue',
51
+ description: TOOL_DESCRIPTIONS['upload-queue'],
52
+ inputSchema: { type: 'object', properties: {} },
53
+ readOnly: true
54
+ };
55
+
56
+ const actionTool: AgentTool = {
57
+ name: 'action',
58
+ description: TOOL_DESCRIPTIONS.action,
59
+ inputSchema: {
60
+ type: 'object',
61
+ properties: {
62
+ action: {
63
+ type: 'string',
64
+ enum: ACTION_NAMES
65
+ },
66
+ args: {
67
+ type: 'object',
68
+ description: ARGUMENT_DESCRIPTIONS.actionArgs
69
+ }
70
+ },
71
+ required: ['action']
72
+ },
73
+ destructive: true
74
+ };
75
+
76
+ function requireIntegration(integration: SdkIntegration | null): SdkIntegration {
77
+ if (!integration) throw new Error('The PowerSync database is not attached yet.');
78
+ return integration;
79
+ }
80
+
81
+ /** Registers the PowerSync agent tools for one database. */
82
+ export function usePowerSyncAgentTools(integration: SdkIntegration | null): void {
83
+ const latest = useRef<{ status: SyncState | null; uploadQueue: UploadQueueState | null }>({
84
+ status: null,
85
+ uploadQueue: null
86
+ });
87
+
88
+ // The status tools answer from the latest pushed snapshots, as the MCP tools do.
89
+ useEffect(() => {
90
+ if (!integration) return;
91
+ let stop: (() => void) | null = null;
92
+ let cancelled = false;
93
+ void integration
94
+ .observeEvents((event) => {
95
+ if (event.type === 'status') latest.current.status = event.payload;
96
+ if (event.type === 'uploadQueue') latest.current.uploadQueue = event.payload;
97
+ })
98
+ .then((unsubscribe) => {
99
+ if (cancelled) unsubscribe();
100
+ else stop = unsubscribe;
101
+ });
102
+ return () => {
103
+ cancelled = true;
104
+ stop?.();
105
+ };
106
+ }, [integration]);
107
+
108
+ const enabled = integration != null;
109
+ useRozenitePluginAgentTool({
110
+ pluginId: PLUGIN_ID,
111
+ tool: queryTool,
112
+ enabled,
113
+ handler: (params: QueryParams) => requireIntegration(integration).runQuery(params)
114
+ });
115
+ useRozenitePluginAgentTool({
116
+ pluginId: PLUGIN_ID,
117
+ tool: schemaTool,
118
+ enabled,
119
+ handler: () => requireIntegration(integration).getSchema()
120
+ });
121
+ useRozenitePluginAgentTool({
122
+ pluginId: PLUGIN_ID,
123
+ tool: infoTool,
124
+ enabled,
125
+ handler: () => requireIntegration(integration).getInfo()
126
+ });
127
+ useRozenitePluginAgentTool({
128
+ pluginId: PLUGIN_ID,
129
+ tool: statusTool,
130
+ enabled,
131
+ handler: () => latest.current.status
132
+ });
133
+ useRozenitePluginAgentTool({
134
+ pluginId: PLUGIN_ID,
135
+ tool: uploadQueueTool,
136
+ enabled,
137
+ handler: () => latest.current.uploadQueue
138
+ });
139
+ useRozenitePluginAgentTool({
140
+ pluginId: PLUGIN_ID,
141
+ tool: actionTool,
142
+ enabled,
143
+ handler: async (request: ActionRequest) => {
144
+ await requireIntegration(integration).action(request);
145
+ return { ok: true };
146
+ }
147
+ });
148
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The contract between the app side (`usePowerSyncDevTools`) and the DevTools panel, carried over a
3
+ * Rozenite plugin channel. Calls go over Rozenite RPC; pushed events go as plain plugin messages.
4
+ */
5
+ import type {
6
+ ActionRequest,
7
+ DiagnosticsEvent,
8
+ ProtocolInfo,
9
+ QueryParams,
10
+ QueryResult,
11
+ SchemaPayload
12
+ } from '@powersync/diagnostics-core';
13
+
14
+ /** The Rozenite plugin id. Rozenite finds the plugin by this package name. */
15
+ export const PLUGIN_ID = '@powersync/diagnostics';
16
+
17
+ /** The message type that carries one {@link DiagnosticsEvent} from the app to the panel. */
18
+ export const EVENT_MESSAGE = 'powersync:event';
19
+
20
+ /** Plugin messages, keyed by type. */
21
+ export type DevToolsEventMap = {
22
+ [EVENT_MESSAGE]: DiagnosticsEvent;
23
+ };
24
+
25
+ /** Methods the app serves to the panel. */
26
+ export type AppMethods = {
27
+ runQuery: (params: QueryParams) => Promise<QueryResult>;
28
+ getSchema: () => Promise<SchemaPayload>;
29
+ getInfo: () => Promise<ProtocolInfo>;
30
+ action: (request: ActionRequest) => Promise<void>;
31
+ /** Starts (or restarts) the event stream; the app pushes the current snapshots first. */
32
+ subscribe: () => Promise<void>;
33
+ };
@@ -0,0 +1,59 @@
1
+ import { useEffect, useState } from 'react';
2
+ import { createRozeniteRpc, useRozeniteDevToolsClient } from '@rozenite/plugin-bridge';
3
+ import type { CommonPowerSyncDatabase } from '@powersync/common';
4
+ import type { SdkIntegration, Unsubscribe } from '@powersync/diagnostics-core';
5
+ import { createIntegration } from '../agent.js';
6
+ import { usePowerSyncAgentTools } from './agent-tools.js';
7
+ import { EVENT_MESSAGE, PLUGIN_ID, type AppMethods, type DevToolsEventMap } from './protocol.js';
8
+
9
+ const SDK = '@powersync/react-native';
10
+
11
+ /**
12
+ * Serves `database` to the PowerSync panel in React Native DevTools (through Rozenite), and to coding
13
+ * agents as Rozenite agent tools. Call it in a component that stays mounted, such as the app root.
14
+ * Pass `null` while the database is not created yet; DevTools attach once it is.
15
+ */
16
+ export function usePowerSyncDevTools(database: CommonPowerSyncDatabase | null): void {
17
+ const client = useRozeniteDevToolsClient<DevToolsEventMap>({ pluginId: PLUGIN_ID });
18
+ const [integration, setIntegration] = useState<SdkIntegration | null>(null);
19
+
20
+ useEffect(() => {
21
+ if (!database) return;
22
+ const created = createIntegration(database, SDK);
23
+ setIntegration(created);
24
+ return () => {
25
+ setIntegration(null);
26
+ void created.close();
27
+ };
28
+ }, [database]);
29
+
30
+ useEffect(() => {
31
+ if (!client || !integration) return;
32
+ const rpc = createRozeniteRpc<AppMethods>(client);
33
+ let stopEvents: Unsubscribe | null = null;
34
+ let closed = false;
35
+
36
+ const handlers = [
37
+ rpc.handle('runQuery', (params) => integration.runQuery(params)),
38
+ rpc.handle('getSchema', () => integration.getSchema()),
39
+ rpc.handle('getInfo', () => integration.getInfo()),
40
+ rpc.handle('action', (request) => integration.action(request)),
41
+ // A panel (re)opening asks for the stream; restarting it replays the current snapshots.
42
+ rpc.handle('subscribe', async () => {
43
+ stopEvents?.();
44
+ const unsubscribe = await integration.observeEvents((event) => client.send(EVENT_MESSAGE, event));
45
+ if (closed) unsubscribe();
46
+ else stopEvents = unsubscribe;
47
+ })
48
+ ];
49
+
50
+ return () => {
51
+ closed = true;
52
+ for (const handler of handlers) handler.remove();
53
+ stopEvents?.();
54
+ rpc.close();
55
+ };
56
+ }, [client, integration]);
57
+
58
+ usePowerSyncAgentTools(integration);
59
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * PowerSync DevTools for React Native apps, as a Rozenite plugin: a panel in React Native DevTools and
3
+ * agent tools for Rozenite's agent CLI. Production bundles get a no-op: the `require` below sits
4
+ * behind a check bundlers resolve at build time, so the DevTools code is left out.
5
+ */
6
+ import type { CommonPowerSyncDatabase } from '@powersync/common';
7
+
8
+ export let usePowerSyncDevTools: (database: CommonPowerSyncDatabase | null) => void;
9
+
10
+ if (process.env.NODE_ENV !== 'production') {
11
+ usePowerSyncDevTools = require('./react-native/usePowerSyncDevTools.js').usePowerSyncDevTools;
12
+ } else {
13
+ usePowerSyncDevTools = () => {};
14
+ }
package/src/rpc-types.ts CHANGED
@@ -22,7 +22,7 @@ export interface SourceInfo {
22
22
  }
23
23
 
24
24
  /** An SDK the UI's "no database" screens can explain, the same names the UI takes as `sdks`. */
25
- export type SetupSdk = 'web' | 'nuxt' | 'node' | 'dart';
25
+ export type SetupSdk = 'web' | 'nuxt' | 'node' | 'react-native' | 'dart';
26
26
 
27
27
  declare module 'devframe/types' {
28
28
  /** Functions the node side serves; called by the UI, by agents over MCP, and by pages announcing a database. */
package/src/tools.ts ADDED
@@ -0,0 +1,35 @@
1
+ /**
2
+ * The agent tools every host offers: the devframe MCP functions and the Rozenite agent tools. Each host
3
+ * adds how its arguments are passed; the names and descriptions stay the same.
4
+ */
5
+ import type { ActionName } from '@powersync/diagnostics-core';
6
+
7
+ // A record, so a new action name fails to compile until it is listed here.
8
+ const actions: Record<ActionName, true> = {
9
+ reconnect: true,
10
+ disconnect: true,
11
+ clearData: true,
12
+ requestCheckpoint: true,
13
+ subscribeStream: true,
14
+ unsubscribeStream: true
15
+ };
16
+
17
+ export const ACTION_NAMES = Object.keys(actions) as [ActionName, ...ActionName[]];
18
+
19
+ export const TOOL_DESCRIPTIONS = {
20
+ query:
21
+ 'Run SQL against the PowerSync SQLite database. App tables are views; the sync client state is in the ps_* tables (ps_buckets, ps_oplog, ps_crud, ps_stream_subscriptions). Returns columns and rows.',
22
+ schema: 'The client schema as the PowerSync SQLite core receives it: tables, columns, indexes.',
23
+ info: 'Connection info of the PowerSync client: endpoint, user id, client id, connection method, core version.',
24
+ status:
25
+ 'The latest sync status the PowerSync client reported: connected, downloading, progress, last sync, errors. Null until it has reported.',
26
+ 'upload-queue': 'Pending local changes waiting to upload, as last reported: count and size. Null until reported.',
27
+ action:
28
+ 'Run a control action on the PowerSync client: reconnect, disconnect, clearData (wipes local data and re-syncs), requestCheckpoint, subscribeStream, unsubscribeStream.'
29
+ } as const;
30
+
31
+ export const ARGUMENT_DESCRIPTIONS = {
32
+ sql: 'SQL to run against the local SQLite database.',
33
+ params: 'Positional parameters for `?` placeholders.',
34
+ actionArgs: 'Stream name and options, for subscribeStream and unsubscribeStream only: { name, params?, ttl?, priority? }.'
35
+ } as const;