@solidactions/cli 3.6.0 → 3.8.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.
@@ -16,7 +16,7 @@ const login_1 = require("./login");
16
16
  const CLI_OAUTH_CLIENT_ID = '9f1b6e2a-9c1e-4b6e-8f0a-6c9f2b1e7d4c';
17
17
  // CLI capability scopes requested at device-code issuance — the server
18
18
  // rejects any scope not pre-registered via Passport::tokensCan().
19
- const CLI_SCOPES = 'env deploy runs docs';
19
+ const CLI_SCOPES = 'env deploy runs docs databases';
20
20
  async function requestDeviceCode(host) {
21
21
  const response = await axios_1.default.post(`${host}/oauth/device/code`, {
22
22
  client_id: CLI_OAUTH_CLIENT_ID,
@@ -56,7 +56,7 @@ async function envList(projectName, options = {}) {
56
56
  const key = mapping.env_name || '?';
57
57
  // Value display (resolved_value includes global/oauth resolution)
58
58
  const rawValue = mapping.resolved_value ?? mapping.value;
59
- const value = mapping.is_secret ? '••••••' : rawValue ? rawValue.toString() : '-';
59
+ let value = mapping.is_secret ? '••••••' : rawValue ? rawValue.toString() : '-';
60
60
  // Type & source (mirrors UI getMappingType)
61
61
  let type;
62
62
  let source;
@@ -64,6 +64,19 @@ async function envList(projectName, options = {}) {
64
64
  type = 'oauth';
65
65
  source = mapping.oauth_connection_name || 'OAuth';
66
66
  }
67
+ else if (mapping.source_type === 'workspace_database') {
68
+ value = '-';
69
+ type = 'database';
70
+ if (mapping.workspace_database_broken) {
71
+ const databaseName = mapping.yaml_default_workspace_database_name || 'Database';
72
+ source = `${databaseName} (missing)`;
73
+ }
74
+ else {
75
+ source = mapping.workspace_database_name
76
+ || mapping.yaml_default_workspace_database_name
77
+ || 'Database';
78
+ }
79
+ }
67
80
  else if (mapping.global_variable_key) {
68
81
  type = 'global';
69
82
  source = mapping.global_variable_key;
@@ -72,6 +85,13 @@ async function envList(projectName, options = {}) {
72
85
  type = 'project var';
73
86
  source = 'local';
74
87
  }
88
+ else if (typeof mapping.yaml_default_workspace_database_name === 'string'
89
+ && mapping.yaml_default_workspace_database_name.length > 0
90
+ && mapping.yaml_default_not_found === true) {
91
+ value = '-';
92
+ type = 'database';
93
+ source = `${mapping.yaml_default_workspace_database_name} (not configured)`;
94
+ }
75
95
  else {
76
96
  type = '-';
77
97
  source = '-';
@@ -251,7 +251,7 @@ async function completeLogin(config, workspaces, options, scope = null, prefligh
251
251
  }
252
252
  else if (workspaces.length === 1) {
253
253
  const selected = workspaces[0];
254
- console.log(chalk_1.default.gray(`Auto-selected workspace: ${selected.name}`));
254
+ console.log(chalk_1.default.gray(`Auto-selected workspace: ${(0, workspace_lookup_1.formatWorkspaceWithOrg)(selected)}`));
255
255
  config.workspace = selected.slug ?? selected.name;
256
256
  config.workspaceId = selected.id;
257
257
  }
@@ -68,7 +68,11 @@ function assembleEnv(opts) {
68
68
  const warnings = [];
69
69
  const env = {};
70
70
  for (const [key, value] of Object.entries(opts.resolved)) {
71
- if (isReservedEnvName(key)) {
71
+ // The resolve endpoint owns this database credential manifest. Local
72
+ // execution must pass it through with the mapped JSON values so the
73
+ // SDK can recognize database variables. All other platform-reserved
74
+ // names remain ignored and are re-added by the CLI where applicable.
75
+ if (key !== 'SOLIDACTIONS__DB_KEYS' && isReservedEnvName(key)) {
72
76
  warnings.push(`crew variable '${key}' is reserved (set by the platform at runtime) — ignored`);
73
77
  continue;
74
78
  }
@@ -5,7 +5,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.workspacesList = workspacesList;
7
7
  exports.workspaceSet = workspaceSet;
8
- const axios_1 = __importDefault(require("axios"));
9
8
  const chalk_1 = __importDefault(require("chalk"));
10
9
  const api_1 = require("../utils/api");
11
10
  const config_1 = require("../utils/config");
@@ -13,46 +12,34 @@ const config_write_target_1 = require("../utils/config-write-target");
13
12
  const workspace_lookup_1 = require("../utils/workspace-lookup");
14
13
  async function workspacesList() {
15
14
  const config = (0, api_1.requireConfig)();
15
+ // Grouping keys are tenant ids (app#1214), so the org header and the
16
+ // same-name disambiguation both come from per-row tenant data, never
17
+ // from the key.
18
+ let workspaces;
16
19
  try {
17
- const response = await axios_1.default.get(`${config.host}/api/v1/workspaces`, {
18
- headers: {
19
- 'Authorization': `Bearer ${config.apiKey}`,
20
- 'Accept': 'application/json',
21
- },
22
- });
23
- // API returns { workspaces: { "Org Name": [{ id, name, role, tenant_name, ... }] } }
24
- const grouped = response.data.workspaces || response.data.data || response.data;
25
- let hasWorkspaces = false;
26
- console.log(chalk_1.default.blue(`\nYour workspaces:\n`));
27
- if (typeof grouped === 'object' && !Array.isArray(grouped)) {
28
- for (const orgName of Object.keys(grouped)) {
29
- console.log(` ${chalk_1.default.white(orgName)}`);
30
- for (const ws of grouped[orgName]) {
31
- hasWorkspaces = true;
32
- const current = config.workspaceId === ws.id ? chalk_1.default.green(' ← current') : '';
33
- console.log(` ${chalk_1.default.white(ws.name)} ${chalk_1.default.gray(`(${ws.role})`)}${current}`);
34
- console.log(chalk_1.default.gray(` ID: ${ws.id}`));
35
- }
36
- }
37
- }
38
- else if (Array.isArray(grouped)) {
39
- for (const ws of grouped) {
40
- hasWorkspaces = true;
41
- const current = config.workspaceId === ws.id ? chalk_1.default.green(' ← current') : '';
42
- console.log(` ${chalk_1.default.white(ws.name)} ${chalk_1.default.gray(`(${ws.org_name || ''}, ${ws.role})`)}${current}`);
43
- console.log(chalk_1.default.gray(` ID: ${ws.id}`));
44
- }
45
- }
46
- if (!hasWorkspaces) {
47
- console.log(chalk_1.default.yellow('No workspaces found.'));
48
- return;
49
- }
50
- console.log('');
20
+ ({ workspaces } = await (0, workspace_lookup_1.fetchWorkspaces)(config));
51
21
  }
52
22
  catch (error) {
53
23
  console.error(chalk_1.default.red('Failed to list workspaces:'), error.response?.data?.message || error.message);
54
24
  process.exit(1);
55
25
  }
26
+ console.log(chalk_1.default.blue(`\nYour workspaces:\n`));
27
+ if (workspaces.length === 0) {
28
+ console.log(chalk_1.default.yellow('No workspaces found.'));
29
+ return;
30
+ }
31
+ for (const group of (0, workspace_lookup_1.groupWorkspacesByOrg)(workspaces)) {
32
+ if (group.header) {
33
+ console.log(` ${chalk_1.default.white(group.header)}`);
34
+ }
35
+ for (const ws of group.workspaces) {
36
+ const current = config.workspaceId === ws.id ? chalk_1.default.green(' ← current') : '';
37
+ const slug = ws.slug ? ` ${chalk_1.default.gray(ws.slug)}` : '';
38
+ console.log(` ${chalk_1.default.white(ws.name)} ${chalk_1.default.gray(`(${ws.role})`)}${slug}${current}`);
39
+ console.log(chalk_1.default.gray(` ID: ${ws.id}`));
40
+ }
41
+ }
42
+ console.log('');
56
43
  }
57
44
  const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
58
45
  function looksLikeUuid(input) {
@@ -84,6 +71,6 @@ async function workspaceSet(input, options = {}) {
84
71
  if (target === 'local') {
85
72
  await (0, config_write_target_1.ensureGitignoreCovers)(process.cwd(), !!options.gitignore);
86
73
  }
87
- console.log(chalk_1.default.green(`Workspace set to: ${workspace.name} (${workspace.id})`));
74
+ console.log(chalk_1.default.green(`Workspace set to: ${(0, workspace_lookup_1.formatWorkspaceWithOrg)(workspace)} (${workspace.id})`));
88
75
  console.log(chalk_1.default.gray(`Saved to ${targetPath}`));
89
76
  }
package/dist/index.js CHANGED
@@ -89,8 +89,10 @@ const crew_env_set_1 = require("./commands/crew-env-set");
89
89
  const crew_env_list_1 = require("./commands/crew-env-list");
90
90
  const crew_env_delete_1 = require("./commands/crew-env-delete");
91
91
  const crew_env_push_1 = require("./commands/crew-env-push");
92
+ const crew_env_map_database_1 = require("./commands/crew-env-map-database");
92
93
  const state_1 = require("./commands/state");
93
94
  const workflow_view_1 = require("./commands/workflow-view");
95
+ const database_1 = require("./commands/database");
94
96
  const config_1 = require("./utils/config");
95
97
  // eslint-disable-next-line @typescript-eslint/no-var-requires
96
98
  const pkg = require('../package.json');
@@ -209,6 +211,101 @@ exports.program
209
211
  (0, dev_1.dev)(file, options);
210
212
  });
211
213
  // =============================================================================
214
+ // database <subcommand>
215
+ // =============================================================================
216
+ // Register the complete public surface up front so help and the generated
217
+ // command manifest stay authoritative while handlers land in focused slices.
218
+ const database = exports.program.command('database').description('Manage workspace databases');
219
+ database
220
+ .command('list')
221
+ .description('List workspace databases')
222
+ .option('--json', 'Output as JSON')
223
+ .action(async (options) => {
224
+ await (0, database_1.databaseList)(options);
225
+ });
226
+ database
227
+ .command('create')
228
+ .description('Create a workspace database')
229
+ .argument('<name>', 'Database name')
230
+ .option('--from <file.sql>', 'Import a SQL file after creation')
231
+ .option('--json', 'Output as JSON')
232
+ .action(async (name, options) => {
233
+ await (0, database_1.databaseCreate)(name, options);
234
+ });
235
+ database
236
+ .command('delete')
237
+ .description('Delete a workspace database')
238
+ .argument('<name>', 'Database name')
239
+ .option('-y, --yes', 'Skip confirmation')
240
+ .option('--json', 'Output as JSON')
241
+ .action(async (name, options) => {
242
+ await (0, database_1.databaseDelete)(name, options);
243
+ });
244
+ database
245
+ .command('undelete')
246
+ .description('Restore a deleted workspace database')
247
+ .argument('<name>', 'Database name')
248
+ .option('--json', 'Output as JSON')
249
+ .action(async (name, options) => {
250
+ await (0, database_1.databaseUndelete)(name, options);
251
+ });
252
+ database
253
+ .command('schema')
254
+ .description('Show a database schema')
255
+ .argument('<name>', 'Database name')
256
+ .option('--json', 'Output as JSON')
257
+ .action(async (name, options) => {
258
+ await (0, database_1.databaseSchema)(name, options);
259
+ });
260
+ database
261
+ .command('query')
262
+ .description('Run a read-only SQL query')
263
+ .argument('<name>', 'Database name')
264
+ .argument('<sql>', 'SQL query')
265
+ .option('--json', 'Output as JSON')
266
+ .action(async (name, sql, options) => {
267
+ await (0, database_1.databaseQuery)(name, sql, options);
268
+ });
269
+ database
270
+ .command('exec')
271
+ .description('Execute a SQL statement')
272
+ .argument('<name>', 'Database name')
273
+ .argument('<sql>', 'SQL statement')
274
+ .option('-y, --yes', 'Skip confirmation')
275
+ .option('--json', 'Output as JSON')
276
+ .action(async (name, sql, options) => {
277
+ await (0, database_1.databaseExec)(name, sql, options);
278
+ });
279
+ database
280
+ .command('dump')
281
+ .description('Download a database SQL dump')
282
+ .argument('<name>', 'Database name')
283
+ .argument('[file]', 'Destination file')
284
+ .option('-y, --yes', 'Overwrite without confirmation')
285
+ .action(async (name, file, options) => {
286
+ await (0, database_1.databaseDump)(name, file, options);
287
+ });
288
+ database
289
+ .command('pull')
290
+ .description('Pull a database into a local file')
291
+ .argument('<name>', 'Database name')
292
+ .argument('[path]', 'Destination path')
293
+ .option('-y, --yes', 'Overwrite without confirmation')
294
+ .option('--writable', 'Open a foreground writable session')
295
+ .action(async (name, destination, options) => {
296
+ await (0, database_1.databasePull)(name, destination, options);
297
+ });
298
+ database
299
+ .command('import')
300
+ .description('Import a SQL file into a database')
301
+ .argument('<name>', 'Database name')
302
+ .argument('<file.sql>', 'SQL file')
303
+ .option('-y, --yes', 'Skip confirmation')
304
+ .option('--resume <checkpoint>', 'Resume from a validated import checkpoint')
305
+ .action(async (name, file, options) => {
306
+ await (0, database_1.databaseImport)(name, file, options);
307
+ });
308
+ // =============================================================================
212
309
  // project <subcommand>
213
310
  // =============================================================================
214
311
  const project = exports.program.command('project').description('Manage projects');
@@ -482,6 +579,15 @@ crewEnv
482
579
  .action((crewArg, options) => {
483
580
  (0, crew_env_list_1.crewEnvList)(crewArg, options);
484
581
  });
582
+ crewEnv
583
+ .command('map-database')
584
+ .description('Map a workspace database into crew sandboxes')
585
+ .argument('<crew>', 'Crew name or id')
586
+ .argument('<key>', 'Variable key')
587
+ .argument('<database>', 'Workspace database name or id')
588
+ .action((crewArg, key, databaseArg) => {
589
+ (0, crew_env_map_database_1.crewEnvMapDatabase)(crewArg, key, databaseArg);
590
+ });
485
591
  crewEnv
486
592
  .command('delete')
487
593
  .description('Delete a crew variable')
package/dist/utils/api.js CHANGED
@@ -7,6 +7,7 @@ exports.SANDBOX_EGRESS_MESSAGE = void 0;
7
7
  exports.augmentSandboxEgressMessage = augmentSandboxEgressMessage;
8
8
  exports.augmentNotFoundMessage = augmentNotFoundMessage;
9
9
  exports.augmentWorkspaceForbiddenMessage = augmentWorkspaceForbiddenMessage;
10
+ exports.augmentTokenMissingAbilityMessage = augmentTokenMissingAbilityMessage;
10
11
  exports.getApiHeaders = getApiHeaders;
11
12
  exports.describeProjectEnvironments = describeProjectEnvironments;
12
13
  exports.formatValidationError = formatValidationError;
@@ -134,7 +135,30 @@ function augmentWorkspaceForbiddenMessage(error) {
134
135
  }
135
136
  return error;
136
137
  }
137
- axios_1.default.interceptors.response.use((response) => response, (error) => Promise.reject(augmentWorkspaceForbiddenMessage(augmentNotFoundMessage(augmentSandboxEgressMessage(error)))));
138
+ /**
139
+ * Existing device tokens predate the coarse `databases` scope. Turn the app's
140
+ * stable missing-ability response into a re-login instruction while preserving
141
+ * its original message. Other ability failures retain their existing behavior.
142
+ */
143
+ function augmentTokenMissingAbilityMessage(error) {
144
+ const response = error?.response;
145
+ const requiredAbility = response?.data?.required_ability;
146
+ const isDatabaseAbility = requiredAbility === 'databases'
147
+ || (typeof requiredAbility === 'string' && requiredAbility.startsWith('databases:'));
148
+ if (response?.status === 403
149
+ && response.data?.code === 'token_missing_ability'
150
+ && isDatabaseAbility) {
151
+ const hint = 'Run `solidactions login --device` to refresh database access.';
152
+ const message = typeof response.data.message === 'string' && response.data.message.length > 0
153
+ ? response.data.message
154
+ : 'This session does not have database access.';
155
+ if (!message.includes('solidactions login --device')) {
156
+ response.data.message = `${message}\n\n${hint}`;
157
+ }
158
+ }
159
+ return error;
160
+ }
161
+ axios_1.default.interceptors.response.use((response) => response, (error) => Promise.reject(augmentTokenMissingAbilityMessage(augmentWorkspaceForbiddenMessage(augmentNotFoundMessage(augmentSandboxEgressMessage(error))))));
138
162
  function getApiHeaders(config, contentType) {
139
163
  const headers = {
140
164
  'Authorization': `Bearer ${config.apiKey}`,
@@ -277,7 +301,7 @@ async function ensureWorkspaceSelected(config, dependencies = {}) {
277
301
  let selected;
278
302
  if (workspaces.length === 1) {
279
303
  selected = workspaces[0];
280
- console.log(chalk_1.default.gray(`Auto-selected workspace: ${selected.name}`));
304
+ console.log(chalk_1.default.gray(`Auto-selected workspace: ${(0, workspace_lookup_1.formatWorkspaceWithOrg)(selected)}`));
281
305
  }
282
306
  else {
283
307
  if (!process.stdin.isTTY) {
@@ -287,7 +311,6 @@ async function ensureWorkspaceSelected(config, dependencies = {}) {
287
311
  }
288
312
  const chosen = await (0, workspace_lookup_1.selectWorkspaceInteractively)(workspaces, {
289
313
  ...dependencies,
290
- label: (ws) => `${ws.name} ${chalk_1.default.gray(`(${ws.org_name}, ${ws.role})`)}`,
291
314
  });
292
315
  if (!chosen) {
293
316
  process.exit(1);
@@ -300,7 +323,6 @@ async function ensureWorkspaceSelected(config, dependencies = {}) {
300
323
  const targetPath = resolved?.activePath ?? (0, config_1.getGlobalConfigPath)();
301
324
  (0, config_1.writeConfigFile)(targetPath, config);
302
325
  }
303
- console.log(chalk_1.default.green(`Workspace set: ${selected.name}`));
304
326
  return config;
305
327
  }
306
328
  async function requireConfigWithWorkspace() {
@@ -0,0 +1,68 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.DatabaseClientUnsupportedError = void 0;
37
+ exports.loadDatabaseClientBeforeMint = loadDatabaseClientBeforeMint;
38
+ class DatabaseClientUnsupportedError extends Error {
39
+ code = 'database_client_unsupported';
40
+ constructor() {
41
+ super('Database commands are not supported on this platform.');
42
+ this.name = 'DatabaseClientUnsupportedError';
43
+ }
44
+ }
45
+ exports.DatabaseClientUnsupportedError = DatabaseClientUnsupportedError;
46
+ /**
47
+ * Load the native-capable client module before requesting a short-lived
48
+ * credential. Import and binding failures are deliberately collapsed to a
49
+ * stable product error so low-level module paths and implementation details do
50
+ * not reach users. Mint failures are left untouched for the API error mapper.
51
+ */
52
+ async function loadDatabaseClientBeforeMint(mintAccess, dependencies = {}) {
53
+ let clientModule;
54
+ try {
55
+ clientModule = await (dependencies.loadClient ?? (() => Promise.resolve().then(() => __importStar(require('@libsql/client')))))();
56
+ if (typeof clientModule.createClient !== 'function') {
57
+ throw new Error('Database client factory is unavailable.');
58
+ }
59
+ }
60
+ catch {
61
+ throw new DatabaseClientUnsupportedError();
62
+ }
63
+ const access = await mintAccess();
64
+ return {
65
+ createClient: clientModule.createClient,
66
+ access,
67
+ };
68
+ }
@@ -0,0 +1,237 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.DatabaseOperationError = exports.DEFAULT_DATABASE_DATA_PLANE_TIMEOUT_MS = exports.DEFAULT_DATABASE_CONTROL_PLANE_TIMEOUT_MS = void 0;
7
+ exports.safeDatabaseRequestError = safeDatabaseRequestError;
8
+ exports.runDatabaseClientOperationWithDeadline = runDatabaseClientOperationWithDeadline;
9
+ exports.requestDatabaseOperation = requestDatabaseOperation;
10
+ exports.requestDatabaseDumpStream = requestDatabaseDumpStream;
11
+ exports.requestDatabaseAccess = requestDatabaseAccess;
12
+ exports.withDatabaseClient = withDatabaseClient;
13
+ exports.normalizeDatabaseValue = normalizeDatabaseValue;
14
+ exports.formatDatabaseTableValue = formatDatabaseTableValue;
15
+ const axios_1 = __importDefault(require("axios"));
16
+ const api_1 = require("./api");
17
+ const database_client_support_1 = require("./database-client-support");
18
+ exports.DEFAULT_DATABASE_CONTROL_PLANE_TIMEOUT_MS = 30_000;
19
+ exports.DEFAULT_DATABASE_DATA_PLANE_TIMEOUT_MS = 120_000;
20
+ class DatabaseOperationError extends Error {
21
+ code;
22
+ status;
23
+ constructor(code, message, status) {
24
+ super(message);
25
+ this.code = code;
26
+ if (status !== undefined) {
27
+ this.status = status;
28
+ }
29
+ // A public command error is deliberately data-only. In particular, it
30
+ // must never retain an upstream stack, request, response, config, or
31
+ // cause that could contain either control- or data-plane credentials.
32
+ delete this.stack;
33
+ }
34
+ }
35
+ exports.DatabaseOperationError = DatabaseOperationError;
36
+ function safeDatabaseRequestError(error) {
37
+ const augmented = (0, api_1.augmentTokenMissingAbilityMessage)(error);
38
+ const response = augmented?.response;
39
+ const status = typeof response?.status === 'number' ? response.status : undefined;
40
+ const codeCandidate = typeof response?.data?.code === 'string'
41
+ ? response.data.code.trim()
42
+ : '';
43
+ const stableCode = codeCandidate.length > 0 ? codeCandidate : null;
44
+ const code = stableCode ?? 'upstream_unavailable';
45
+ const appMessage = stableCode !== null
46
+ && typeof response?.data?.message === 'string'
47
+ && response.data.message.trim().length > 0
48
+ ? response.data.message
49
+ : 'Database request failed.';
50
+ const message = code === 'unauthenticated'
51
+ ? `${appMessage} Run solidactions login to authenticate again.`
52
+ : appMessage;
53
+ return new DatabaseOperationError(code, message, status);
54
+ }
55
+ function positiveTimeout(value, fallback) {
56
+ return typeof value === 'number' && Number.isFinite(value) && value > 0
57
+ ? value
58
+ : fallback;
59
+ }
60
+ class DatabaseDeadlineElapsed extends DatabaseOperationError {
61
+ constructor(message) {
62
+ super('upstream_unavailable', message);
63
+ }
64
+ }
65
+ async function requestWithDeadline(operation, timeoutMs) {
66
+ const controller = new AbortController();
67
+ let timer;
68
+ const deadline = new Promise((_resolve, reject) => {
69
+ timer = setTimeout(() => {
70
+ controller.abort();
71
+ reject(new DatabaseDeadlineElapsed('Database request timed out.'));
72
+ }, timeoutMs);
73
+ });
74
+ try {
75
+ return await Promise.race([operation(controller.signal, timeoutMs), deadline]);
76
+ }
77
+ finally {
78
+ if (timer)
79
+ clearTimeout(timer);
80
+ }
81
+ }
82
+ /**
83
+ * Bound a Hrana operation and actively invoke its cancellation/close hook when
84
+ * the deadline expires. Callers can inject a shorter timeout per command.
85
+ */
86
+ async function runDatabaseClientOperationWithDeadline(operation, onTimeout, timeoutMs = exports.DEFAULT_DATABASE_DATA_PLANE_TIMEOUT_MS) {
87
+ const boundedTimeout = positiveTimeout(timeoutMs, exports.DEFAULT_DATABASE_DATA_PLANE_TIMEOUT_MS);
88
+ let timer;
89
+ const deadline = new Promise((_resolve, reject) => {
90
+ timer = setTimeout(() => {
91
+ try {
92
+ void Promise.resolve(onTimeout?.()).catch(() => undefined);
93
+ }
94
+ finally {
95
+ reject(new DatabaseDeadlineElapsed('Database operation timed out.'));
96
+ }
97
+ }, boundedTimeout);
98
+ });
99
+ try {
100
+ return await Promise.race([Promise.resolve().then(operation), deadline]);
101
+ }
102
+ finally {
103
+ if (timer)
104
+ clearTimeout(timer);
105
+ }
106
+ }
107
+ /**
108
+ * Call the single CLI database control-plane endpoint and discard all Axios
109
+ * transport state at the error boundary.
110
+ */
111
+ async function requestDatabaseOperation(config, body, dependencies = {}) {
112
+ const post = dependencies.post ?? axios_1.default.post;
113
+ const timeoutMs = positiveTimeout(dependencies.controlPlaneTimeoutMs, exports.DEFAULT_DATABASE_CONTROL_PLANE_TIMEOUT_MS);
114
+ try {
115
+ const response = await requestWithDeadline((signal, timeout) => post(`${config.host}/api/v1/databases`, body, {
116
+ headers: (0, api_1.getApiHeaders)(config, 'application/json'),
117
+ signal,
118
+ timeout,
119
+ }), timeoutMs);
120
+ return response.data;
121
+ }
122
+ catch (error) {
123
+ throw safeDatabaseRequestError(error);
124
+ }
125
+ }
126
+ /** Request the existing server-side SQL dump as a stream. */
127
+ async function requestDatabaseDumpStream(config, name, dependencies = {}) {
128
+ const post = dependencies.post ?? axios_1.default.post;
129
+ const timeoutMs = positiveTimeout(dependencies.controlPlaneTimeoutMs, exports.DEFAULT_DATABASE_CONTROL_PLANE_TIMEOUT_MS);
130
+ try {
131
+ const response = await requestWithDeadline((signal, timeout) => post(`${config.host}/api/v1/databases`, { operation: 'dump', name }, {
132
+ headers: {
133
+ ...(0, api_1.getApiHeaders)(config, 'application/json'),
134
+ Accept: 'application/sql',
135
+ },
136
+ responseType: 'stream',
137
+ signal,
138
+ timeout,
139
+ }), timeoutMs);
140
+ return response.data;
141
+ }
142
+ catch (error) {
143
+ throw safeDatabaseRequestError(error);
144
+ }
145
+ }
146
+ function safeDirectClientError() {
147
+ return new DatabaseOperationError('upstream_unavailable', 'Database operation failed.');
148
+ }
149
+ /**
150
+ * Request a short-lived direct database credential from the app control plane.
151
+ * Any Axios transport object is discarded at this boundary.
152
+ */
153
+ async function requestDatabaseAccess(config, name, mode, dependencies = {}) {
154
+ return requestDatabaseOperation(config, { operation: 'access', name, mode }, dependencies);
155
+ }
156
+ /**
157
+ * Run one foreground operation with an ephemeral direct client. Native support
158
+ * is loaded before access is minted, and the client is always closed once it
159
+ * exists. Direct-client details are collapsed to a credential-safe error.
160
+ */
161
+ async function withDatabaseClient(config, name, mode, operation, dependencies = {}) {
162
+ const { createClient, access } = await (0, database_client_support_1.loadDatabaseClientBeforeMint)(() => requestDatabaseAccess(config, name, mode, {
163
+ post: dependencies.post,
164
+ controlPlaneTimeoutMs: dependencies.controlPlaneTimeoutMs,
165
+ }), { loadClient: dependencies.loadClient });
166
+ let client;
167
+ try {
168
+ client = createClient({
169
+ url: access.url,
170
+ authToken: access.token,
171
+ intMode: 'string',
172
+ });
173
+ }
174
+ catch {
175
+ throw safeDirectClientError();
176
+ }
177
+ const dataPlaneTimeoutMs = positiveTimeout(dependencies.dataPlaneTimeoutMs, exports.DEFAULT_DATABASE_DATA_PLANE_TIMEOUT_MS);
178
+ let closePromise;
179
+ const closeClient = () => {
180
+ closePromise ??= runDatabaseClientOperationWithDeadline(async () => { await client.close(); }, undefined, dataPlaneTimeoutMs);
181
+ return closePromise;
182
+ };
183
+ let primaryFailure;
184
+ try {
185
+ return await runDatabaseClientOperationWithDeadline(() => operation(client), closeClient, dataPlaneTimeoutMs);
186
+ }
187
+ catch (error) {
188
+ primaryFailure = error instanceof DatabaseDeadlineElapsed
189
+ ? new DatabaseOperationError(error.code, error.message, error.status)
190
+ : safeDirectClientError();
191
+ throw primaryFailure;
192
+ }
193
+ finally {
194
+ try {
195
+ await closeClient();
196
+ }
197
+ catch {
198
+ if (!primaryFailure) {
199
+ throw safeDirectClientError();
200
+ }
201
+ }
202
+ }
203
+ }
204
+ function blobBytes(value) {
205
+ if (ArrayBuffer.isView(value)) {
206
+ return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
207
+ }
208
+ if (value instanceof ArrayBuffer) {
209
+ return new Uint8Array(value);
210
+ }
211
+ return null;
212
+ }
213
+ /** Normalize direct-client values into the stable JSON contract. */
214
+ function normalizeDatabaseValue(value) {
215
+ if (typeof value === 'bigint') {
216
+ return value.toString(10);
217
+ }
218
+ const bytes = blobBytes(value);
219
+ if (bytes) {
220
+ return { base64: Buffer.from(bytes).toString('base64') };
221
+ }
222
+ return value;
223
+ }
224
+ /** Render one direct-client value as a concise, implementation-neutral cell. */
225
+ function formatDatabaseTableValue(value) {
226
+ if (value === null) {
227
+ return 'NULL';
228
+ }
229
+ if (typeof value === 'bigint') {
230
+ return value.toString(10);
231
+ }
232
+ const bytes = blobBytes(value);
233
+ if (bytes) {
234
+ return `<blob ${bytes.byteLength} bytes>`;
235
+ }
236
+ return String(value);
237
+ }