rocketride 1.0.6 → 1.1.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 (159) hide show
  1. package/README.md +2 -2
  2. package/dist/cjs/account.js +284 -0
  3. package/dist/cjs/account.js.map +1 -0
  4. package/dist/cjs/billing.js +171 -0
  5. package/dist/cjs/billing.js.map +1 -0
  6. package/dist/cjs/client.js +1208 -756
  7. package/dist/cjs/client.js.map +1 -1
  8. package/dist/cjs/constants.js +10 -1
  9. package/dist/cjs/constants.js.map +1 -1
  10. package/dist/cjs/core/DAPBase.js +4 -1
  11. package/dist/cjs/core/DAPBase.js.map +1 -1
  12. package/dist/cjs/core/DAPClient.js +121 -50
  13. package/dist/cjs/core/DAPClient.js.map +1 -1
  14. package/dist/cjs/core/TransportBase.js +0 -10
  15. package/dist/cjs/core/TransportBase.js.map +1 -1
  16. package/dist/cjs/core/TransportWebSocket.js +30 -19
  17. package/dist/cjs/core/TransportWebSocket.js.map +1 -1
  18. package/dist/cjs/database.js +121 -0
  19. package/dist/cjs/database.js.map +1 -0
  20. package/dist/cjs/index.js +4 -0
  21. package/dist/cjs/index.js.map +1 -1
  22. package/dist/cjs/schema/Question.js +2 -0
  23. package/dist/cjs/schema/Question.js.map +1 -1
  24. package/dist/cjs/types/account.js +26 -0
  25. package/dist/cjs/types/account.js.map +1 -0
  26. package/dist/cjs/types/billing.js +26 -0
  27. package/dist/cjs/types/billing.js.map +1 -0
  28. package/dist/cjs/types/client.js +14 -0
  29. package/dist/cjs/types/client.js.map +1 -1
  30. package/dist/cjs/types/cprofile.js +26 -0
  31. package/dist/cjs/types/cprofile.js.map +1 -0
  32. package/dist/cjs/types/dashboard.js +26 -0
  33. package/dist/cjs/types/dashboard.js.map +1 -0
  34. package/dist/cjs/types/events.js +5 -1
  35. package/dist/cjs/types/events.js.map +1 -1
  36. package/dist/cjs/types/index.js +5 -0
  37. package/dist/cjs/types/index.js.map +1 -1
  38. package/dist/cjs/types/service.js +85 -0
  39. package/dist/cjs/types/service.js.map +1 -0
  40. package/dist/cli/cli/rocketride.js +335 -113
  41. package/dist/cli/cli/rocketride.js.map +1 -1
  42. package/dist/cli/client/account.js +284 -0
  43. package/dist/cli/client/account.js.map +1 -0
  44. package/dist/cli/client/billing.js +171 -0
  45. package/dist/cli/client/billing.js.map +1 -0
  46. package/dist/cli/client/client.js +1208 -756
  47. package/dist/cli/client/client.js.map +1 -1
  48. package/dist/cli/client/constants.js +10 -1
  49. package/dist/cli/client/constants.js.map +1 -1
  50. package/dist/cli/client/core/DAPBase.js +4 -1
  51. package/dist/cli/client/core/DAPBase.js.map +1 -1
  52. package/dist/cli/client/core/DAPClient.js +121 -50
  53. package/dist/cli/client/core/DAPClient.js.map +1 -1
  54. package/dist/cli/client/core/TransportBase.js +0 -10
  55. package/dist/cli/client/core/TransportBase.js.map +1 -1
  56. package/dist/cli/client/core/TransportWebSocket.js +30 -19
  57. package/dist/cli/client/core/TransportWebSocket.js.map +1 -1
  58. package/dist/cli/client/database.js +121 -0
  59. package/dist/cli/client/database.js.map +1 -0
  60. package/dist/cli/client/index.js +4 -0
  61. package/dist/cli/client/index.js.map +1 -1
  62. package/dist/cli/client/schema/Question.js +2 -0
  63. package/dist/cli/client/schema/Question.js.map +1 -1
  64. package/dist/cli/client/types/account.js +26 -0
  65. package/dist/cli/client/types/account.js.map +1 -0
  66. package/dist/cli/client/types/billing.js +26 -0
  67. package/dist/cli/client/types/billing.js.map +1 -0
  68. package/dist/cli/client/types/client.js +14 -0
  69. package/dist/cli/client/types/client.js.map +1 -1
  70. package/dist/cli/client/types/cprofile.js +26 -0
  71. package/dist/cli/client/types/cprofile.js.map +1 -0
  72. package/dist/cli/client/types/dashboard.js +26 -0
  73. package/dist/cli/client/types/dashboard.js.map +1 -0
  74. package/dist/cli/client/types/events.js +5 -1
  75. package/dist/cli/client/types/events.js.map +1 -1
  76. package/dist/cli/client/types/index.js +5 -0
  77. package/dist/cli/client/types/index.js.map +1 -1
  78. package/dist/cli/client/types/service.js +85 -0
  79. package/dist/cli/client/types/service.js.map +1 -0
  80. package/dist/esm/account.js +280 -0
  81. package/dist/esm/account.js.map +1 -0
  82. package/dist/esm/billing.js +167 -0
  83. package/dist/esm/billing.js.map +1 -0
  84. package/dist/esm/client.js +1208 -756
  85. package/dist/esm/client.js.map +1 -1
  86. package/dist/esm/constants.js +9 -0
  87. package/dist/esm/constants.js.map +1 -1
  88. package/dist/esm/core/DAPBase.js +4 -1
  89. package/dist/esm/core/DAPBase.js.map +1 -1
  90. package/dist/esm/core/DAPClient.js +121 -50
  91. package/dist/esm/core/DAPClient.js.map +1 -1
  92. package/dist/esm/core/TransportBase.js +0 -10
  93. package/dist/esm/core/TransportBase.js.map +1 -1
  94. package/dist/esm/core/TransportWebSocket.js +30 -19
  95. package/dist/esm/core/TransportWebSocket.js.map +1 -1
  96. package/dist/esm/database.js +117 -0
  97. package/dist/esm/database.js.map +1 -0
  98. package/dist/esm/index.js +4 -0
  99. package/dist/esm/index.js.map +1 -1
  100. package/dist/esm/schema/Question.js +2 -0
  101. package/dist/esm/schema/Question.js.map +1 -1
  102. package/dist/esm/types/account.js +25 -0
  103. package/dist/esm/types/account.js.map +1 -0
  104. package/dist/esm/types/billing.js +25 -0
  105. package/dist/esm/types/billing.js.map +1 -0
  106. package/dist/esm/types/client.js +13 -1
  107. package/dist/esm/types/client.js.map +1 -1
  108. package/dist/esm/types/cprofile.js +25 -0
  109. package/dist/esm/types/cprofile.js.map +1 -0
  110. package/dist/esm/types/dashboard.js +25 -0
  111. package/dist/esm/types/dashboard.js.map +1 -0
  112. package/dist/esm/types/events.js +5 -1
  113. package/dist/esm/types/events.js.map +1 -1
  114. package/dist/esm/types/index.js +5 -0
  115. package/dist/esm/types/index.js.map +1 -1
  116. package/dist/esm/types/service.js +82 -0
  117. package/dist/esm/types/service.js.map +1 -0
  118. package/dist/types/account.d.ts +209 -0
  119. package/dist/types/account.d.ts.map +1 -0
  120. package/dist/types/billing.d.ts +135 -0
  121. package/dist/types/billing.d.ts.map +1 -0
  122. package/dist/types/client.d.ts +553 -285
  123. package/dist/types/client.d.ts.map +1 -1
  124. package/dist/types/constants.d.ts +9 -0
  125. package/dist/types/constants.d.ts.map +1 -1
  126. package/dist/types/core/DAPBase.d.ts.map +1 -1
  127. package/dist/types/core/DAPClient.d.ts +89 -7
  128. package/dist/types/core/DAPClient.d.ts.map +1 -1
  129. package/dist/types/core/TransportBase.d.ts +1 -11
  130. package/dist/types/core/TransportBase.d.ts.map +1 -1
  131. package/dist/types/core/TransportWebSocket.d.ts +14 -11
  132. package/dist/types/core/TransportWebSocket.d.ts.map +1 -1
  133. package/dist/types/database.d.ts +90 -0
  134. package/dist/types/database.d.ts.map +1 -0
  135. package/dist/types/index.d.ts +2 -0
  136. package/dist/types/index.d.ts.map +1 -1
  137. package/dist/types/schema/Question.d.ts +3 -1
  138. package/dist/types/schema/Question.d.ts.map +1 -1
  139. package/dist/types/types/account.d.ts +171 -0
  140. package/dist/types/types/account.d.ts.map +1 -0
  141. package/dist/types/types/billing.d.ts +115 -0
  142. package/dist/types/types/billing.d.ts.map +1 -0
  143. package/dist/types/types/client.d.ts +241 -1
  144. package/dist/types/types/client.d.ts.map +1 -1
  145. package/dist/types/types/cprofile.d.ts +67 -0
  146. package/dist/types/types/cprofile.d.ts.map +1 -0
  147. package/dist/types/types/dashboard.d.ts +198 -0
  148. package/dist/types/types/dashboard.d.ts.map +1 -0
  149. package/dist/types/types/events.d.ts +90 -95
  150. package/dist/types/types/events.d.ts.map +1 -1
  151. package/dist/types/types/index.d.ts +5 -0
  152. package/dist/types/types/index.d.ts.map +1 -1
  153. package/dist/types/types/pipeline.d.ts +10 -2
  154. package/dist/types/types/pipeline.d.ts.map +1 -1
  155. package/dist/types/types/service.d.ts +189 -0
  156. package/dist/types/types/service.d.ts.map +1 -0
  157. package/dist/types/types/task.d.ts +5 -1
  158. package/dist/types/types/task.d.ts.map +1 -1
  159. package/package.json +12 -7
@@ -26,8 +26,12 @@ Object.defineProperty(exports, "__esModule", { value: true });
26
26
  exports.default = exports.RocketRideClient = exports.DataPipe = void 0;
27
27
  const TransportWebSocket_js_1 = require("./core/TransportWebSocket.js");
28
28
  const DAPClient_js_1 = require("./core/DAPClient.js");
29
+ const index_js_1 = require("./types/index.js");
29
30
  const constants_js_1 = require("./constants.js");
30
- const index_js_1 = require("./exceptions/index.js");
31
+ const account_js_1 = require("./account.js");
32
+ const billing_js_1 = require("./billing.js");
33
+ const database_js_1 = require("./database.js");
34
+ const index_js_2 = require("./exceptions/index.js");
31
35
  // Global counter for generating unique client IDs
32
36
  let clientId = 0;
33
37
  /**
@@ -100,7 +104,8 @@ class DataPipe {
100
104
  * unique pipe ID that is used for subsequent operations.
101
105
  *
102
106
  * @returns This DataPipe instance (for method chaining)
103
- * @throws Error if the pipe is already opened or if the pipeline is not running
107
+ * @throws Error if the pipe is already opened
108
+ * @throws PipeException if the server rejects the open request
104
109
  */
105
110
  async open() {
106
111
  if (this._opened) {
@@ -117,15 +122,32 @@ class DataPipe {
117
122
  });
118
123
  const response = await this._client.request(request);
119
124
  if (this._client.didFail(response)) {
120
- throw new Error(response.message || 'Your pipeline is not currently running.');
125
+ const base = response.message || 'Failed to open a data pipe.';
126
+ const msg = `${base}\n\n` + 'Common causes:\n' + "- Pipeline isn't running (wrong token or task terminated)\n" + "- Pipeline source is 'chat' (use client.chat()), not webhook/dropper\n" + "- MIME type doesn't match the source lane (try mimeType='text/plain')\n";
127
+ throw new index_js_2.PipeException({ ...response, message: msg });
121
128
  }
122
129
  this._pipeId = response.body?.pipe_id;
123
- this._opened = true;
124
130
  // If an SSE callback was provided, subscribe and register for this pipe
125
131
  if (this._onSSE !== undefined && this._pipeId !== undefined) {
126
- await this._client.setEvents(this._token, ['SSE'], this._pipeId);
132
+ try {
133
+ await this._client.setEvents(this._token, ['SSE'], this._pipeId);
134
+ }
135
+ catch (err) {
136
+ // Roll back: don't leave the pipe half-open on the server.
137
+ try {
138
+ await this.close();
139
+ }
140
+ catch {
141
+ // Best-effort cleanup
142
+ }
143
+ const errMsg = err instanceof Error ? err.message : String(err);
144
+ const msg = `Failed to subscribe to SSE events for this data pipe.\n\n${errMsg}`;
145
+ throw new index_js_2.PipeException({ message: msg });
146
+ }
127
147
  this._client._ssePipeCallbacks.set(this._pipeId, this._onSSE);
128
148
  }
149
+ // Only mark opened after the server-side pipe is fully consistent (including SSE setup).
150
+ this._opened = true;
129
151
  return this;
130
152
  }
131
153
  /**
@@ -135,7 +157,8 @@ class DataPipe {
135
157
  * multiple times to stream large datasets. The pipe must be opened first.
136
158
  *
137
159
  * @param buffer - Data to write, must be a Uint8Array
138
- * @throws Error if the pipe is not opened, buffer is invalid, or write fails
160
+ * @throws Error if the pipe is not opened or buffer is invalid
161
+ * @throws PipeException if the server reports a write failure
139
162
  */
140
163
  async write(buffer) {
141
164
  if (!this._opened) {
@@ -154,7 +177,8 @@ class DataPipe {
154
177
  });
155
178
  const response = await this._client.request(request);
156
179
  if (this._client.didFail(response)) {
157
- throw new Error(response.message || 'Failed to write to pipe');
180
+ const msg = response.message || 'Failed to write to a data pipe.';
181
+ throw new index_js_2.PipeException({ ...response, message: msg });
158
182
  }
159
183
  }
160
184
  /**
@@ -165,10 +189,12 @@ class DataPipe {
165
189
  * the pipe cannot be reopened or written to again.
166
190
  *
167
191
  * @returns The processing result from the server, or undefined if already closed
168
- * @throws Error if closing the pipe fails
192
+ * @throws PipeException if the server reports a failure while finalizing the pipe
169
193
  */
170
194
  async close() {
171
- if (!this._opened || this._closed) {
195
+ // Allow closing after a failed open() path where the server assigned a pipe_id
196
+ // but we never flipped _opened=true (e.g., SSE subscription failure).
197
+ if (this._closed || (this._pipeId === undefined && !this._opened)) {
172
198
  return;
173
199
  }
174
200
  try {
@@ -181,12 +207,14 @@ class DataPipe {
181
207
  });
182
208
  const response = await this._client.request(request);
183
209
  if (this._client.didFail(response)) {
184
- throw new Error(response.message || 'Failed to close pipe');
210
+ const msg = response.message || 'Failed to close a data pipe.';
211
+ throw new index_js_2.PipeException({ ...response, message: msg });
185
212
  }
186
213
  return response.body;
187
214
  }
188
215
  finally {
189
216
  this._closed = true;
217
+ this._opened = false;
190
218
  // Unregister SSE callback and scoped monitor subscription
191
219
  if (this._onSSE !== undefined && this._pipeId !== undefined) {
192
220
  this._client._ssePipeCallbacks.delete(this._pipeId);
@@ -201,24 +229,6 @@ class DataPipe {
201
229
  }
202
230
  }
203
231
  exports.DataPipe = DataPipe;
204
- /**
205
- * Main RocketRide client for connecting to RocketRide servers and services.
206
- *
207
- * This client provides a comprehensive API for interacting with RocketRide services,
208
- * including connection management, pipeline execution, data operations, AI chat,
209
- * event handling, and server connectivity testing.
210
- *
211
- * Key features:
212
- * - Single shared WebSocket connection for all operations
213
- * - Connection management (connect/disconnect) with optional persistence
214
- * - Automatic reconnection when persist mode is enabled
215
- * - Pipeline execution (use, terminate, getTaskStatus)
216
- * - Data operations (send, sendFiles, pipe)
217
- * - AI chat functionality (chat)
218
- * - Event handling (setEvents, event callbacks)
219
- * - Server connectivity testing (ping)
220
- * - Full TypeScript type safety
221
- */
222
232
  class RocketRideClient extends DAPClient_js_1.DAPClient {
223
233
  /**
224
234
  * Creates a new RocketRideClient instance.
@@ -281,24 +291,26 @@ class RocketRideClient extends DAPClient_js_1.DAPClient {
281
291
  }
282
292
  }
283
293
  }
284
- const { auth = config.auth || clientEnv.ROCKETRIDE_APIKEY, uri = config.uri || clientEnv.ROCKETRIDE_URI || constants_js_1.CONST_DEFAULT_WEB_CLOUD, onEvent, onConnected, onDisconnected, onConnectError, persist, maxRetryTime, module, } = config;
294
+ const { auth = config.auth, uri = config.uri || clientEnv.ROCKETRIDE_URI || constants_js_1.CONST_DEFAULT_WEB_CLOUD, onEvent, onConnected, onDisconnected, onConnectError, persist, module } = config;
285
295
  // Create unique client identifier
286
296
  const clientName = module || `CLIENT-${clientId++}`;
287
- // Initialize the DAPClient without a transport; transport is created in _internalConnect (CONNECTION_LOGIC.md §3)
297
+ // Initialize the DAPClient without a transport; transport is created in _internalAttach
288
298
  super(clientName, undefined, config);
289
299
  this._dapAttempted = false;
290
300
  this._nextChatId = 1;
291
301
  /** Maps pipe_id → SSE callback for pipe-scoped real-time event dispatch. */
292
302
  this._ssePipeCallbacks = new Map();
293
- // Persistence properties for automatic reconnection
303
+ // Desired state model replaces old flag soup
304
+ this._desiredState = 'detached';
305
+ this._authenticated = false;
294
306
  this._persist = false;
295
- this._manualDisconnect = false;
296
307
  this._currentReconnectDelay = 250;
297
- /** True after onConnected has been invoked; used to only invoke onDisconnected when we had a connection. */
298
- this._didNotifyConnected = false;
308
+ /** Reference-counted monitor subscriptions: keyString Map<eventType, refCount> */
309
+ this._monitorKeys = new Map();
299
310
  // Store connection details and environment
311
+ this._wsPath = config.wsPath;
300
312
  this._setUri(uri);
301
- this._setAuth(auth);
313
+ this._setAuth(auth ?? '');
302
314
  this._env = clientEnv;
303
315
  // Set up callbacks if provided
304
316
  if (onEvent)
@@ -309,9 +321,11 @@ class RocketRideClient extends DAPClient_js_1.DAPClient {
309
321
  this._callerOnDisconnected = onDisconnected;
310
322
  if (onConnectError)
311
323
  this._callerOnConnectError = onConnectError;
324
+ if (config.onTrace)
325
+ this._onTrace = config.onTrace;
312
326
  // Set up persistence options
313
327
  this._persist = persist ?? false;
314
- this._maxRetryTime = maxRetryTime;
328
+ // maxRetryTime accepted for backward compat but ignored (linear backoff never gives up)
315
329
  }
316
330
  /**
317
331
  * Normalize a user-provided URI into a fully-formed HTTP/HTTPS URL.
@@ -329,7 +343,16 @@ class RocketRideClient extends DAPClient_js_1.DAPClient {
329
343
  }
330
344
  try {
331
345
  const url = new URL(normalized);
332
- if (!url.port && !url.hostname.includes('rocketride.ai')) {
346
+ // The URL API silently strips ports that are default-for-scheme
347
+ // (e.g. :443 on https, :80 on http), so url.port alone cannot
348
+ // distinguish "no port given" from "scheme-default port given".
349
+ // Check the raw input for an explicit `:digits` after the scheme.
350
+ const withoutScheme = normalized.replace(/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//, '');
351
+ const authority = withoutScheme.split(/[/?#]/, 1)[0] ?? '';
352
+ const hasExplicitPort = authority.startsWith('[')
353
+ ? /\]:\d+$/.test(authority) // IPv6 literal with explicit port
354
+ : /:\d+$/.test(authority); // hostname/IPv4 with explicit port
355
+ if (!url.port && !hasExplicitPort && !url.hostname.includes('rocketride.ai')) {
333
356
  url.port = constants_js_1.CONST_DEFAULT_WEB_PORT;
334
357
  }
335
358
  return `${url.protocol}//${url.host}`;
@@ -338,19 +361,57 @@ class RocketRideClient extends DAPClient_js_1.DAPClient {
338
361
  return normalized;
339
362
  }
340
363
  }
364
+ /**
365
+ * Probe a server for its capabilities without authenticating.
366
+ *
367
+ * Creates a temporary public connection and sends an
368
+ * ``rrext_public_probe`` command. The server responds with version,
369
+ * capabilities, platform, and public apps without requiring credentials.
370
+ *
371
+ * @param uri - Server URI (e.g. ``"localhost:5565"``, ``"https://cloud.rocketride.ai"``)
372
+ * @param timeout - Optional timeout in ms for the entire operation
373
+ * @returns Server info including version and capability tags
374
+ * @throws Error if the server is unreachable or does not support probes
375
+ *
376
+ * @example
377
+ * ```typescript
378
+ * const info = await RocketRideClient.getServerInfo('localhost:5565');
379
+ * if (info.capabilities.includes('saas')) {
380
+ * // Show cloud sign-in options
381
+ * }
382
+ * ```
383
+ */
384
+ static async getServerInfo(uri, timeout) {
385
+ const client = new RocketRideClient({ uri, persist: false });
386
+ try {
387
+ // Open a public connection (no auth handshake)
388
+ await client.attach(uri, { timeout });
389
+ // Send rrext_public_probe — allowed on unauthenticated connections
390
+ const message = client.buildRequest('rrext_public_probe', {});
391
+ const response = await client.request(message, timeout);
392
+ if (response.success === false) {
393
+ throw new Error(response.message || 'Server info request failed');
394
+ }
395
+ return (response.body ?? {});
396
+ }
397
+ finally {
398
+ await client.disconnect();
399
+ }
400
+ }
341
401
  /**
342
402
  * Normalize a user-provided URI into a fully-formed WebSocket address.
343
403
  * Builds on normalizeUri, then converts to ws/wss and appends /task/service.
344
404
  */
345
405
  _getWebsocketUri(uri) {
346
406
  const httpUrl = RocketRideClient.normalizeUri(uri);
407
+ const path = this._wsPath ?? '/task/service';
347
408
  try {
348
409
  const url = new URL(httpUrl);
349
- const wsScheme = (url.protocol === 'https:' || url.protocol === 'wss:') ? 'wss:' : 'ws:';
350
- return `${wsScheme}//${url.host}/task/service`;
410
+ const wsScheme = url.protocol === 'https:' || url.protocol === 'wss:' ? 'wss:' : 'ws:';
411
+ return `${wsScheme}//${url.host}${path}`;
351
412
  }
352
413
  catch {
353
- return `${httpUrl}/task/service`;
414
+ return `${httpUrl}${path}`;
354
415
  }
355
416
  }
356
417
  /**
@@ -365,182 +426,318 @@ class RocketRideClient extends DAPClient_js_1.DAPClient {
365
426
  _setAuth(auth) {
366
427
  this._apikey = auth;
367
428
  }
368
- /**
369
- * Clear any pending reconnection timeout.
370
- */
371
- _clearReconnectTimeout() {
372
- if (this._reconnectTimeout) {
373
- clearTimeout(this._reconnectTimeout);
374
- this._reconnectTimeout = undefined;
375
- }
376
- }
377
429
  // ============================================================================
378
- // CONNECTION METHODS
430
+ // INTERNAL CONNECTION HELPERS
379
431
  // ============================================================================
380
432
  /**
381
- * Single place for physical connection. Creates transport if needed, then
382
- * calls DAPClient.connect (transport connect + auth handshake + onConnected).
433
+ * Create transport if needed and open the WebSocket. No auth.
383
434
  */
384
- async _internalConnect(timeout) {
435
+ async _internalAttach(timeout) {
385
436
  if (!this._transport) {
386
- const transport = new TransportWebSocket_js_1.TransportWebSocket(this._uri, this._apikey);
437
+ const transport = new TransportWebSocket_js_1.TransportWebSocket(this._uri);
387
438
  this._bindTransport(transport);
388
439
  }
389
- await super.connect(timeout);
440
+ await super._dapConnect(timeout);
441
+ }
442
+ /**
443
+ * Send the ``auth`` DAP command over the open transport.
444
+ * Sets ``_authenticated`` and ``_connectResult`` on success.
445
+ * Throws ``AuthenticationException`` on failure (transport stays open).
446
+ */
447
+ async _internalLogin(timeout) {
448
+ // Build auth args with credential + client identification
449
+ const authArgs = { auth: this._apikey ?? '' };
450
+ if (this._clientDisplayName)
451
+ authArgs.clientName = this._clientDisplayName;
452
+ if (this._clientDisplayVersion)
453
+ authArgs.clientVersion = this._clientDisplayVersion;
454
+ const resp = await this.request({ type: 'request', command: 'auth', seq: 0, arguments: authArgs }, timeout);
455
+ const success = resp.success;
456
+ if (!success) {
457
+ throw new index_js_2.AuthenticationException(resp);
458
+ }
459
+ this._connectResult = resp.body;
460
+ this._authenticated = true;
461
+ // Store userToken for future reconnects
462
+ if (this._connectResult?.userToken) {
463
+ this._apikey = this._connectResult.userToken;
464
+ }
465
+ // Resubscribe monitors and notify
466
+ await this._resubscribeAllMonitors();
467
+ const connectionInfo = this._transport?.getConnectionInfo() ?? '';
468
+ if (this._callerOnConnected) {
469
+ try {
470
+ await this._callerOnConnected(connectionInfo);
471
+ }
472
+ catch (e) {
473
+ this.debugMessage(`Error in user onConnected handler: ${e}`);
474
+ }
475
+ }
476
+ await super.onConnected(connectionInfo);
477
+ return this._connectResult;
478
+ }
479
+ /**
480
+ * Send the ``deauth`` DAP command to revert to unauthenticated.
481
+ */
482
+ async _internalLogout() {
483
+ if (!this._authenticated || !this._transport?.isConnected())
484
+ return;
485
+ try {
486
+ await this.request({ type: 'request', command: 'deauth', seq: 0, arguments: {} });
487
+ }
488
+ catch {
489
+ // Best-effort — server may have already disconnected
490
+ }
491
+ this._connectResult = undefined;
492
+ this._authenticated = false;
390
493
  }
391
494
  /**
392
- * Single place for physical disconnect. Closes the transport directly,
393
- * which triggers onDisconnected via the transport callback.
495
+ * Close the transport. Triggers onDisconnected via the transport callback.
394
496
  */
395
- async _internalDisconnect(reason, hasError) {
497
+ async _internalDisconnect() {
396
498
  if (!this._transport)
397
499
  return;
398
- await this._transport.disconnect(reason, hasError);
500
+ await this._transport.disconnect();
399
501
  }
400
502
  /**
401
- * Try to connect; on auth error notify and stop; on other error notify and
402
- * reschedule with exponential backoff. Used by persist-mode connect() and
403
- * by the reconnect timer.
503
+ * Clear the reconnect timer if active.
404
504
  */
405
- async _attemptConnection(timeout) {
406
- try {
407
- await this._internalConnect(timeout);
408
- this._reconnectTimeout = undefined;
409
- this.debugMessage('Connection successful');
505
+ _clearReconnectTimer() {
506
+ if (this._reconnectTimer) {
507
+ clearTimeout(this._reconnectTimer);
508
+ this._reconnectTimer = undefined;
410
509
  }
411
- catch (error) {
412
- const err = error instanceof Error ? error : new Error(String(error));
413
- this.debugMessage(`Connection failed: ${err}`);
414
- await this.onConnectError(err);
415
- if (error instanceof index_js_1.AuthenticationException) {
416
- return;
417
- }
418
- if (this._retryStartTime === undefined) {
419
- this._retryStartTime = Date.now();
510
+ }
511
+ /**
512
+ * Reconnect engine driven by ``_desiredState``.
513
+ *
514
+ * Schedules a timer that re-attaches (and re-logins if the user had
515
+ * been authenticated). Checks ``_desiredState`` after every await so
516
+ * user actions mid-reconnect are respected immediately.
517
+ *
518
+ * Linear backoff: 250ms → 500ms → ... → 15 000ms cap.
519
+ */
520
+ _scheduleReconnect() {
521
+ this.debugMessage(`Scheduling reconnect in ${this._currentReconnectDelay}ms`);
522
+ this._reconnectTimer = setTimeout(async () => {
523
+ try {
524
+ // Re-attach transport
525
+ await this._internalAttach();
526
+ if (this._desiredState === 'detached') {
527
+ this._reconnectTimer = undefined;
528
+ return;
529
+ }
530
+ // Re-login if the user was authenticated
531
+ if (this._desiredState === 'authenticated') {
532
+ await this._internalLogin();
533
+ if (this._desiredState === 'detached') {
534
+ this._reconnectTimer = undefined;
535
+ return;
536
+ }
537
+ }
538
+ // Success — reset backoff
539
+ this._reconnectTimer = undefined;
540
+ this._currentReconnectDelay = 250;
541
+ this.debugMessage('Reconnect successful');
420
542
  }
421
- if (this._maxRetryTime !== undefined) {
422
- if (Date.now() - this._retryStartTime >= this._maxRetryTime) {
543
+ catch (err) {
544
+ // User changed intent — stop (desiredState may have been changed by detach() during await)
545
+ if (this._desiredState === 'detached') {
546
+ this._reconnectTimer = undefined;
423
547
  return;
424
548
  }
549
+ // Auth rejected — downgrade to attached, stop retrying auth
550
+ if (err instanceof index_js_2.AuthenticationException) {
551
+ this._desiredState = 'attached';
552
+ this._reconnectTimer = undefined;
553
+ await this.onConnectError(err);
554
+ return;
555
+ }
556
+ // Transient failure — linear backoff, cap at 15s
557
+ this._currentReconnectDelay = Math.min(this._currentReconnectDelay + 250, 15000);
558
+ const error = err instanceof Error ? err : new Error(String(err));
559
+ await this.onConnectError(error);
560
+ this._scheduleReconnect(); // replaces timer with new delay
425
561
  }
426
- this._currentReconnectDelay = Math.min(this._currentReconnectDelay * 2, 2500);
427
- this._scheduleReconnect();
428
- }
562
+ }, this._currentReconnectDelay);
429
563
  }
564
+ // ============================================================================
565
+ // PUBLIC API — TRANSPORT
566
+ // ============================================================================
430
567
  /**
431
- * Schedule a reconnection attempt with exponential backoff.
568
+ * Attach to a RocketRide server (open WebSocket, no auth).
569
+ *
570
+ * If ``uri`` is provided and differs from the current URI, detaches
571
+ * first. If already attached to the same URI, this is a no-op.
572
+ *
573
+ * After attach, public APIs (``rrext_public_*``) are available.
574
+ *
575
+ * @param uri - Server URI override. Updates the stored URI if provided.
576
+ * @param options - Optional timeout for the WebSocket handshake.
432
577
  */
433
- _scheduleReconnect() {
434
- this._clearReconnectTimeout();
435
- if (this._maxRetryTime !== undefined && this._retryStartTime !== undefined) {
436
- if (Date.now() - this._retryStartTime >= this._maxRetryTime) {
437
- this.onConnectError(new Error('Max retry time exceeded'));
438
- return;
578
+ async attach(uri, options) {
579
+ // URI change → detach first, then update
580
+ if (uri) {
581
+ const normalised = this._getWebsocketUri(uri);
582
+ if (normalised !== this._uri) {
583
+ if (this.isAttached())
584
+ await this.detach();
585
+ this._setUri(uri);
439
586
  }
440
587
  }
441
- this.debugMessage(`Scheduling reconnection in ${this._currentReconnectDelay}ms`);
442
- this._reconnectTimeout = setTimeout(async () => {
443
- if (this._persist && !this._manualDisconnect) {
444
- this.debugMessage('Attempting to reconnect...');
445
- await this._attemptConnection();
446
- }
447
- }, this._currentReconnectDelay);
588
+ // Already attached → no-op
589
+ if (this.isAttached()) {
590
+ this._desiredState = this._desiredState === 'detached' ? 'attached' : this._desiredState;
591
+ return;
592
+ }
593
+ this._desiredState = 'attached';
594
+ await this._internalAttach(options?.timeout);
448
595
  }
449
596
  /**
450
- * Check if the client is currently connected to the RocketRide server.
597
+ * Detach from the server (close WebSocket, cancel reconnection).
598
+ *
599
+ * Sets ``_desiredState`` to ``'detached'`` so the reconnect engine
600
+ * stops and ``onDisconnected`` does not restart it.
451
601
  */
452
- isConnected() {
602
+ async detach() {
603
+ this._desiredState = 'detached';
604
+ this._clearReconnectTimer();
605
+ this._authenticated = false;
606
+ this._connectResult = undefined;
607
+ if (this._transport?.isConnected()) {
608
+ await this._internalDisconnect();
609
+ }
610
+ }
611
+ /**
612
+ * True when the WebSocket transport is connected (regardless of auth).
613
+ */
614
+ isAttached() {
453
615
  return this._transport?.isConnected() || false;
454
616
  }
617
+ // ============================================================================
618
+ // PUBLIC API — AUTH
619
+ // ============================================================================
455
620
  /**
456
- * Connect to the RocketRide server.
621
+ * Authenticate over an attached transport.
457
622
  *
458
- * Must be called before executing pipelines or other operations.
459
- * In persist mode, enables automatic reconnection on disconnect and on initial failure
460
- * (calls onConnectError on each failed attempt and keeps retrying).
461
- * @param options - Optional timeout (number) or connection parameters object with uri, auth, and timeout.
623
+ * If ``uri`` is provided and differs, detaches and re-attaches first.
624
+ * If ``auth`` is provided and differs from the current credential,
625
+ * logs out (best-effort) before logging in with the new credential.
626
+ * If already authenticated with the same credential, this is a no-op.
627
+ *
628
+ * @param credential - API key, rr_ token, or PKCE code object.
629
+ * @param options - Optional URI override and/or timeout.
630
+ * @returns ConnectResult with user identity on success.
631
+ * @throws AuthenticationException on auth failure (transport stays attached).
462
632
  */
463
- async connect(options) {
464
- let uri;
465
- let auth;
466
- let timeout;
467
- if (typeof options === 'number') {
468
- timeout = options;
469
- }
470
- else if (options) {
471
- ({ uri, auth, timeout } = options);
633
+ async login(credential, options) {
634
+ // Resolve credential
635
+ let resolvedCredential;
636
+ if (credential && typeof credential === 'object') {
637
+ resolvedCredential = 'cd_' + btoa(JSON.stringify(credential));
472
638
  }
473
- // Apply optional overrides so they're used for this connect
474
- if (uri !== undefined) {
475
- this._setUri(uri);
639
+ else {
640
+ const envKey = this._env['ROCKETRIDE_APIKEY'];
641
+ const envCredential = typeof envKey === 'string' && envKey.trim() !== '' ? envKey : undefined;
642
+ resolvedCredential = credential ?? envCredential ?? this._apikey ?? '';
643
+ }
644
+ // URI change → detach + re-attach
645
+ if (options?.uri) {
646
+ const normalised = this._getWebsocketUri(options.uri);
647
+ if (normalised !== this._uri) {
648
+ await this.detach();
649
+ this._setUri(options.uri);
650
+ await this._internalAttach(options.timeout);
651
+ }
476
652
  }
477
- if (auth !== undefined) {
478
- this._setAuth(auth);
653
+ // Ensure attached
654
+ if (!this.isAttached()) {
655
+ await this._internalAttach(options?.timeout);
479
656
  }
480
- this._manualDisconnect = false;
481
- this._currentReconnectDelay = 250;
482
- this._retryStartTime = undefined;
483
- // If already connected, disconnect first without setting _manualDisconnect
484
- if (this.isConnected()) {
485
- await this._internalDisconnect();
486
- }
487
- if (this._persist) {
488
- this._clearReconnectTimeout();
489
- await this._attemptConnection(timeout);
657
+ // Auth change → logout first (best-effort)
658
+ if (resolvedCredential !== this._apikey && this._authenticated) {
659
+ try {
660
+ await this._internalLogout();
661
+ }
662
+ catch { }
490
663
  }
491
- else {
492
- await this._internalConnect(timeout);
664
+ this._setAuth(resolvedCredential);
665
+ // Already authenticated with same credential → no-op
666
+ if (this._authenticated) {
667
+ this._desiredState = 'authenticated';
668
+ return this._connectResult ?? {};
493
669
  }
670
+ this._desiredState = 'authenticated';
671
+ return this._internalLogin(options?.timeout);
494
672
  }
495
673
  /**
496
- * Disconnect from the RocketRide server and stop automatic reconnection.
674
+ * Deauthenticate: sends ``deauth`` to the server, clears client auth state.
675
+ * The transport stays attached — public APIs continue to work.
676
+ */
677
+ async logout() {
678
+ await this._internalLogout();
679
+ this._desiredState = 'attached';
680
+ }
681
+ /**
682
+ * True when the auth handshake has succeeded on the current connection.
683
+ */
684
+ isAuthenticated() {
685
+ return this._authenticated;
686
+ }
687
+ // ============================================================================
688
+ // COMPAT API — connect() / disconnect()
689
+ // ============================================================================
690
+ /**
691
+ * Check if the client is currently connected to the RocketRide server.
692
+ * Equivalent to ``isAttached()`` — kept for backward compatibility.
693
+ */
694
+ isConnected() {
695
+ return this.isAttached();
696
+ }
697
+ /**
698
+ * Connect to the RocketRide server and authenticate in a single call.
699
+ *
700
+ * Backward-compatible wrapper around ``attach()`` + ``login()``.
701
+ * Sends the credential as the first DAP message and returns the full
702
+ * ConnectResult (user identity + organizations + teams) on success.
497
703
  *
498
- * Should be called when finished with the client to clean up resources.
704
+ * @param credential - API key / Zitadel access_token / rr_ user token / PKCE code object.
705
+ * @param options - Optional overrides: uri and/or timeout.
499
706
  */
500
- async disconnect() {
501
- this._manualDisconnect = true;
502
- this._clearReconnectTimeout();
503
- if (this._transport && this.isConnected()) {
504
- await this._internalDisconnect();
505
- }
707
+ async connect(credential, options) {
708
+ this._currentReconnectDelay = 250;
709
+ await this.attach(options?.uri, { timeout: options?.timeout });
710
+ return this.login(credential, options);
506
711
  }
507
712
  /**
508
- * Update server URI and/or auth at runtime. If currently connected,
509
- * disconnects and reconnects with the new params. In persist mode,
510
- * reconnection is scheduled only if we were connected.
713
+ * Get the ConnectResult from the last successful connect().
714
+ * Returns undefined if not connected or not yet authenticated.
511
715
  */
512
- async setConnectionParams(options) {
513
- if (options.uri !== undefined) {
514
- this._setUri(options.uri);
515
- }
516
- if (options.auth !== undefined) {
517
- this._setAuth(options.auth);
518
- }
519
- const wasAlreadyConnected = this.isConnected();
520
- this._manualDisconnect = true;
521
- this._clearReconnectTimeout();
522
- if (wasAlreadyConnected) {
523
- await this._internalDisconnect();
524
- }
525
- // Destroy transport so next connect() creates a new one with updated uri/auth (CONNECTION_LOGIC.md §2c)
526
- if (options.uri !== undefined || options.auth !== undefined) {
527
- this._transport = undefined;
528
- }
529
- if (this._persist && wasAlreadyConnected) {
530
- this._manualDisconnect = false;
531
- this._scheduleReconnect();
532
- }
533
- else if (wasAlreadyConnected) {
534
- this._manualDisconnect = false;
535
- await this._internalConnect();
536
- }
537
- else {
538
- this._manualDisconnect = false;
539
- }
716
+ getAccountInfo() {
717
+ return this._connectResult;
718
+ }
719
+ /**
720
+ * Returns the ID of the user's primary organization.
721
+ */
722
+ getOrgId() {
723
+ return this._connectResult?.organizations?.[0]?.id;
540
724
  }
725
+ /**
726
+ * Disconnect from the RocketRide server and stop automatic reconnection.
727
+ * Backward-compatible wrapper around ``logout()`` + ``detach()``.
728
+ */
729
+ async disconnect() {
730
+ await this.logout();
731
+ await this.detach();
732
+ }
733
+ /**
734
+ * Update the environment variables used for pipeline substitution.
735
+ *
736
+ * The env dictionary is used by {@link use} and {@link validate} to replace
541
737
  // ============================================================================
542
738
  // PING METHODS
543
739
  // ============================================================================
740
+
544
741
  /**
545
742
  * Test connectivity to the RocketRide server.
546
743
  *
@@ -549,59 +746,16 @@ class RocketRideClient extends DAPClient_js_1.DAPClient {
549
746
  * and measuring response times.
550
747
  */
551
748
  async ping(token) {
552
- // Build ping request
553
- const request = this.buildRequest('rrext_ping', { token });
554
- // Send to server and wait for response
555
- const response = await this.request(request);
556
- // Check if ping failed
557
- if (this.didFail(response)) {
558
- const errorMsg = response.message || 'Ping failed';
559
- throw new Error(`Ping failed: ${errorMsg}`);
749
+ try {
750
+ await this.call('rrext_ping', undefined, { token });
751
+ }
752
+ catch (err) {
753
+ throw new Error(`Ping failed: ${err instanceof Error ? err.message : err}`);
560
754
  }
561
755
  }
562
756
  // ============================================================================
563
757
  // EXECUTION METHODS
564
758
  // ============================================================================
565
- /**
566
- * Substitute environment variables in a string.
567
- * Replaces ${ROCKETRIDE_*} patterns with values from client's env dictionary.
568
- * If variable is not found, leaves it unchanged.
569
- */
570
- substituteEnvVars(value) {
571
- // Match ${ROCKETRIDE_*} patterns
572
- return value.replace(/\$\{(ROCKETRIDE_[^}]+)\}/g, (match, varName) => {
573
- // Check if variable exists in client's env
574
- if (varName in this._env) {
575
- return String(this._env[varName]);
576
- }
577
- // If not found, leave as is
578
- return match;
579
- });
580
- }
581
- /**
582
- * Recursively process an object/array to substitute environment variables.
583
- * Only processes string values, leaving other types unchanged.
584
- */
585
- processEnvSubstitution(obj) {
586
- if (typeof obj === 'string') {
587
- // If it's a string, perform substitution
588
- return this.substituteEnvVars(obj);
589
- }
590
- else if (Array.isArray(obj)) {
591
- // If it's an array, process each element
592
- return obj.map(item => this.processEnvSubstitution(item));
593
- }
594
- else if (obj !== null && typeof obj === 'object') {
595
- // If it's an object, process each property
596
- const result = {};
597
- for (const [key, value] of Object.entries(obj)) {
598
- result[key] = this.processEnvSubstitution(value);
599
- }
600
- return result;
601
- }
602
- // For other types (number, boolean, null), return as is
603
- return obj;
604
- }
605
759
  /**
606
760
  * Load Node.js fs/promises at runtime without static imports.
607
761
  * This keeps browser bundles free of Node built-ins while preserving Node features.
@@ -661,19 +815,16 @@ class RocketRideClient extends DAPClient_js_1.DAPClient {
661
815
  */
662
816
  async validate(options) {
663
817
  const { pipeline, source } = options;
664
- const arguments_ = { pipeline };
818
+ const args = { pipeline };
665
819
  if (source !== undefined) {
666
- arguments_.source = source;
820
+ args.source = source;
667
821
  }
668
- const request = this.buildRequest('rrext_validate', {
669
- arguments: arguments_
670
- });
671
- const response = await this.request(request);
672
- if (this.didFail(response)) {
673
- const errorMsg = response.message || 'Validation failed';
674
- throw new Error(`Pipeline validation failed: ${errorMsg}`);
822
+ try {
823
+ return await this.call('rrext_validate', args);
824
+ }
825
+ catch (err) {
826
+ throw new Error(`Pipeline validation failed: ${err instanceof Error ? err.message : err}`);
675
827
  }
676
- return response.body || {};
677
828
  }
678
829
  // ============================================================================
679
830
  // PIPELINE EXECUTION METHODS
@@ -722,7 +873,7 @@ class RocketRideClient extends DAPClient_js_1.DAPClient {
722
873
  * ```
723
874
  */
724
875
  async use(options = {}) {
725
- const { token, filepath, pipeline, source, threads, useExisting, args, ttl, pipelineTraceLevel } = options;
876
+ const { token, filepath, pipeline, source, threads, useExisting, args, ttl, pipelineTraceLevel, name, env, teamId } = options;
726
877
  // Validate required parameters
727
878
  if (!pipeline && !filepath) {
728
879
  throw new Error('Pipeline configuration or file path is required and must be specified');
@@ -745,9 +896,7 @@ class RocketRideClient extends DAPClient_js_1.DAPClient {
745
896
  pipelineConfig = pipeline;
746
897
  }
747
898
  // Create a deep copy of the pipeline config to avoid modifying the original
748
- let processedConfig = JSON.parse(JSON.stringify(pipelineConfig));
749
- // Perform environment variable substitution on the pipeline configuration
750
- processedConfig = this.processEnvSubstitution(processedConfig);
899
+ const processedConfig = JSON.parse(JSON.stringify(pipelineConfig));
751
900
  // Override source if specified (after substitution)
752
901
  if (source !== undefined) {
753
902
  processedConfig.source = source;
@@ -774,54 +923,135 @@ class RocketRideClient extends DAPClient_js_1.DAPClient {
774
923
  if (pipelineTraceLevel !== undefined) {
775
924
  arguments_.pipelineTraceLevel = pipelineTraceLevel;
776
925
  }
926
+ // Build ROCKETRIDE_* env from client's .env + caller overrides
927
+ const rocketEnv = {};
928
+ for (const [k, v] of Object.entries(this._env)) {
929
+ if (k.startsWith('ROCKETRIDE_'))
930
+ rocketEnv[k] = v;
931
+ }
932
+ if (env)
933
+ Object.assign(rocketEnv, env);
934
+ if (Object.keys(rocketEnv).length > 0) {
935
+ arguments_.env = rocketEnv;
936
+ }
937
+ // Derive display name from filepath if not explicitly provided
938
+ const effectiveName = name ?? (filepath ? filepath.replace(/^.*[\\/]/, '').replace(/\.pipe(?:\.json)?$/, '') : undefined);
939
+ if (effectiveName !== undefined) {
940
+ arguments_.name = effectiveName;
941
+ }
942
+ if (teamId !== undefined) {
943
+ arguments_.teamId = teamId;
944
+ }
777
945
  // Send execution request to server
778
- const request = this.buildRequest('execute', { arguments: arguments_ });
779
- const response = await this.request(request);
780
- // Check for execution errors
781
- if (this.didFail(response)) {
782
- const errorMsg = response.message || 'Unknown execution error';
783
- this.debugMessage(`Pipeline execution failed: ${errorMsg}`);
784
- throw new Error(errorMsg);
946
+ try {
947
+ const body = await this.call('execute', arguments_);
948
+ // Extract and validate response
949
+ const responseBody = body || {};
950
+ const taskToken = responseBody.token;
951
+ if (!taskToken) {
952
+ throw new Error('Server did not return a task token in successful response');
953
+ }
954
+ this.debugMessage(`Pipeline execution started successfully, task token: ${taskToken}`);
955
+ // Type assertion to ensure token is present
956
+ return responseBody;
785
957
  }
786
- // Extract and validate response
787
- const responseBody = response.body || {};
788
- const taskToken = responseBody.token;
789
- if (!taskToken) {
790
- throw new Error('Server did not return a task token in successful response');
958
+ catch (err) {
959
+ const errorMsg = err instanceof Error ? err.message : String(err);
960
+ this.debugMessage(`Pipeline execution failed: ${errorMsg}`);
961
+ throw err;
791
962
  }
792
- this.debugMessage(`Pipeline execution started successfully, task token: ${taskToken}`);
793
- // Type assertion to ensure token is present
794
- return responseBody;
795
963
  }
796
964
  /**
797
965
  * Terminate a running pipeline.
798
966
  */
799
967
  async terminate(token) {
800
- // Send termination request
801
- const request = this.buildRequest('terminate', { token });
802
- const response = await this.request(request);
803
- // Check for termination errors
804
- if (this.didFail(response)) {
805
- const errorMsg = response.message || 'Unknown termination error';
968
+ try {
969
+ await this.call('terminate', undefined, { token });
970
+ }
971
+ catch (err) {
972
+ const errorMsg = err instanceof Error ? err.message : String(err);
806
973
  this.debugMessage(`Pipeline termination failed: ${errorMsg}`);
807
974
  throw new Error(errorMsg);
808
975
  }
809
976
  }
977
+ /**
978
+ * Restart a running pipeline with a new configuration.
979
+ *
980
+ * Looks up the existing task by project/source, terminates it, and
981
+ * starts a new execution in one server round-trip.
982
+ *
983
+ * @param options.token - Existing task token (optional, resolved server-side if omitted).
984
+ * @param options.projectId - The project identifier.
985
+ * @param options.source - The source component identifier.
986
+ * @param options.pipeline - The pipeline configuration to restart with.
987
+ */
988
+ async restart(options) {
989
+ try {
990
+ await this.call('restart', {
991
+ token: options.token,
992
+ projectId: options.projectId,
993
+ source: options.source,
994
+ pipeline: options.pipeline,
995
+ }, { token: '*' });
996
+ }
997
+ catch (err) {
998
+ const errorMsg = err instanceof Error ? err.message : String(err);
999
+ this.debugMessage(`Pipeline restart failed: ${errorMsg}`);
1000
+ throw new Error(errorMsg);
1001
+ }
1002
+ }
810
1003
  /**
811
1004
  * Get the current status of a running pipeline.
1005
+ *
1006
+ * By default this call is bounded to 15s so callers/tests don't hang forever if the engine
1007
+ * stops responding mid-request (especially important in CI). Pass `{ timeout: false }` to
1008
+ * restore the previous behavior of using only the client-level request timeout (if any).
812
1009
  */
813
- async getTaskStatus(token) {
814
- // Send status request
815
- const request = this.buildRequest('rrext_get_task_status', { token });
816
- const response = await this.request(request);
817
- // Check for status retrieval errors
818
- if (this.didFail(response)) {
819
- const errorMsg = response.message || 'Unknown status retrieval error';
1010
+ async getTaskStatus(token, options) {
1011
+ try {
1012
+ const callOptions = { token };
1013
+ if (options?.timeout === false) {
1014
+ // Intentionally omit per-call timeout override.
1015
+ }
1016
+ else {
1017
+ callOptions.timeout = options?.timeout ?? 15000;
1018
+ }
1019
+ return await this.call('rrext_get_task_status', undefined, callOptions);
1020
+ }
1021
+ catch (err) {
1022
+ const errorMsg = err instanceof Error ? err.message : String(err);
820
1023
  this.debugMessage(`Pipeline status retrieval failed: ${errorMsg}`);
821
1024
  throw new Error(errorMsg);
822
1025
  }
823
- // Return status information
824
- return response.body || {};
1026
+ }
1027
+ /**
1028
+ * Resolve a running task's token from its project ID and source component.
1029
+ *
1030
+ * The token is required for operations like terminate and restart.
1031
+ * Returns undefined if no task is currently running for the given project/source.
1032
+ *
1033
+ * @param options.projectId - The project identifier.
1034
+ * @param options.source - The source component identifier.
1035
+ */
1036
+ async getTaskToken(options) {
1037
+ const body = await this.call('rrext_get_token', {
1038
+ projectId: options.projectId,
1039
+ source: options.source,
1040
+ });
1041
+ return body?.token;
1042
+ }
1043
+ /**
1044
+ * Returns the unresolved pipeline for a running task.
1045
+ *
1046
+ * The pipeline is returned exactly as stored — ${ROCKETRIDE_*} placeholders are
1047
+ * NOT substituted, so no secrets are included in the response.
1048
+ *
1049
+ * @param token - Task token returned by {@link getTaskToken}.
1050
+ * @returns The unresolved pipeline dict, or undefined if the task is not found.
1051
+ */
1052
+ async getTaskPipeline(token) {
1053
+ const body = await this.call('rrext_get_pipeline', undefined, { token });
1054
+ return body?.pipeline;
825
1055
  }
826
1056
  // ============================================================================
827
1057
  // DATA METHODS
@@ -916,7 +1146,7 @@ class RocketRideClient extends DAPClient_js_1.DAPClient {
916
1146
  event: 'apaevt_status_upload',
917
1147
  body: body,
918
1148
  seq: 0,
919
- type: 'event'
1149
+ type: 'event',
920
1150
  };
921
1151
  this.onEvent(eventMessage);
922
1152
  };
@@ -1008,7 +1238,7 @@ class RocketRideClient extends DAPClient_js_1.DAPClient {
1008
1238
  results[index] = finalResult;
1009
1239
  };
1010
1240
  // Create a promise for every file - let server handle queuing
1011
- const uploadPromises = files.map((fileData, index) => uploadFile(fileData, index).catch(err => {
1241
+ const uploadPromises = files.map((fileData, index) => uploadFile(fileData, index).catch((err) => {
1012
1242
  // Ensure errors don't kill the whole batch
1013
1243
  console.error(`Upload failed for ${fileData.file.name}:`, err);
1014
1244
  }));
@@ -1110,6 +1340,13 @@ class RocketRideClient extends DAPClient_js_1.DAPClient {
1110
1340
  const seqNum = message.seq || 0;
1111
1341
  // Forward to debugging interface if available
1112
1342
  this._sendVSCodeEvent(eventType, eventBody);
1343
+ // Update cached ConnectResult when the server pushes a full account refresh
1344
+ if (eventType === 'apaext_account') {
1345
+ this._connectResult = eventBody;
1346
+ if (this._connectResult?.userToken) {
1347
+ this._apikey = this._connectResult.userToken;
1348
+ }
1349
+ }
1113
1350
  // Dispatch pipe-scoped SSE events to the registered DataPipe callback
1114
1351
  if (eventType === 'apaevt_sse') {
1115
1352
  const pipeId = eventBody?.pipe_id;
@@ -1146,7 +1383,8 @@ class RocketRideClient extends DAPClient_js_1.DAPClient {
1146
1383
  async onConnectError(error) {
1147
1384
  if (this._callerOnConnectError) {
1148
1385
  try {
1149
- await this._callerOnConnectError(error instanceof Error ? error.message : String(error));
1386
+ const connectionError = error instanceof index_js_2.ConnectionException ? error : new index_js_2.ConnectionException({ message: String(error) });
1387
+ await this._callerOnConnectError(connectionError);
1150
1388
  }
1151
1389
  catch (e) {
1152
1390
  this.debugMessage(`Error in user onConnectError handler: ${e}`);
@@ -1155,564 +1393,697 @@ class RocketRideClient extends DAPClient_js_1.DAPClient {
1155
1393
  await super.onConnectError(error);
1156
1394
  }
1157
1395
  /**
1158
- * Handle connected events from the RocketRide server.
1396
+ * Handle transport-level connected event.
1397
+ *
1398
+ * With the attach/login split, this fires when the WebSocket opens
1399
+ * (before auth). The ``_internalLogin`` method handles the auth
1400
+ * notification separately, so this is intentionally minimal.
1159
1401
  */
1160
1402
  async onConnected(connectionInfo) {
1161
- this._manualDisconnect = false;
1162
- this._didNotifyConnected = true;
1163
- this._clearReconnectTimeout();
1164
- this._currentReconnectDelay = 250;
1165
- this._retryStartTime = undefined;
1166
- // Call user-provided event handler if available
1167
- if (this._callerOnConnected) {
1168
- try {
1169
- await this._callerOnConnected(connectionInfo);
1170
- }
1171
- catch (error) {
1172
- // Log errors but don't let user code break the connection
1173
- this.debugMessage(`Error in user onConnected handler for ${connectionInfo}: ${error}`);
1174
- }
1175
- }
1176
1403
  await super.onConnected(connectionInfo);
1177
1404
  }
1178
1405
  /**
1179
- * Handle disconnected events from the RocketRide server.
1180
- * Only invokes the user's onDisconnected if onConnected had previously been called
1181
- * (so "disconnect without ever connecting" does not fire the user callback).
1406
+ * Handle transport disconnection.
1407
+ *
1408
+ * Clears transport and auth state, notifies the user callback,
1409
+ * then consults ``_desiredState`` to decide whether to reconnect.
1182
1410
  */
1183
1411
  async onDisconnected(reason, hasError) {
1184
- if (this._didNotifyConnected) {
1185
- this._didNotifyConnected = false;
1186
- if (this._callerOnDisconnected) {
1187
- try {
1188
- await this._callerOnDisconnected(reason, hasError);
1189
- }
1190
- catch (error) {
1191
- // Log errors but don't let user code break the connection
1192
- this.debugMessage(`Error in user onDisconnected handler for ${reason}: ${error}`);
1193
- }
1412
+ // Transport is gone — clear so next attach creates a fresh one
1413
+ this._transport = undefined;
1414
+ this._connectResult = undefined;
1415
+ this._authenticated = false;
1416
+ // Notify user callback
1417
+ if (this._callerOnDisconnected) {
1418
+ try {
1419
+ await this._callerOnDisconnected(reason, hasError);
1420
+ }
1421
+ catch (error) {
1422
+ this.debugMessage(`Error in user onDisconnected handler for ${reason}: ${error}`);
1194
1423
  }
1195
- // Chain to parent to clear pending requests
1196
- await super.onDisconnected(reason, hasError);
1197
1424
  }
1198
- // Schedule reconnection if persist is enabled and not a manual disconnect
1199
- if (this._persist && !this._manualDisconnect) {
1200
- this._scheduleReconnect();
1425
+ // Chain to parent to clear pending requests
1426
+ await super.onDisconnected(reason, hasError);
1427
+ // Reconnect engine: honour _desiredState
1428
+ if (this._desiredState === 'detached')
1429
+ return;
1430
+ if (!this._persist) {
1431
+ this._desiredState = 'detached';
1432
+ return;
1201
1433
  }
1434
+ if (this._reconnectTimer)
1435
+ return; // engine already active
1436
+ this._currentReconnectDelay = 250;
1437
+ this._scheduleReconnect();
1202
1438
  }
1203
1439
  /**
1204
1440
  * Subscribe to specific types of events from the server.
1441
+ * @deprecated Use {@link addMonitor} / {@link removeMonitor} instead.
1205
1442
  */
1206
1443
  async setEvents(token, eventTypes, pipeId) {
1207
- // Build event subscription request
1444
+ // Build event subscription args
1208
1445
  const args = { types: eventTypes };
1209
1446
  if (pipeId !== undefined)
1210
1447
  args.pipeId = pipeId;
1211
- const request = this.buildRequest('rrext_monitor', {
1212
- arguments: args,
1213
- token,
1214
- });
1215
- // Send to server
1216
- const response = await this.request(request);
1217
- // Check for errors
1218
- if (this.didFail(response)) {
1219
- const errorMsg = response.message || 'Event subscription failed';
1220
- throw new Error(errorMsg);
1448
+ try {
1449
+ await this.call('rrext_monitor', args, { token });
1450
+ }
1451
+ catch (err) {
1452
+ throw new Error(`Event subscription failed: ${err instanceof Error ? err.message : err}`);
1221
1453
  }
1222
1454
  }
1223
1455
  // ============================================================================
1224
- // PROJECT STORAGE MANAGEMENT
1456
+ // MONITOR SUBSCRIPTION MANAGEMENT
1225
1457
  // ============================================================================
1226
1458
  /**
1227
- * Save or update a project pipeline.
1459
+ * Add a monitor subscription. If the key already exists, the new types are
1460
+ * merged via reference counting and the merged set is sent to the server.
1228
1461
  *
1229
- * Stores a project pipeline configuration on the server. If the project
1230
- * already exists, it will be updated. Use expectedVersion to ensure
1231
- * you're updating the version you expect (prevents conflicts).
1232
- *
1233
- * @param options - Save project options
1234
- * @param options.projectId - Unique identifier for the project
1235
- * @param options.pipeline - Pipeline configuration object
1236
- * @param options.expectedVersion - Expected current version for atomic updates (optional)
1237
- * @returns Promise resolving to save result with success status, projectId, and new version
1238
- * @throws Error if save fails due to version mismatch, storage error, or invalid input
1239
- *
1240
- * @example
1241
- * ```typescript
1242
- * // Save a new project
1243
- * const result = await client.saveProject({
1244
- * projectId: 'proj-123',
1245
- * pipeline: {
1246
- * name: 'Data Processor',
1247
- * source: 'source_1',
1248
- * components: [...]
1249
- * }
1250
- * });
1251
- * console.log(`Saved version: ${result.version}`);
1252
- *
1253
- * // Update existing project with version check
1254
- * const existing = await client.getProject({ projectId: 'proj-123' });
1255
- * existing.name = 'Updated Name';
1256
- * const updated = await client.saveProject({
1257
- * projectId: 'proj-123',
1258
- * pipeline: existing,
1259
- * expectedVersion: existing.version
1260
- * });
1261
- * ```
1462
+ * @param key - Monitor key: `{ token }` for a running task, or `{ projectId, source }` for a project.
1463
+ * @param types - Event types to subscribe to (e.g. `['summary', 'flow']`).
1262
1464
  */
1263
- async saveProject(options) {
1264
- const { projectId, pipeline, expectedVersion } = options;
1265
- // Validate inputs
1266
- if (!projectId) {
1267
- throw new Error('projectId is required');
1268
- }
1269
- if (!pipeline || typeof pipeline !== 'object') {
1270
- throw new Error('pipeline must be a non-empty object');
1465
+ async addMonitor(key, types) {
1466
+ const keyStr = this._monitorKeyToString(key);
1467
+ let refCounts = this._monitorKeys.get(keyStr);
1468
+ if (!refCounts) {
1469
+ refCounts = new Map();
1470
+ this._monitorKeys.set(keyStr, refCounts);
1471
+ }
1472
+ // Increment reference counts
1473
+ for (const t of types) {
1474
+ refCounts.set(t, (refCounts.get(t) ?? 0) + 1);
1475
+ }
1476
+ // Send merged types to server — rollback on failure
1477
+ try {
1478
+ await this._syncMonitor(key, refCounts);
1271
1479
  }
1272
- // Build request arguments
1273
- const args = {
1274
- subcommand: 'save_project',
1275
- projectId,
1276
- pipeline,
1277
- };
1278
- // Add optional version for atomic updates
1279
- if (expectedVersion !== undefined) {
1280
- args.expectedVersion = expectedVersion;
1281
- }
1282
- // Send request to server
1283
- const request = this.buildRequest('rrext_store', { arguments: args });
1284
- const response = await this.request(request);
1285
- // Check for errors
1286
- if (this.didFail(response)) {
1287
- const errorMsg = response.message || 'Unknown error saving project';
1288
- this.debugMessage(`Project save failed: ${errorMsg}`);
1289
- throw new Error(errorMsg);
1480
+ catch (error) {
1481
+ for (const t of types) {
1482
+ const current = refCounts.get(t) ?? 0;
1483
+ if (current <= 1) {
1484
+ refCounts.delete(t);
1485
+ }
1486
+ else {
1487
+ refCounts.set(t, current - 1);
1488
+ }
1489
+ }
1490
+ if (refCounts.size === 0) {
1491
+ this._monitorKeys.delete(keyStr);
1492
+ }
1493
+ throw error;
1290
1494
  }
1291
- // Extract and return response
1292
- this.debugMessage(`Project saved successfully: ${projectId}, version: ${response.body?.version}`);
1293
- return response.body;
1294
1495
  }
1295
1496
  /**
1296
- * Retrieve a project by its ID.
1297
- *
1298
- * Fetches the complete pipeline configuration and current version for
1299
- * the specified project. Use this before updating to get the current
1300
- * version for atomic updates.
1301
- *
1302
- * @param options - Get project options
1303
- * @param options.projectId - Unique identifier of the project to retrieve
1304
- * @returns Promise resolving to project data with success status, pipeline, and version
1305
- * @throws Error if project doesn't exist or retrieval fails
1306
- *
1307
- * @example
1308
- * ```typescript
1309
- * // Get a project
1310
- * try {
1311
- * const project = await client.getProject({ projectId: 'proj-123' });
1312
- * console.log(`Project: ${project.name}`);
1313
- * console.log(`Version: ${project.version}`);
1314
- * } catch (error) {
1315
- * if (error.message.includes('NOT_FOUND')) {
1316
- * console.log("Project doesn't exist");
1317
- * }
1318
- * }
1497
+ * Remove a monitor subscription. Decrements reference counts for the given
1498
+ * types. Only unsubscribes a type from the server when its count reaches 0.
1319
1499
  *
1320
- * // Before updating - get current version
1321
- * const project = await client.getProject({ projectId: 'proj-123' });
1322
- * project.name = 'Updated';
1323
- * await client.saveProject({
1324
- * projectId: 'proj-123',
1325
- * pipeline: project,
1326
- * expectedVersion: project.version
1327
- * });
1328
- * ```
1500
+ * @param key - Monitor key (must match the key used in addMonitor).
1501
+ * @param types - Event types to unsubscribe from.
1329
1502
  */
1330
- async getProject(options) {
1331
- const { projectId } = options;
1332
- // Validate inputs
1333
- if (!projectId) {
1334
- throw new Error('projectId is required');
1503
+ async removeMonitor(key, types) {
1504
+ const keyStr = this._monitorKeyToString(key);
1505
+ const refCounts = this._monitorKeys.get(keyStr);
1506
+ if (!refCounts)
1507
+ return;
1508
+ // Decrement reference counts
1509
+ for (const t of types) {
1510
+ const current = refCounts.get(t) ?? 0;
1511
+ if (current <= 1) {
1512
+ refCounts.delete(t);
1513
+ }
1514
+ else {
1515
+ refCounts.set(t, current - 1);
1516
+ }
1335
1517
  }
1336
- // Build request
1337
- const args = {
1338
- subcommand: 'get_project',
1339
- projectId,
1340
- };
1341
- // Send request to server
1342
- const request = this.buildRequest('rrext_store', { arguments: args });
1343
- const response = await this.request(request);
1344
- // Check for errors
1345
- if (this.didFail(response)) {
1346
- const errorMsg = response.message || 'Unknown error retrieving project';
1347
- this.debugMessage(`Project retrieval failed: ${errorMsg}`);
1348
- throw new Error(errorMsg);
1518
+ // Send merged types (or unsubscribe if empty)
1519
+ await this._syncMonitor(key, refCounts);
1520
+ // Clean up empty keys
1521
+ if (refCounts.size === 0) {
1522
+ this._monitorKeys.delete(keyStr);
1349
1523
  }
1350
- // Extract and return response
1351
- this.debugMessage(`Project retrieved successfully: ${projectId}`);
1352
- return response.body;
1353
1524
  }
1354
1525
  /**
1355
- * Delete a project by its ID.
1356
- *
1357
- * Permanently removes a project from storage. Optionally verify the
1358
- * version before deletion to ensure you're deleting the version you
1359
- * expect (prevents accidental deletion of modified projects).
1360
- *
1361
- * @param options - Delete project options
1362
- * @param options.projectId - Unique identifier of the project to delete
1363
- * @param options.expectedVersion - Expected current version for atomic deletion (required)
1364
- * @returns Promise resolving to deletion result with success status and message
1365
- * @throws Error if project doesn't exist, version mismatch, or deletion fails
1366
- *
1367
- * @example
1368
- * ```typescript
1369
- * // Safe deletion with version check
1370
- * const project = await client.getProject({ projectId: 'proj-123' });
1371
- * try {
1372
- * const result = await client.deleteProject({
1373
- * projectId: 'proj-123',
1374
- * expectedVersion: project.version
1375
- * });
1376
- * console.log('Project deleted successfully');
1377
- * } catch (error) {
1378
- * if (error.message.includes('CONFLICT')) {
1379
- * console.log('Project was modified, deletion cancelled');
1380
- * }
1381
- * }
1382
- * ```
1526
+ * Send the merged type list for a monitor key to the server.
1383
1527
  */
1384
- async deleteProject(options) {
1385
- const { projectId, expectedVersion } = options;
1386
- // Validate inputs
1387
- if (!projectId) {
1388
- throw new Error('projectId is required');
1528
+ async _syncMonitor(key, refCounts) {
1529
+ if (!this.isConnected())
1530
+ return;
1531
+ const mergedTypes = Array.from(refCounts.keys());
1532
+ if ('token' in key) {
1533
+ await this.call('rrext_monitor', { types: mergedTypes }, { token: key.token });
1389
1534
  }
1390
- // Build request
1391
- const args = {
1392
- subcommand: 'delete_project',
1393
- projectId,
1394
- };
1395
- // Add optional version for atomic deletion
1396
- if (expectedVersion !== undefined) {
1397
- args.expectedVersion = expectedVersion;
1398
- }
1399
- // Send request to server
1400
- const request = this.buildRequest('rrext_store', { arguments: args });
1401
- const response = await this.request(request);
1402
- // Check for errors
1403
- if (this.didFail(response)) {
1404
- const errorMsg = response.message || 'Unknown error deleting project';
1405
- this.debugMessage(`Project deletion failed: ${errorMsg}`);
1406
- throw new Error(errorMsg);
1535
+ else {
1536
+ const args = {
1537
+ projectId: key.projectId,
1538
+ source: key.source,
1539
+ types: mergedTypes,
1540
+ };
1541
+ if (key.pipeId !== undefined) {
1542
+ args.pipeId = key.pipeId;
1543
+ }
1544
+ await this.call('rrext_monitor', args);
1407
1545
  }
1408
- // Extract and return response
1409
- this.debugMessage(`Project deleted successfully: ${projectId}`);
1410
- return response.body;
1411
1546
  }
1412
1547
  /**
1413
- * List all projects for the current user.
1414
- *
1415
- * Retrieves a summary of all projects stored for the authenticated user.
1416
- * Each project summary includes the ID, name, list of data sources, and total component count.
1417
- *
1418
- * @returns Promise resolving to list result with success status, projects array, and count
1419
- * @throws Error if retrieval fails
1420
- *
1421
- * @example
1422
- * ```typescript
1423
- * // List all projects
1424
- * const result = await client.getAllProjects();
1425
- * console.log(`Found ${result.count} projects:`);
1426
- * for (const project of result.projects) {
1427
- * console.log(`- ${project.id}: ${project.name} (${project.totalComponents} components)`);
1428
- * for (const source of project.sources) {
1429
- * console.log(` * ${source.name} (${source.provider})`);
1430
- * }
1431
- * }
1432
- *
1433
- * // Find specific project
1434
- * const result = await client.getAllProjects();
1435
- * const myProject = result.projects.find(p => p.id === 'proj-123');
1436
- * ```
1548
+ * Replay all active monitor subscriptions to the server.
1549
+ * Called automatically after reconnection.
1437
1550
  */
1438
- async getAllProjects() {
1439
- // Build request
1440
- const args = {
1441
- subcommand: 'get_all_projects',
1442
- };
1443
- // Send request to server
1444
- const request = this.buildRequest('rrext_store', { arguments: args });
1445
- const response = await this.request(request);
1446
- // Check for errors
1447
- if (this.didFail(response)) {
1448
- const errorMsg = response.message || 'Unknown error listing projects';
1449
- this.debugMessage(`Project list retrieval failed: ${errorMsg}`);
1450
- throw new Error(errorMsg);
1551
+ async _resubscribeAllMonitors() {
1552
+ for (const [keyStr, refCounts] of this._monitorKeys) {
1553
+ if (refCounts.size === 0)
1554
+ continue;
1555
+ const key = this._monitorStringToKey(keyStr);
1556
+ if (key) {
1557
+ try {
1558
+ await this._syncMonitor(key, refCounts);
1559
+ }
1560
+ catch (error) {
1561
+ this.debugMessage(`Failed to resubscribe monitor ${keyStr}: ${error}`);
1562
+ }
1563
+ }
1564
+ }
1565
+ }
1566
+ /**
1567
+ * Convert a MonitorKey to a stable string for map lookup.
1568
+ */
1569
+ _monitorKeyToString(key) {
1570
+ if ('token' in key) {
1571
+ return `t:${key.token}`;
1572
+ }
1573
+ let s = `p:${key.projectId}.${key.source}`;
1574
+ if (key.pipeId !== undefined) {
1575
+ s += `.${key.pipeId}`;
1451
1576
  }
1452
- // Extract and return response
1453
- const projectCount = response.body?.count || 0;
1454
- this.debugMessage(`Projects retrieved successfully: ${projectCount} projects`);
1455
- return response.body;
1577
+ return s;
1578
+ }
1579
+ /**
1580
+ * Reverse a key-string back to a MonitorKey (for resubscribeAll).
1581
+ */
1582
+ _monitorStringToKey(keyStr) {
1583
+ if (keyStr.startsWith('t:')) {
1584
+ return { token: keyStr.slice(2) };
1585
+ }
1586
+ if (keyStr.startsWith('p:')) {
1587
+ const rest = keyStr.slice(2);
1588
+ const dotIdx = rest.indexOf('.');
1589
+ if (dotIdx === -1)
1590
+ return null;
1591
+ const projectId = rest.slice(0, dotIdx);
1592
+ const remaining = rest.slice(dotIdx + 1);
1593
+ const parts = remaining.split('.');
1594
+ if (parts.length === 2 && !isNaN(Number(parts[1]))) {
1595
+ return { projectId, source: parts[0], pipeId: Number(parts[1]) };
1596
+ }
1597
+ return { projectId, source: remaining };
1598
+ }
1599
+ return null;
1456
1600
  }
1457
1601
  // ============================================================================
1458
- // TEMPLATE STORAGE MANAGEMENT (System-wide templates)
1602
+ // TEMPLATE STORAGE MANAGEMENT (convenience wrappers using fsReadJson/fsWriteJson)
1459
1603
  // ============================================================================
1460
1604
  /**
1461
- * Save or update a template pipeline.
1605
+ * Persist a pipeline configuration as a named template in the account store.
1462
1606
  *
1463
- * Stores a template pipeline configuration on the server. Templates are system-wide
1464
- * and accessible to all users. If the template already exists, it will be updated.
1465
- * Use expectedVersion to ensure you're updating the version you expect.
1607
+ * Templates are stored as JSON files under `.templates/<templateId>.json`.
1608
+ * Saving a template with an existing ID overwrites the previous version.
1466
1609
  *
1467
- * @param options - Save template options
1468
- * @param options.templateId - Unique identifier for the template
1469
- * @param options.pipeline - Pipeline configuration object
1470
- * @param options.expectedVersion - Expected current version for atomic updates (optional)
1471
- * @returns Promise resolving to save result with success status, templateId, and new version
1472
- * @throws Error if save fails due to version mismatch, storage error, or invalid input
1610
+ * @param options.templateId - Unique identifier for the template (no path separators)
1611
+ * @param options.pipeline - Pipeline configuration object to save
1612
+ * @throws Error if templateId is invalid or pipeline is not a non-empty object
1473
1613
  */
1474
1614
  async saveTemplate(options) {
1475
- const { templateId, pipeline, expectedVersion } = options;
1476
- // Validate inputs
1477
- if (!templateId) {
1478
- throw new Error('templateId is required');
1479
- }
1480
- if (!pipeline || typeof pipeline !== 'object') {
1615
+ // Validate the template ID to prevent path traversal or invalid filenames
1616
+ this.validateId(options.templateId, 'templateId');
1617
+ // Ensure the pipeline payload is a non-null object before writing
1618
+ if (!options.pipeline || typeof options.pipeline !== 'object')
1481
1619
  throw new Error('pipeline must be a non-empty object');
1482
- }
1483
- // Build request arguments
1484
- const args = {
1485
- subcommand: 'save_template',
1486
- templateId,
1487
- pipeline,
1488
- };
1489
- // Add optional version for atomic updates
1490
- if (expectedVersion !== undefined) {
1491
- args.expectedVersion = expectedVersion;
1492
- }
1493
- // Send request to server
1494
- const request = this.buildRequest('rrext_store', { arguments: args });
1495
- const response = await this.request(request);
1496
- // Check for errors
1497
- if (this.didFail(response)) {
1498
- const errorMsg = response.message || 'Unknown error saving template';
1499
- this.debugMessage(`Template save failed: ${errorMsg}`);
1500
- throw new Error(errorMsg);
1501
- }
1502
- // Extract and return response
1503
- this.debugMessage(`Template saved successfully: ${templateId}, version: ${response.body?.version}`);
1504
- return response.body;
1620
+ // Serialise and write the pipeline under the .templates virtual directory
1621
+ await this.fsWriteJson(`.templates/${options.templateId}.json`, options.pipeline);
1505
1622
  }
1506
1623
  /**
1507
- * Retrieve a template by its ID.
1624
+ * Retrieve a previously saved pipeline template from the account store.
1625
+ *
1626
+ * @param options.templateId - Unique identifier of the template to retrieve
1627
+ * @returns The pipeline configuration object that was saved
1628
+ * @throws Error if the template does not exist or templateId is invalid
1508
1629
  */
1509
1630
  async getTemplate(options) {
1510
- const { templateId } = options;
1511
- // Validate inputs
1512
- if (!templateId) {
1513
- throw new Error('templateId is required');
1514
- }
1515
- // Build request
1516
- const args = {
1517
- subcommand: 'get_template',
1518
- templateId,
1519
- };
1520
- // Send request to server
1521
- const request = this.buildRequest('rrext_store', { arguments: args });
1522
- const response = await this.request(request);
1523
- // Check for errors
1524
- if (this.didFail(response)) {
1525
- const errorMsg = response.message || 'Unknown error retrieving template';
1526
- this.debugMessage(`Template retrieval failed: ${errorMsg}`);
1527
- throw new Error(errorMsg);
1528
- }
1529
- // Extract and return response
1530
- this.debugMessage(`Template retrieved successfully: ${templateId}`);
1531
- return response.body;
1631
+ // Validate the ID before constructing the storage path
1632
+ this.validateId(options.templateId, 'templateId');
1633
+ // Read and parse the JSON file from the .templates virtual directory
1634
+ return this.fsReadJson(`.templates/${options.templateId}.json`);
1532
1635
  }
1533
1636
  /**
1534
- * Delete a template by its ID.
1637
+ * Delete a pipeline template from the account store.
1638
+ *
1639
+ * @param options.templateId - Unique identifier of the template to delete
1640
+ * @throws Error if the template does not exist or templateId is invalid
1535
1641
  */
1536
1642
  async deleteTemplate(options) {
1537
- const { templateId, expectedVersion } = options;
1538
- // Validate inputs
1539
- if (!templateId) {
1540
- throw new Error('templateId is required');
1541
- }
1542
- // Build request
1543
- const args = {
1544
- subcommand: 'delete_template',
1545
- templateId,
1546
- };
1547
- // Add optional version for atomic deletion
1548
- if (expectedVersion !== undefined) {
1549
- args.expectedVersion = expectedVersion;
1550
- }
1551
- // Send request to server
1552
- const request = this.buildRequest('rrext_store', { arguments: args });
1553
- const response = await this.request(request);
1554
- // Check for errors
1555
- if (this.didFail(response)) {
1556
- const errorMsg = response.message || 'Unknown error deleting template';
1557
- this.debugMessage(`Template deletion failed: ${errorMsg}`);
1558
- throw new Error(errorMsg);
1559
- }
1560
- // Extract and return response
1561
- this.debugMessage(`Template deleted successfully: ${templateId}`);
1562
- return response.body;
1643
+ // Validate the ID before constructing the storage path
1644
+ this.validateId(options.templateId, 'templateId');
1645
+ // Delete the JSON file from the .templates virtual directory
1646
+ await this.fsDelete(`.templates/${options.templateId}.json`);
1563
1647
  }
1564
1648
  /**
1565
- * List all templates.
1649
+ * List all pipeline templates stored in the account store.
1650
+ *
1651
+ * Reads the `.templates` directory, parses each `.json` file, and extracts
1652
+ * a summary for each template. Files that cannot be parsed are silently
1653
+ * skipped so a single corrupt template does not break the entire listing.
1654
+ *
1655
+ * @returns Array of template summaries sorted in directory-listing order.
1656
+ * Each entry contains the template ID, display name, source components,
1657
+ * and total component count.
1566
1658
  */
1567
1659
  async getAllTemplates() {
1568
- // Build request
1569
- const args = {
1570
- subcommand: 'get_all_templates',
1571
- };
1572
- // Send request to server
1573
- const request = this.buildRequest('rrext_store', { arguments: args });
1574
- const response = await this.request(request);
1575
- // Check for errors
1576
- if (this.didFail(response)) {
1577
- const errorMsg = response.message || 'Unknown error listing templates';
1578
- this.debugMessage(`Template list retrieval failed: ${errorMsg}`);
1579
- throw new Error(errorMsg);
1660
+ // Fetch the list of entries under the .templates virtual directory
1661
+ const dir = await this.fsListDir('.templates');
1662
+ const templates = [];
1663
+ for (const entry of dir.entries) {
1664
+ // Skip directories and any non-JSON files (e.g. temp files)
1665
+ if (entry.type !== 'file' || !entry.name.endsWith('.json'))
1666
+ continue;
1667
+ try {
1668
+ // Derive the template ID by stripping the .json extension
1669
+ const id = entry.name.slice(0, -5);
1670
+ // Load and parse the template JSON
1671
+ const pipeline = await this.fsReadJson(`.templates/${entry.name}`);
1672
+ // Extract Source-mode components to populate the sources summary list
1673
+ const sources = (pipeline.components || []).filter((c) => c.config?.mode === 'Source').map((c) => ({ id: c.id, provider: c.provider, name: c.config?.name || c.id }));
1674
+ // Push the summary (use template ID as display name)
1675
+ templates.push({ id, name: id, sources, totalComponents: (pipeline.components || []).length });
1676
+ }
1677
+ catch (err) {
1678
+ // Log the failure but continue so one bad file doesn't block others
1679
+ console.debug(`[RocketRideClient] Failed to read .templates/${entry.name}:`, err);
1680
+ continue;
1681
+ }
1580
1682
  }
1581
- // Extract and return response
1582
- const templateCount = response.body?.count || 0;
1583
- this.debugMessage(`Templates retrieved successfully: ${templateCount} templates`);
1584
- return response.body;
1683
+ return templates;
1585
1684
  }
1586
1685
  // ============================================================================
1587
- // LOG STORAGE MANAGEMENT (Per-project log files for historical tracking)
1686
+ // LOG STORAGE MANAGEMENT (convenience wrappers using fsReadJson/fsWriteJson)
1588
1687
  // ============================================================================
1589
1688
  /**
1590
- * Save a log file for a source run.
1689
+ * Persist a pipeline execution log to the account store.
1690
+ *
1691
+ * Logs are stored under `.logs/<projectId>/<source>-<startTime>.log`.
1692
+ * The filename is derived from `contents.body.startTime` so logs are
1693
+ * naturally sortable by execution start time.
1694
+ *
1695
+ * @param options.projectId - Project identifier that owns this log
1696
+ * @param options.source - Source component identifier the log is associated with
1697
+ * @param options.contents - Log payload; must contain `body.startTime`
1698
+ * @returns The generated filename (e.g. `"ingest-1714000000000.log"`)
1699
+ * @throws Error if any ID is invalid, contents is not an object, or startTime is missing
1591
1700
  */
1592
1701
  async saveLog(options) {
1593
- const { projectId, source, contents } = options;
1594
- // Validate inputs
1595
- if (!projectId) {
1596
- throw new Error('projectId is required');
1597
- }
1598
- if (!source) {
1599
- throw new Error('source is required');
1600
- }
1601
- if (!contents || typeof contents !== 'object') {
1702
+ // Validate identifiers to prevent path traversal
1703
+ this.validateId(options.projectId, 'projectId');
1704
+ this.validateId(options.source, 'source');
1705
+ // Ensure the contents payload is a non-null object
1706
+ if (!options.contents || typeof options.contents !== 'object')
1602
1707
  throw new Error('contents must be a non-empty object');
1603
- }
1604
- // Build request arguments
1605
- const args = {
1606
- subcommand: 'save_log',
1607
- projectId,
1608
- source,
1609
- contents,
1610
- };
1611
- // Send request to server
1612
- const request = this.buildRequest('rrext_store', { arguments: args });
1613
- const response = await this.request(request);
1614
- // Check for errors
1615
- if (this.didFail(response)) {
1616
- const errorMsg = response.message || 'Unknown error saving log';
1617
- this.debugMessage(`Log save failed: ${errorMsg}`);
1618
- throw new Error(errorMsg);
1619
- }
1620
- // Extract and return response
1621
- this.debugMessage(`Log saved successfully: ${response.body?.filename}`);
1622
- return response.body;
1708
+ // startTime is required; it forms part of the filename for chronological ordering.
1709
+ // Reject anything other than a non-empty number or numeric-looking string to
1710
+ // prevent path-separator chars from slipping into the generated filename.
1711
+ const startTime = options.contents?.body?.startTime;
1712
+ if (startTime === undefined || startTime === null)
1713
+ throw new Error('contents must contain body.startTime');
1714
+ if (typeof startTime !== 'number' && typeof startTime !== 'string') {
1715
+ throw new Error('contents.body.startTime must be a number or string');
1716
+ }
1717
+ const startTimeStr = String(startTime);
1718
+ if (!startTimeStr || /[\\/]/.test(startTimeStr)) {
1719
+ throw new Error('contents.body.startTime must not be empty or contain path separators');
1720
+ }
1721
+ // Construct a deterministic filename from source and start time
1722
+ const filename = `${options.source}-${startTimeStr}.log`;
1723
+ // Write the log JSON to the per-project logs directory
1724
+ await this.fsWriteJson(`.logs/${options.projectId}/${filename}`, options.contents);
1725
+ return filename;
1623
1726
  }
1624
1727
  /**
1625
- * Get a log file by source name and start time.
1728
+ * Retrieve a previously saved pipeline execution log from the account store.
1729
+ *
1730
+ * @param options.projectId - Project identifier that owns the log
1731
+ * @param options.name - Filename of the log (as returned by saveLog)
1732
+ * @returns The log payload that was saved
1733
+ * @throws Error if the log does not exist or projectId is invalid
1626
1734
  */
1627
1735
  async getLog(options) {
1628
- const { projectId, source, startTime } = options;
1629
- // Validate inputs
1630
- if (!projectId) {
1631
- throw new Error('projectId is required');
1632
- }
1633
- if (!source) {
1634
- throw new Error('source is required');
1635
- }
1636
- if (startTime === undefined || startTime === null) {
1637
- throw new Error('startTime is required');
1638
- }
1639
- // Build request
1640
- const args = {
1641
- subcommand: 'get_log',
1642
- projectId,
1643
- source,
1644
- startTime,
1645
- };
1646
- // Send request to server
1647
- const request = this.buildRequest('rrext_store', { arguments: args });
1648
- const response = await this.request(request);
1649
- // Check for errors
1650
- if (this.didFail(response)) {
1651
- const errorMsg = response.message || 'Unknown error retrieving log';
1652
- this.debugMessage(`Log retrieval failed: ${errorMsg}`);
1653
- throw new Error(errorMsg);
1654
- }
1655
- // Extract and return response
1656
- this.debugMessage(`Log retrieved successfully: ${projectId}/${source}`);
1657
- return response.body;
1736
+ // Validate the project ID before constructing the storage path
1737
+ this.validateId(options.projectId, 'projectId');
1738
+ if (!options.name)
1739
+ throw new Error('name is required');
1740
+ // Read and parse the log JSON from the per-project logs directory
1741
+ return this.fsReadJson(`.logs/${options.projectId}/${options.name}`);
1742
+ }
1743
+ /**
1744
+ * Delete a pipeline execution log from the account store.
1745
+ *
1746
+ * @param options.projectId - Project identifier that owns the log
1747
+ * @param options.name - Filename of the log to delete
1748
+ * @throws Error if the log does not exist or projectId is invalid
1749
+ */
1750
+ async deleteLog(options) {
1751
+ // Validate the project ID before constructing the storage path
1752
+ this.validateId(options.projectId, 'projectId');
1753
+ if (!options.name)
1754
+ throw new Error('name is required');
1755
+ // Delete the log file from the per-project logs directory
1756
+ await this.fsDelete(`.logs/${options.projectId}/${options.name}`);
1658
1757
  }
1659
1758
  /**
1660
- * List log files for a project.
1759
+ * List pipeline execution logs stored for a project, optionally filtered by source.
1760
+ *
1761
+ * Results are sorted ascending by `modified` timestamp so the oldest log
1762
+ * appears first. The caller can page through or slice the array as needed.
1763
+ *
1764
+ * @param options.projectId - Project identifier whose logs to list
1765
+ * @param options.source - Optional source component filter; when set, only logs
1766
+ * whose filename starts with `<source>-` are returned
1767
+ * @returns Array of log name and optional modified timestamp, sorted oldest-first
1768
+ * @throws Error if projectId (or source when provided) is invalid
1661
1769
  */
1662
1770
  async listLogs(options) {
1663
- const { projectId, source, page } = options;
1664
- // Validate inputs
1665
- if (!projectId) {
1666
- throw new Error('projectId is required');
1667
- }
1668
- // Build request
1669
- const args = {
1670
- subcommand: 'list_logs',
1671
- projectId,
1672
- };
1673
- // Add optional parameters
1674
- if (source !== undefined) {
1675
- args.source = source;
1771
+ // Validate identifiers before constructing the storage path
1772
+ this.validateId(options.projectId, 'projectId');
1773
+ if (options.source)
1774
+ this.validateId(options.source, 'source');
1775
+ // List all entries in the per-project logs directory
1776
+ const dir = await this.fsListDir(`.logs/${options.projectId}`);
1777
+ // Keep only .log files and map to the public shape (name + modified)
1778
+ let logs = dir.entries.filter((e) => e.type === 'file' && e.name.endsWith('.log')).map((e) => ({ name: e.name, modified: e.modified }));
1779
+ // Apply optional source prefix filter when a source was specified
1780
+ if (options.source) {
1781
+ logs = logs.filter((l) => l.name.startsWith(`${options.source}-`));
1782
+ }
1783
+ // Sort ascending by modified timestamp; treat missing timestamps as epoch 0
1784
+ logs.sort((a, b) => (a.modified || 0) - (b.modified || 0));
1785
+ return logs;
1786
+ }
1787
+ // ============================================================================
1788
+ // HANDLE-BASED FILE STORE OPERATIONS
1789
+ // ============================================================================
1790
+ /**
1791
+ * Open a file handle for reading or writing.
1792
+ *
1793
+ * @param path - Relative path within the account store
1794
+ * @param mode - 'r' for read, 'w' for write (default: 'r')
1795
+ * @param offset - Initial byte offset (read mode only)
1796
+ * @returns Object with 'handle' (string). Read mode also includes 'size' (number).
1797
+ */
1798
+ async fsOpen(path, mode = 'r') {
1799
+ this.validateStorePath(path);
1800
+ return this.call('rrext_store', { subcommand: 'fs_open', path, mode });
1801
+ }
1802
+ /**
1803
+ * Read data from an open read handle.
1804
+ *
1805
+ * @param handle - Handle ID returned by fsOpen
1806
+ * @param offset - Byte offset to read from
1807
+ * @param length - Max bytes to read (default 4 MB). Empty Uint8Array indicates EOF.
1808
+ * @returns The bytes read
1809
+ */
1810
+ async fsRead(handle, offset = 0, length = 4194304) {
1811
+ // Bypass call() which unwraps response.body, losing response.arguments
1812
+ // where the server places the binary data payload.
1813
+ const message = this.buildRequest('rrext_store', {
1814
+ arguments: { subcommand: 'fs_read', handle, offset, length },
1815
+ });
1816
+ this._onTrace?.(index_js_1.TraceType.Request, message);
1817
+ const response = await this.request(message);
1818
+ if (response.success === false) {
1819
+ this._onTrace?.(index_js_1.TraceType.Error, response);
1820
+ throw new Error(response.message ?? 'fs_read failed');
1821
+ }
1822
+ this._onTrace?.(index_js_1.TraceType.Success, response);
1823
+ return response.arguments?.data || new Uint8Array(0);
1824
+ }
1825
+ /**
1826
+ * Write data to an open write handle.
1827
+ *
1828
+ * @param handle - Handle ID returned by fsOpen
1829
+ * @param data - Raw bytes to write
1830
+ * @returns Number of bytes written
1831
+ */
1832
+ async fsWrite(handle, data) {
1833
+ const body = await this.call('rrext_store', { subcommand: 'fs_write', handle, data });
1834
+ return body?.bytesWritten ?? 0;
1835
+ }
1836
+ /**
1837
+ * Close a file handle.
1838
+ *
1839
+ * @param handle - Handle ID returned by fsOpen
1840
+ * @param mode - 'r' or 'w' (must match the mode used in fsOpen)
1841
+ */
1842
+ async fsClose(handle, mode) {
1843
+ await this.call('rrext_store', { subcommand: 'fs_close', handle, mode });
1844
+ }
1845
+ /**
1846
+ * Delete a file.
1847
+ *
1848
+ * @param path - Relative path within the account store
1849
+ * @throws Error if file does not exist or delete fails
1850
+ */
1851
+ async fsDelete(path) {
1852
+ this.validateStorePath(path);
1853
+ await this.call('rrext_store', { subcommand: 'fs_delete', path });
1854
+ }
1855
+ /**
1856
+ * List immediate children of a directory.
1857
+ *
1858
+ * @param path - Relative directory path (default: account root)
1859
+ * @returns Directory entries with name and type (file or dir)
1860
+ */
1861
+ async fsListDir(path = '') {
1862
+ if (path)
1863
+ this.validateStorePath(path);
1864
+ return this.call('rrext_store', { subcommand: 'fs_list_dir', path });
1865
+ }
1866
+ /**
1867
+ * Create a directory.
1868
+ *
1869
+ * @param path - Relative directory path
1870
+ */
1871
+ async fsMkdir(path) {
1872
+ this.validateStorePath(path);
1873
+ await this.call('rrext_store', { subcommand: 'fs_mkdir', path });
1874
+ }
1875
+ /**
1876
+ * Remove a directory.
1877
+ *
1878
+ * @param path - Relative directory path
1879
+ * @param recursive - If true, delete contents recursively (default: false)
1880
+ * @throws Error if directory is not empty (when recursive is false) or delete fails
1881
+ */
1882
+ async fsRmdir(path, recursive = false) {
1883
+ this.validateStorePath(path);
1884
+ await this.call('rrext_store', { subcommand: 'fs_rmdir', path, recursive });
1885
+ }
1886
+ /**
1887
+ * Get file or directory metadata.
1888
+ *
1889
+ * @param path - Relative path within the account store
1890
+ * @returns Metadata including existence, type, size (bytes), and modified epoch timestamp (for files)
1891
+ */
1892
+ async fsStat(path) {
1893
+ this.validateStorePath(path);
1894
+ return this.call('rrext_store', { subcommand: 'fs_stat', path });
1895
+ }
1896
+ /**
1897
+ * Rename a file or directory.
1898
+ *
1899
+ * On object stores this is implemented as copy + delete. For directories,
1900
+ * all contents are moved recursively.
1901
+ *
1902
+ * @param oldPath - Current relative path within the account store
1903
+ * @param newPath - New relative path within the account store
1904
+ * @throws Error if oldPath does not exist or rename fails
1905
+ */
1906
+ async fsRename(oldPath, newPath) {
1907
+ this.validateStorePath(oldPath);
1908
+ this.validateStorePath(newPath);
1909
+ await this.call('rrext_store', { subcommand: 'fs_rename', old_path: oldPath, new_path: newPath });
1910
+ }
1911
+ // ============================================================================
1912
+ // CONVENIENCE WRAPPERS (text/JSON over binary, handle open/close internally)
1913
+ // ============================================================================
1914
+ /** Read a file as a UTF-8 string. */
1915
+ async fsReadString(path) {
1916
+ const { handle } = await this.fsOpen(path, 'r');
1917
+ try {
1918
+ const chunks = [];
1919
+ let offset = 0;
1920
+ while (true) {
1921
+ const chunk = await this.fsRead(handle, offset);
1922
+ if (chunk.length === 0)
1923
+ break;
1924
+ chunks.push(chunk);
1925
+ offset += chunk.length;
1926
+ }
1927
+ const total = new Uint8Array(offset);
1928
+ let pos = 0;
1929
+ for (const chunk of chunks) {
1930
+ total.set(chunk, pos);
1931
+ pos += chunk.length;
1932
+ }
1933
+ return new TextDecoder().decode(total);
1676
1934
  }
1677
- if (page !== undefined) {
1678
- args.page = page;
1935
+ finally {
1936
+ await this.fsClose(handle, 'r');
1679
1937
  }
1680
- // Send request to server
1681
- const request = this.buildRequest('rrext_store', { arguments: args });
1682
- const response = await this.request(request);
1683
- // Check for errors
1684
- if (this.didFail(response)) {
1685
- const errorMsg = response.message || 'Unknown error listing logs';
1686
- this.debugMessage(`Log list retrieval failed: ${errorMsg}`);
1687
- throw new Error(errorMsg);
1938
+ }
1939
+ /** Write a UTF-8 string to a file. */
1940
+ async fsWriteString(path, text) {
1941
+ const { handle } = await this.fsOpen(path, 'w');
1942
+ try {
1943
+ await this.fsWrite(handle, new TextEncoder().encode(text));
1944
+ await this.fsClose(handle, 'w');
1945
+ }
1946
+ catch (err) {
1947
+ try {
1948
+ await this.fsClose(handle, 'w');
1949
+ }
1950
+ catch {
1951
+ /* best-effort */
1952
+ }
1953
+ throw err;
1954
+ }
1955
+ }
1956
+ /** Read a JSON file. */
1957
+ async fsReadJson(path) {
1958
+ const text = await this.fsReadString(path);
1959
+ return JSON.parse(text);
1960
+ }
1961
+ /** Write an object as JSON. */
1962
+ async fsWriteJson(path, obj) {
1963
+ await this.fsWriteString(path, JSON.stringify(obj, null, 2));
1964
+ }
1965
+ /**
1966
+ * Validate a relative path intended for the account file store.
1967
+ *
1968
+ * Splits the path on `/` (after normalising backslashes) and checks every
1969
+ * segment for path-traversal attempts (`..`) and forbidden characters.
1970
+ * Empty segments (from leading/trailing/double slashes) are skipped because
1971
+ * they carry no security risk on the server side.
1972
+ *
1973
+ * @param path - Relative path to validate (e.g. `.templates/my-pipe.json`)
1974
+ * @throws Error if any segment is `..` or contains illegal characters
1975
+ */
1976
+ validateStorePath(path) {
1977
+ // Normalise Windows-style backslashes to forward slashes before splitting
1978
+ for (const segment of path.replace(/\\/g, '/').split('/')) {
1979
+ // Reject parent-directory traversal attempts in any position of the path
1980
+ if (segment === '..')
1981
+ throw new Error(`Path traversal not allowed: ${path}`);
1982
+ // Only validate non-empty segments (empty ones arise from leading/trailing slashes)
1983
+ if (segment) {
1984
+ for (const ch of segment) {
1985
+ // Reject forbidden metacharacters and ASCII control characters (< 0x20)
1986
+ if (RocketRideClient.INVALID_PATH_CHARS.has(ch) || ch.charCodeAt(0) < 0x20) {
1987
+ throw new Error(`Path contains invalid characters: ${path}`);
1988
+ }
1989
+ }
1990
+ }
1991
+ }
1992
+ }
1993
+ /**
1994
+ * Validate a single identifier (projectId, source, templateId, etc.) used
1995
+ * to construct store paths.
1996
+ *
1997
+ * IDs must be non-empty strings that contain no path separators and no
1998
+ * characters from the forbidden set. This prevents an ID from escaping its
1999
+ * intended directory when interpolated into a path.
2000
+ *
2001
+ * @param value - The identifier string to validate
2002
+ * @param name - Human-readable field name used in error messages (e.g. `"projectId"`)
2003
+ * @throws Error if value is empty, contains path separators, or contains illegal characters
2004
+ */
2005
+ validateId(value, name) {
2006
+ // Require a non-empty value
2007
+ if (!value)
2008
+ throw new Error(`${name} is required`);
2009
+ // Reject forward and backward slashes to prevent path injection
2010
+ if (value.includes('/') || value.includes('\\'))
2011
+ throw new Error(`${name} must not contain path separators`);
2012
+ // Reject any forbidden metacharacter or ASCII control character
2013
+ for (const ch of value) {
2014
+ if (RocketRideClient.INVALID_PATH_CHARS.has(ch) || ch.charCodeAt(0) < 0x20) {
2015
+ throw new Error(`${name} contains invalid characters: ${value}`);
2016
+ }
1688
2017
  }
1689
- // Extract and return response
1690
- const logCount = response.body?.total_count || 0;
1691
- this.debugMessage(`Logs retrieved successfully: ${logCount} logs`);
1692
- return response.body;
1693
2018
  }
1694
2019
  // ============================================================================
1695
- // RAW REQUEST METHOD
2020
+ // DASHBOARD METHODS
1696
2021
  // ============================================================================
1697
2022
  /**
1698
- * Send an arbitrary DAP command with command name, arguments, and optional token.
2023
+ * Retrieve a server dashboard snapshot.
1699
2024
  *
1700
- * This is a convenience method for callers that don't want to construct
1701
- * full DAPMessage objects. It builds the request internally and delegates
1702
- * to the underlying request() method.
2025
+ * Returns the current state of all connections, tasks, and aggregate
2026
+ * metrics from the server. Requires 'task.monitor' permission.
1703
2027
  *
1704
- * @param command - The DAP command name (e.g., 'rrext_services', 'rrext_monitor')
1705
- * @param args - Optional arguments for the command
1706
- * @param token - Optional task/session token
1707
- * @param timeout - Optional per-request timeout in ms
1708
- * @returns The response DAPMessage from the server
2028
+ * @returns DashboardResponse containing overview, connections, and tasks
1709
2029
  */
1710
- async dapRequest(command, args, token, timeout) {
1711
- const message = this.buildRequest(command, {
1712
- arguments: args,
1713
- token,
1714
- });
1715
- return await this.request(message, timeout);
2030
+ async getDashboard() {
2031
+ return this.call('rrext_dashboard', {});
2032
+ }
2033
+ // ============================================================================
2034
+ // CPROFILE PROFILING
2035
+ // ============================================================================
2036
+ /**
2037
+ * Start a cProfile profiling session on the server process or a pipeline.
2038
+ *
2039
+ * @param target - Task token to profile a pipeline subprocess, or
2040
+ * undefined/null to profile the server process itself.
2041
+ * @param session - Optional human-readable session name.
2042
+ * @returns Status object with session info and start time.
2043
+ */
2044
+ async cprofileStart(target, session) {
2045
+ const args = {};
2046
+ if (target)
2047
+ args.target = target;
2048
+ if (session)
2049
+ args.session = session;
2050
+ return this.call('rrext_cprofile_start', args);
2051
+ }
2052
+ /**
2053
+ * Stop the active cProfile profiling session.
2054
+ *
2055
+ * @param target - Task token if profiling a pipeline, or undefined for server.
2056
+ * @returns Result with session name and runtime.
2057
+ */
2058
+ async cprofileStop(target) {
2059
+ const args = {};
2060
+ if (target)
2061
+ args.target = target;
2062
+ return this.call('rrext_cprofile_stop', args);
2063
+ }
2064
+ /**
2065
+ * Get the current cProfile profiling status.
2066
+ *
2067
+ * @param target - Task token if querying a pipeline, or undefined for server.
2068
+ * @returns Status indicating active/inactive, owner, runtime.
2069
+ */
2070
+ async cprofileStatus(target) {
2071
+ const args = {};
2072
+ if (target)
2073
+ args.target = target;
2074
+ return this.call('rrext_cprofile_status', args);
2075
+ }
2076
+ /**
2077
+ * Get the full cProfile report from the last completed session.
2078
+ *
2079
+ * @param target - Task token if querying a pipeline, or undefined for server.
2080
+ * @returns Object containing the full pstats text report.
2081
+ */
2082
+ async cprofileReport(target) {
2083
+ const args = {};
2084
+ if (target)
2085
+ args.target = target;
2086
+ return this.call('rrext_cprofile_report', args);
1716
2087
  }
1717
2088
  // ============================================================================
1718
2089
  // CONTEXT MANAGER SUPPORT - Python-style async context manager
@@ -1731,7 +2102,7 @@ class RocketRideClient extends DAPClient_js_1.DAPClient {
1731
2102
  static async withConnection(config, callback) {
1732
2103
  const client = new RocketRideClient(config);
1733
2104
  try {
1734
- await client.connect();
2105
+ await client.connect(config.auth);
1735
2106
  return await callback(client);
1736
2107
  }
1737
2108
  finally {
@@ -1768,17 +2139,7 @@ class RocketRideClient extends DAPClient_js_1.DAPClient {
1768
2139
  * ```
1769
2140
  */
1770
2141
  async getServices() {
1771
- // Build services request (no service argument = get all)
1772
- const request = this.buildRequest('rrext_services', {});
1773
- // Send to server and wait for response
1774
- const response = await this.request(request);
1775
- // Check if request failed
1776
- if (this.didFail(response)) {
1777
- const errorMsg = response.message || 'Failed to retrieve services';
1778
- throw new Error(`Failed to retrieve services: ${errorMsg}`);
1779
- }
1780
- // Return the body containing all service definitions
1781
- return response.body || {};
2142
+ return this.call('rrext_services', {});
1782
2143
  }
1783
2144
  /**
1784
2145
  * Retrieve a specific service definition from the server.
@@ -1806,19 +2167,7 @@ class RocketRideClient extends DAPClient_js_1.DAPClient {
1806
2167
  if (!service) {
1807
2168
  throw new Error('Service name is required');
1808
2169
  }
1809
- // Build services request with specific service name
1810
- const request = this.buildRequest('rrext_services', {
1811
- arguments: { service }
1812
- });
1813
- // Send to server and wait for response
1814
- const response = await this.request(request);
1815
- // Check if request failed
1816
- if (this.didFail(response)) {
1817
- const errorMsg = response.message || `Service '${service}' not found`;
1818
- throw new Error(`Failed to retrieve service '${service}': ${errorMsg}`);
1819
- }
1820
- // Return the body containing the service definition
1821
- return response.body;
2170
+ return this.call('rrext_services', { service });
1822
2171
  }
1823
2172
  // ============================================================================
1824
2173
  // ADDITIONAL CONVENIENCE METHODS
@@ -1839,7 +2188,110 @@ class RocketRideClient extends DAPClient_js_1.DAPClient {
1839
2188
  getApiKey() {
1840
2189
  return this._apikey;
1841
2190
  }
2191
+ // ============================================================================
2192
+ // ACCOUNT & BILLING NAMESPACES
2193
+ // ============================================================================
2194
+ /**
2195
+ * Lazily-initialised account API namespace.
2196
+ *
2197
+ * Provides typed methods for managing the authenticated user's profile,
2198
+ * API keys, organization, members, and teams.
2199
+ *
2200
+ * @example
2201
+ * ```typescript
2202
+ * const profile = await client.account.getProfile();
2203
+ * ```
2204
+ */
2205
+ get account() {
2206
+ if (!this._account) {
2207
+ this._account = new account_js_1.AccountApi(this);
2208
+ }
2209
+ return this._account;
2210
+ }
2211
+ /**
2212
+ * Lazily-initialised billing API namespace.
2213
+ *
2214
+ * Provides typed methods for managing subscriptions, Stripe checkout
2215
+ * sessions, billing portal access, and compute credit wallets.
2216
+ *
2217
+ * @example
2218
+ * ```typescript
2219
+ * const details = await client.billing.getDetails(orgId);
2220
+ * ```
2221
+ */
2222
+ get billing() {
2223
+ if (!this._billing) {
2224
+ this._billing = new billing_js_1.BillingApi(this);
2225
+ }
2226
+ return this._billing;
2227
+ }
2228
+ /**
2229
+ * Lazily-initialised database API namespace.
2230
+ *
2231
+ * Provides direct SQL/Cypher execution against database pipelines, bypassing
2232
+ * the LLM translation layer that {@link RocketRideClient.chat} uses.
2233
+ *
2234
+ * @example
2235
+ * ```typescript
2236
+ * const result = await client.database.query({ token, sql: 'SELECT 1' });
2237
+ * ```
2238
+ */
2239
+ get database() {
2240
+ if (!this._database) {
2241
+ this._database = new database_js_1.DatabaseApi(this);
2242
+ }
2243
+ return this._database;
2244
+ }
2245
+ // ============================================================================
2246
+ // CALL — PUBLIC DAP COMMAND INTERFACE
2247
+ // ============================================================================
2248
+ /**
2249
+ * Sends a DAP command, unwraps the response body, and throws on failure.
2250
+ *
2251
+ * This is the single public entry point for all typed DAP operations.
2252
+ * The {@link AccountApi} and {@link BillingApi} namespaces delegate here.
2253
+ *
2254
+ * If an `onTrace` callback was provided in the constructor config, it is
2255
+ * invoked before the request (TraceType.Request) and after completion
2256
+ * (TraceType.Success or TraceType.Error).
2257
+ *
2258
+ * @param command - DAP command name (e.g. "rrext_account_me").
2259
+ * @param args - Key/value arguments forwarded in the request.
2260
+ * @param options - Optional token (for task-scoped calls) and timeout in ms.
2261
+ * @returns The `body` field of a successful DAP response.
2262
+ * @throws Error if the server signals failure.
2263
+ */
2264
+ async call(command, args, options) {
2265
+ // Build the raw DAP request
2266
+ const message = this.buildRequest(command, {
2267
+ arguments: args,
2268
+ token: options?.token,
2269
+ });
2270
+ // Trace: outbound request
2271
+ this._onTrace?.(index_js_1.TraceType.Request, message);
2272
+ const response = await this.request(message, options?.timeout);
2273
+ // Throw on server-reported failure
2274
+ if (response.success === false) {
2275
+ this._onTrace?.(index_js_1.TraceType.Error, response);
2276
+ throw new Error(response.message ?? `${command} failed`);
2277
+ }
2278
+ // Trace: success response
2279
+ this._onTrace?.(index_js_1.TraceType.Success, response);
2280
+ // Unwrap the body envelope
2281
+ return (response.body ?? response);
2282
+ }
1842
2283
  }
1843
2284
  exports.RocketRideClient = RocketRideClient;
1844
2285
  exports.default = RocketRideClient;
2286
+ // ============================================================================
2287
+ // PATH AND ID VALIDATION
2288
+ // ============================================================================
2289
+ /**
2290
+ * Characters that are illegal in store paths and IDs on all supported
2291
+ * platforms (Windows, Linux, macOS, and object-storage back-ends).
2292
+ *
2293
+ * `\x00` is the null byte; the rest are shell/filesystem metacharacters
2294
+ * that would cause ambiguous or dangerous behaviour in path construction.
2295
+ */
2296
+ RocketRideClient.INVALID_PATH_CHARS = new Set(['*', '?', '<', '>', '|', '"', '\x00']);
1845
2297
  //# sourceMappingURL=client.js.map