backant-cli 0.0.0-stage → 0.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.
package/dist/index.js ADDED
@@ -0,0 +1,49 @@
1
+ import { Command } from "commander";
2
+ import { initCommand } from "./commands/init.js";
3
+ import { validateCommand } from "./commands/validate.js";
4
+ import { snapshotCommand } from "./commands/snapshot.js";
5
+ import { loginCommandDefinition } from "./commands/login.js";
6
+ import { pushCommandDefinition } from "./commands/push.js";
7
+ import { pullCommandDefinition } from "./commands/pull.js";
8
+ import { formatCommandDefinition } from "./commands/format.js";
9
+ import { dataExplorationCommand, liveDataCommand } from "./commands/data-exploration.js";
10
+ import { logsCommand } from "./commands/logs.js";
11
+ import { applicationAuthCommand } from "./commands/application-auth.js";
12
+ import { secretsCommand } from "./commands/secrets.js";
13
+ import { skillCommand } from "./commands/skill.js";
14
+ import { getCliVersion } from "./utils/package-info.js";
15
+ const program = new Command();
16
+ program
17
+ .name("backant")
18
+ .description("Backant CLI")
19
+ .version(getCliVersion())
20
+ .showHelpAfterError()
21
+ .addHelpText("after", `
22
+ Common workflow:
23
+ backant init <name> Create a project scaffold
24
+ cd <name> Enter the new project directory
25
+ backant login Sign in to BE Studio Cloud
26
+ backant validate Check the current project
27
+ backant push --env dev Push to Cloud's dev environment
28
+
29
+ Target selection:
30
+ Cloud is the default target. Use --local on supported commands to target
31
+ a local BE Studio instance (http://localhost:3000). --env selects the
32
+ environment on that target; it does not select Cloud or local.
33
+
34
+ Run "backant <command> --help" for command-specific options and examples.
35
+ `);
36
+ program.addCommand(initCommand);
37
+ program.addCommand(validateCommand);
38
+ program.addCommand(snapshotCommand);
39
+ program.addCommand(loginCommandDefinition);
40
+ program.addCommand(pushCommandDefinition);
41
+ program.addCommand(pullCommandDefinition);
42
+ program.addCommand(formatCommandDefinition);
43
+ program.addCommand(dataExplorationCommand);
44
+ program.addCommand(liveDataCommand);
45
+ program.addCommand(logsCommand);
46
+ program.addCommand(applicationAuthCommand);
47
+ program.addCommand(secretsCommand);
48
+ program.addCommand(skillCommand);
49
+ program.parse(process.argv);
@@ -0,0 +1,20 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+ /**
4
+ * Scan assets directory and return assets config
5
+ */
6
+ export function scanAssets(projectRoot) {
7
+ const assetsDir = path.join(projectRoot, "assets");
8
+ const storageJsonPath = path.join(assetsDir, "storage.json");
9
+ if (!fs.existsSync(storageJsonPath)) {
10
+ return null;
11
+ }
12
+ try {
13
+ const content = fs.readFileSync(storageJsonPath, "utf-8");
14
+ const config = JSON.parse(content);
15
+ return config;
16
+ }
17
+ catch (error) {
18
+ throw new Error(`Failed to parse assets/storage.json: ${error.message}`);
19
+ }
20
+ }
@@ -0,0 +1,115 @@
1
+ import { createHash } from "node:crypto";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ export const DEFAULT_API_URL = "https://api.backant.app";
6
+ export const LOCAL_API_URL = "http://localhost:3000";
7
+ export function normalizeApiUrl(value) {
8
+ let parsed;
9
+ try {
10
+ parsed = new URL(value.trim());
11
+ }
12
+ catch {
13
+ throw new Error(`Invalid BE Studio API URL: ${value}`);
14
+ }
15
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
16
+ throw new Error("BE Studio API URL must use HTTP or HTTPS.");
17
+ }
18
+ parsed.search = "";
19
+ parsed.hash = "";
20
+ parsed.pathname = parsed.pathname.replace(/\/+$/, "").replace(/\/api$/i, "");
21
+ return parsed.toString().replace(/\/$/, "");
22
+ }
23
+ export function getTargetApiUrl(options = {}) {
24
+ if (options.local && options.url?.trim()) {
25
+ throw new Error("Use either --local or --url, not both.");
26
+ }
27
+ if (!options.local && !options.url?.trim() && process.env.BESTUDIO_API_URL?.trim()) {
28
+ throw new Error("BESTUDIO_API_URL is no longer used for target selection. Use --local for local BE Studio or omit it for Cloud.");
29
+ }
30
+ if (options.local)
31
+ return LOCAL_API_URL;
32
+ return normalizeApiUrl(options.url?.trim() || DEFAULT_API_URL);
33
+ }
34
+ export function getConnectionTarget(options = {}) {
35
+ const apiUrl = getTargetApiUrl(options);
36
+ if (options.local || apiUrl === normalizeApiUrl(LOCAL_API_URL))
37
+ return "local";
38
+ if (apiUrl === normalizeApiUrl(DEFAULT_API_URL))
39
+ return "cloud";
40
+ return `custom:${apiUrl}`;
41
+ }
42
+ function authDirectory() {
43
+ return path.join(os.homedir(), ".bestudio");
44
+ }
45
+ function legacyAuthPath() {
46
+ return path.join(authDirectory(), "auth.json");
47
+ }
48
+ function targetProfilePath(target) {
49
+ const directory = path.join(authDirectory(), "auth");
50
+ if (target === "local" || target === "cloud") {
51
+ return path.join(directory, `${target}.json`);
52
+ }
53
+ const key = createHash("sha256").update(target).digest("hex");
54
+ return path.join(directory, `${key}.json`);
55
+ }
56
+ function readMatchingProfile(filePath, apiUrl) {
57
+ try {
58
+ const value = JSON.parse(fs.readFileSync(filePath, "utf8"));
59
+ if (typeof value.apiUrl !== "string" ||
60
+ normalizeApiUrl(value.apiUrl) !== apiUrl ||
61
+ typeof value.accessToken !== "string" ||
62
+ value.accessToken.length === 0) {
63
+ return null;
64
+ }
65
+ return { ...value, apiUrl };
66
+ }
67
+ catch {
68
+ return null;
69
+ }
70
+ }
71
+ export function loadAuthForTarget(target, apiUrl) {
72
+ const normalizedUrl = normalizeApiUrl(apiUrl);
73
+ const profile = readMatchingProfile(targetProfilePath(target), normalizedUrl);
74
+ if (profile)
75
+ return profile;
76
+ // Backward compatibility: reuse the old single auth.json only for its own
77
+ // recorded API URL. Never send its token to a different target.
78
+ return readMatchingProfile(legacyAuthPath(), normalizedUrl);
79
+ }
80
+ export function saveAuthProfile(target, apiUrl, profile) {
81
+ const normalizedUrl = normalizeApiUrl(apiUrl);
82
+ const directory = path.join(authDirectory(), "auth");
83
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
84
+ try {
85
+ fs.chmodSync(directory, 0o700);
86
+ }
87
+ catch {
88
+ // Some filesystems do not support chmod; the profile file is still private.
89
+ }
90
+ const filePath = targetProfilePath(target);
91
+ const temporaryPath = `${filePath}.${process.pid}.tmp`;
92
+ const contents = JSON.stringify({ ...profile, apiUrl: normalizedUrl }, null, 2) + "\n";
93
+ fs.writeFileSync(temporaryPath, contents, { encoding: "utf8", mode: 0o600 });
94
+ fs.renameSync(temporaryPath, filePath);
95
+ try {
96
+ fs.chmodSync(filePath, 0o600);
97
+ }
98
+ catch {
99
+ // Keep login working on filesystems that do not expose POSIX permissions.
100
+ }
101
+ }
102
+ export function resolveConnection(options = {}) {
103
+ const apiUrl = getTargetApiUrl(options);
104
+ const target = getConnectionTarget(options);
105
+ const explicitToken = options.token?.trim();
106
+ if (!explicitToken && process.env.BESTUDIO_TOKEN?.trim()) {
107
+ throw new Error("BESTUDIO_TOKEN is not used because tokens are scoped to an API URL. Run `backant login` for the selected target.");
108
+ }
109
+ const auth = loadAuthForTarget(target, apiUrl);
110
+ const accessToken = explicitToken || auth?.accessToken;
111
+ if (!accessToken) {
112
+ throw new Error(`Not logged in to ${options.local ? "local" : options.url ? "custom API target" : "BE Studio Cloud"}. Run \`backant login${options.local ? " --local" : options.url ? ` --url ${options.url}` : ""}\` first.`);
113
+ }
114
+ return { ...auth, apiUrl, accessToken, target };
115
+ }
@@ -0,0 +1,92 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+ /**
4
+ * Scan flows directory and return structured flows, errors, and warnings
5
+ */
6
+ export function scanFlowsDetailed(projectRoot) {
7
+ const flowsDir = path.join(projectRoot, "flows");
8
+ const flows = [];
9
+ const errors = [];
10
+ const warnings = [];
11
+ if (!fs.existsSync(flowsDir) || !fs.statSync(flowsDir).isDirectory()) {
12
+ return { flows, errors, warnings };
13
+ }
14
+ const flowDirs = fs
15
+ .readdirSync(flowsDir, { withFileTypes: true })
16
+ .filter((dirent) => dirent.isDirectory())
17
+ .map((dirent) => dirent.name)
18
+ .sort((a, b) => a.localeCompare(b));
19
+ for (const flowDir of flowDirs) {
20
+ const flowFilePath = path.join(flowsDir, flowDir, "flow.json");
21
+ const relativePath = path
22
+ .relative(projectRoot, flowFilePath)
23
+ .replace(/\\/g, "/");
24
+ if (!fs.existsSync(flowFilePath)) {
25
+ warnings.push({
26
+ path: `flows/${flowDir}/`,
27
+ message: "flow.json not found, skipping",
28
+ });
29
+ continue;
30
+ }
31
+ let flowJson;
32
+ try {
33
+ const content = fs.readFileSync(flowFilePath, "utf-8");
34
+ flowJson = JSON.parse(content);
35
+ }
36
+ catch (error) {
37
+ errors.push({
38
+ path: relativePath,
39
+ message: `JSON parse error: ${error.message}`,
40
+ });
41
+ continue;
42
+ }
43
+ if (!flowJson || typeof flowJson !== "object" || Array.isArray(flowJson)) {
44
+ errors.push({
45
+ path: relativePath,
46
+ message: "invalid flow.json format: root must be a JSON object",
47
+ });
48
+ continue;
49
+ }
50
+ const hasValidEntry = typeof flowJson.entry === "string" && flowJson.entry.trim() !== "";
51
+ const hasValidNodes = Boolean(flowJson.nodes) &&
52
+ typeof flowJson.nodes === "object" &&
53
+ !Array.isArray(flowJson.nodes);
54
+ if (!hasValidEntry || !hasValidNodes) {
55
+ if (!hasValidEntry) {
56
+ errors.push({
57
+ path: relativePath,
58
+ message: "flow.json missing entry node id",
59
+ });
60
+ }
61
+ if (!hasValidNodes) {
62
+ errors.push({
63
+ path: relativePath,
64
+ message: "flow.json missing or invalid nodes object",
65
+ });
66
+ }
67
+ continue;
68
+ }
69
+ flows.push({
70
+ id: flowDir,
71
+ name: typeof flowJson.name === "string" && flowJson.name.trim() !== ""
72
+ ? flowJson.name
73
+ : flowDir,
74
+ flow: flowJson,
75
+ filePath: relativePath,
76
+ });
77
+ }
78
+ return { flows, errors, warnings };
79
+ }
80
+ /**
81
+ * Scan flows directory and return all valid flow definitions
82
+ */
83
+ export function scanFlows(projectRoot) {
84
+ const result = scanFlowsDetailed(projectRoot);
85
+ for (const warning of result.warnings) {
86
+ console.warn(`⚠ ${warning.path}\n → ${warning.message}`);
87
+ }
88
+ for (const error of result.errors) {
89
+ console.warn(`⚠ ${error.path}\n → ${error.message}`);
90
+ }
91
+ return result.flows;
92
+ }
@@ -0,0 +1,266 @@
1
+ /**
2
+ * Format Utilities
3
+ *
4
+ * Provides canonicalization functions for workspace files.
5
+ * Format ensures deterministic file structure without affecting hash or runtime behavior.
6
+ *
7
+ * CRITICAL: Format NEVER touches snapshot, NEVER changes hash.
8
+ * Hash uses snapshot (not workspace files), so format changes don't affect hash.
9
+ */
10
+ import fs from "fs";
11
+ import path from "path";
12
+ /**
13
+ * Canonicalize JSON with deterministic key order
14
+ * Keys are sorted alphabetically
15
+ */
16
+ export function canonicalizeJson(obj, keyOrder) {
17
+ // Remove undefined and null values first
18
+ const cleaned = {};
19
+ for (const key in obj) {
20
+ if (obj[key] !== undefined && obj[key] !== null) {
21
+ cleaned[key] = obj[key];
22
+ }
23
+ }
24
+ if (keyOrder) {
25
+ // Use provided key order
26
+ const ordered = {};
27
+ for (const key of keyOrder) {
28
+ if (key in cleaned) {
29
+ ordered[key] = cleaned[key];
30
+ }
31
+ }
32
+ // Add any remaining keys in alphabetical order
33
+ const remainingKeys = Object.keys(cleaned)
34
+ .filter((k) => !keyOrder.includes(k))
35
+ .sort();
36
+ for (const key of remainingKeys) {
37
+ ordered[key] = cleaned[key];
38
+ }
39
+ return JSON.stringify(ordered, null, 2) + "\n";
40
+ }
41
+ else {
42
+ // Sort all keys alphabetically
43
+ const sorted = Object.keys(cleaned)
44
+ .sort()
45
+ .reduce((acc, key) => {
46
+ acc[key] = cleaned[key];
47
+ return acc;
48
+ }, {});
49
+ return JSON.stringify(sorted, null, 2) + "\n";
50
+ }
51
+ }
52
+ /**
53
+ * Check if workspace is canonical
54
+ * Checks:
55
+ * - Key order in JSON files
56
+ * - Line endings (LF only)
57
+ * - EOF newline
58
+ * - Indentation (2 spaces)
59
+ * - Route/job/model sorting
60
+ */
61
+ export function isCanonical(domain, workspacePath) {
62
+ // For now, always return false to trigger formatting
63
+ // Full implementation would check all criteria above
64
+ // This is acceptable since format is idempotent
65
+ return false;
66
+ }
67
+ /**
68
+ * Canonicalize routes
69
+ * Sorts routes by method, then path, then id
70
+ * Formats each route's fields alphabetically
71
+ */
72
+ export function canonicalizeRoutes(routes) {
73
+ return [...routes]
74
+ .sort((a, b) => {
75
+ const methodCompare = a.method.localeCompare(b.method);
76
+ if (methodCompare !== 0)
77
+ return methodCompare;
78
+ const pathCompare = a.path.localeCompare(b.path);
79
+ if (pathCompare !== 0)
80
+ return pathCompare;
81
+ return a.id.localeCompare(b.id);
82
+ })
83
+ .map((route) => {
84
+ // Format route object fields alphabetically
85
+ const formatted = {};
86
+ const keys = Object.keys(route).sort();
87
+ for (const key of keys) {
88
+ if (route[key] !== undefined && route[key] !== null) {
89
+ formatted[key] = route[key];
90
+ }
91
+ }
92
+ return formatted;
93
+ });
94
+ }
95
+ /**
96
+ * Canonicalize jobs
97
+ * Sorts jobs by id, and formats each job's fields alphabetically
98
+ */
99
+ export function canonicalizeJobs(jobs) {
100
+ return [...jobs]
101
+ .sort((a, b) => a.id.localeCompare(b.id))
102
+ .map((job) => {
103
+ // Format job object fields alphabetically
104
+ const formatted = {};
105
+ const keys = Object.keys(job).sort();
106
+ for (const key of keys) {
107
+ if (job[key] !== undefined && job[key] !== null) {
108
+ formatted[key] = job[key];
109
+ }
110
+ }
111
+ return formatted;
112
+ });
113
+ }
114
+ /**
115
+ * Canonicalize models
116
+ * Sorts models and nested arrays
117
+ * Formats each model's fields alphabetically
118
+ */
119
+ export function canonicalizeModels(models) {
120
+ return [...models]
121
+ .sort((a, b) => a.modelName.localeCompare(b.modelName))
122
+ .map((model) => {
123
+ // Sort nested arrays
124
+ const sortedFields = [...(model.fields || [])].sort((a, b) => a.name.localeCompare(b.name));
125
+ const sortedIndexes = [...(model.indexes || [])].sort((a, b) => {
126
+ const keyA = a.name || a.fields?.join(",") || "";
127
+ const keyB = b.name || b.fields?.join(",") || "";
128
+ return keyA.localeCompare(keyB);
129
+ });
130
+ const sortedUniqueConstraints = [
131
+ ...(model.uniqueConstraints || []),
132
+ ].sort((a, b) => {
133
+ const keyA = a.fields?.join(",") || "";
134
+ const keyB = b.fields?.join(",") || "";
135
+ return keyA.localeCompare(keyB);
136
+ });
137
+ // Format model object fields alphabetically
138
+ const formatted = {
139
+ fields: sortedFields,
140
+ indexes: sortedIndexes,
141
+ uniqueConstraints: sortedUniqueConstraints,
142
+ };
143
+ // Add other fields in alphabetical order
144
+ const otherKeys = Object.keys(model)
145
+ .filter((k) => !["fields", "indexes", "uniqueConstraints"].includes(k))
146
+ .sort();
147
+ for (const key of otherKeys) {
148
+ if (model[key] !== undefined && model[key] !== null) {
149
+ formatted[key] = model[key];
150
+ }
151
+ }
152
+ return formatted;
153
+ });
154
+ }
155
+ /**
156
+ * Canonicalize actions
157
+ * Sorts actions by id, and formats each action's fields alphabetically
158
+ */
159
+ export function canonicalizeActions(actions) {
160
+ return [...actions]
161
+ .sort((a, b) => a.id.localeCompare(b.id))
162
+ .map((action) => {
163
+ // Format action object fields alphabetically
164
+ const formatted = {};
165
+ const keys = Object.keys(action).sort();
166
+ for (const key of keys) {
167
+ if (action[key] !== undefined && action[key] !== null) {
168
+ formatted[key] = action[key];
169
+ }
170
+ }
171
+ return formatted;
172
+ });
173
+ } /**
174
+ * Canonicalize workspace files for a specific domain
175
+ */
176
+ export function canonicalizeWorkspace(domain, projectRoot) {
177
+ if (domain === "routes") {
178
+ // Format route.json files
179
+ const routesDir = path.join(projectRoot, "routes");
180
+ if (fs.existsSync(routesDir)) {
181
+ const collectRouteJsonFiles = (dir) => {
182
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
183
+ const files = [];
184
+ for (const entry of entries) {
185
+ const fullPath = path.join(dir, entry.name);
186
+ if (entry.isDirectory()) {
187
+ files.push(...collectRouteJsonFiles(fullPath));
188
+ }
189
+ else if (entry.isFile() && entry.name === "route.json") {
190
+ files.push(fullPath);
191
+ }
192
+ }
193
+ return files;
194
+ };
195
+ const routeJsonFiles = collectRouteJsonFiles(routesDir);
196
+ for (const routeJsonPath of routeJsonFiles) {
197
+ try {
198
+ const content = fs.readFileSync(routeJsonPath, "utf-8");
199
+ const routeJson = JSON.parse(content);
200
+ const formatted = canonicalizeJson(routeJson, [
201
+ "method",
202
+ "path",
203
+ "action",
204
+ "flow",
205
+ ]);
206
+ fs.writeFileSync(routeJsonPath, formatted, "utf-8");
207
+ }
208
+ catch (error) {
209
+ // Skip invalid files
210
+ }
211
+ }
212
+ }
213
+ }
214
+ else if (domain === "models") {
215
+ // Format model.json files
216
+ const modelsDir = path.join(projectRoot, "models");
217
+ if (fs.existsSync(modelsDir)) {
218
+ const modelDirs = fs
219
+ .readdirSync(modelsDir, { withFileTypes: true })
220
+ .filter((dirent) => dirent.isDirectory())
221
+ .map((dirent) => dirent.name);
222
+ for (const modelDir of modelDirs) {
223
+ const modelPath = path.join(modelsDir, modelDir, "model.json");
224
+ if (fs.existsSync(modelPath)) {
225
+ try {
226
+ const content = fs.readFileSync(modelPath, "utf-8");
227
+ const modelJson = JSON.parse(content);
228
+ const formatted = canonicalizeJson(modelJson);
229
+ fs.writeFileSync(modelPath, formatted, "utf-8");
230
+ }
231
+ catch (error) {
232
+ // Skip invalid files
233
+ }
234
+ }
235
+ }
236
+ }
237
+ }
238
+ // Actions and jobs are .ts files, not JSON, so no formatting needed
239
+ }
240
+ /**
241
+ * Canonicalize snapshot for a specific domain (or all domains)
242
+ */
243
+ export function canonicalizeSnapshot(snapshot, domain) {
244
+ const result = { ...snapshot };
245
+ if (!domain || domain === "routes") {
246
+ if (result.routes && Array.isArray(result.routes)) {
247
+ result.routes = canonicalizeRoutes(result.routes);
248
+ }
249
+ }
250
+ if (!domain || domain === "actions") {
251
+ if (result.actions && Array.isArray(result.actions)) {
252
+ result.actions = canonicalizeActions(result.actions);
253
+ }
254
+ }
255
+ if (!domain || domain === "jobs") {
256
+ if (result.jobs && Array.isArray(result.jobs)) {
257
+ result.jobs = canonicalizeJobs(result.jobs);
258
+ }
259
+ }
260
+ if (!domain || domain === "models") {
261
+ if (result.models && Array.isArray(result.models)) {
262
+ result.models = canonicalizeModels(result.models);
263
+ }
264
+ }
265
+ return result;
266
+ }