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.
@@ -0,0 +1,227 @@
1
+ import { createHash } from "crypto";
2
+ /**
3
+ * Hash Utilities for CLI
4
+ *
5
+ * Provides deterministic hash calculation for domains (routes, jobs, models)
6
+ * Hash is calculated from snapshot data, not workspace files directly.
7
+ */
8
+ /**
9
+ * Normalize line endings: Convert \r\n → \n
10
+ * This ensures cross-platform consistency
11
+ */
12
+ export function normalizeLineEndings(text) {
13
+ return text.replace(/\r\n/g, "\n");
14
+ }
15
+ /**
16
+ * Normalize configCode: Convert undefined → ""
17
+ * This ensures optional fields don't cause hash variance
18
+ */
19
+ export function normalizeConfigCode(code) {
20
+ return code ?? "";
21
+ }
22
+ /**
23
+ * Calculate algorithm hash
24
+ * This represents the hash algorithm specification itself
25
+ * CLI calculates at runtime, BE uses constant
26
+ */
27
+ export function calculateAlgorithmHash() {
28
+ const algorithmSpec = "domains:" +
29
+ "routes=id,method,path,actionId|" +
30
+ "actions=id,code,configCode|" +
31
+ "jobs=id,code|" +
32
+ "models=modelName,schema|" +
33
+ "sort:routes(method,path,id),actions(id),jobs(id),models(modelName)|" +
34
+ "tuple:key:value|sha256";
35
+ return sha256(algorithmSpec);
36
+ }
37
+ /**
38
+ * Calculate hash for empty domain
39
+ * Returns sha256("EMPTY") to distinguish [] from undefined
40
+ */
41
+ export function calculateEmptyDomainHash() {
42
+ return sha256("EMPTY");
43
+ }
44
+ /**
45
+ * Project route entity for hashing
46
+ * Only includes fields that affect runtime behavior
47
+ * Routes now reference actions by actionId, not inline source
48
+ */
49
+ function projectRoute(route) {
50
+ return [
51
+ ["id", route.id],
52
+ ["method", route.method],
53
+ ["path", route.path],
54
+ ["actionId", route.actionId || ""],
55
+ ["file.entry", route.file?.entry || ""],
56
+ ];
57
+ }
58
+ /**
59
+ * Project action entity for hashing
60
+ * Actions are now a separate domain
61
+ */
62
+ function projectAction(action) {
63
+ const normalizedCode = normalizeLineEndings(action.code);
64
+ const normalizedConfigCode = normalizeConfigCode(action.configCode);
65
+ return [
66
+ ["id", action.id],
67
+ ["code", normalizedCode],
68
+ ["configCode", normalizedConfigCode],
69
+ ["file.entry", action.file?.entry || ""],
70
+ ];
71
+ }
72
+ /**
73
+ * Project job entity for hashing
74
+ */
75
+ function projectJob(job) {
76
+ const normalizedCode = normalizeLineEndings(job.code);
77
+ return [
78
+ ["id", job.id],
79
+ ["code", normalizedCode],
80
+ ["file.entry", job.file?.entry || ""],
81
+ ];
82
+ }
83
+ /**
84
+ * Sort model schema fields by name
85
+ */
86
+ function sortModelFields(fields) {
87
+ return [...fields].sort((a, b) => {
88
+ const nameA = a.name || "";
89
+ const nameB = b.name || "";
90
+ return nameA.localeCompare(nameB);
91
+ });
92
+ }
93
+ /**
94
+ * Sort model indexes by name (or fields.join(",") if no name)
95
+ */
96
+ function sortModelIndexes(indexes) {
97
+ return [...indexes].sort((a, b) => {
98
+ const keyA = a.name || a.fields?.join(",") || "";
99
+ const keyB = b.name || b.fields?.join(",") || "";
100
+ return keyA.localeCompare(keyB);
101
+ });
102
+ }
103
+ /**
104
+ * Sort model uniqueConstraints by fields.join(",")
105
+ */
106
+ function sortModelUniqueConstraints(constraints) {
107
+ return [...constraints].sort((a, b) => {
108
+ const keyA = a.fields?.join(",") || "";
109
+ const keyB = b.fields?.join(",") || "";
110
+ return keyA.localeCompare(keyB);
111
+ });
112
+ }
113
+ /**
114
+ * Project model entity for hashing
115
+ * Includes nested array sorting
116
+ */
117
+ function projectModel(model) {
118
+ // Sort nested arrays
119
+ const sortedFields = model.fields ? sortModelFields(model.fields) : [];
120
+ const sortedIndexes = model.indexes ? sortModelIndexes(model.indexes) : [];
121
+ const sortedUniqueConstraints = model.uniqueConstraints
122
+ ? sortModelUniqueConstraints(model.uniqueConstraints)
123
+ : [];
124
+ // Create schema object with sorted arrays
125
+ const schema = {
126
+ fields: sortedFields,
127
+ indexes: sortedIndexes,
128
+ uniqueConstraints: sortedUniqueConstraints,
129
+ };
130
+ // Convert schema to deterministic string
131
+ const schemaString = JSON.stringify(schema);
132
+ return [
133
+ ["modelName", model.modelName],
134
+ ["schema", schemaString],
135
+ ["file.entry", model.file?.entry || ""],
136
+ ];
137
+ }
138
+ /**
139
+ * Convert entity tuple array to hash string
140
+ * Format: "key:value|key:value|..."
141
+ */
142
+ function tupleArrayToString(tuples) {
143
+ return tuples.map(([key, value]) => `${key}:${value}`).join("|");
144
+ }
145
+ /**
146
+ * Sort routes by method, then path, then id
147
+ */
148
+ function sortRoutes(routes) {
149
+ return [...routes].sort((a, b) => {
150
+ // First by method
151
+ const methodCompare = a.method.localeCompare(b.method);
152
+ if (methodCompare !== 0)
153
+ return methodCompare;
154
+ // Then by path
155
+ const pathCompare = a.path.localeCompare(b.path);
156
+ if (pathCompare !== 0)
157
+ return pathCompare;
158
+ // Finally by id
159
+ return a.id.localeCompare(b.id);
160
+ });
161
+ }
162
+ /**
163
+ * Sort actions by id
164
+ */
165
+ function sortActions(actions) {
166
+ return [...actions].sort((a, b) => a.id.localeCompare(b.id));
167
+ }
168
+ /**
169
+ * Sort jobs by id
170
+ */
171
+ function sortJobs(jobs) {
172
+ return [...jobs].sort((a, b) => a.id.localeCompare(b.id));
173
+ }
174
+ /**
175
+ * Sort models by modelName
176
+ */
177
+ function sortModels(models) {
178
+ return [...models].sort((a, b) => a.modelName.localeCompare(b.modelName));
179
+ }
180
+ /**
181
+ * Calculate domain hash
182
+ * @param domain - Domain name: "routes", "actions", "jobs", or "models"
183
+ * @param entities - Array of entities for the domain
184
+ */
185
+ export function calculateDomainHash(domain, entities) {
186
+ // Empty domain handling
187
+ if (entities.length === 0) {
188
+ return calculateEmptyDomainHash();
189
+ }
190
+ let sortedEntities;
191
+ let projectFn;
192
+ switch (domain) {
193
+ case "routes":
194
+ sortedEntities = sortRoutes(entities);
195
+ projectFn = projectRoute;
196
+ break;
197
+ case "actions":
198
+ sortedEntities = sortActions(entities);
199
+ projectFn = projectAction;
200
+ break;
201
+ case "jobs":
202
+ sortedEntities = sortJobs(entities);
203
+ projectFn = projectJob;
204
+ break;
205
+ case "models":
206
+ sortedEntities = sortModels(entities);
207
+ projectFn = projectModel;
208
+ break;
209
+ default:
210
+ throw new Error(`Unknown domain: ${domain}`);
211
+ }
212
+ // Project each entity to tuple array, then to string
213
+ const entityStrings = sortedEntities.map((entity) => {
214
+ const tuples = projectFn(entity);
215
+ return tupleArrayToString(tuples);
216
+ });
217
+ // Join all entity strings
218
+ const combined = entityStrings.join("\n");
219
+ // Hash the combined string
220
+ return sha256(combined);
221
+ }
222
+ /**
223
+ * SHA256 hash function
224
+ */
225
+ function sha256(input) {
226
+ return createHash("sha256").update(input, "utf8").digest("hex");
227
+ }
@@ -0,0 +1,35 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+ /**
4
+ * Scan jobs directory and return all job definitions
5
+ */
6
+ export function scanJobs(projectRoot) {
7
+ const jobsDir = path.join(projectRoot, "jobs");
8
+ const jobs = [];
9
+ if (!fs.existsSync(jobsDir)) {
10
+ return jobs;
11
+ }
12
+ const jobDirs = fs.readdirSync(jobsDir, { withFileTypes: true })
13
+ .filter(dirent => dirent.isDirectory())
14
+ .map(dirent => dirent.name);
15
+ for (const jobDir of jobDirs) {
16
+ const jobFilePath = path.join(jobsDir, jobDir, "job.ts");
17
+ const relativePath = path.relative(projectRoot, jobFilePath).replace(/\\/g, "/");
18
+ if (!fs.existsSync(jobFilePath)) {
19
+ console.warn(`⚠ jobs/${jobDir}/\n → job.ts not found, skipping`);
20
+ continue;
21
+ }
22
+ try {
23
+ const code = fs.readFileSync(jobFilePath, "utf-8");
24
+ jobs.push({
25
+ id: jobDir,
26
+ code,
27
+ filePath: relativePath,
28
+ });
29
+ }
30
+ catch (error) {
31
+ console.warn(`⚠ jobs/${jobDir}/job.ts\n → Failed to read file: ${error.message}`);
32
+ }
33
+ }
34
+ return jobs;
35
+ }
@@ -0,0 +1,189 @@
1
+ /**
2
+ * Generate LiveModels TypeScript types from model schemas
3
+ */
4
+ /**
5
+ * Convert model field type to TypeScript type string
6
+ */
7
+ function fieldTypeToTS(field, indent = "") {
8
+ const { type, schema, items } = field;
9
+ switch (type) {
10
+ case "string":
11
+ case "objectId":
12
+ return "string";
13
+ case "number":
14
+ return "number";
15
+ case "boolean":
16
+ return "boolean";
17
+ case "date":
18
+ return "string"; // ISO date string
19
+ case "object":
20
+ if (schema && schema.length > 0) {
21
+ const props = schema
22
+ .map((f) => {
23
+ const tsType = fieldTypeToTS(f, indent + " ");
24
+ const optional = f.rules.every((r) => r.type !== "required")
25
+ ? "?"
26
+ : "";
27
+ return `${indent} ${f.name}${optional}: ${tsType};`;
28
+ })
29
+ .join("\n");
30
+ return `{\n${props}\n${indent}}`;
31
+ }
32
+ return "Record<string, any>";
33
+ case "array":
34
+ if (items) {
35
+ const itemType = fieldTypeToTS(items, indent + " ");
36
+ return `${itemType}[]`;
37
+ }
38
+ return "any[]";
39
+ default:
40
+ return "any";
41
+ }
42
+ }
43
+ /**
44
+ * Get enum values from field rules
45
+ */
46
+ function getEnumValues(field) {
47
+ const enumRule = field.rules.find((r) => r.type === "enum");
48
+ if (enumRule && Array.isArray(enumRule.value)) {
49
+ return enumRule.value;
50
+ }
51
+ return null;
52
+ }
53
+ /**
54
+ * Generate filters type from model schema
55
+ */
56
+ function generateFilters(schema) {
57
+ const filterFields = [];
58
+ // Always include id filter
59
+ filterFields.push("id?: string;");
60
+ // Add indexed fields as filters
61
+ if (schema.indexes) {
62
+ for (const index of schema.indexes) {
63
+ for (const fieldName of index.fields) {
64
+ if (fieldName !== "id" &&
65
+ !filterFields.some((f) => f.startsWith(fieldName))) {
66
+ const field = schema.fields.find((f) => f.name === fieldName);
67
+ if (field) {
68
+ const enumValues = getEnumValues(field);
69
+ if (enumValues) {
70
+ const unionType = enumValues.map((v) => `"${v}"`).join(" | ");
71
+ filterFields.push(`${fieldName}?: ${unionType};`);
72
+ }
73
+ else {
74
+ filterFields.push(`${fieldName}?: ${fieldTypeToTS(field)};`);
75
+ }
76
+ }
77
+ }
78
+ }
79
+ }
80
+ }
81
+ if (filterFields.length === 0) {
82
+ return "{}";
83
+ }
84
+ return `{\n ${filterFields.join("\n ")}\n }`;
85
+ }
86
+ /**
87
+ * Generate orderBy type from model schema
88
+ */
89
+ function generateOrderBy(schema) {
90
+ // Prefer createdAt if it exists and is indexed
91
+ const createdAtIndexed = schema.indexes?.some((idx) => idx.fields.includes("createdAt")) ||
92
+ schema.options?.timestamps;
93
+ if (createdAtIndexed) {
94
+ return '"createdAt"';
95
+ }
96
+ // Use first indexed field
97
+ if (schema.indexes && schema.indexes.length > 0) {
98
+ const firstIndexedField = schema.indexes[0].fields[0];
99
+ return `"${firstIndexedField}"`;
100
+ }
101
+ // Default to createdAt if timestamps enabled
102
+ if (schema.options?.timestamps) {
103
+ return '"createdAt"';
104
+ }
105
+ // Fallback to first field
106
+ if (schema.fields.length > 0) {
107
+ return `"${schema.fields[0].name}"`;
108
+ }
109
+ return '"id"';
110
+ }
111
+ /**
112
+ * Generate __result type from model schema
113
+ */
114
+ function generateResultType(schema) {
115
+ const resultFields = [];
116
+ for (const field of schema.fields) {
117
+ const tsType = fieldTypeToTS(field, " ");
118
+ const optional = field.rules.every((r) => r.type !== "required") ? "?" : "";
119
+ resultFields.push(` ${field.name}${optional}: ${tsType};`);
120
+ }
121
+ // Add timestamps if enabled
122
+ if (schema.options?.timestamps) {
123
+ if (!resultFields.some((f) => f.includes("createdAt"))) {
124
+ resultFields.push(" createdAt?: string;");
125
+ }
126
+ if (!resultFields.some((f) => f.includes("updatedAt"))) {
127
+ resultFields.push(" updatedAt?: string;");
128
+ }
129
+ }
130
+ return `{\n${resultFields.join("\n")}\n }`;
131
+ }
132
+ /**
133
+ * Generate fields union type from model schema
134
+ */
135
+ function generateFieldsUnion(schema) {
136
+ const fieldNames = schema.fields.map((f) => `"${f.name}"`);
137
+ // Add timestamps if enabled
138
+ if (schema.options?.timestamps) {
139
+ if (!fieldNames.includes('"createdAt"')) {
140
+ fieldNames.push('"createdAt"');
141
+ }
142
+ if (!fieldNames.includes('"updatedAt"')) {
143
+ fieldNames.push('"updatedAt"');
144
+ }
145
+ }
146
+ return fieldNames.join("\n | ");
147
+ }
148
+ /**
149
+ * Generate LiveModels type definition for a single model
150
+ */
151
+ function generateModelType(schema) {
152
+ const modelName = schema.modelName;
153
+ const fields = generateFieldsUnion(schema);
154
+ const filters = generateFilters(schema);
155
+ const orderBy = generateOrderBy(schema);
156
+ const result = generateResultType(schema);
157
+ return ` ${modelName}: {
158
+ fields:
159
+ | ${fields};
160
+ filters: ${filters};
161
+ orderBy: ${orderBy};
162
+ maxLimit: 100;
163
+ __result: ${result};
164
+ };`;
165
+ }
166
+ /**
167
+ * Generate complete LiveModels file content
168
+ */
169
+ export function generateLiveModels(models, serverId, baseUrl) {
170
+ const modelTypes = models.map((m) => generateModelType(m)).join("\n\n");
171
+ return `/**
172
+ * LiveModels Contract & SDK Instance
173
+ *
174
+ * This file is auto-generated by Backant CLI.
175
+ * Do not edit manually - it will be overwritten on next push.
176
+ *
177
+ * Generated at: ${new Date().toISOString()}
178
+ */
179
+
180
+ // LiveModels contract
181
+ export type LiveModels = {
182
+ ${modelTypes}
183
+ };
184
+
185
+ // SDK oluştur
186
+ export const SERVER_ID = "${serverId}";
187
+ export const BASE_URL = "${baseUrl}";
188
+ `;
189
+ }
@@ -0,0 +1,43 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+ /**
4
+ * Scan models directory and return all model definitions
5
+ */
6
+ export function scanModels(projectRoot) {
7
+ const modelsDir = path.join(projectRoot, "models");
8
+ const models = [];
9
+ if (!fs.existsSync(modelsDir)) {
10
+ return models;
11
+ }
12
+ const modelDirs = fs
13
+ .readdirSync(modelsDir, { withFileTypes: true })
14
+ .filter((dirent) => dirent.isDirectory())
15
+ .map((dirent) => dirent.name);
16
+ for (const modelDir of modelDirs) {
17
+ const modelFilePath = path.join(modelsDir, modelDir, "model.json");
18
+ const relativePath = path
19
+ .relative(projectRoot, modelFilePath)
20
+ .replace(/\\/g, "/");
21
+ if (!fs.existsSync(modelFilePath)) {
22
+ console.warn(`⚠ models/${modelDir}/\n → model.json not found, skipping`);
23
+ continue;
24
+ }
25
+ try {
26
+ const content = fs.readFileSync(modelFilePath, "utf-8");
27
+ const schema = JSON.parse(content);
28
+ // Use schema.modelName as source of truth (no fallback)
29
+ if (!schema.modelName) {
30
+ console.warn(`⚠ models/${modelDir}/model.json\n → modelName is missing in schema, skipping`);
31
+ continue;
32
+ }
33
+ models.push({
34
+ ...schema,
35
+ filePath: relativePath,
36
+ });
37
+ }
38
+ catch (error) {
39
+ console.warn(`⚠ models/${modelDir}/model.json\n → Failed to read/parse file: ${error.message}`);
40
+ }
41
+ }
42
+ return models;
43
+ }
@@ -0,0 +1,31 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+ import { fileURLToPath } from "url";
4
+ const packageRoot = findCliPackageRoot(path.dirname(fileURLToPath(import.meta.url)));
5
+ const packageJsonPath = path.join(packageRoot, "package.json");
6
+ function findCliPackageRoot(startDirectory) {
7
+ let directory = startDirectory;
8
+ while (true) {
9
+ const candidate = path.join(directory, "package.json");
10
+ try {
11
+ const metadata = JSON.parse(fs.readFileSync(candidate, "utf8"));
12
+ if (metadata.name === "backant-cli")
13
+ return directory;
14
+ }
15
+ catch {
16
+ // Keep walking until the CLI package root is found.
17
+ }
18
+ const parent = path.dirname(directory);
19
+ if (parent === directory) {
20
+ throw new Error("Could not locate the BE Studio CLI package root");
21
+ }
22
+ directory = parent;
23
+ }
24
+ }
25
+ export function getCliVersion() {
26
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
27
+ if (typeof packageJson.version !== "string" || packageJson.version.length === 0) {
28
+ throw new Error("package.json must contain a non-empty version string");
29
+ }
30
+ return packageJson.version;
31
+ }
@@ -0,0 +1,46 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+ /**
4
+ * Scan services directory and return merged services config
5
+ */
6
+ export function scanServices(projectRoot) {
7
+ const servicesDir = path.join(projectRoot, "services");
8
+ if (!fs.existsSync(servicesDir)) {
9
+ return null;
10
+ }
11
+ const servicesFiles = fs.readdirSync(servicesDir, { withFileTypes: true })
12
+ .filter(dirent => dirent.isFile() && dirent.name.endsWith(".json"))
13
+ .map(dirent => dirent.name);
14
+ const services = {};
15
+ const seenServices = new Set();
16
+ for (const file of servicesFiles) {
17
+ const serviceName = path.basename(file, ".json");
18
+ const filePath = path.join(servicesDir, file);
19
+ // Check for duplicates (before parsing)
20
+ if (seenServices.has(serviceName)) {
21
+ throw new Error(`Duplicate service definition: ${serviceName} (found in multiple files)`);
22
+ }
23
+ seenServices.add(serviceName);
24
+ try {
25
+ const content = fs.readFileSync(filePath, "utf-8");
26
+ const config = JSON.parse(content);
27
+ // Validate service name is one of the known services
28
+ const knownServices = ['tts', 'image', 'pdf', 'csv', 'json', 'video', 'llm', 'email'];
29
+ if (!knownServices.includes(serviceName)) {
30
+ console.warn(`⚠ services/${file}\n → Unknown service name: ${serviceName}, skipping`);
31
+ continue;
32
+ }
33
+ // Add to services object
34
+ services[serviceName] = config;
35
+ }
36
+ catch (error) {
37
+ // Re-throw duplicate errors
38
+ if (error.message.includes("Duplicate service definition")) {
39
+ throw error;
40
+ }
41
+ // Wrap other errors with file context
42
+ throw new Error(`Failed to parse services/${file}: ${error.message}`);
43
+ }
44
+ }
45
+ return Object.keys(services).length > 0 ? services : null;
46
+ }