@baclet/cli 0.1.6 → 0.1.7
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 +20 -0
- package/package.json +1 -1
- package/src/commands/setup-diagnostics.js +184 -0
- package/src/commands/setup-diagnostics.test.js +83 -0
- package/src/commands/setup.js +928 -0
- package/src/commands/setup.test.js +361 -0
- package/src/config.js +31 -6
- package/src/index.js +3 -0
|
@@ -0,0 +1,928 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { copyFile, mkdir, readFile, rename, stat, unlink, writeFile } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { checkbox, confirm, input, select } from "@inquirer/prompts";
|
|
5
|
+
import fg from "fast-glob";
|
|
6
|
+
import { findConfig, loadConfig, loadModels } from "../config.js";
|
|
7
|
+
import { scanSource, validateModels } from "./setup-diagnostics.js";
|
|
8
|
+
|
|
9
|
+
const runtimes = {
|
|
10
|
+
vite: { label: "Vite or browser (VITE_*)", prefix: "VITE_BACLET_", envSource: "import.meta" },
|
|
11
|
+
next: { label: "Next.js (NEXT_PUBLIC_*)", prefix: "NEXT_PUBLIC_BACLET_", envSource: "process" },
|
|
12
|
+
nuxt: { label: "Nuxt (NUXT_PUBLIC_*)", prefix: "NUXT_PUBLIC_BACLET_", envSource: "import.meta" },
|
|
13
|
+
node: { label: "Node.js or other (BACLET_*)", prefix: "BACLET_", envSource: "process" },
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
const languages = {
|
|
17
|
+
ts: "TypeScript",
|
|
18
|
+
js: "JavaScript",
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
const authMethodOptions = {
|
|
22
|
+
email: {
|
|
23
|
+
label: "Email sign-in and sign-up",
|
|
24
|
+
imports: ["createUserWithEmailAndPassword", "signInWithEmailAndPassword"],
|
|
25
|
+
},
|
|
26
|
+
guest: { label: "Anonymous sign-in", imports: ["signInAnonymously"] },
|
|
27
|
+
session: { label: "Session helpers", imports: ["getCurrentUser", "getIdToken", "signOut"] },
|
|
28
|
+
recovery: { label: "Password recovery", imports: ["forgotPassword", "resetPassword"] },
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
const storageOperationOptions = {
|
|
32
|
+
upload: { label: "Upload files", imports: ["uploadBytes"] },
|
|
33
|
+
url: { label: "Get download URLs", imports: ["getDownloadURL"] },
|
|
34
|
+
remove: { label: "Delete files", imports: ["deleteObject"] },
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
const databaseOperationOptions = {
|
|
38
|
+
list: { label: "List records", imports: ["get", "orderByChild", "equalTo", "limitToLast", "query"] },
|
|
39
|
+
get: { label: "Get one record", imports: ["get"] },
|
|
40
|
+
create: { label: "Create records", imports: ["push"] },
|
|
41
|
+
set: { label: "Replace records", imports: ["set"] },
|
|
42
|
+
update: { label: "Patch records", imports: ["update"] },
|
|
43
|
+
remove: { label: "Delete records", imports: ["remove"] },
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const validationOptions = {
|
|
47
|
+
strict: "Required fields and allowed fields",
|
|
48
|
+
basic: "Allowed fields only",
|
|
49
|
+
none: "No runtime validation",
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
export const defaultIntent = {
|
|
53
|
+
authMethods: Object.keys(authMethodOptions),
|
|
54
|
+
storageOps: Object.keys(storageOperationOptions),
|
|
55
|
+
databaseOps: Object.keys(databaseOperationOptions),
|
|
56
|
+
queryOptions: true,
|
|
57
|
+
validation: "strict",
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
export function normalizeIntent(options = {}) {
|
|
61
|
+
const intent = { ...defaultIntent, ...options };
|
|
62
|
+
for (const [key, allowed] of [
|
|
63
|
+
["authMethods", Object.keys(authMethodOptions)],
|
|
64
|
+
["storageOps", Object.keys(storageOperationOptions)],
|
|
65
|
+
["databaseOps", Object.keys(databaseOperationOptions)],
|
|
66
|
+
]) {
|
|
67
|
+
if (!Array.isArray(intent[key])) throw new Error(`${key} must be an array.`);
|
|
68
|
+
const unknown = intent[key].filter((value) => !allowed.includes(value));
|
|
69
|
+
if (unknown.length) throw new Error(`Unknown ${key}: ${unknown.join(", ")}.`);
|
|
70
|
+
intent[key] = [...new Set(intent[key])];
|
|
71
|
+
}
|
|
72
|
+
if (!validationOptions[intent.validation]) throw new Error(`Unknown validation mode "${intent.validation}".`);
|
|
73
|
+
if (typeof intent.queryOptions !== "boolean") throw new Error("queryOptions must be a boolean.");
|
|
74
|
+
return intent;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async function exists(file) {
|
|
78
|
+
try {
|
|
79
|
+
await stat(file);
|
|
80
|
+
return true;
|
|
81
|
+
} catch (error) {
|
|
82
|
+
if (error.code === "ENOENT") return false;
|
|
83
|
+
throw error;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async function isDirectory(file) {
|
|
88
|
+
try {
|
|
89
|
+
return (await stat(file)).isDirectory();
|
|
90
|
+
} catch (error) {
|
|
91
|
+
if (error.code === "ENOENT") return false;
|
|
92
|
+
throw error;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async function readJson(file) {
|
|
97
|
+
try {
|
|
98
|
+
return JSON.parse(await readFile(file, "utf8"));
|
|
99
|
+
} catch (error) {
|
|
100
|
+
if (error.code === "ENOENT" || error instanceof SyntaxError) return {};
|
|
101
|
+
throw error;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export function resolveInside(root, target) {
|
|
106
|
+
const base = path.resolve(root);
|
|
107
|
+
const resolved = path.resolve(base, String(target ?? ""));
|
|
108
|
+
if (resolved === base || !resolved.startsWith(base + path.sep)) {
|
|
109
|
+
throw new Error("Generated files must stay inside the project root.");
|
|
110
|
+
}
|
|
111
|
+
return resolved;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function slug(value) {
|
|
115
|
+
const result = String(value)
|
|
116
|
+
.toLowerCase()
|
|
117
|
+
.replace(/[^a-z0-9]+/g, "-")
|
|
118
|
+
.replace(/^-+|-+$/g, "");
|
|
119
|
+
return result || "model";
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function pascal(value) {
|
|
123
|
+
const words = String(value).split(/[^a-zA-Z0-9]+/).filter(Boolean);
|
|
124
|
+
const joined = words.map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("");
|
|
125
|
+
const cleaned = joined.replace(/[^A-Za-z0-9]/g, "");
|
|
126
|
+
return /^[A-Za-z]/.test(cleaned) ? cleaned : `Model${cleaned}`;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function propertyKey(name) {
|
|
130
|
+
return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : JSON.stringify(name);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function fieldType(field) {
|
|
134
|
+
const type = field?.type;
|
|
135
|
+
if (["string", "text", "uuid"].includes(type)) return "string";
|
|
136
|
+
if (["integer", "decimal"].includes(type)) return "number";
|
|
137
|
+
if (type === "boolean") return "boolean";
|
|
138
|
+
if (["timestamp", "date"].includes(type)) return "string";
|
|
139
|
+
if (type === "json") return "unknown";
|
|
140
|
+
if (type === "enum") {
|
|
141
|
+
const values = Array.isArray(field.values) ? field.values : [];
|
|
142
|
+
return values.length ? values.map((value) => JSON.stringify(String(value))).join(" | ") : "string";
|
|
143
|
+
}
|
|
144
|
+
return "unknown";
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function hasDefault(field) {
|
|
148
|
+
return Object.prototype.hasOwnProperty.call(field ?? {}, "default");
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function recordType(model, language, input) {
|
|
152
|
+
if (language !== "ts") return "";
|
|
153
|
+
const lines = Object.entries(model.fields).map(([name, field]) => {
|
|
154
|
+
const optional = input ? !field?.required || hasDefault(field) : !field?.required;
|
|
155
|
+
return ` ${propertyKey(name)}${optional ? "?" : ""}: ${fieldType(field)};`;
|
|
156
|
+
});
|
|
157
|
+
if (!input) lines.push(" key?: string;");
|
|
158
|
+
return lines.join("\n");
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function modelMetadata(models) {
|
|
162
|
+
const usedFiles = new Set();
|
|
163
|
+
const usedIdentifiers = new Set(["authActions", "storageActions", "baclet"]);
|
|
164
|
+
const usedTypes = new Set();
|
|
165
|
+
|
|
166
|
+
return models.map((model) => {
|
|
167
|
+
let fileBase = slug(model.name);
|
|
168
|
+
if (["auth", "storage", "baclet", "index"].includes(fileBase)) fileBase = `model-${fileBase}`;
|
|
169
|
+
let fileName = fileBase;
|
|
170
|
+
let fileIndex = 2;
|
|
171
|
+
while (usedFiles.has(fileName)) fileName = `${fileBase}-${fileIndex++}`;
|
|
172
|
+
usedFiles.add(fileName);
|
|
173
|
+
|
|
174
|
+
const baseName = pascal(model.name);
|
|
175
|
+
let identifier = `${baseName.charAt(0).toLowerCase()}${baseName.slice(1)}Actions`;
|
|
176
|
+
let identifierIndex = 2;
|
|
177
|
+
while (usedIdentifiers.has(identifier)) identifier = `${baseName}Actions${identifierIndex++}`;
|
|
178
|
+
usedIdentifiers.add(identifier);
|
|
179
|
+
|
|
180
|
+
let typeBase = baseName;
|
|
181
|
+
let typeIndex = 2;
|
|
182
|
+
while (usedTypes.has(typeBase)) typeBase = `${baseName}${typeIndex++}`;
|
|
183
|
+
usedTypes.add(typeBase);
|
|
184
|
+
|
|
185
|
+
return {
|
|
186
|
+
model,
|
|
187
|
+
fileName,
|
|
188
|
+
identifier,
|
|
189
|
+
recordName: `${typeBase}Record`,
|
|
190
|
+
inputName: `${typeBase}Input`,
|
|
191
|
+
};
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function envExpression(runtime, language) {
|
|
196
|
+
if (runtime === "vite" || runtime === "nuxt") {
|
|
197
|
+
if (language === "ts") {
|
|
198
|
+
return "(import.meta as unknown as { env?: Record<string, string | undefined> }).env ?? {}";
|
|
199
|
+
}
|
|
200
|
+
return "import.meta.env ?? {}";
|
|
201
|
+
}
|
|
202
|
+
if (language === "ts") {
|
|
203
|
+
return "(globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env ?? {}";
|
|
204
|
+
}
|
|
205
|
+
return "globalThis.process?.env ?? {}";
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function clientFile(runtime, language, features) {
|
|
209
|
+
const spec = runtimes[runtime];
|
|
210
|
+
const publishableKey = `${spec.prefix}PUBLISHABLE_KEY`;
|
|
211
|
+
const apiUrl = `${spec.prefix}API_URL`;
|
|
212
|
+
const storageBucket = `${spec.prefix}STORAGE_BUCKET`;
|
|
213
|
+
const lines = [`import { initializeBaclet } from "@baclet/sdk";`];
|
|
214
|
+
|
|
215
|
+
if (features.includes("database")) {
|
|
216
|
+
lines.push(`import { enableDatabasePersistence } from "@baclet/sdk/database";`);
|
|
217
|
+
}
|
|
218
|
+
lines.push("", `const env = ${envExpression(runtime, language)};`, "");
|
|
219
|
+
lines.push(`const publishableKey = env.${publishableKey};`);
|
|
220
|
+
lines.push("if (!publishableKey) {");
|
|
221
|
+
lines.push(` throw new Error("Missing ${publishableKey}. Copy .env.example to .env and set your BACLET publishable key.");`);
|
|
222
|
+
lines.push("}", "");
|
|
223
|
+
lines.push("export const baclet = initializeBaclet({");
|
|
224
|
+
lines.push(` apiUrl: env.${apiUrl} || "https://api.baclet.app",`);
|
|
225
|
+
lines.push(" publishableKey,");
|
|
226
|
+
if (features.includes("storage")) {
|
|
227
|
+
lines.push(` ...(env.${storageBucket} ? { storageBucket: env.${storageBucket} } : {}),`);
|
|
228
|
+
}
|
|
229
|
+
lines.push("});");
|
|
230
|
+
if (features.includes("database")) {
|
|
231
|
+
lines.push("", "enableDatabasePersistence();");
|
|
232
|
+
}
|
|
233
|
+
return `${lines.join("\n")}\n`;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function authFile(language, methods) {
|
|
237
|
+
const imports = [...new Set(["getAuth", ...methods.flatMap((method) => authMethodOptions[method].imports)])];
|
|
238
|
+
const entries = [];
|
|
239
|
+
if (methods.includes("email")) {
|
|
240
|
+
entries.push(
|
|
241
|
+
language === "ts"
|
|
242
|
+
? " signIn: (email: string, password: string) => signInWithEmailAndPassword(auth, email, password),"
|
|
243
|
+
: " signIn: (email, password) => signInWithEmailAndPassword(auth, email, password),",
|
|
244
|
+
language === "ts"
|
|
245
|
+
? " signUp: (email: string, password: string, fullName?: string) =>"
|
|
246
|
+
: " signUp: (email, password, fullName) =>",
|
|
247
|
+
" createUserWithEmailAndPassword(auth, email, password, fullName),",
|
|
248
|
+
);
|
|
249
|
+
}
|
|
250
|
+
if (methods.includes("guest")) {
|
|
251
|
+
entries.push(" signInAsGuest: () => signInAnonymously(auth),");
|
|
252
|
+
}
|
|
253
|
+
if (methods.includes("session")) {
|
|
254
|
+
entries.push(
|
|
255
|
+
" signOut: () => signOut(auth),",
|
|
256
|
+
" currentUser: () => getCurrentUser(auth),",
|
|
257
|
+
" idToken: () => getIdToken(auth),",
|
|
258
|
+
);
|
|
259
|
+
}
|
|
260
|
+
if (methods.includes("recovery")) {
|
|
261
|
+
entries.push(
|
|
262
|
+
language === "ts"
|
|
263
|
+
? " forgotPassword: (email: string) => forgotPassword(auth, email),"
|
|
264
|
+
: " forgotPassword: (email) => forgotPassword(auth, email),",
|
|
265
|
+
language === "ts"
|
|
266
|
+
? " resetPassword: (token: string, password: string) => resetPassword(auth, token, password),"
|
|
267
|
+
: " resetPassword: (token, password) => resetPassword(auth, token, password),",
|
|
268
|
+
);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
const lines = [
|
|
272
|
+
"import {",
|
|
273
|
+
...imports.map((name) => ` ${name},`),
|
|
274
|
+
'} from "@baclet/sdk/auth";',
|
|
275
|
+
'import { baclet } from "../baclet.js";',
|
|
276
|
+
"",
|
|
277
|
+
"const auth = getAuth(baclet);",
|
|
278
|
+
"",
|
|
279
|
+
"export const authActions = {",
|
|
280
|
+
...entries,
|
|
281
|
+
"};",
|
|
282
|
+
];
|
|
283
|
+
return `${lines.join("\n")}\n`;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function storageFile(language, operations) {
|
|
287
|
+
const imports = [...new Set(["getStorage", "ref", ...operations.flatMap((operation) => storageOperationOptions[operation].imports)])];
|
|
288
|
+
const entries = [];
|
|
289
|
+
if (operations.includes("upload")) {
|
|
290
|
+
entries.push(
|
|
291
|
+
language === "ts"
|
|
292
|
+
? " upload: (path: string, file: Blob, metadata: UploadMetadata = {}) =>"
|
|
293
|
+
: " upload: (path, file, metadata = {}) =>",
|
|
294
|
+
" uploadBytes(ref(storage, path), file, metadata),",
|
|
295
|
+
);
|
|
296
|
+
}
|
|
297
|
+
if (operations.includes("url")) {
|
|
298
|
+
entries.push(
|
|
299
|
+
language === "ts"
|
|
300
|
+
? " url: (path: string) => getDownloadURL(ref(storage, path)),"
|
|
301
|
+
: " url: (path) => getDownloadURL(ref(storage, path)),",
|
|
302
|
+
);
|
|
303
|
+
}
|
|
304
|
+
if (operations.includes("remove")) {
|
|
305
|
+
entries.push(
|
|
306
|
+
language === "ts"
|
|
307
|
+
? " remove: (path: string) => deleteObject(ref(storage, path)),"
|
|
308
|
+
: " remove: (path) => deleteObject(ref(storage, path)),",
|
|
309
|
+
);
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
const lines = ["import {", ...imports.map((name) => ` ${name},`), '} from "@baclet/sdk/storage";'];
|
|
313
|
+
if (language === "ts" && operations.includes("upload")) {
|
|
314
|
+
lines.push('import type { UploadMetadata } from "@baclet/sdk/storage";');
|
|
315
|
+
}
|
|
316
|
+
lines.push(
|
|
317
|
+
'import { baclet } from "../baclet.js";',
|
|
318
|
+
"",
|
|
319
|
+
"const storage = getStorage(baclet);",
|
|
320
|
+
"",
|
|
321
|
+
"export const storageActions = {",
|
|
322
|
+
...entries,
|
|
323
|
+
"};",
|
|
324
|
+
);
|
|
325
|
+
return `${lines.join("\n")}\n`;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
function modelFile(meta, language, intent) {
|
|
329
|
+
const { model, identifier, recordName, inputName } = meta;
|
|
330
|
+
const fields = Object.keys(model.fields);
|
|
331
|
+
const requiredFields = fields.filter((field) => model.fields[field]?.required === true);
|
|
332
|
+
const operations = intent.databaseOps;
|
|
333
|
+
const keyedOperations = operations.filter((operation) => ["get", "set", "update", "remove"].includes(operation));
|
|
334
|
+
const writeOperations = operations.filter((operation) => ["create", "set", "update"].includes(operation));
|
|
335
|
+
const usesQuery = operations.includes("list") && intent.queryOptions;
|
|
336
|
+
const validates = intent.validation !== "none" && writeOperations.length > 0;
|
|
337
|
+
const validatesRequired = intent.validation === "strict" && validates;
|
|
338
|
+
const needsAllowedFields = usesQuery || validates;
|
|
339
|
+
|
|
340
|
+
const imports = [...new Set([
|
|
341
|
+
"getDatabase",
|
|
342
|
+
"ref",
|
|
343
|
+
...operations.flatMap((operation) =>
|
|
344
|
+
operation === "list" && !usesQuery ? ["get"] : databaseOperationOptions[operation].imports,
|
|
345
|
+
),
|
|
346
|
+
])];
|
|
347
|
+
const lines = ["import {", ...imports.map((name) => ` ${name},`), '} from "@baclet/sdk/database";'];
|
|
348
|
+
if (language === "ts" && usesQuery) {
|
|
349
|
+
lines.push('import type { QueryConstraint } from "@baclet/sdk/database";');
|
|
350
|
+
}
|
|
351
|
+
lines.push(
|
|
352
|
+
'import { baclet } from "../baclet.js";',
|
|
353
|
+
"",
|
|
354
|
+
"const database = getDatabase(baclet);",
|
|
355
|
+
`const collection = ${JSON.stringify(model.name)};`,
|
|
356
|
+
);
|
|
357
|
+
if (needsAllowedFields) {
|
|
358
|
+
lines.push(
|
|
359
|
+
language === "ts"
|
|
360
|
+
? `const allowedFields = new Set<string>(${JSON.stringify(fields)});`
|
|
361
|
+
: `const allowedFields = new Set(${JSON.stringify(fields)});`,
|
|
362
|
+
);
|
|
363
|
+
}
|
|
364
|
+
if (validatesRequired) {
|
|
365
|
+
lines.push(`const requiredFields = new Set(${JSON.stringify(requiredFields)});`);
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
if (keyedOperations.length) {
|
|
369
|
+
lines.push(
|
|
370
|
+
"",
|
|
371
|
+
language === "ts" ? "function assertKey(key: string) {" : "function assertKey(key) {",
|
|
372
|
+
' if (!key || key.includes("/") || key.includes("..")) {',
|
|
373
|
+
' throw new Error("Invalid BACLET record key.");',
|
|
374
|
+
" }",
|
|
375
|
+
" return key;",
|
|
376
|
+
"}",
|
|
377
|
+
);
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
if (validates) {
|
|
381
|
+
lines.push(
|
|
382
|
+
"",
|
|
383
|
+
language === "ts"
|
|
384
|
+
? "function assertValues(values: object, requireAll: boolean) {"
|
|
385
|
+
: "function assertValues(values, requireAll) {",
|
|
386
|
+
' if (!values || typeof values !== "object" || Array.isArray(values)) {',
|
|
387
|
+
' throw new Error("Invalid BACLET record values.");',
|
|
388
|
+
" }",
|
|
389
|
+
" const entries = Object.entries(values);",
|
|
390
|
+
" for (const [key] of entries) {",
|
|
391
|
+
" if (!allowedFields.has(key)) {",
|
|
392
|
+
' throw new Error(`Unknown field "${key}" for ${collection}.`);',
|
|
393
|
+
" }",
|
|
394
|
+
" }",
|
|
395
|
+
);
|
|
396
|
+
if (validatesRequired) {
|
|
397
|
+
lines.push(
|
|
398
|
+
" if (requireAll) {",
|
|
399
|
+
" for (const key of requiredFields) {",
|
|
400
|
+
" if (!entries.some(([entryKey, value]) => entryKey === key && value !== undefined)) {",
|
|
401
|
+
' throw new Error(`Missing required field "${key}" for ${collection}.`);',
|
|
402
|
+
" }",
|
|
403
|
+
" }",
|
|
404
|
+
" }",
|
|
405
|
+
);
|
|
406
|
+
}
|
|
407
|
+
lines.push("}");
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
if (language === "ts") {
|
|
411
|
+
lines.push("", `export type ${recordName} = {`, recordType(model, language, false), "};");
|
|
412
|
+
lines.push("", `export type ${inputName} = {`, recordType(model, language, true), "};");
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
const entries = [];
|
|
416
|
+
if (operations.includes("list")) {
|
|
417
|
+
entries.push(
|
|
418
|
+
usesQuery
|
|
419
|
+
? language === "ts"
|
|
420
|
+
? " list: async (options: { field?: string; equalTo?: unknown; limit?: number } = {}) => {"
|
|
421
|
+
: " list: async (options = {}) => {"
|
|
422
|
+
: " list: async () => {",
|
|
423
|
+
" let reference = ref(database, collection);",
|
|
424
|
+
);
|
|
425
|
+
if (usesQuery) {
|
|
426
|
+
entries.push(
|
|
427
|
+
" const constraints = " + (language === "ts" ? "[] as QueryConstraint[]" : "[]") + ";",
|
|
428
|
+
" if (options.field) {",
|
|
429
|
+
" if (!allowedFields.has(options.field)) {",
|
|
430
|
+
' throw new Error(`Unknown field "${options.field}" for ${collection}.`);',
|
|
431
|
+
" }",
|
|
432
|
+
" constraints.push(orderByChild(options.field));",
|
|
433
|
+
" } else if (options.equalTo !== undefined) {",
|
|
434
|
+
' throw new Error("equalTo requires a field.");',
|
|
435
|
+
" }",
|
|
436
|
+
" if (options.equalTo !== undefined) constraints.push(equalTo(options.equalTo));",
|
|
437
|
+
" if (options.limit !== undefined) {",
|
|
438
|
+
" if (!Number.isInteger(options.limit) || options.limit < 1) {",
|
|
439
|
+
' throw new Error("limit must be a positive integer.");',
|
|
440
|
+
" }",
|
|
441
|
+
" constraints.push(limitToLast(options.limit));",
|
|
442
|
+
" }",
|
|
443
|
+
" if (constraints.length) reference = query(reference, ...constraints);",
|
|
444
|
+
);
|
|
445
|
+
}
|
|
446
|
+
entries.push(
|
|
447
|
+
" const snapshot = await get(reference);",
|
|
448
|
+
language === "ts"
|
|
449
|
+
? ` return Object.values((snapshot.val() ?? {}) as Record<string, ${recordName}>);`
|
|
450
|
+
: " return Object.values(snapshot.val() ?? {});",
|
|
451
|
+
" },",
|
|
452
|
+
);
|
|
453
|
+
}
|
|
454
|
+
if (operations.includes("get")) {
|
|
455
|
+
entries.push(
|
|
456
|
+
language === "ts" ? " get: async (key: string) => {" : " get: async (key) => {",
|
|
457
|
+
" const snapshot = await get(ref(database, `${collection}/${assertKey(key)}`));",
|
|
458
|
+
language === "ts"
|
|
459
|
+
? ` return snapshot.exists() ? (snapshot.val() as ${recordName}) : null;`
|
|
460
|
+
: " return snapshot.exists() ? snapshot.val() : null;",
|
|
461
|
+
" },",
|
|
462
|
+
);
|
|
463
|
+
}
|
|
464
|
+
if (operations.includes("create")) {
|
|
465
|
+
entries.push(
|
|
466
|
+
language === "ts" ? ` create: (values: ${inputName}) => {` : " create: (values) => {",
|
|
467
|
+
...(validates ? [" assertValues(values, " + (validatesRequired ? "true" : "false") + ");"] : []),
|
|
468
|
+
" return push(ref(database, collection), values);",
|
|
469
|
+
" },",
|
|
470
|
+
);
|
|
471
|
+
}
|
|
472
|
+
if (operations.includes("set")) {
|
|
473
|
+
entries.push(
|
|
474
|
+
language === "ts" ? ` set: (key: string, values: ${inputName}) => {` : " set: (key, values) => {",
|
|
475
|
+
...(validates ? [" assertValues(values, " + (validatesRequired ? "true" : "false") + ");"] : []),
|
|
476
|
+
" return set(ref(database, `${collection}/${assertKey(key)}`), values);",
|
|
477
|
+
" },",
|
|
478
|
+
);
|
|
479
|
+
}
|
|
480
|
+
if (operations.includes("update")) {
|
|
481
|
+
entries.push(
|
|
482
|
+
language === "ts" ? ` update: (key: string, values: Partial<${inputName}>) => {` : " update: (key, values) => {",
|
|
483
|
+
...(validates ? [" assertValues(values, false);"] : []),
|
|
484
|
+
language === "ts"
|
|
485
|
+
? " return update(ref(database, `${collection}/${assertKey(key)}`), values as Record<string, unknown>);"
|
|
486
|
+
: " return update(ref(database, `${collection}/${assertKey(key)}`), values);",
|
|
487
|
+
" },",
|
|
488
|
+
);
|
|
489
|
+
}
|
|
490
|
+
if (operations.includes("remove")) {
|
|
491
|
+
entries.push(
|
|
492
|
+
language === "ts"
|
|
493
|
+
? " remove: (key: string) => remove(ref(database, `${collection}/${assertKey(key)}`)),"
|
|
494
|
+
: " remove: (key) => remove(ref(database, `${collection}/${assertKey(key)}`)),",
|
|
495
|
+
);
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
lines.push("", `export const ${identifier} = {`, ...entries, "};");
|
|
499
|
+
return `${lines.join("\n")}\n`;
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
function indexFile(language, features, metadata) {
|
|
503
|
+
const lines = ['export { baclet } from "./baclet.js";'];
|
|
504
|
+
if (features.includes("auth")) lines.push('export { authActions } from "./actions/auth.js";');
|
|
505
|
+
if (features.includes("storage")) lines.push('export { storageActions } from "./actions/storage.js";');
|
|
506
|
+
for (const meta of metadata) {
|
|
507
|
+
lines.push(`export { ${meta.identifier} } from "./actions/${meta.fileName}.js";`);
|
|
508
|
+
if (language === "ts") {
|
|
509
|
+
lines.push(`export type { ${meta.inputName}, ${meta.recordName} } from "./actions/${meta.fileName}.js";`);
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
return `${lines.join("\n")}\n`;
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
function envKeys(runtime, storage) {
|
|
516
|
+
const prefix = runtimes[runtime].prefix;
|
|
517
|
+
const keys = [
|
|
518
|
+
{ name: `${prefix}PUBLISHABLE_KEY`, value: "pb_your_publishable_key" },
|
|
519
|
+
{ name: `${prefix}API_URL`, value: "https://api.baclet.app" },
|
|
520
|
+
];
|
|
521
|
+
if (storage) keys.push({ name: `${prefix}STORAGE_BUCKET`, value: "your_storage_bucket" });
|
|
522
|
+
return keys;
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
export function mergeEnvExample(existing, keys) {
|
|
526
|
+
const present = new Set();
|
|
527
|
+
for (const line of existing.split(/\r?\n/)) {
|
|
528
|
+
const match = line.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/);
|
|
529
|
+
if (match) present.add(match[1]);
|
|
530
|
+
}
|
|
531
|
+
const missing = keys.filter((key) => !present.has(key.name));
|
|
532
|
+
if (!missing.length) return { content: existing, changed: false };
|
|
533
|
+
const separator = existing.length === 0 ? "" : existing.endsWith("\n") ? "\n" : "\n\n";
|
|
534
|
+
const addition = `${missing.map((key) => `${key.name}=${key.value}`).join("\n")}\n`;
|
|
535
|
+
return { content: `${existing}${separator}${addition}`, changed: true };
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
export function mergeGitignore(existing, entries) {
|
|
539
|
+
const present = new Set(
|
|
540
|
+
existing
|
|
541
|
+
.split(/\r?\n/)
|
|
542
|
+
.map((line) => line.trim())
|
|
543
|
+
.filter(Boolean),
|
|
544
|
+
);
|
|
545
|
+
const missing = entries.filter((entry) => !present.has(entry));
|
|
546
|
+
if (!missing.length) return { content: existing, changed: false };
|
|
547
|
+
const separator = existing.length === 0 ? "" : existing.endsWith("\n") ? "" : "\n";
|
|
548
|
+
return { content: `${existing}${separator}${missing.join("\n")}\n`, changed: true };
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
export function buildPlan({ root, libDir, language, runtime, features, models, intent = {} }) {
|
|
552
|
+
const base = path.resolve(root);
|
|
553
|
+
const selected = [...new Set(features)];
|
|
554
|
+
const options = normalizeIntent(intent);
|
|
555
|
+
for (const feature of selected) {
|
|
556
|
+
if (!["auth", "storage", "database"].includes(feature)) {
|
|
557
|
+
throw new Error(`Unknown setup feature "${feature}".`);
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
if (!runtimes[runtime]) throw new Error(`Unknown runtime "${runtime}".`);
|
|
561
|
+
if (!languages[language]) throw new Error(`Unknown language "${language}".`);
|
|
562
|
+
if (selected.includes("database") && !models?.length) {
|
|
563
|
+
throw new Error("Database actions require at least one model.");
|
|
564
|
+
}
|
|
565
|
+
if (selected.includes("auth") && !options.authMethods.length) {
|
|
566
|
+
throw new Error("Select at least one auth method.");
|
|
567
|
+
}
|
|
568
|
+
if (selected.includes("storage") && !options.storageOps.length) {
|
|
569
|
+
throw new Error("Select at least one storage operation.");
|
|
570
|
+
}
|
|
571
|
+
if (selected.includes("database") && !options.databaseOps.length) {
|
|
572
|
+
throw new Error("Select at least one database operation.");
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
const resolvedLib = resolveInside(base, libDir);
|
|
576
|
+
const metadata = selected.includes("database") ? modelMetadata(models) : [];
|
|
577
|
+
const plan = [
|
|
578
|
+
{
|
|
579
|
+
path: path.join(resolvedLib, `baclet.${language}`),
|
|
580
|
+
content: clientFile(runtime, language, selected),
|
|
581
|
+
merge: null,
|
|
582
|
+
},
|
|
583
|
+
];
|
|
584
|
+
|
|
585
|
+
if (selected.includes("auth")) {
|
|
586
|
+
plan.push({
|
|
587
|
+
path: path.join(resolvedLib, "actions", `auth.${language}`),
|
|
588
|
+
content: authFile(language, options.authMethods),
|
|
589
|
+
merge: null,
|
|
590
|
+
});
|
|
591
|
+
}
|
|
592
|
+
if (selected.includes("storage")) {
|
|
593
|
+
plan.push({
|
|
594
|
+
path: path.join(resolvedLib, "actions", `storage.${language}`),
|
|
595
|
+
content: storageFile(language, options.storageOps),
|
|
596
|
+
merge: null,
|
|
597
|
+
});
|
|
598
|
+
}
|
|
599
|
+
for (const meta of metadata) {
|
|
600
|
+
plan.push({
|
|
601
|
+
path: path.join(resolvedLib, "actions", `${meta.fileName}.${language}`),
|
|
602
|
+
content: modelFile(meta, language, options),
|
|
603
|
+
merge: null,
|
|
604
|
+
});
|
|
605
|
+
}
|
|
606
|
+
plan.push({
|
|
607
|
+
path: path.join(resolvedLib, `index.${language}`),
|
|
608
|
+
content: indexFile(language, selected, metadata),
|
|
609
|
+
merge: null,
|
|
610
|
+
});
|
|
611
|
+
const keys = envKeys(runtime, selected.includes("storage"));
|
|
612
|
+
const ignoreEntries = [".env", ".env.local", ".env.*.local"];
|
|
613
|
+
plan.push({
|
|
614
|
+
path: path.join(base, ".env.example"),
|
|
615
|
+
content: `${keys.map((key) => `${key.name}=${key.value}`).join("\n")}\n`,
|
|
616
|
+
merge: "env",
|
|
617
|
+
keys,
|
|
618
|
+
});
|
|
619
|
+
plan.push({
|
|
620
|
+
path: path.join(base, ".gitignore"),
|
|
621
|
+
content: `${ignoreEntries.join("\n")}\n`,
|
|
622
|
+
merge: "gitignore",
|
|
623
|
+
entries: ignoreEntries,
|
|
624
|
+
});
|
|
625
|
+
|
|
626
|
+
return plan;
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
async function writeAtomic(file, content) {
|
|
630
|
+
const temp = path.join(path.dirname(file), `.${path.basename(file)}.${randomUUID()}.tmp`);
|
|
631
|
+
try {
|
|
632
|
+
await writeFile(temp, content, { mode: 0o644 });
|
|
633
|
+
await rename(temp, file);
|
|
634
|
+
} catch (error) {
|
|
635
|
+
await unlink(temp).catch(() => {});
|
|
636
|
+
throw error;
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
export async function writeWithBackup(file, content) {
|
|
641
|
+
const current = await readFile(file, "utf8").catch((error) => {
|
|
642
|
+
if (error.code === "ENOENT") return null;
|
|
643
|
+
throw error;
|
|
644
|
+
});
|
|
645
|
+
if (current !== null) await copyFile(file, `${file}.bak`);
|
|
646
|
+
await writeAtomic(file, content);
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
export async function writePlan(plan, options = {}) {
|
|
650
|
+
const overwrite = options.overwrite === true;
|
|
651
|
+
const result = { created: [], updated: [], skipped: [], merged: [] };
|
|
652
|
+
|
|
653
|
+
for (const item of plan) {
|
|
654
|
+
await mkdir(path.dirname(item.path), { recursive: true });
|
|
655
|
+
const current = await readFile(item.path, "utf8").catch((error) => {
|
|
656
|
+
if (error.code === "ENOENT") return null;
|
|
657
|
+
throw error;
|
|
658
|
+
});
|
|
659
|
+
|
|
660
|
+
if (item.merge === "env") {
|
|
661
|
+
const merged = mergeEnvExample(current ?? "", item.keys);
|
|
662
|
+
if (current !== null && !merged.changed) {
|
|
663
|
+
result.skipped.push(item.path);
|
|
664
|
+
continue;
|
|
665
|
+
}
|
|
666
|
+
await writeAtomic(item.path, merged.content);
|
|
667
|
+
if (current === null) result.created.push(item.path);
|
|
668
|
+
else result.merged.push(item.path);
|
|
669
|
+
continue;
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
if (item.merge === "gitignore") {
|
|
673
|
+
const merged = mergeGitignore(current ?? "", item.entries);
|
|
674
|
+
if (current !== null && !merged.changed) {
|
|
675
|
+
result.skipped.push(item.path);
|
|
676
|
+
continue;
|
|
677
|
+
}
|
|
678
|
+
await writeAtomic(item.path, merged.content);
|
|
679
|
+
if (current === null) result.created.push(item.path);
|
|
680
|
+
else result.merged.push(item.path);
|
|
681
|
+
continue;
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
if (current !== null && !overwrite) {
|
|
685
|
+
result.skipped.push(item.path);
|
|
686
|
+
continue;
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
await writeWithBackup(item.path, item.content);
|
|
690
|
+
if (current === null) result.created.push(item.path);
|
|
691
|
+
else result.updated.push(item.path);
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
return result;
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
export async function detectDefaults(project) {
|
|
698
|
+
const { root, configPath, models } = project;
|
|
699
|
+
const pkg = await readJson(path.join(root, "package.json"));
|
|
700
|
+
const dependencies = { ...pkg.dependencies, ...pkg.devDependencies };
|
|
701
|
+
let runtime = "node";
|
|
702
|
+
if (dependencies.next) runtime = "next";
|
|
703
|
+
else if (dependencies.nuxt) runtime = "nuxt";
|
|
704
|
+
else if (dependencies.vite) runtime = "vite";
|
|
705
|
+
|
|
706
|
+
const usesTypeScript =
|
|
707
|
+
(await exists(path.join(root, "tsconfig.json"))) || /\.m?ts$/.test(configPath ?? "");
|
|
708
|
+
const libDir = (await isDirectory(path.join(root, "src"))) ? "src/lib" : "lib";
|
|
709
|
+
return { runtime, language: usesTypeScript ? "ts" : "js", libDir, hasModels: models.length > 0 };
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
function printSummary(result) {
|
|
713
|
+
if (result.created.length) console.log(`Created ${result.created.length} file(s):`);
|
|
714
|
+
for (const file of result.created) console.log(` + ${file}`);
|
|
715
|
+
if (result.updated.length) console.log(`Updated ${result.updated.length} file(s):`);
|
|
716
|
+
for (const file of result.updated) console.log(` ~ ${file}`);
|
|
717
|
+
if (result.merged.length) console.log(`Updated ${result.merged.length} existing file(s):`);
|
|
718
|
+
for (const file of result.merged) console.log(` ~ ${file}`);
|
|
719
|
+
if (result.skipped.length) console.log(`Skipped ${result.skipped.length} existing file(s):`);
|
|
720
|
+
for (const file of result.skipped) console.log(` = ${file}`);
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
function printDiagnostics(scan, log) {
|
|
724
|
+
log(`\n${scan.file}:`);
|
|
725
|
+
for (const fix of scan.fixes) {
|
|
726
|
+
log(` ! line ${fix.line}: ${fix.message}`);
|
|
727
|
+
if (fix.before) log(` ${fix.before.trim()} -> ${fix.after.trim()}`);
|
|
728
|
+
}
|
|
729
|
+
for (const issue of scan.manual) {
|
|
730
|
+
log(` !${issue.line ? ` line ${issue.line}` : ""}: ${issue.message}`);
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
function printModelIssues(issues) {
|
|
735
|
+
if (!issues.length) return;
|
|
736
|
+
console.log("\nBACLET model issues:");
|
|
737
|
+
for (const issue of issues) console.log(` ! ${issue.message}`);
|
|
738
|
+
console.log(" These need manual changes; nothing was rewritten.");
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
export function describePlanItem(item) {
|
|
742
|
+
if (item.merge === "env") return { label: "env keys", details: item.keys.map((key) => key.name) };
|
|
743
|
+
if (item.merge === "gitignore") return { label: "ignore entries", details: item.entries };
|
|
744
|
+
const exports = [...item.content.matchAll(/export (?:const|type) (\w+)/g)].map((match) => match[1]);
|
|
745
|
+
const actionBlock = item.content.match(/export const \w+ = \{([\s\S]*)\n\};/);
|
|
746
|
+
const actions = actionBlock
|
|
747
|
+
? [...actionBlock[1].matchAll(/^ (\w+):/gm)].map((match) => match[1])
|
|
748
|
+
: [];
|
|
749
|
+
return { exports, actions };
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
function printPlanPreview(plan, full, log) {
|
|
753
|
+
log("\nPlanned changes:");
|
|
754
|
+
for (const item of plan) {
|
|
755
|
+
const info = describePlanItem(item);
|
|
756
|
+
log(` ${path.relative(process.cwd(), item.path)}`);
|
|
757
|
+
if (info.actions?.length) log(` actions: ${info.actions.join(", ")}`);
|
|
758
|
+
if (info.details?.length) log(` ${info.label}: ${info.details.join(", ")}`);
|
|
759
|
+
if (full) {
|
|
760
|
+
for (const line of item.content.split("\n")) log(` | ${line}`);
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
export async function reviewSource(file, kind, useDefaults, ask = confirm, log = console.log) {
|
|
766
|
+
const content = await readFile(file, "utf8");
|
|
767
|
+
const scan = scanSource(file, content, kind);
|
|
768
|
+
if (!scan.fixes.length && !scan.manual.length) return false;
|
|
769
|
+
printDiagnostics(scan, log);
|
|
770
|
+
if (!scan.fixes.length) return false;
|
|
771
|
+
if (useDefaults) {
|
|
772
|
+
log(` Skipped ${scan.fixes.length} suggested fix(es); run interactively to review them.`);
|
|
773
|
+
return false;
|
|
774
|
+
}
|
|
775
|
+
const approved = await ask({
|
|
776
|
+
message: `Apply ${scan.fixes.length} suggested fix(es) to ${path.basename(file)}?`,
|
|
777
|
+
default: false,
|
|
778
|
+
});
|
|
779
|
+
if (!approved) {
|
|
780
|
+
log(" Left unchanged.");
|
|
781
|
+
return false;
|
|
782
|
+
}
|
|
783
|
+
await writeWithBackup(file, scan.fixed);
|
|
784
|
+
log(` Applied ${scan.fixes.length} fix(es) to ${file}.`);
|
|
785
|
+
return true;
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
export async function setup(args = []) {
|
|
789
|
+
const useDefaults = args.includes("--yes");
|
|
790
|
+
const previewOnly = args.includes("--preview");
|
|
791
|
+
const nonInteractive = useDefaults || previewOnly;
|
|
792
|
+
if (!nonInteractive && !process.stdin.isTTY) {
|
|
793
|
+
throw new Error("baclet setup needs a terminal. Use `baclet setup --yes` or `baclet setup --preview`.");
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
const configPath = await findConfig(process.cwd());
|
|
797
|
+
await reviewSource(configPath, "config", nonInteractive);
|
|
798
|
+
const project = await loadConfig(process.cwd());
|
|
799
|
+
const modelFiles = (
|
|
800
|
+
await fg(project.patterns, { cwd: project.root, absolute: true, onlyFiles: true })
|
|
801
|
+
).sort();
|
|
802
|
+
for (const file of modelFiles) await reviewSource(file, "model", nonInteractive);
|
|
803
|
+
const models = await loadModels(project, { allowEmpty: true });
|
|
804
|
+
printModelIssues(validateModels(models));
|
|
805
|
+
if (!models.length) {
|
|
806
|
+
console.log(`No models found yet. Add them to ${project.patterns.join(", ")} and run \`baclet setup\` again for database actions.`);
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
const defaults = await detectDefaults({ ...project, models });
|
|
810
|
+
let runtime = defaults.runtime;
|
|
811
|
+
let language = defaults.language;
|
|
812
|
+
let libDir = defaults.libDir;
|
|
813
|
+
let features = ["auth", "storage", "database"].filter(
|
|
814
|
+
(feature) => feature !== "database" || models.length > 0,
|
|
815
|
+
);
|
|
816
|
+
const intent = normalizeIntent();
|
|
817
|
+
|
|
818
|
+
if (!nonInteractive) {
|
|
819
|
+
const choices = [
|
|
820
|
+
{ name: "Auth actions", value: "auth" },
|
|
821
|
+
{ name: "Storage actions", value: "storage" },
|
|
822
|
+
];
|
|
823
|
+
if (models.length) {
|
|
824
|
+
choices.push({ name: `Database actions (${models.length} model${models.length === 1 ? "" : "s"})`, value: "database" });
|
|
825
|
+
}
|
|
826
|
+
features = await checkbox({
|
|
827
|
+
message: "What would you like to set up?",
|
|
828
|
+
choices,
|
|
829
|
+
default: features.filter((feature) => choices.some((choice) => choice.value === feature)),
|
|
830
|
+
});
|
|
831
|
+
if (features.includes("auth")) {
|
|
832
|
+
intent.authMethods = await checkbox({
|
|
833
|
+
message: "Which auth actions do you need?",
|
|
834
|
+
choices: Object.entries(authMethodOptions).map(([value, spec]) => ({ name: spec.label, value })),
|
|
835
|
+
default: intent.authMethods,
|
|
836
|
+
});
|
|
837
|
+
}
|
|
838
|
+
if (features.includes("storage")) {
|
|
839
|
+
intent.storageOps = await checkbox({
|
|
840
|
+
message: "Which storage actions do you need?",
|
|
841
|
+
choices: Object.entries(storageOperationOptions).map(([value, spec]) => ({ name: spec.label, value })),
|
|
842
|
+
default: intent.storageOps,
|
|
843
|
+
});
|
|
844
|
+
}
|
|
845
|
+
if (features.includes("database")) {
|
|
846
|
+
intent.databaseOps = await checkbox({
|
|
847
|
+
message: "Which database actions do you need?",
|
|
848
|
+
choices: Object.entries(databaseOperationOptions).map(([value, spec]) => ({ name: spec.label, value })),
|
|
849
|
+
default: intent.databaseOps,
|
|
850
|
+
});
|
|
851
|
+
if (intent.databaseOps.includes("list")) {
|
|
852
|
+
intent.queryOptions = await confirm({
|
|
853
|
+
message: "Should list actions support field filters and limits?",
|
|
854
|
+
default: true,
|
|
855
|
+
});
|
|
856
|
+
}
|
|
857
|
+
intent.validation = await select({
|
|
858
|
+
message: "How strict should generated value validation be?",
|
|
859
|
+
choices: Object.entries(validationOptions).map(([value, name]) => ({ name, value })),
|
|
860
|
+
default: intent.validation,
|
|
861
|
+
});
|
|
862
|
+
}
|
|
863
|
+
runtime = await select({
|
|
864
|
+
message: "Which environment should generated code read?",
|
|
865
|
+
choices: Object.entries(runtimes).map(([value, spec]) => ({ name: spec.label, value })),
|
|
866
|
+
default: runtime,
|
|
867
|
+
});
|
|
868
|
+
language = await select({
|
|
869
|
+
message: "Which language should be generated?",
|
|
870
|
+
choices: [
|
|
871
|
+
{ name: languages.ts, value: "ts" },
|
|
872
|
+
{ name: languages.js, value: "js" },
|
|
873
|
+
],
|
|
874
|
+
default: language,
|
|
875
|
+
});
|
|
876
|
+
libDir = await input({
|
|
877
|
+
message: "Where should BACLET files be written?",
|
|
878
|
+
default: libDir,
|
|
879
|
+
});
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
if (!features.length) throw new Error("Select at least one feature to set up.");
|
|
883
|
+
|
|
884
|
+
const plan = buildPlan({
|
|
885
|
+
root: project.root,
|
|
886
|
+
libDir,
|
|
887
|
+
language,
|
|
888
|
+
runtime,
|
|
889
|
+
features,
|
|
890
|
+
models,
|
|
891
|
+
intent,
|
|
892
|
+
});
|
|
893
|
+
printPlanPreview(plan, previewOnly, console.log);
|
|
894
|
+
if (previewOnly) {
|
|
895
|
+
console.log("Preview only. No files were written.");
|
|
896
|
+
return;
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
const existing = [];
|
|
900
|
+
for (const item of plan) {
|
|
901
|
+
if (item.merge !== null) continue;
|
|
902
|
+
if (await exists(item.path)) existing.push(item.path);
|
|
903
|
+
}
|
|
904
|
+
let overwrite = false;
|
|
905
|
+
if (existing.length) {
|
|
906
|
+
overwrite = useDefaults
|
|
907
|
+
? false
|
|
908
|
+
: await confirm({
|
|
909
|
+
message: `${existing.length} file(s) already exist. Overwrite them? Backups will be saved as .bak`,
|
|
910
|
+
default: false,
|
|
911
|
+
});
|
|
912
|
+
}
|
|
913
|
+
if (!useDefaults) {
|
|
914
|
+
const proceed = await confirm({
|
|
915
|
+
message: `Write this plan (${plan.length} file(s))?`,
|
|
916
|
+
default: true,
|
|
917
|
+
});
|
|
918
|
+
if (!proceed) {
|
|
919
|
+
console.log("Cancelled. No files were written.");
|
|
920
|
+
return;
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
|
|
924
|
+
const result = await writePlan(plan, { overwrite });
|
|
925
|
+
printSummary(result);
|
|
926
|
+
console.log(`Import everything from ${path.join(resolveInside(project.root, libDir), `index.${language}`)}.`);
|
|
927
|
+
console.log("Copy .env.example to .env and add your BACLET publishable key. Secret keys are never written by this command.");
|
|
928
|
+
}
|