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/README.md +292 -2
- package/bin/backant.js +3 -0
- package/dist/commands/application-auth.js +315 -0
- package/dist/commands/data-exploration.js +334 -0
- package/dist/commands/format.js +78 -0
- package/dist/commands/init.js +97 -0
- package/dist/commands/login.js +154 -0
- package/dist/commands/logs.js +103 -0
- package/dist/commands/pull.js +186 -0
- package/dist/commands/push.js +678 -0
- package/dist/commands/secrets.js +48 -0
- package/dist/commands/skill.js +57 -0
- package/dist/commands/snapshot.js +312 -0
- package/dist/commands/validate.js +1429 -0
- package/dist/index.js +49 -0
- package/dist/utils/assets-scanner.js +20 -0
- package/dist/utils/connection.js +115 -0
- package/dist/utils/flow-scanner.js +92 -0
- package/dist/utils/format-utils.js +266 -0
- package/dist/utils/hash-utils.js +227 -0
- package/dist/utils/job-scanner.js +35 -0
- package/dist/utils/live-models-generator.js +189 -0
- package/dist/utils/model-scanner.js +43 -0
- package/dist/utils/package-info.js +31 -0
- package/dist/utils/services-scanner.js +46 -0
- package/dist/utils/skill-installer.js +135 -0
- package/dist/utils/snapshot-writer.js +216 -0
- package/package.json +34 -4
- package/skills/bestudio/SKILL.md +36 -0
- package/skills/bestudio/project-entrypoint.md +12 -0
- package/skills/bestudio/references/project-definitions.md +24 -0
|
@@ -0,0 +1,678 @@
|
|
|
1
|
+
import { Command } from "commander";
|
|
2
|
+
import fs from "fs";
|
|
3
|
+
import path from "path";
|
|
4
|
+
import { scanJobs } from "../utils/job-scanner.js";
|
|
5
|
+
import { scanServices } from "../utils/services-scanner.js";
|
|
6
|
+
import { scanAssets } from "../utils/assets-scanner.js";
|
|
7
|
+
import { scanModels } from "../utils/model-scanner.js";
|
|
8
|
+
import { scanFlows } from "../utils/flow-scanner.js";
|
|
9
|
+
import { generateLiveModels } from "../utils/live-models-generator.js";
|
|
10
|
+
import { calculateDomainHash, calculateAlgorithmHash, } from "../utils/hash-utils.js";
|
|
11
|
+
import { canonicalizeWorkspace, canonicalizeSnapshot, } from "../utils/format-utils.js";
|
|
12
|
+
import { validateProject } from "./validate.js";
|
|
13
|
+
import { resolveConnection } from "../utils/connection.js";
|
|
14
|
+
// Helper function to scan routes in workspace format (with actionId or flowId)
|
|
15
|
+
function scanRoutesForSnapshot(projectRoot) {
|
|
16
|
+
const routesDir = path.join(projectRoot, "routes");
|
|
17
|
+
const routes = [];
|
|
18
|
+
if (!fs.existsSync(routesDir)) {
|
|
19
|
+
return routes;
|
|
20
|
+
}
|
|
21
|
+
// Recursively collect all route.json files
|
|
22
|
+
const collectRouteJsonFiles = (dir) => {
|
|
23
|
+
const entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
24
|
+
const files = [];
|
|
25
|
+
for (const entry of entries) {
|
|
26
|
+
const fullPath = path.join(dir, entry.name);
|
|
27
|
+
if (entry.isDirectory()) {
|
|
28
|
+
files.push(...collectRouteJsonFiles(fullPath));
|
|
29
|
+
}
|
|
30
|
+
else if (entry.isFile() && entry.name === "route.json") {
|
|
31
|
+
files.push(fullPath);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return files;
|
|
35
|
+
};
|
|
36
|
+
const routeJsonPaths = collectRouteJsonFiles(routesDir);
|
|
37
|
+
for (const routeJsonPath of routeJsonPaths) {
|
|
38
|
+
const routeJson = readRouteJson(routeJsonPath);
|
|
39
|
+
if (!routeJson ||
|
|
40
|
+
!routeJson.method ||
|
|
41
|
+
!routeJson.path ||
|
|
42
|
+
(!routeJson.action && !routeJson.flow)) {
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
// Generate route ID
|
|
46
|
+
const routeId = `${routeJson.method}:${routeJson.path}`;
|
|
47
|
+
const routeJsonRelativePath = path
|
|
48
|
+
.relative(projectRoot, routeJsonPath)
|
|
49
|
+
.replace(/\\/g, "/");
|
|
50
|
+
if (routeJson.flow) {
|
|
51
|
+
routes.push({
|
|
52
|
+
id: routeId,
|
|
53
|
+
method: routeJson.method,
|
|
54
|
+
path: routeJson.path,
|
|
55
|
+
file: {
|
|
56
|
+
entry: routeJsonRelativePath,
|
|
57
|
+
},
|
|
58
|
+
flowId: routeJson.flow,
|
|
59
|
+
...(routeJson.metadata && { metadata: routeJson.metadata }),
|
|
60
|
+
});
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
// Generate actionId from route ID
|
|
64
|
+
const actionId = `action-${routeId}`;
|
|
65
|
+
routes.push({
|
|
66
|
+
id: routeId,
|
|
67
|
+
method: routeJson.method,
|
|
68
|
+
path: routeJson.path,
|
|
69
|
+
file: {
|
|
70
|
+
entry: routeJsonRelativePath,
|
|
71
|
+
},
|
|
72
|
+
actionId,
|
|
73
|
+
...(routeJson.metadata && { metadata: routeJson.metadata }),
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
return routes;
|
|
77
|
+
}
|
|
78
|
+
const VALID_ENVS = ["dev", "staging", "prod"];
|
|
79
|
+
function assertValidEnv(env) {
|
|
80
|
+
if (!VALID_ENVS.includes(env)) {
|
|
81
|
+
throw new Error(`Invalid environment "${env}". Must be one of: ${VALID_ENVS.join(", ")}`);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
function loadConfig(projectRoot) {
|
|
85
|
+
const configPath = path.join(projectRoot, "bestudio.config.json");
|
|
86
|
+
if (!fs.existsSync(configPath)) {
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
try {
|
|
90
|
+
const content = fs.readFileSync(configPath, "utf-8");
|
|
91
|
+
const config = JSON.parse(content);
|
|
92
|
+
if (!config.name) {
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
return config;
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
function runValidate(projectRoot, validateFn = validateProject) {
|
|
102
|
+
const result = validateFn(projectRoot);
|
|
103
|
+
if (result.warnings.length > 0) {
|
|
104
|
+
for (const warning of result.warnings) {
|
|
105
|
+
console.log(`ā ${warning.path}\n ā ${warning.message}`);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (!result.valid) {
|
|
109
|
+
for (const error of result.errors) {
|
|
110
|
+
console.error(`ā ${error.path}\n ā ${error.message}`);
|
|
111
|
+
}
|
|
112
|
+
return false;
|
|
113
|
+
}
|
|
114
|
+
return true;
|
|
115
|
+
}
|
|
116
|
+
function readRouteJson(routeJsonPath) {
|
|
117
|
+
if (!fs.existsSync(routeJsonPath)) {
|
|
118
|
+
return null;
|
|
119
|
+
}
|
|
120
|
+
try {
|
|
121
|
+
const content = fs.readFileSync(routeJsonPath, "utf-8");
|
|
122
|
+
return JSON.parse(content);
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
return null;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
function readActionSource(actionPath, routeJsonPath) {
|
|
129
|
+
const fullPath = path.resolve(path.dirname(routeJsonPath), actionPath);
|
|
130
|
+
if (!fs.existsSync(fullPath)) {
|
|
131
|
+
return null;
|
|
132
|
+
}
|
|
133
|
+
try {
|
|
134
|
+
return fs.readFileSync(fullPath, "utf-8");
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
return null;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
function readActionConfig(actionPath, routeJsonPath) {
|
|
141
|
+
// config.ts should be in the same directory as the action file
|
|
142
|
+
const actionDir = path.dirname(path.resolve(path.dirname(routeJsonPath), actionPath));
|
|
143
|
+
const configPath = path.join(actionDir, "config.ts");
|
|
144
|
+
if (!fs.existsSync(configPath)) {
|
|
145
|
+
return null;
|
|
146
|
+
}
|
|
147
|
+
try {
|
|
148
|
+
return fs.readFileSync(configPath, "utf-8");
|
|
149
|
+
}
|
|
150
|
+
catch {
|
|
151
|
+
return null;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
export function generatePushSnapshot(projectRoot, config) {
|
|
155
|
+
const routesDir = path.join(projectRoot, "routes");
|
|
156
|
+
const routes = [];
|
|
157
|
+
const actionsMap = new Map();
|
|
158
|
+
// Scan routes
|
|
159
|
+
if (fs.existsSync(routesDir)) {
|
|
160
|
+
const routeDirs = fs
|
|
161
|
+
.readdirSync(routesDir, { withFileTypes: true })
|
|
162
|
+
.filter((dirent) => dirent.isDirectory())
|
|
163
|
+
.map((dirent) => dirent.name);
|
|
164
|
+
// Recursively collect all route.json files under routes/*
|
|
165
|
+
const collectRouteJsonFiles = (dir) => {
|
|
166
|
+
const entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
167
|
+
const files = [];
|
|
168
|
+
for (const entry of entries) {
|
|
169
|
+
const fullPath = path.join(dir, entry.name);
|
|
170
|
+
if (entry.isDirectory()) {
|
|
171
|
+
files.push(...collectRouteJsonFiles(fullPath));
|
|
172
|
+
}
|
|
173
|
+
else if (entry.isFile() && entry.name === "route.json") {
|
|
174
|
+
files.push(fullPath);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return files;
|
|
178
|
+
};
|
|
179
|
+
const routeJsonPaths = [];
|
|
180
|
+
for (const routeDir of routeDirs) {
|
|
181
|
+
const baseDir = path.join(routesDir, routeDir);
|
|
182
|
+
routeJsonPaths.push(...collectRouteJsonFiles(baseDir));
|
|
183
|
+
}
|
|
184
|
+
routeJsonPaths.forEach((routeJsonPath, index) => {
|
|
185
|
+
const routeJson = readRouteJson(routeJsonPath);
|
|
186
|
+
if (!routeJson ||
|
|
187
|
+
!routeJson.method ||
|
|
188
|
+
!routeJson.path ||
|
|
189
|
+
(!routeJson.action && !routeJson.flow)) {
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
// Generate route ID from method + path (stable identifier)
|
|
193
|
+
const routeId = `${routeJson.method}:${routeJson.path}`;
|
|
194
|
+
// Calculate file paths
|
|
195
|
+
const routeJsonRelativePath = path
|
|
196
|
+
.relative(projectRoot, routeJsonPath)
|
|
197
|
+
.replace(/\\/g, "/");
|
|
198
|
+
if (routeJson.flow) {
|
|
199
|
+
routes.push({
|
|
200
|
+
id: routeId,
|
|
201
|
+
method: routeJson.method,
|
|
202
|
+
path: routeJson.path,
|
|
203
|
+
flowId: routeJson.flow,
|
|
204
|
+
file: {
|
|
205
|
+
entry: routeJsonRelativePath,
|
|
206
|
+
},
|
|
207
|
+
});
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
// Read action source
|
|
211
|
+
const actionSource = readActionSource(routeJson.action, routeJsonPath);
|
|
212
|
+
if (!actionSource) {
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
// Read action config (config.ts) if it exists
|
|
216
|
+
const configCode = readActionConfig(routeJson.action, routeJsonPath);
|
|
217
|
+
// Generate action ID from route ID (for now, can be improved later)
|
|
218
|
+
const actionId = `action-${routeId}`;
|
|
219
|
+
const actionFullPath = path.resolve(path.dirname(routeJsonPath), routeJson.action);
|
|
220
|
+
const actionRelativePath = path
|
|
221
|
+
.relative(projectRoot, actionFullPath)
|
|
222
|
+
.replace(/\\/g, "/");
|
|
223
|
+
// Add action to map (deduplicate by actionId)
|
|
224
|
+
if (!actionsMap.has(actionId)) {
|
|
225
|
+
actionsMap.set(actionId, {
|
|
226
|
+
id: actionId,
|
|
227
|
+
code: actionSource,
|
|
228
|
+
...(configCode && { configCode }),
|
|
229
|
+
file: {
|
|
230
|
+
entry: actionRelativePath,
|
|
231
|
+
},
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
// Add route with actionId reference and file.entry
|
|
235
|
+
routes.push({
|
|
236
|
+
id: routeId,
|
|
237
|
+
method: routeJson.method,
|
|
238
|
+
path: routeJson.path,
|
|
239
|
+
actionId,
|
|
240
|
+
file: {
|
|
241
|
+
entry: routeJsonRelativePath,
|
|
242
|
+
},
|
|
243
|
+
});
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
// Scan jobs, services, assets, models, flows
|
|
247
|
+
const jobs = scanJobs(projectRoot);
|
|
248
|
+
const services = scanServices(projectRoot);
|
|
249
|
+
const assets = scanAssets(projectRoot);
|
|
250
|
+
const models = scanModels(projectRoot);
|
|
251
|
+
const flowsRaw = scanFlows(projectRoot);
|
|
252
|
+
const flows = flowsRaw.map((f) => ({
|
|
253
|
+
id: f.id,
|
|
254
|
+
name: f.name,
|
|
255
|
+
flow: f.flow,
|
|
256
|
+
file: {
|
|
257
|
+
entry: f.filePath,
|
|
258
|
+
},
|
|
259
|
+
}));
|
|
260
|
+
const actions = actionsMap.size > 0
|
|
261
|
+
? Array.from(actionsMap.values()).sort((a, b) => a.id.localeCompare(b.id))
|
|
262
|
+
: undefined;
|
|
263
|
+
return {
|
|
264
|
+
project: {
|
|
265
|
+
name: config.name,
|
|
266
|
+
},
|
|
267
|
+
...(config.applicationAuth && { applicationAuth: config.applicationAuth }),
|
|
268
|
+
routes,
|
|
269
|
+
actions,
|
|
270
|
+
flows: flows.length > 0 ? flows : undefined,
|
|
271
|
+
jobs: jobs.length > 0
|
|
272
|
+
? jobs.map((j) => ({
|
|
273
|
+
id: j.id,
|
|
274
|
+
code: j.code,
|
|
275
|
+
file: {
|
|
276
|
+
entry: j.filePath,
|
|
277
|
+
},
|
|
278
|
+
}))
|
|
279
|
+
: undefined,
|
|
280
|
+
models: models.length > 0
|
|
281
|
+
? models.map((m) => {
|
|
282
|
+
const { filePath, ...modelWithoutFilePath } = m;
|
|
283
|
+
return {
|
|
284
|
+
...modelWithoutFilePath,
|
|
285
|
+
file: {
|
|
286
|
+
entry: filePath,
|
|
287
|
+
},
|
|
288
|
+
}; // Type assertion: filePath removed, file.entry added
|
|
289
|
+
})
|
|
290
|
+
: undefined,
|
|
291
|
+
services: services || undefined,
|
|
292
|
+
assets: assets || undefined,
|
|
293
|
+
createdAt: new Date().toISOString(),
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
function loadSnapshotFile(projectRoot) {
|
|
297
|
+
const snapshotPath = path.join(projectRoot, ".bestudio", "snapshot.json");
|
|
298
|
+
if (!fs.existsSync(snapshotPath)) {
|
|
299
|
+
return null;
|
|
300
|
+
}
|
|
301
|
+
try {
|
|
302
|
+
const content = fs.readFileSync(snapshotPath, "utf-8");
|
|
303
|
+
return JSON.parse(content);
|
|
304
|
+
}
|
|
305
|
+
catch {
|
|
306
|
+
return null;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
export async function pushSnapshot(apiUrl, accessToken, snapshot, algorithmHash, lastKnownHashes, env = "dev") {
|
|
310
|
+
assertValidEnv(env);
|
|
311
|
+
const url = `${apiUrl.replace(/\/+$/, "")}/system/snapshot/push`;
|
|
312
|
+
// Build domain-based push request
|
|
313
|
+
const pushRequest = {
|
|
314
|
+
snapshot: {
|
|
315
|
+
project: snapshot.project,
|
|
316
|
+
...(snapshot.applicationAuth && { applicationAuth: snapshot.applicationAuth }),
|
|
317
|
+
},
|
|
318
|
+
domains: {},
|
|
319
|
+
algorithmHash,
|
|
320
|
+
env,
|
|
321
|
+
};
|
|
322
|
+
// Add routes domain
|
|
323
|
+
if (snapshot.routes && snapshot.routes.length > 0) {
|
|
324
|
+
pushRequest.domains.routes = {
|
|
325
|
+
snapshot: snapshot.routes,
|
|
326
|
+
...(lastKnownHashes.routes && { lastKnownHash: lastKnownHashes.routes }),
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
// Add actions domain
|
|
330
|
+
if (snapshot.actions && snapshot.actions.length > 0) {
|
|
331
|
+
pushRequest.domains.actions = {
|
|
332
|
+
snapshot: snapshot.actions,
|
|
333
|
+
...(lastKnownHashes.actions && {
|
|
334
|
+
lastKnownHash: lastKnownHashes.actions,
|
|
335
|
+
}),
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
// Add jobs domain
|
|
339
|
+
if (snapshot.jobs && snapshot.jobs.length > 0) {
|
|
340
|
+
pushRequest.domains.jobs = {
|
|
341
|
+
snapshot: snapshot.jobs,
|
|
342
|
+
...(lastKnownHashes.jobs && { lastKnownHash: lastKnownHashes.jobs }),
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
// Add models domain
|
|
346
|
+
if (snapshot.models && snapshot.models.length > 0) {
|
|
347
|
+
pushRequest.domains.models = {
|
|
348
|
+
snapshot: snapshot.models,
|
|
349
|
+
...(lastKnownHashes.models && { lastKnownHash: lastKnownHashes.models }),
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
// Add flows domain
|
|
353
|
+
if (snapshot.flows && snapshot.flows.length > 0) {
|
|
354
|
+
pushRequest.domains.flows = {
|
|
355
|
+
snapshot: snapshot.flows,
|
|
356
|
+
};
|
|
357
|
+
}
|
|
358
|
+
// Add services domain
|
|
359
|
+
if (snapshot.services && Object.keys(snapshot.services).length > 0) {
|
|
360
|
+
pushRequest.domains.services = {
|
|
361
|
+
snapshot: snapshot.services,
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
// Add assets domain
|
|
365
|
+
if (snapshot.assets && Object.keys(snapshot.assets).length > 0) {
|
|
366
|
+
pushRequest.domains.assets = {
|
|
367
|
+
snapshot: snapshot.assets,
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
let response;
|
|
371
|
+
try {
|
|
372
|
+
response = await fetch(url, {
|
|
373
|
+
method: "POST",
|
|
374
|
+
headers: {
|
|
375
|
+
Authorization: `Bearer ${accessToken}`,
|
|
376
|
+
"Content-Type": "application/json",
|
|
377
|
+
},
|
|
378
|
+
body: JSON.stringify(pushRequest),
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
catch (error) {
|
|
382
|
+
throw new Error(`Network error: ${error.message || "Failed to connect to server"}`);
|
|
383
|
+
}
|
|
384
|
+
let apiResponse;
|
|
385
|
+
try {
|
|
386
|
+
apiResponse = (await response.json());
|
|
387
|
+
}
|
|
388
|
+
catch (error) {
|
|
389
|
+
throw new Error("Failed to parse response as JSON");
|
|
390
|
+
}
|
|
391
|
+
if (!response.ok || !apiResponse.success) {
|
|
392
|
+
const errorMessage = apiResponse.error || response.statusText || "Push failed";
|
|
393
|
+
throw new Error(errorMessage);
|
|
394
|
+
}
|
|
395
|
+
const results = apiResponse.results || {};
|
|
396
|
+
if (apiResponse.data) {
|
|
397
|
+
Object.defineProperty(results, "__meta", {
|
|
398
|
+
value: apiResponse.data,
|
|
399
|
+
enumerable: false,
|
|
400
|
+
configurable: true,
|
|
401
|
+
});
|
|
402
|
+
}
|
|
403
|
+
return results;
|
|
404
|
+
}
|
|
405
|
+
export async function pushCommand(options = {}, deps) {
|
|
406
|
+
// 1. Resolve environment and target-scoped credentials.
|
|
407
|
+
const resolvedEnv = options.env || process.env.BESTUDIO_ENV || "dev";
|
|
408
|
+
try {
|
|
409
|
+
assertValidEnv(resolvedEnv);
|
|
410
|
+
}
|
|
411
|
+
catch (error) {
|
|
412
|
+
console.error(`ā ${error.message}`);
|
|
413
|
+
process.exit(1);
|
|
414
|
+
}
|
|
415
|
+
let apiUrl;
|
|
416
|
+
let accessToken;
|
|
417
|
+
try {
|
|
418
|
+
const connection = resolveConnection(options);
|
|
419
|
+
apiUrl = connection.apiUrl;
|
|
420
|
+
accessToken = connection.accessToken;
|
|
421
|
+
}
|
|
422
|
+
catch (error) {
|
|
423
|
+
console.error(`ā ${error.message || "Connection could not be resolved"}`);
|
|
424
|
+
process.exit(1);
|
|
425
|
+
}
|
|
426
|
+
// 2. Check project
|
|
427
|
+
const projectRoot = options.projectRoot || process.cwd();
|
|
428
|
+
const config = loadConfig(projectRoot);
|
|
429
|
+
if (!config) {
|
|
430
|
+
console.error("ā Not a BE Studio project");
|
|
431
|
+
process.exit(1);
|
|
432
|
+
}
|
|
433
|
+
// 3. Canonical format check (unless --force)
|
|
434
|
+
if (!options.force) {
|
|
435
|
+
const { isCanonical } = await import("../utils/format-utils.js");
|
|
436
|
+
const routesCanonical = isCanonical("routes", projectRoot);
|
|
437
|
+
const jobsCanonical = isCanonical("jobs", projectRoot);
|
|
438
|
+
const modelsCanonical = isCanonical("models", projectRoot);
|
|
439
|
+
if (!routesCanonical || !jobsCanonical || !modelsCanonical) {
|
|
440
|
+
// For now, canonical check is basic - format system can be enhanced
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
// 4. Run validation
|
|
444
|
+
console.log("š Validating project...");
|
|
445
|
+
const isValid = runValidate(projectRoot, deps?.validateProject ?? validateProject);
|
|
446
|
+
if (!isValid) {
|
|
447
|
+
console.error("ā Validation failed. Fix errors before push.");
|
|
448
|
+
process.exit(1);
|
|
449
|
+
}
|
|
450
|
+
// 5. Generate snapshot
|
|
451
|
+
console.log("š¦ Generating snapshot...");
|
|
452
|
+
const snapshot = generatePushSnapshot(projectRoot, config);
|
|
453
|
+
// 6. Calculate hashes
|
|
454
|
+
const algorithmHash = calculateAlgorithmHash();
|
|
455
|
+
// Calculate domain hashes for current snapshot
|
|
456
|
+
const routesHash = calculateDomainHash("routes", snapshot.routes);
|
|
457
|
+
const actionsHash = snapshot.actions
|
|
458
|
+
? calculateDomainHash("actions", snapshot.actions)
|
|
459
|
+
: undefined;
|
|
460
|
+
const jobsHash = snapshot.jobs
|
|
461
|
+
? calculateDomainHash("jobs", snapshot.jobs)
|
|
462
|
+
: undefined;
|
|
463
|
+
const modelsHash = snapshot.models
|
|
464
|
+
? calculateDomainHash("models", snapshot.models)
|
|
465
|
+
: undefined;
|
|
466
|
+
// 7. Load last known hashes from snapshot file
|
|
467
|
+
const snapshotFile = loadSnapshotFile(projectRoot);
|
|
468
|
+
const lastKnownHashes = {};
|
|
469
|
+
if (snapshotFile?.hashes) {
|
|
470
|
+
if (snapshotFile.hashes.routes) {
|
|
471
|
+
lastKnownHashes.routes = snapshotFile.hashes.routes;
|
|
472
|
+
}
|
|
473
|
+
if (snapshotFile.hashes.actions) {
|
|
474
|
+
lastKnownHashes.actions = snapshotFile.hashes.actions;
|
|
475
|
+
}
|
|
476
|
+
if (snapshotFile.hashes.jobs) {
|
|
477
|
+
lastKnownHashes.jobs = snapshotFile.hashes.jobs;
|
|
478
|
+
}
|
|
479
|
+
if (snapshotFile.hashes.models) {
|
|
480
|
+
lastKnownHashes.models = snapshotFile.hashes.models;
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
// 8. Push to backend
|
|
484
|
+
console.log("š Pushing to BE Studio...");
|
|
485
|
+
try {
|
|
486
|
+
const pushFn = deps?.pushSnapshot ?? pushSnapshot;
|
|
487
|
+
const results = await pushFn(apiUrl, accessToken, snapshot, algorithmHash, lastKnownHashes, resolvedEnv);
|
|
488
|
+
// 9. Handle results (partial success)
|
|
489
|
+
if (!results) {
|
|
490
|
+
console.error("ā Push failed: No results returned");
|
|
491
|
+
process.exit(1);
|
|
492
|
+
}
|
|
493
|
+
const domainEntries = [
|
|
494
|
+
["routes", "Routes"],
|
|
495
|
+
["actions", "Actions"],
|
|
496
|
+
["jobs", "Jobs"],
|
|
497
|
+
["models", "Models"],
|
|
498
|
+
["flows", "Flows"],
|
|
499
|
+
["services", "Services"],
|
|
500
|
+
["assets", "Assets"],
|
|
501
|
+
["applicationAuth", "Application auth"],
|
|
502
|
+
];
|
|
503
|
+
let hasConflicts = false;
|
|
504
|
+
let hasErrors = false;
|
|
505
|
+
let hasSuccess = false;
|
|
506
|
+
for (const [domainKey, label] of domainEntries) {
|
|
507
|
+
const domainResult = results[domainKey];
|
|
508
|
+
if (!domainResult)
|
|
509
|
+
continue;
|
|
510
|
+
if (domainResult.conflict) {
|
|
511
|
+
hasConflicts = true;
|
|
512
|
+
console.error(`ā ${label}: Conflict detected`);
|
|
513
|
+
if (domainResult.currentHash) {
|
|
514
|
+
console.error(` Current hash: ${domainResult.currentHash}`);
|
|
515
|
+
}
|
|
516
|
+
if (domainResult.reason) {
|
|
517
|
+
console.error(` ${domainResult.reason}`);
|
|
518
|
+
}
|
|
519
|
+
if (domainResult.suggestion) {
|
|
520
|
+
console.error(` ${domainResult.suggestion}`);
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
else if (domainResult.error || domainResult.success === false) {
|
|
524
|
+
hasErrors = true;
|
|
525
|
+
console.error(`ā ${label}: ${domainResult.error || domainResult.reason || "Push failed"}`);
|
|
526
|
+
}
|
|
527
|
+
else if (domainResult.success) {
|
|
528
|
+
hasSuccess = true;
|
|
529
|
+
console.log(`ā ${label}: Pushed successfully`);
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
// 10. Update snapshot file with new hashes (even if conflicts exist)
|
|
533
|
+
// This ensures snapshot.json has the latest currentHash values for next push
|
|
534
|
+
const snapshotPath = path.join(projectRoot, ".bestudio", "snapshot.json");
|
|
535
|
+
const snapshotDir = path.dirname(snapshotPath);
|
|
536
|
+
if (!fs.existsSync(snapshotDir)) {
|
|
537
|
+
fs.mkdirSync(snapshotDir, { recursive: true });
|
|
538
|
+
}
|
|
539
|
+
// Load existing snapshot or create new
|
|
540
|
+
const existingSnapshot = snapshotFile || {
|
|
541
|
+
snapshotFormatVersion: 1,
|
|
542
|
+
project: snapshot.project,
|
|
543
|
+
routes: [],
|
|
544
|
+
actions: [],
|
|
545
|
+
jobs: [],
|
|
546
|
+
models: [],
|
|
547
|
+
};
|
|
548
|
+
const meta = results?.__meta;
|
|
549
|
+
const resolvedServerId = meta?.serverId || existingSnapshot.serverId;
|
|
550
|
+
const resolvedVersion = meta?.version ?? existingSnapshot.version;
|
|
551
|
+
// Convert routes to workspace format
|
|
552
|
+
// This ensures snapshot file format consistency with snapshot command
|
|
553
|
+
const routesInWorkspaceFormat = scanRoutesForSnapshot(projectRoot);
|
|
554
|
+
// Update with new data and hashes
|
|
555
|
+
// For conflicts, keep existing hash (don't update) so user must pull first
|
|
556
|
+
const snapshotToSave = {
|
|
557
|
+
snapshotFormatVersion: 1,
|
|
558
|
+
project: snapshot.project,
|
|
559
|
+
...(snapshot.applicationAuth && { applicationAuth: snapshot.applicationAuth }),
|
|
560
|
+
routes: routesInWorkspaceFormat,
|
|
561
|
+
actions: snapshot.actions
|
|
562
|
+
? [...snapshot.actions].sort((a, b) => a.id.localeCompare(b.id))
|
|
563
|
+
: [],
|
|
564
|
+
jobs: snapshot.jobs || [],
|
|
565
|
+
models: snapshot.models || [],
|
|
566
|
+
flows: snapshot.flows || [],
|
|
567
|
+
services: snapshot.services,
|
|
568
|
+
assets: snapshot.assets,
|
|
569
|
+
hashes: {
|
|
570
|
+
routes: results?.routes?.hash ||
|
|
571
|
+
(results?.routes?.conflict
|
|
572
|
+
? existingSnapshot.hashes?.routes
|
|
573
|
+
: undefined) ||
|
|
574
|
+
routesHash,
|
|
575
|
+
// Success: use new hash, Conflict: keep existing hash, Neither: use local hash
|
|
576
|
+
actions: results?.actions?.hash ||
|
|
577
|
+
(results?.actions?.conflict
|
|
578
|
+
? existingSnapshot.hashes?.actions
|
|
579
|
+
: undefined) ||
|
|
580
|
+
actionsHash,
|
|
581
|
+
jobs: results?.jobs?.hash ||
|
|
582
|
+
(results?.jobs?.conflict
|
|
583
|
+
? existingSnapshot.hashes?.jobs
|
|
584
|
+
: undefined) ||
|
|
585
|
+
jobsHash,
|
|
586
|
+
models: results?.models?.hash ||
|
|
587
|
+
(results?.models?.conflict
|
|
588
|
+
? existingSnapshot.hashes?.models
|
|
589
|
+
: undefined) ||
|
|
590
|
+
modelsHash,
|
|
591
|
+
algorithm: algorithmHash,
|
|
592
|
+
},
|
|
593
|
+
...(resolvedServerId && { serverId: resolvedServerId }),
|
|
594
|
+
...(resolvedVersion !== undefined && { version: resolvedVersion }),
|
|
595
|
+
...(existingSnapshot.createdAt && {
|
|
596
|
+
createdAt: existingSnapshot.createdAt,
|
|
597
|
+
}),
|
|
598
|
+
pushedAt: new Date().toISOString(),
|
|
599
|
+
};
|
|
600
|
+
fs.writeFileSync(snapshotPath, JSON.stringify(snapshotToSave, null, 2), "utf-8");
|
|
601
|
+
const relativePath = path
|
|
602
|
+
.relative(projectRoot, snapshotPath)
|
|
603
|
+
.replace(/\\/g, "/");
|
|
604
|
+
console.log(`ā Snapshot saved: ${relativePath}`);
|
|
605
|
+
// 11. Generate LiveModels if models exist
|
|
606
|
+
if (snapshot.models && snapshot.models.length > 0) {
|
|
607
|
+
console.log("š Generating LiveModels...");
|
|
608
|
+
const liveModelsPath = path.join(projectRoot, ".bestudio", "live-models.ts");
|
|
609
|
+
// Extract base URL from apiUrl (remove /api suffix if exists)
|
|
610
|
+
let baseUrl = apiUrl;
|
|
611
|
+
if (baseUrl.endsWith("/api")) {
|
|
612
|
+
baseUrl = baseUrl.slice(0, -4);
|
|
613
|
+
}
|
|
614
|
+
const serverId = resolvedServerId || "unknown";
|
|
615
|
+
const liveModelsContent = generateLiveModels(snapshot.models, serverId, baseUrl);
|
|
616
|
+
fs.writeFileSync(liveModelsPath, liveModelsContent, "utf-8");
|
|
617
|
+
const liveModelsRelativePath = path
|
|
618
|
+
.relative(projectRoot, liveModelsPath)
|
|
619
|
+
.replace(/\\/g, "/");
|
|
620
|
+
console.log(`ā LiveModels generated: ${liveModelsRelativePath}`);
|
|
621
|
+
}
|
|
622
|
+
// 12. Check conflicts / errors after saving snapshot
|
|
623
|
+
if (hasConflicts) {
|
|
624
|
+
console.error("\nā Push completed with conflicts");
|
|
625
|
+
console.error(" Resolve conflicts and push again");
|
|
626
|
+
process.exit(1);
|
|
627
|
+
}
|
|
628
|
+
if (hasErrors) {
|
|
629
|
+
console.error("\nā Push completed with errors");
|
|
630
|
+
process.exit(1);
|
|
631
|
+
}
|
|
632
|
+
if (!hasSuccess) {
|
|
633
|
+
console.error("ā No domains were pushed");
|
|
634
|
+
process.exit(1);
|
|
635
|
+
}
|
|
636
|
+
// Apply autoFormat if enabled
|
|
637
|
+
const autoFormat = config.autoFormat !== false; // Default to true
|
|
638
|
+
if (autoFormat) {
|
|
639
|
+
// Format workspace files for all domains
|
|
640
|
+
for (const domainToFormat of ["routes", "actions", "jobs", "models"]) {
|
|
641
|
+
canonicalizeWorkspace(domainToFormat, projectRoot);
|
|
642
|
+
}
|
|
643
|
+
// Format snapshot
|
|
644
|
+
const snapshotPath = path.join(projectRoot, ".bestudio", "snapshot.json");
|
|
645
|
+
if (fs.existsSync(snapshotPath)) {
|
|
646
|
+
const snapshotContent = fs.readFileSync(snapshotPath, "utf-8");
|
|
647
|
+
const snapshot = JSON.parse(snapshotContent);
|
|
648
|
+
const formattedSnapshot = canonicalizeSnapshot(snapshot);
|
|
649
|
+
fs.writeFileSync(snapshotPath, JSON.stringify(formattedSnapshot, null, 2) + "\n", "utf-8");
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
console.log("\nā Push completed successfully");
|
|
653
|
+
}
|
|
654
|
+
catch (error) {
|
|
655
|
+
console.error("ā Push failed");
|
|
656
|
+
if (error.message) {
|
|
657
|
+
console.error(` ${error.message}`);
|
|
658
|
+
}
|
|
659
|
+
process.exit(1);
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
export const pushCommandDefinition = new Command("push")
|
|
663
|
+
.description("Push project snapshot to BE Studio Cloud by default; use --local for local development")
|
|
664
|
+
.option("--force", "Bypass canonical format check")
|
|
665
|
+
.option("--local", "Target local BE Studio at http://localhost:3000")
|
|
666
|
+
.option("--env <env>", "Environment on the selected target (default: BESTUDIO_ENV or dev)")
|
|
667
|
+
.option("--url <apiUrl>", "API URL for a custom BE Studio instance; cannot be combined with --local")
|
|
668
|
+
.option("--token <token>", "Access token for this command; otherwise use saved target credentials")
|
|
669
|
+
.addHelpText("after", `
|
|
670
|
+
Examples:
|
|
671
|
+
backant validate
|
|
672
|
+
backant push --env dev
|
|
673
|
+
backant push --local --env dev
|
|
674
|
+
|
|
675
|
+
Cloud is the default target. --local selects the local BE Studio server;
|
|
676
|
+
--env selects dev, staging, or prod within the selected server.
|
|
677
|
+
`)
|
|
678
|
+
.action((options) => pushCommand(options));
|