@baclet/cli 0.1.7 → 0.1.8
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 +8 -4
- package/package.json +1 -1
- package/src/commands/setup.js +638 -27
- package/src/commands/setup.test.js +149 -0
- package/src/index.js +1 -1
package/README.md
CHANGED
|
@@ -28,7 +28,7 @@ Node.js 18 or later is required.
|
|
|
28
28
|
| `baclet logout` | Remove local credentials and revoke the CLI token. |
|
|
29
29
|
| `baclet whoami` | Show the authorized user's name and email. |
|
|
30
30
|
| `baclet init [--publishable-key KEY]` | Create `baclet.config.ts`, selecting a project when logged in. |
|
|
31
|
-
| `baclet setup [--yes\|--preview]` |
|
|
31
|
+
| `baclet setup [--yes\|--preview]` | Suggest/generate models, then generate env-driven lib files and actions. |
|
|
32
32
|
| `baclet projects list` | List projects you can access. |
|
|
33
33
|
| `baclet db status` | Print the schema diff without applying it. |
|
|
34
34
|
| `baclet db push [--yes]` | Apply the schema diff after confirmation. |
|
|
@@ -53,18 +53,22 @@ baclet init --publishable-key pb_...
|
|
|
53
53
|
baclet setup
|
|
54
54
|
```
|
|
55
55
|
|
|
56
|
-
`baclet setup` reads `baclet.config.ts`,
|
|
56
|
+
`baclet setup` reads `baclet.config.ts`, checks it and every matched model for common BACLET syntax mistakes, then scans your frontend files (forms, labels, demo arrays, and data access) for reviewable model suggestions. You can accept, edit, or add your own models and field types. Fields use `name:type` with optional flags: `!` required, `*` unique, `+` index, `@now`, `enum(admin|user)`, `decimal(10,2)`, and `ref:model.field ondelete:cascade`. Sensitive names such as passwords and tokens are skipped. New models are written to the folder matched by `schema.models` (for example `src/models/products.ts`), then database actions are generated from the saved models.
|
|
57
57
|
|
|
58
|
-
|
|
58
|
+
The command detects your framework (Next.js, Nuxt, Vite + React/Vue, SvelteKit, or Node) and asks you to confirm the environment before generating files. When logged in, it checks whether Google sign-in is enabled in the connected project and adds Google helpers only when the provider is configured; otherwise it prints the dashboard steps. Feature questions cover auth methods (email, Google when enabled, guest, session, recovery), storage operations (upload, URL, delete), and database operations (list, get, create, set, update, remove) with optional filters and validation strictness. It writes a client initialization file, an `actions/` directory, a barrel export, `.env.example`, and `.env` ignore rules into the chosen lib directory. Existing application files are never rewritten; generated imports keep `.js` extensions so they work in Node and bundlers.
|
|
59
|
+
|
|
60
|
+
Every planned file, export, and action is previewed before writing, and the final write requires confirmation. `baclet setup --preview` prints the full generated content and writes nothing. `baclet setup --yes` uses detected defaults without generating unreviewed model guesses; code-fix suggestions are still skipped because they always require confirmation.
|
|
59
61
|
|
|
60
62
|
Before generating files, `baclet setup` checks `baclet.config.ts` and every matched model file for common BACLET syntax mistakes (wrong field type aliases, quoted booleans, `default: "now()"`, string enum values, missing helper imports, and more). Unambiguous fixes are shown with before/after text and applied only after you confirm per file; declined or manual-only issues are left untouched. Fixes are backed up as `.bak`. Generated code reads only public configuration from the environment (publishable key, optional API URL, optional storage bucket), and no secret key is ever written to source or `.env.example`.
|
|
61
63
|
|
|
62
|
-
|
|
64
|
+
After setup, copy `.env.example` to `.env`, run `baclet db status` and `baclet db push` to sync models, and import features from the generated index file:
|
|
63
65
|
|
|
64
66
|
```ts
|
|
65
67
|
import { baclet, authActions, productActions } from "./lib/index.js";
|
|
66
68
|
```
|
|
67
69
|
|
|
70
|
+
If Google sign-in was enabled, call `authActions.handleOAuthRedirect()` once at app startup and add the printed callback URL to your dashboard's allowed redirects.
|
|
71
|
+
|
|
68
72
|
## Schema push
|
|
69
73
|
|
|
70
74
|
Run `baclet init` while logged in to select a project and write the config automatically. Pass `--publishable-key pb_...` to supply the key directly. The CLI extracts the project UUID from the key before each request.
|
package/package.json
CHANGED
package/src/commands/setup.js
CHANGED
|
@@ -4,6 +4,8 @@ import path from "node:path";
|
|
|
4
4
|
import { checkbox, confirm, input, select } from "@inquirer/prompts";
|
|
5
5
|
import fg from "fast-glob";
|
|
6
6
|
import { findConfig, loadConfig, loadModels } from "../config.js";
|
|
7
|
+
import { loadCredentials } from "../credentials.js";
|
|
8
|
+
import { request } from "../http.js";
|
|
7
9
|
import { scanSource, validateModels } from "./setup-diagnostics.js";
|
|
8
10
|
|
|
9
11
|
const runtimes = {
|
|
@@ -23,11 +25,43 @@ const authMethodOptions = {
|
|
|
23
25
|
label: "Email sign-in and sign-up",
|
|
24
26
|
imports: ["createUserWithEmailAndPassword", "signInWithEmailAndPassword"],
|
|
25
27
|
},
|
|
28
|
+
google: {
|
|
29
|
+
label: "Google sign-in",
|
|
30
|
+
imports: ["getGoogleAuthorizationURL", "signInWithGoogle", "handleOAuthRedirect", "capabilities"],
|
|
31
|
+
},
|
|
26
32
|
guest: { label: "Anonymous sign-in", imports: ["signInAnonymously"] },
|
|
27
33
|
session: { label: "Session helpers", imports: ["getCurrentUser", "getIdToken", "signOut"] },
|
|
28
34
|
recovery: { label: "Password recovery", imports: ["forgotPassword", "resetPassword"] },
|
|
29
35
|
};
|
|
30
36
|
|
|
37
|
+
const fieldTypes = [
|
|
38
|
+
"string",
|
|
39
|
+
"text",
|
|
40
|
+
"integer",
|
|
41
|
+
"decimal",
|
|
42
|
+
"boolean",
|
|
43
|
+
"uuid",
|
|
44
|
+
"timestamp",
|
|
45
|
+
"date",
|
|
46
|
+
"json",
|
|
47
|
+
"enum",
|
|
48
|
+
];
|
|
49
|
+
|
|
50
|
+
const fieldTypeAliases = {
|
|
51
|
+
int: "integer",
|
|
52
|
+
datetime: "timestamp",
|
|
53
|
+
bool: "boolean",
|
|
54
|
+
object: "json",
|
|
55
|
+
array: "json",
|
|
56
|
+
"string[]": "json",
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
const sensitiveField = /pass(word)?|secret|token|api[-_]?key|credential|session|cookie|authorization/i;
|
|
60
|
+
const genericNames = new Set([
|
|
61
|
+
"items", "data", "list", "rows", "options", "fields", "constraints", "entries", "values",
|
|
62
|
+
"children", "deps", "props", "state", "array", "objects", "records", "results", "content",
|
|
63
|
+
]);
|
|
64
|
+
|
|
31
65
|
const storageOperationOptions = {
|
|
32
66
|
upload: { label: "Upload files", imports: ["uploadBytes"] },
|
|
33
67
|
url: { label: "Get download URLs", imports: ["getDownloadURL"] },
|
|
@@ -50,7 +84,7 @@ const validationOptions = {
|
|
|
50
84
|
};
|
|
51
85
|
|
|
52
86
|
export const defaultIntent = {
|
|
53
|
-
authMethods: Object.keys(authMethodOptions),
|
|
87
|
+
authMethods: Object.keys(authMethodOptions).filter((method) => method !== "google"),
|
|
54
88
|
storageOps: Object.keys(storageOperationOptions),
|
|
55
89
|
databaseOps: Object.keys(databaseOperationOptions),
|
|
56
90
|
queryOptions: true,
|
|
@@ -130,6 +164,397 @@ function propertyKey(name) {
|
|
|
130
164
|
return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : JSON.stringify(name);
|
|
131
165
|
}
|
|
132
166
|
|
|
167
|
+
function normalizeName(value, fallback = "model") {
|
|
168
|
+
const result = String(value ?? "")
|
|
169
|
+
.toLowerCase()
|
|
170
|
+
.replace(/[^a-z0-9]+/g, "_")
|
|
171
|
+
.replace(/^_+|_+$/g, "");
|
|
172
|
+
return result || fallback;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function pluralize(value) {
|
|
176
|
+
if (/s$/.test(value)) return value;
|
|
177
|
+
if (/(ch|sh|x|z)$/.test(value)) return `${value}es`;
|
|
178
|
+
if (/y$/.test(value) && !/[aeiou]y$/.test(value)) return `${value.slice(0, -1)}ies`;
|
|
179
|
+
return `${value}s`;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function inferType(name) {
|
|
183
|
+
if (/^(id|uuid|guid)$/.test(name)) return "uuid";
|
|
184
|
+
if (/price|amount|cost|total|rating|score|quantity|count|age|weight|height/.test(name)) {
|
|
185
|
+
return /quantity|count|age|rating|score/.test(name) ? "integer" : "decimal";
|
|
186
|
+
}
|
|
187
|
+
if (/created|updated|_at$|date|time|deadline/.test(name)) return "timestamp";
|
|
188
|
+
if (/^(is|has|can|should)_|active|enabled|published|verified|paid|available/.test(name)) return "boolean";
|
|
189
|
+
if (/^(status|role|state|kind|category|type)$/.test(name)) return "enum";
|
|
190
|
+
if (/content|description|body|message|bio|notes?|html|markdown/.test(name)) return "text";
|
|
191
|
+
if (/image|photo|avatar|thumbnail|picture/.test(name)) return "string";
|
|
192
|
+
return "string";
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function escapeRegExp(value) {
|
|
196
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function splitTopLevel(text, delimiter) {
|
|
200
|
+
const parts = [];
|
|
201
|
+
let current = "";
|
|
202
|
+
let depth = 0;
|
|
203
|
+
let quote = null;
|
|
204
|
+
for (const char of text) {
|
|
205
|
+
if (quote) {
|
|
206
|
+
current += char;
|
|
207
|
+
if (char === quote) quote = null;
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
if (char === '"' || char === "'" || char === "`") {
|
|
211
|
+
quote = char;
|
|
212
|
+
current += char;
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
if ("([{".includes(char)) depth++;
|
|
216
|
+
if (")]}".includes(char)) depth--;
|
|
217
|
+
if (char === delimiter && depth === 0) {
|
|
218
|
+
parts.push(current);
|
|
219
|
+
current = "";
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
222
|
+
current += char;
|
|
223
|
+
}
|
|
224
|
+
parts.push(current);
|
|
225
|
+
return parts;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function parseLiteral(value) {
|
|
229
|
+
const trimmed = value.trim();
|
|
230
|
+
try {
|
|
231
|
+
return JSON.parse(trimmed);
|
|
232
|
+
} catch {
|
|
233
|
+
return trimmed;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function parseFieldDraft(segment) {
|
|
238
|
+
const trimmed = segment.trim();
|
|
239
|
+
if (!trimmed) return null;
|
|
240
|
+
const match = trimmed.match(/^([A-Za-z_][A-Za-z0-9_-]*)(?:\s*:\s*([A-Za-z][A-Za-z0-9[\]]*))?([\s\S]*)$/);
|
|
241
|
+
if (!match) return { error: `Cannot parse field "${trimmed}".` };
|
|
242
|
+
|
|
243
|
+
const name = normalizeName(match[1], "");
|
|
244
|
+
if (!name) return { error: `Invalid field name in "${trimmed}".` };
|
|
245
|
+
if (sensitiveField.test(name)) return { warnings: [`Skipped sensitive field "${name}".`] };
|
|
246
|
+
|
|
247
|
+
const requestedType = (match[2] || "string").toLowerCase();
|
|
248
|
+
let type = fieldTypeAliases[requestedType] || requestedType;
|
|
249
|
+
let rest = (match[3] || "").trim();
|
|
250
|
+
if (requestedType === "ref") {
|
|
251
|
+
type = "string";
|
|
252
|
+
rest = `ref${rest}`;
|
|
253
|
+
}
|
|
254
|
+
if (!fieldTypes.includes(type)) {
|
|
255
|
+
return { error: `Unknown type "${requestedType}" for ${name}. Allowed: ${fieldTypes.join(", ")}.` };
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const field = { type };
|
|
259
|
+
const parenthesized = rest.match(/\(([^)]*)\)/);
|
|
260
|
+
if (parenthesized) {
|
|
261
|
+
rest = rest.replace(parenthesized[0], " ").trim();
|
|
262
|
+
if (type === "enum") {
|
|
263
|
+
const values = parenthesized[1].split("|").map((value) => value.trim()).filter(Boolean);
|
|
264
|
+
if (!values.length) return { error: `Enum field ${name} needs values, for example ${name}:enum(admin|user).` };
|
|
265
|
+
field.values = values;
|
|
266
|
+
} else if (type === "decimal") {
|
|
267
|
+
const [precision, scale] = parenthesized[1].split(",").map((value) => Number(value.trim()));
|
|
268
|
+
if (Number.isInteger(precision) && precision > 0) field.precision = precision;
|
|
269
|
+
if (Number.isInteger(scale) && scale >= 0) field.scale = scale;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
for (const token of rest.split(/[\s,]+/).filter(Boolean)) {
|
|
274
|
+
if (/^[!*+]+$/.test(token)) {
|
|
275
|
+
for (const flag of token) {
|
|
276
|
+
if (flag === "!") field.required = true;
|
|
277
|
+
if (flag === "*") field.unique = true;
|
|
278
|
+
if (flag === "+") field.index = true;
|
|
279
|
+
}
|
|
280
|
+
} else if (token === "@now") field.default = { expr: "now()" };
|
|
281
|
+
else if (token.startsWith("ref:")) {
|
|
282
|
+
const [refModel, refField] = token.slice(4).split(".");
|
|
283
|
+
if (!refModel) return { error: `Reference for ${name} needs a model name.` };
|
|
284
|
+
field.reference = { model: normalizeName(refModel), ...(refField ? { field: normalizeName(refField) } : {}) };
|
|
285
|
+
} else if (token.startsWith("ondelete:")) {
|
|
286
|
+
const onDelete = token.slice(9).replace(/_/g, " ");
|
|
287
|
+
if (!["cascade", "restrict", "set null"].includes(onDelete)) {
|
|
288
|
+
return { error: `onDelete for ${name} must be cascade, restrict, or set null.` };
|
|
289
|
+
}
|
|
290
|
+
field.reference = { ...(field.reference ?? {}), model: field.reference?.model ?? "", onDelete };
|
|
291
|
+
} else if (token.startsWith("default:")) {
|
|
292
|
+
field.default = parseLiteral(token.slice(8));
|
|
293
|
+
} else {
|
|
294
|
+
return { error: `Unknown option "${token}" for ${name}.` };
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
if (field.reference && !field.reference.model) {
|
|
298
|
+
return { error: `Reference for ${name} needs a model name.` };
|
|
299
|
+
}
|
|
300
|
+
return { name, field };
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
export function parseFieldsDraft(text) {
|
|
304
|
+
const fields = {};
|
|
305
|
+
const errors = [];
|
|
306
|
+
const warnings = [];
|
|
307
|
+
for (const segment of splitTopLevel(String(text ?? ""), ",")) {
|
|
308
|
+
const parsed = parseFieldDraft(segment);
|
|
309
|
+
if (!parsed) continue;
|
|
310
|
+
if (parsed.error) errors.push(parsed.error);
|
|
311
|
+
if (parsed.warnings) warnings.push(...parsed.warnings);
|
|
312
|
+
if (parsed.name) fields[parsed.name] = parsed.field;
|
|
313
|
+
}
|
|
314
|
+
return { fields, errors, warnings };
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
export function normalizeModelDraft(name, fields) {
|
|
318
|
+
const normalized = { name: normalizeName(name), fields: { ...fields } };
|
|
319
|
+
for (const [fieldName, field] of Object.entries(normalized.fields)) {
|
|
320
|
+
if (!/^[a-z0-9_]+$/.test(fieldName)) throw new Error(`Invalid field name "${fieldName}".`);
|
|
321
|
+
if (!fieldTypes.includes(field?.type)) throw new Error(`Unknown type "${field?.type}" for ${fieldName}.`);
|
|
322
|
+
if (field.type === "enum" && !Array.isArray(field.values)) {
|
|
323
|
+
throw new Error(`Enum field ${fieldName} needs a values array.`);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
if (!normalized.fields.created_at) {
|
|
327
|
+
normalized.fields.created_at = { type: "timestamp", default: { expr: "now()" } };
|
|
328
|
+
}
|
|
329
|
+
if (!normalized.fields.updated_at) {
|
|
330
|
+
normalized.fields.updated_at = { type: "timestamp", default: { expr: "now()" } };
|
|
331
|
+
}
|
|
332
|
+
return normalized;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
function renderField(field) {
|
|
336
|
+
const parts = [`type: ${JSON.stringify(field.type)}`];
|
|
337
|
+
if (field.required) parts.push("required: true");
|
|
338
|
+
if (field.unique) parts.push("unique: true");
|
|
339
|
+
if (field.index) parts.push("index: true");
|
|
340
|
+
if (field.values?.length) parts.push(`values: ${JSON.stringify(field.values)}`);
|
|
341
|
+
if (field.type === "decimal") {
|
|
342
|
+
if (field.precision) parts.push(`precision: ${field.precision}`);
|
|
343
|
+
if (field.scale !== undefined) parts.push(`scale: ${field.scale}`);
|
|
344
|
+
}
|
|
345
|
+
if (field.reference?.model) {
|
|
346
|
+
const reference = [`model: ${JSON.stringify(field.reference.model)}`];
|
|
347
|
+
if (field.reference.field) reference.push(`field: ${JSON.stringify(field.reference.field)}`);
|
|
348
|
+
if (field.reference.onDelete) reference.push(`onDelete: ${JSON.stringify(field.reference.onDelete)}`);
|
|
349
|
+
parts.push(`reference: { ${reference.join(", ")} }`);
|
|
350
|
+
}
|
|
351
|
+
if (Object.prototype.hasOwnProperty.call(field, "default")) {
|
|
352
|
+
parts.push(
|
|
353
|
+
field.default && typeof field.default === "object" && !Array.isArray(field.default)
|
|
354
|
+
? `default: { expr: ${JSON.stringify(field.default.expr)} }`
|
|
355
|
+
: `default: ${JSON.stringify(field.default)}`,
|
|
356
|
+
);
|
|
357
|
+
}
|
|
358
|
+
return `{ ${parts.join(", ")} }`;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
export function renderModelFile(model) {
|
|
362
|
+
const lines = [
|
|
363
|
+
'import { defineModel } from "@baclet/sdk";',
|
|
364
|
+
"",
|
|
365
|
+
`export const ${pascal(model.name)} = defineModel({`,
|
|
366
|
+
` name: ${JSON.stringify(model.name)},`,
|
|
367
|
+
" fields: {",
|
|
368
|
+
];
|
|
369
|
+
for (const [name, field] of Object.entries(model.fields)) {
|
|
370
|
+
lines.push(` ${propertyKey(name)}: ${renderField(field)},`);
|
|
371
|
+
}
|
|
372
|
+
lines.push(" },", "});", "");
|
|
373
|
+
return lines.join("\n");
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
export function formatFieldDraft(fields = {}) {
|
|
377
|
+
const entries = Object.entries(fields)
|
|
378
|
+
.filter(([name]) => !["created_at", "updated_at"].includes(name))
|
|
379
|
+
.map(([name, field]) => {
|
|
380
|
+
let value = `${name}:${field?.type ?? "string"}`;
|
|
381
|
+
if (field?.values?.length) value += `(${field.values.join("|")})`;
|
|
382
|
+
else if (field?.type === "decimal" && field.precision) value += `(${field.precision},${field.scale ?? 0})`;
|
|
383
|
+
if (field?.required) value += "!";
|
|
384
|
+
if (field?.unique) value += "*";
|
|
385
|
+
if (field?.index) value += "+";
|
|
386
|
+
if (field?.default && typeof field.default === "object") value += " @now";
|
|
387
|
+
if (field?.reference?.model) {
|
|
388
|
+
value += ` ref:${field.reference.model}${field.reference.field ? `.${field.reference.field}` : ""}`;
|
|
389
|
+
}
|
|
390
|
+
return value;
|
|
391
|
+
});
|
|
392
|
+
return entries.join(", ");
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
export function modelDirFromPatterns(root, patterns = []) {
|
|
396
|
+
for (const raw of patterns) {
|
|
397
|
+
const cleaned = String(raw).replace(/\\/g, "/");
|
|
398
|
+
const parts = cleaned.split("/");
|
|
399
|
+
const wildcard = parts.findIndex((part) => /[*?{\[]/.test(part));
|
|
400
|
+
const dirParts = (wildcard >= 0 ? parts.slice(0, wildcard) : parts.slice(0, -1)).filter(Boolean);
|
|
401
|
+
const dir = cleaned.startsWith("/") ? path.resolve("/", ...dirParts) : path.resolve(root, ...dirParts);
|
|
402
|
+
try {
|
|
403
|
+
resolveInside(root, dir);
|
|
404
|
+
return { dir, ext: cleaned.match(/\.(m?[jt]s)$/)?.[1] ?? ".ts" };
|
|
405
|
+
} catch {
|
|
406
|
+
continue;
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
return { dir: path.join(root, "models"), ext: ".ts" };
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
export function buildModelPlan({ root, patterns = [], models = [] }) {
|
|
413
|
+
const { dir, ext } = modelDirFromPatterns(root, patterns);
|
|
414
|
+
const seen = new Set();
|
|
415
|
+
const plan = [];
|
|
416
|
+
for (const model of models) {
|
|
417
|
+
const fileName = `${normalizeName(model.name)}.${ext}`;
|
|
418
|
+
if (seen.has(fileName)) throw new Error(`Duplicate model name "${model.name}".`);
|
|
419
|
+
seen.add(fileName);
|
|
420
|
+
plan.push({
|
|
421
|
+
path: path.join(dir, fileName),
|
|
422
|
+
content: renderModelFile(model),
|
|
423
|
+
merge: null,
|
|
424
|
+
});
|
|
425
|
+
}
|
|
426
|
+
return plan;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
const ignoredFieldNames = new Set([
|
|
430
|
+
"id", "key", "children", "classname", "style", "onclick", "onchange", "onsubmit",
|
|
431
|
+
"defaultvalue", "placeholder", "required", "disabled", "rows", "cols", "href", "src",
|
|
432
|
+
"alt", "props", "state", "index", "length", "constructor", "prototype", "args", "argv",
|
|
433
|
+
]);
|
|
434
|
+
|
|
435
|
+
function extractFieldNames(content, names) {
|
|
436
|
+
const found = new Map();
|
|
437
|
+
const add = (raw) => {
|
|
438
|
+
const name = normalizeName(raw, "");
|
|
439
|
+
if (!name || sensitiveField.test(name) || ignoredFieldNames.has(name)) return;
|
|
440
|
+
if (name === "created_at" || name === "updated_at") return;
|
|
441
|
+
found.set(name, (found.get(name) ?? 0) + 1);
|
|
442
|
+
};
|
|
443
|
+
|
|
444
|
+
for (const match of content.matchAll(/<(?:input|textarea|select)\b[^>]*?\b(?:name|placeholder|aria-label|id)\s*=\s*["']([^"']+)["']/gi)) {
|
|
445
|
+
add(match[1]);
|
|
446
|
+
}
|
|
447
|
+
for (const match of content.matchAll(/<label\b[^>]*>([\s\S]{0,160}?)<\/label>/gi)) {
|
|
448
|
+
add(match[1].replace(/<[^>]+>/g, " ").trim());
|
|
449
|
+
}
|
|
450
|
+
for (const name of names) {
|
|
451
|
+
const singular = name.endsWith("ies") ? `${name.slice(0, -3)}y` : name.replace(/s$/, "");
|
|
452
|
+
const access = new RegExp(`\\b(?:${escapeRegExp(singular)}|item|row|record|entry)\\s*\\.\\s*([A-Za-z_][A-Za-z0-9_]*)`, "g");
|
|
453
|
+
for (const match of content.matchAll(access)) add(match[1]);
|
|
454
|
+
}
|
|
455
|
+
for (const match of content.matchAll(/(?:^|[{,\s])([A-Za-z_][A-Za-z0-9_]*)\s*:\s*[^,\n}]+/gm)) {
|
|
456
|
+
add(match[1]);
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
return [...found.entries()]
|
|
460
|
+
.sort((left, right) => right[1] - left[1] || left[0].localeCompare(right[0]))
|
|
461
|
+
.slice(0, 12)
|
|
462
|
+
.map(([name]) => ({ name, type: inferType(name) }));
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
export async function suggestModels(root, options = {}) {
|
|
466
|
+
const files = await fg(["**/*.{ts,tsx,js,jsx,vue,svelte}"], {
|
|
467
|
+
cwd: root,
|
|
468
|
+
absolute: true,
|
|
469
|
+
onlyFiles: true,
|
|
470
|
+
suppressErrors: true,
|
|
471
|
+
ignore: [
|
|
472
|
+
"**/node_modules/**", "**/dist/**", "**/build/**", "**/.next/**", "**/.nuxt/**",
|
|
473
|
+
"**/coverage/**", "**/lib/**", "**/models/**", "**/*.test.*", "**/*.spec.*",
|
|
474
|
+
"baclet.config.*",
|
|
475
|
+
],
|
|
476
|
+
});
|
|
477
|
+
|
|
478
|
+
const byName = new Map();
|
|
479
|
+
for (const file of files.slice(0, options.maxFiles ?? 60)) {
|
|
480
|
+
const content = await readFile(file, "utf8").catch(() => "");
|
|
481
|
+
if (!content || content.length > 200_000) continue;
|
|
482
|
+
|
|
483
|
+
const names = [];
|
|
484
|
+
const base = path.basename(file).replace(/\.[^.]+$/, "");
|
|
485
|
+
const cleaned = normalizeName(base.replace(/[-_](card|item|list|page|modal|panel|form|view|detail|details|table|row)$/i, ""), "");
|
|
486
|
+
if (cleaned && !genericNames.has(cleaned)) names.push(pluralize(cleaned));
|
|
487
|
+
|
|
488
|
+
for (const pattern of [
|
|
489
|
+
/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=]+)?=\s*\[/g,
|
|
490
|
+
/\b([A-Za-z_$][\w$]*)\s*:\s*\[/g,
|
|
491
|
+
]) {
|
|
492
|
+
for (const match of content.matchAll(pattern)) {
|
|
493
|
+
const candidate = normalizeName(match[1], "");
|
|
494
|
+
if (candidate && !genericNames.has(candidate)) names.push(pluralize(candidate));
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
for (const match of content.matchAll(/\b(?:collection|model|table|resource)\s*[:=]\s*["']([a-z0-9_]+)["']/g)) {
|
|
498
|
+
names.push(match[1]);
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
const fields = extractFieldNames(content, names);
|
|
502
|
+
if (!fields.length) continue;
|
|
503
|
+
for (const name of [...new Set(names)].slice(0, 3)) {
|
|
504
|
+
const current = byName.get(name) ?? { name, fields: {}, source: path.relative(root, file) };
|
|
505
|
+
for (const field of fields) {
|
|
506
|
+
current.fields[field.name] = field.type;
|
|
507
|
+
}
|
|
508
|
+
byName.set(name, current);
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
return [...byName.values()]
|
|
513
|
+
.map((entry) => ({
|
|
514
|
+
name: entry.name,
|
|
515
|
+
fields: Object.fromEntries(Object.entries(entry.fields).map(([name, type]) => [name, { type }])),
|
|
516
|
+
source: entry.source,
|
|
517
|
+
}))
|
|
518
|
+
.sort((left, right) => Object.keys(right.fields).length - Object.keys(left.fields).length)
|
|
519
|
+
.slice(0, options.limit ?? 6);
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
export async function checkGoogleAuth({ root, projectId, requestFn = request, credentialsFn = loadCredentials } = {}) {
|
|
523
|
+
const credentials = await credentialsFn();
|
|
524
|
+
if (!credentials?.accessToken) {
|
|
525
|
+
return { enabled: false, checked: false, reason: "not logged in" };
|
|
526
|
+
}
|
|
527
|
+
try {
|
|
528
|
+
const payload = await requestFn({
|
|
529
|
+
method: "GET",
|
|
530
|
+
path: "/api/v1/me/projects",
|
|
531
|
+
token: credentials.accessToken,
|
|
532
|
+
});
|
|
533
|
+
const selected = (payload?.projects ?? []).find(
|
|
534
|
+
(project) => project.id === projectId || project.uuid === projectId,
|
|
535
|
+
);
|
|
536
|
+
if (!selected?.workspace_slug || !selected?.slug) {
|
|
537
|
+
return { enabled: false, checked: false, reason: "project not found" };
|
|
538
|
+
}
|
|
539
|
+
const settings = await requestFn({
|
|
540
|
+
method: "GET",
|
|
541
|
+
path: `/api/v1/workspaces/${encodeURIComponent(selected.workspace_slug)}/projects/${encodeURIComponent(selected.slug)}/auth/settings`,
|
|
542
|
+
token: credentials.accessToken,
|
|
543
|
+
});
|
|
544
|
+
const provider = settings?.providers?.google;
|
|
545
|
+
const status = provider?.validation?.status;
|
|
546
|
+
const enabled = provider?.enabled === true && (status === "configuration_valid" || status === undefined);
|
|
547
|
+
return {
|
|
548
|
+
enabled,
|
|
549
|
+
checked: true,
|
|
550
|
+
reason: enabled ? "enabled" : provider?.validation?.error || "Google sign-in is disabled",
|
|
551
|
+
callbackUrl: settings?.callback_urls?.google,
|
|
552
|
+
};
|
|
553
|
+
} catch (error) {
|
|
554
|
+
return { enabled: false, checked: false, reason: error.message };
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
|
|
133
558
|
function fieldType(field) {
|
|
134
559
|
const type = field?.type;
|
|
135
560
|
if (["string", "text", "uuid"].includes(type)) return "string";
|
|
@@ -247,6 +672,19 @@ function authFile(language, methods) {
|
|
|
247
672
|
" createUserWithEmailAndPassword(auth, email, password, fullName),",
|
|
248
673
|
);
|
|
249
674
|
}
|
|
675
|
+
if (methods.includes("google")) {
|
|
676
|
+
entries.push(
|
|
677
|
+
language === "ts"
|
|
678
|
+
? " signInWithGoogle: (redirectTo?: string) => signInWithGoogle(auth, redirectTo ? { redirectTo } : {}),"
|
|
679
|
+
: " signInWithGoogle: (redirectTo) => signInWithGoogle(auth, redirectTo ? { redirectTo } : {}),",
|
|
680
|
+
" handleOAuthRedirect: () => handleOAuthRedirect(auth),",
|
|
681
|
+
language === "ts"
|
|
682
|
+
? " googleAuthorizationURL: (redirectTo?: string) =>"
|
|
683
|
+
: " googleAuthorizationURL: (redirectTo) =>",
|
|
684
|
+
" getGoogleAuthorizationURL(auth, redirectTo ? { redirectTo } : {}),",
|
|
685
|
+
" authCapabilities: () => capabilities(auth),",
|
|
686
|
+
);
|
|
687
|
+
}
|
|
250
688
|
if (methods.includes("guest")) {
|
|
251
689
|
entries.push(" signInAsGuest: () => signInAnonymously(auth),");
|
|
252
690
|
}
|
|
@@ -694,19 +1132,33 @@ export async function writePlan(plan, options = {}) {
|
|
|
694
1132
|
return result;
|
|
695
1133
|
}
|
|
696
1134
|
|
|
697
|
-
export async function
|
|
698
|
-
const { root, configPath, models } = project;
|
|
1135
|
+
export async function detectFramework(root) {
|
|
699
1136
|
const pkg = await readJson(path.join(root, "package.json"));
|
|
700
1137
|
const dependencies = { ...pkg.dependencies, ...pkg.devDependencies };
|
|
701
|
-
|
|
702
|
-
if (dependencies.
|
|
703
|
-
|
|
704
|
-
|
|
1138
|
+
if (dependencies.next) return { id: "next", label: "Next.js", runtime: "next" };
|
|
1139
|
+
if (dependencies.nuxt) return { id: "nuxt", label: "Nuxt", runtime: "nuxt" };
|
|
1140
|
+
if (dependencies["@sveltejs/kit"]) return { id: "sveltekit", label: "SvelteKit", runtime: "vite" };
|
|
1141
|
+
if (dependencies.vite) {
|
|
1142
|
+
if (dependencies.vue) return { id: "vite-vue", label: "Vite + Vue", runtime: "vite" };
|
|
1143
|
+
if (dependencies.react) return { id: "vite-react", label: "Vite + React", runtime: "vite" };
|
|
1144
|
+
return { id: "vite", label: "Vite", runtime: "vite" };
|
|
1145
|
+
}
|
|
1146
|
+
return { id: "node", label: "Node.js / other", runtime: "node" };
|
|
1147
|
+
}
|
|
705
1148
|
|
|
1149
|
+
export async function detectDefaults(project) {
|
|
1150
|
+
const { root, configPath, models } = project;
|
|
1151
|
+
const framework = await detectFramework(root);
|
|
706
1152
|
const usesTypeScript =
|
|
707
1153
|
(await exists(path.join(root, "tsconfig.json"))) || /\.m?ts$/.test(configPath ?? "");
|
|
708
1154
|
const libDir = (await isDirectory(path.join(root, "src"))) ? "src/lib" : "lib";
|
|
709
|
-
return {
|
|
1155
|
+
return {
|
|
1156
|
+
runtime: framework.runtime,
|
|
1157
|
+
framework,
|
|
1158
|
+
language: usesTypeScript ? "ts" : "js",
|
|
1159
|
+
libDir,
|
|
1160
|
+
hasModels: models.length > 0,
|
|
1161
|
+
};
|
|
710
1162
|
}
|
|
711
1163
|
|
|
712
1164
|
function printSummary(result) {
|
|
@@ -785,6 +1237,103 @@ export async function reviewSource(file, kind, useDefaults, ask = confirm, log =
|
|
|
785
1237
|
return true;
|
|
786
1238
|
}
|
|
787
1239
|
|
|
1240
|
+
function printSuggestions(suggestions, log = console.log) {
|
|
1241
|
+
if (!suggestions.length) return;
|
|
1242
|
+
log("\nModel suggestions from your project (review before writing):");
|
|
1243
|
+
for (const suggestion of suggestions) {
|
|
1244
|
+
const fields = formatFieldDraft(suggestion.fields);
|
|
1245
|
+
log(` ${suggestion.name}: ${fields || "no fields detected"} (${suggestion.source})`);
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
async function askModelDraft({ name, initialFields = {}, usedNames }) {
|
|
1250
|
+
let modelName;
|
|
1251
|
+
while (true) {
|
|
1252
|
+
modelName = normalizeName(
|
|
1253
|
+
await input({
|
|
1254
|
+
message: "Model name (lowercase letters, numbers, underscores)",
|
|
1255
|
+
default: name,
|
|
1256
|
+
}),
|
|
1257
|
+
);
|
|
1258
|
+
if (!/^[a-z0-9_]+$/.test(modelName)) {
|
|
1259
|
+
console.log("Use lowercase letters, numbers and underscores.");
|
|
1260
|
+
continue;
|
|
1261
|
+
}
|
|
1262
|
+
if (usedNames.has(modelName)) {
|
|
1263
|
+
console.log(`Model "${modelName}" already exists. Choose a different name.`);
|
|
1264
|
+
continue;
|
|
1265
|
+
}
|
|
1266
|
+
break;
|
|
1267
|
+
}
|
|
1268
|
+
|
|
1269
|
+
while (true) {
|
|
1270
|
+
const text = await input({
|
|
1271
|
+
message: `Fields for ${modelName}\nTypes: ${fieldTypes.join(", ")}. Flags: ! required, * unique, + index, @now, enum(a|b), ref:model.field`,
|
|
1272
|
+
default: formatFieldDraft(initialFields),
|
|
1273
|
+
});
|
|
1274
|
+
const parsed = parseFieldsDraft(text);
|
|
1275
|
+
for (const warning of parsed.warnings) console.log(` ! ${warning}`);
|
|
1276
|
+
if (parsed.errors.length) {
|
|
1277
|
+
for (const error of parsed.errors) console.log(` ! ${error}`);
|
|
1278
|
+
continue;
|
|
1279
|
+
}
|
|
1280
|
+
if (!Object.keys(parsed.fields).length) {
|
|
1281
|
+
console.log("Add at least one field.");
|
|
1282
|
+
continue;
|
|
1283
|
+
}
|
|
1284
|
+
usedNames.add(modelName);
|
|
1285
|
+
return normalizeModelDraft(modelName, parsed.fields);
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
|
|
1289
|
+
async function collectModelDrafts({ suggestions = [], existingModels = [] }) {
|
|
1290
|
+
const usedNames = new Set(existingModels.map((model) => model.name));
|
|
1291
|
+
const drafts = [];
|
|
1292
|
+
if (suggestions.length) {
|
|
1293
|
+
const selected = await checkbox({
|
|
1294
|
+
message: "Generate model files from these suggestions?",
|
|
1295
|
+
choices: suggestions.map((suggestion) => ({
|
|
1296
|
+
name: `${suggestion.name}: ${formatFieldDraft(suggestion.fields) || "no fields detected"} (${suggestion.source})`,
|
|
1297
|
+
value: suggestion.name,
|
|
1298
|
+
})),
|
|
1299
|
+
default: suggestions.map((suggestion) => suggestion.name),
|
|
1300
|
+
});
|
|
1301
|
+
for (const name of selected) {
|
|
1302
|
+
const suggestion = suggestions.find((item) => item.name === name);
|
|
1303
|
+
drafts.push(await askModelDraft({ name, initialFields: suggestion?.fields ?? {}, usedNames }));
|
|
1304
|
+
}
|
|
1305
|
+
}
|
|
1306
|
+
|
|
1307
|
+
while (true) {
|
|
1308
|
+
const custom = await input({ message: "Add another model name? (blank to finish)", default: "" });
|
|
1309
|
+
if (!custom.trim()) break;
|
|
1310
|
+
drafts.push(await askModelDraft({ name: custom, usedNames }));
|
|
1311
|
+
}
|
|
1312
|
+
return drafts;
|
|
1313
|
+
}
|
|
1314
|
+
|
|
1315
|
+
async function printNextSteps({ root, libDir, features, googleEnabled, hasModels }) {
|
|
1316
|
+
const libIndex = path.join(resolveInside(root, libDir), "index.js");
|
|
1317
|
+
const appRoot = (await isDirectory(path.join(root, "src"))) ? path.join(root, "src") : root;
|
|
1318
|
+
const relative = path.relative(appRoot, libIndex).replace(/\\/g, "/");
|
|
1319
|
+
const importPath = relative.startsWith(".") ? relative : `./${relative}`;
|
|
1320
|
+
|
|
1321
|
+
console.log("\nNext steps:");
|
|
1322
|
+
console.log(` 1. Copy .env.example to .env and set your BACLET publishable key.`);
|
|
1323
|
+
let step = 2;
|
|
1324
|
+
if (hasModels && features.includes("database")) {
|
|
1325
|
+
console.log(` ${step}. Run \`npx baclet db status\` then \`npx baclet db push\` to sync your models.`);
|
|
1326
|
+
step++;
|
|
1327
|
+
}
|
|
1328
|
+
if (googleEnabled && features.includes("auth")) {
|
|
1329
|
+
console.log(` ${step}. Call authActions.handleOAuthRedirect() once at app startup.`);
|
|
1330
|
+
step++;
|
|
1331
|
+
console.log(` ${step}. Add the Google callback URL to your dashboard's allowed redirects.`);
|
|
1332
|
+
step++;
|
|
1333
|
+
}
|
|
1334
|
+
console.log(` Import from "${importPath}". Keep the generated .js import extensions.`);
|
|
1335
|
+
}
|
|
1336
|
+
|
|
788
1337
|
export async function setup(args = []) {
|
|
789
1338
|
const useDefaults = args.includes("--yes");
|
|
790
1339
|
const previewOnly = args.includes("--preview");
|
|
@@ -800,28 +1349,51 @@ export async function setup(args = []) {
|
|
|
800
1349
|
await fg(project.patterns, { cwd: project.root, absolute: true, onlyFiles: true })
|
|
801
1350
|
).sort();
|
|
802
1351
|
for (const file of modelFiles) await reviewSource(file, "model", nonInteractive);
|
|
803
|
-
|
|
1352
|
+
let models = await loadModels(project, { allowEmpty: true });
|
|
804
1353
|
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
1354
|
|
|
809
1355
|
const defaults = await detectDefaults({ ...project, models });
|
|
1356
|
+
const suggestions = await suggestModels(project.root);
|
|
1357
|
+
if (!nonInteractive) printSuggestions(suggestions);
|
|
1358
|
+
else if (suggestions.length) {
|
|
1359
|
+
console.log(`Found ${suggestions.length} model suggestion(s). Run \`baclet setup\` interactively to review and generate them.`);
|
|
1360
|
+
}
|
|
1361
|
+
|
|
1362
|
+
let drafts = [];
|
|
1363
|
+
if (!nonInteractive) {
|
|
1364
|
+
const message = models.length
|
|
1365
|
+
? "Add or regenerate model files from suggestions or your own names?"
|
|
1366
|
+
: "No models found. Generate model files from suggestions or add your own?";
|
|
1367
|
+
if (await confirm({ message, default: !models.length })) {
|
|
1368
|
+
drafts = await collectModelDrafts({ suggestions, existingModels: models });
|
|
1369
|
+
}
|
|
1370
|
+
}
|
|
1371
|
+
const modelPlan = drafts.length
|
|
1372
|
+
? buildModelPlan({ root: project.root, patterns: project.patterns, models: drafts })
|
|
1373
|
+
: [];
|
|
1374
|
+
const effectiveModels = drafts.length
|
|
1375
|
+
? [...new Map([...models, ...drafts].map((model) => [model.name, model])).values()]
|
|
1376
|
+
: models;
|
|
1377
|
+
if (!effectiveModels.length) {
|
|
1378
|
+
console.log(`No models found yet. Add them to ${project.patterns.join(", ")} and rerun \`baclet setup\` for database actions.`);
|
|
1379
|
+
}
|
|
1380
|
+
|
|
810
1381
|
let runtime = defaults.runtime;
|
|
811
1382
|
let language = defaults.language;
|
|
812
1383
|
let libDir = defaults.libDir;
|
|
813
|
-
let features = ["auth", "storage"
|
|
814
|
-
|
|
815
|
-
);
|
|
1384
|
+
let features = ["auth", "storage"];
|
|
1385
|
+
if (effectiveModels.length) features.push("database");
|
|
816
1386
|
const intent = normalizeIntent();
|
|
1387
|
+
let googleState = { enabled: false, checked: false, reason: "not checked" };
|
|
817
1388
|
|
|
818
1389
|
if (!nonInteractive) {
|
|
819
1390
|
const choices = [
|
|
820
1391
|
{ name: "Auth actions", value: "auth" },
|
|
821
1392
|
{ name: "Storage actions", value: "storage" },
|
|
822
1393
|
];
|
|
823
|
-
if (
|
|
824
|
-
|
|
1394
|
+
if (effectiveModels.length) {
|
|
1395
|
+
const count = effectiveModels.length;
|
|
1396
|
+
choices.push({ name: `Database actions (${count} model${count === 1 ? "" : "s"})`, value: "database" });
|
|
825
1397
|
}
|
|
826
1398
|
features = await checkbox({
|
|
827
1399
|
message: "What would you like to set up?",
|
|
@@ -834,6 +1406,18 @@ export async function setup(args = []) {
|
|
|
834
1406
|
choices: Object.entries(authMethodOptions).map(([value, spec]) => ({ name: spec.label, value })),
|
|
835
1407
|
default: intent.authMethods,
|
|
836
1408
|
});
|
|
1409
|
+
googleState = await checkGoogleAuth({ root: project.root, projectId: project.projectId });
|
|
1410
|
+
if (googleState.enabled && !intent.authMethods.includes("google")) {
|
|
1411
|
+
const includeGoogle = await confirm({
|
|
1412
|
+
message: googleState.callbackUrl
|
|
1413
|
+
? `Google sign-in is enabled (callback: ${googleState.callbackUrl}). Include Google actions?`
|
|
1414
|
+
: "Google sign-in is enabled. Include Google actions?",
|
|
1415
|
+
default: true,
|
|
1416
|
+
});
|
|
1417
|
+
if (includeGoogle) intent.authMethods = [...intent.authMethods, "google"];
|
|
1418
|
+
} else if (!googleState.enabled && intent.authMethods.includes("google")) {
|
|
1419
|
+
console.log(`Google actions were selected, but ${googleState.reason}. Enable Google in the dashboard before using them.`);
|
|
1420
|
+
}
|
|
837
1421
|
}
|
|
838
1422
|
if (features.includes("storage")) {
|
|
839
1423
|
intent.storageOps = await checkbox({
|
|
@@ -861,9 +1445,14 @@ export async function setup(args = []) {
|
|
|
861
1445
|
});
|
|
862
1446
|
}
|
|
863
1447
|
runtime = await select({
|
|
864
|
-
message:
|
|
865
|
-
choices:
|
|
866
|
-
|
|
1448
|
+
message: `Framework detected: ${defaults.framework.label}. Confirm the generated environment?`,
|
|
1449
|
+
choices: [
|
|
1450
|
+
{ name: `Yes — ${runtimes[defaults.runtime].label}`, value: defaults.runtime },
|
|
1451
|
+
...Object.entries(runtimes)
|
|
1452
|
+
.filter(([value]) => value !== defaults.runtime)
|
|
1453
|
+
.map(([value, spec]) => ({ name: spec.label, value })),
|
|
1454
|
+
],
|
|
1455
|
+
default: defaults.runtime,
|
|
867
1456
|
});
|
|
868
1457
|
language = await select({
|
|
869
1458
|
message: "Which language should be generated?",
|
|
@@ -877,19 +1466,26 @@ export async function setup(args = []) {
|
|
|
877
1466
|
message: "Where should BACLET files be written?",
|
|
878
1467
|
default: libDir,
|
|
879
1468
|
});
|
|
1469
|
+
} else if (useDefaults && features.includes("auth")) {
|
|
1470
|
+
googleState = await checkGoogleAuth({ root: project.root, projectId: project.projectId });
|
|
1471
|
+
if (googleState.enabled) intent.authMethods = [...new Set([...intent.authMethods, "google"])];
|
|
880
1472
|
}
|
|
881
1473
|
|
|
882
1474
|
if (!features.length) throw new Error("Select at least one feature to set up.");
|
|
1475
|
+
if (previewOnly && features.includes("auth")) {
|
|
1476
|
+
console.log("Google sign-in availability is not checked in preview mode.");
|
|
1477
|
+
}
|
|
883
1478
|
|
|
884
|
-
const
|
|
1479
|
+
const planArgs = {
|
|
885
1480
|
root: project.root,
|
|
886
1481
|
libDir,
|
|
887
1482
|
language,
|
|
888
1483
|
runtime,
|
|
889
1484
|
features,
|
|
890
|
-
models,
|
|
1485
|
+
models: effectiveModels,
|
|
891
1486
|
intent,
|
|
892
|
-
}
|
|
1487
|
+
};
|
|
1488
|
+
const plan = [...modelPlan, ...buildPlan(planArgs)];
|
|
893
1489
|
printPlanPreview(plan, previewOnly, console.log);
|
|
894
1490
|
if (previewOnly) {
|
|
895
1491
|
console.log("Preview only. No files were written.");
|
|
@@ -921,8 +1517,23 @@ export async function setup(args = []) {
|
|
|
921
1517
|
}
|
|
922
1518
|
}
|
|
923
1519
|
|
|
924
|
-
const
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
1520
|
+
const results = [];
|
|
1521
|
+
if (modelPlan.length) {
|
|
1522
|
+
results.push(await writePlan(modelPlan, { overwrite }));
|
|
1523
|
+
models = await loadModels(project, { allowEmpty: true });
|
|
1524
|
+
printModelIssues(validateModels(models));
|
|
1525
|
+
if (features.includes("database") && !models.length) {
|
|
1526
|
+
throw new Error("No models could be loaded after writing model files. Database actions were not generated.");
|
|
1527
|
+
}
|
|
1528
|
+
}
|
|
1529
|
+
const libPlan = buildPlan({ ...planArgs, models });
|
|
1530
|
+
results.push(await writePlan(libPlan, { overwrite }));
|
|
1531
|
+
for (const result of results) printSummary(result);
|
|
1532
|
+
await printNextSteps({
|
|
1533
|
+
root: project.root,
|
|
1534
|
+
libDir,
|
|
1535
|
+
features,
|
|
1536
|
+
googleEnabled: googleState.enabled && intent.authMethods.includes("google"),
|
|
1537
|
+
hasModels: models.length > 0,
|
|
1538
|
+
});
|
|
928
1539
|
}
|
|
@@ -6,15 +6,23 @@ import test from "node:test";
|
|
|
6
6
|
import { transform } from "esbuild";
|
|
7
7
|
import { loadConfig, loadModels, loadProject } from "../config.js";
|
|
8
8
|
import {
|
|
9
|
+
buildModelPlan,
|
|
9
10
|
buildPlan,
|
|
11
|
+
checkGoogleAuth,
|
|
10
12
|
defaultIntent,
|
|
11
13
|
describePlanItem,
|
|
12
14
|
detectDefaults,
|
|
15
|
+
detectFramework,
|
|
16
|
+
formatFieldDraft,
|
|
13
17
|
normalizeIntent,
|
|
18
|
+
normalizeModelDraft,
|
|
14
19
|
mergeEnvExample,
|
|
15
20
|
mergeGitignore,
|
|
21
|
+
parseFieldsDraft,
|
|
22
|
+
renderModelFile,
|
|
16
23
|
resolveInside,
|
|
17
24
|
reviewSource,
|
|
25
|
+
suggestModels,
|
|
18
26
|
writePlan,
|
|
19
27
|
writeWithBackup,
|
|
20
28
|
} from "./setup.js";
|
|
@@ -222,6 +230,7 @@ test("detectDefaults uses package metadata and project layout", async () => {
|
|
|
222
230
|
});
|
|
223
231
|
assert.deepEqual(defaults, {
|
|
224
232
|
runtime: "next",
|
|
233
|
+
framework: { id: "next", label: "Next.js", runtime: "next" },
|
|
225
234
|
language: "ts",
|
|
226
235
|
libDir: "src/lib",
|
|
227
236
|
hasModels: false,
|
|
@@ -233,11 +242,151 @@ test("detectDefaults uses package metadata and project layout", async () => {
|
|
|
233
242
|
|
|
234
243
|
test("normalizeIntent validates options and keeps safe defaults", () => {
|
|
235
244
|
assert.deepEqual(normalizeIntent(), defaultIntent);
|
|
245
|
+
assert.equal(defaultIntent.authMethods.includes("google"), false);
|
|
236
246
|
assert.throws(() => normalizeIntent({ authMethods: ["nope"] }), /Unknown authMethods/);
|
|
237
247
|
assert.throws(() => normalizeIntent({ validation: "unsafe" }), /Unknown validation mode/);
|
|
238
248
|
assert.throws(() => normalizeIntent({ queryOptions: "yes" }), /must be a boolean/);
|
|
239
249
|
});
|
|
240
250
|
|
|
251
|
+
test("model drafts parse constraints and render into the configured models folder", async () => {
|
|
252
|
+
const root = await tempDir();
|
|
253
|
+
try {
|
|
254
|
+
const parsed = parseFieldsDraft(
|
|
255
|
+
"email:string!*, status:enum(admin|user)!, price:decimal(10,2)!, owner:ref:user_profiles.id ondelete:cascade, password:string",
|
|
256
|
+
);
|
|
257
|
+
assert.deepEqual(parsed.errors, []);
|
|
258
|
+
assert.match(parsed.warnings.join(" "), /Skipped sensitive field "password"/);
|
|
259
|
+
|
|
260
|
+
const model = normalizeModelDraft("products", parsed.fields);
|
|
261
|
+
const plan = buildModelPlan({
|
|
262
|
+
root,
|
|
263
|
+
patterns: ["./src/models/**/*.ts"],
|
|
264
|
+
models: [model],
|
|
265
|
+
});
|
|
266
|
+
assert.equal(plan.length, 1);
|
|
267
|
+
assert.equal(path.relative(root, plan[0].path), path.join("src", "models", "products.ts"));
|
|
268
|
+
assert.match(plan[0].content, /name: "products"/);
|
|
269
|
+
assert.match(plan[0].content, /email: \{ type: "string", required: true, unique: true \}/);
|
|
270
|
+
assert.match(plan[0].content, /status: \{ type: "enum", required: true, values: \["admin","user"\] \}/);
|
|
271
|
+
assert.match(plan[0].content, /price: \{ type: "decimal", required: true, precision: 10, scale: 2 \}/);
|
|
272
|
+
assert.match(plan[0].content, /reference: \{ model: "user_profiles", field: "id", onDelete: "cascade" \}/);
|
|
273
|
+
assert.match(plan[0].content, /created_at: \{ type: "timestamp", default: \{ expr: "now\(\)" \} \}/);
|
|
274
|
+
assert.match(formatFieldDraft(model.fields), /email:string!\*/);
|
|
275
|
+
await transform(plan[0].content, { loader: "ts" });
|
|
276
|
+
} finally {
|
|
277
|
+
await rm(root, { recursive: true, force: true });
|
|
278
|
+
}
|
|
279
|
+
});
|
|
280
|
+
|
|
281
|
+
test("suggestModels extracts reviewable fields and skips sensitive values", async () => {
|
|
282
|
+
const root = await tempDir();
|
|
283
|
+
try {
|
|
284
|
+
await mkdir(path.join(root, "src", "components"), { recursive: true });
|
|
285
|
+
await writeFile(
|
|
286
|
+
path.join(root, "src", "components", "product-card.tsx"),
|
|
287
|
+
`export function ProductCard({ product }) {
|
|
288
|
+
return (
|
|
289
|
+
<div>
|
|
290
|
+
<label>Product name</label>
|
|
291
|
+
<input name="price" placeholder="Price" />
|
|
292
|
+
<span>{product.description}</span>
|
|
293
|
+
<span>{product.status}</span>
|
|
294
|
+
<input name="apiKey" />
|
|
295
|
+
</div>
|
|
296
|
+
);
|
|
297
|
+
}
|
|
298
|
+
const products = [{ name: "Shirt", price: 10, status: "active" }];
|
|
299
|
+
`,
|
|
300
|
+
);
|
|
301
|
+
|
|
302
|
+
const suggestions = await suggestModels(root);
|
|
303
|
+
const products = suggestions.find((suggestion) => suggestion.name === "products");
|
|
304
|
+
assert.ok(products);
|
|
305
|
+
assert.ok(products.fields.name);
|
|
306
|
+
assert.equal(products.fields.price.type, "decimal");
|
|
307
|
+
assert.equal(products.fields.status.type, "enum");
|
|
308
|
+
assert.ok(products.fields.description);
|
|
309
|
+
assert.equal(products.fields.api_key, undefined);
|
|
310
|
+
} finally {
|
|
311
|
+
await rm(root, { recursive: true, force: true });
|
|
312
|
+
}
|
|
313
|
+
});
|
|
314
|
+
|
|
315
|
+
test("checkGoogleAuth reads provider enablement from project settings", async () => {
|
|
316
|
+
const projectId = "45a8d1b2-3da5-4e1a-9435-ec40b58ee68b";
|
|
317
|
+
const callbackUrl = "https://api.baclet.app/v1/auth/oauth/callback/google/45a8d1b2-3da5-4e1a-9435-ec40b58ee68b";
|
|
318
|
+
const paths = [];
|
|
319
|
+
const result = await checkGoogleAuth({
|
|
320
|
+
root: await tempDir(),
|
|
321
|
+
projectId,
|
|
322
|
+
credentialsFn: async () => ({ accessToken: "test-token" }),
|
|
323
|
+
requestFn: async ({ path: requestPath }) => {
|
|
324
|
+
paths.push(requestPath);
|
|
325
|
+
if (requestPath.endsWith("/me/projects")) {
|
|
326
|
+
return { projects: [{ id: projectId, workspace_slug: "acme", slug: "shop" }] };
|
|
327
|
+
}
|
|
328
|
+
return {
|
|
329
|
+
providers: { google: { enabled: true, validation: { status: "configuration_valid" } } },
|
|
330
|
+
callback_urls: { google: callbackUrl },
|
|
331
|
+
};
|
|
332
|
+
},
|
|
333
|
+
});
|
|
334
|
+
assert.equal(result.enabled, true);
|
|
335
|
+
assert.equal(result.callbackUrl, callbackUrl);
|
|
336
|
+
assert.match(paths.join(" "), /\/workspaces\/acme\/projects\/shop\/auth\/settings/);
|
|
337
|
+
|
|
338
|
+
const invalid = await checkGoogleAuth({
|
|
339
|
+
root: await tempDir(),
|
|
340
|
+
projectId,
|
|
341
|
+
credentialsFn: async () => ({ accessToken: "test-token" }),
|
|
342
|
+
requestFn: async ({ path: requestPath }) =>
|
|
343
|
+
requestPath.endsWith("/me/projects")
|
|
344
|
+
? { projects: [{ id: projectId, workspace_slug: "acme", slug: "shop" }] }
|
|
345
|
+
: { providers: { google: { enabled: true, validation: { status: "invalid_configuration" } } } },
|
|
346
|
+
});
|
|
347
|
+
assert.equal(invalid.enabled, false);
|
|
348
|
+
});
|
|
349
|
+
|
|
350
|
+
test("buildPlan generates Google auth helpers when the provider is enabled", async () => {
|
|
351
|
+
const root = await tempDir();
|
|
352
|
+
try {
|
|
353
|
+
const plan = buildPlan({
|
|
354
|
+
root,
|
|
355
|
+
libDir: "lib",
|
|
356
|
+
language: "ts",
|
|
357
|
+
runtime: "vite",
|
|
358
|
+
features: ["auth"],
|
|
359
|
+
models: [],
|
|
360
|
+
intent: { ...defaultIntent, authMethods: ["email", "google"] },
|
|
361
|
+
});
|
|
362
|
+
const auth = plan.find((item) => item.path.endsWith("auth.ts")).content;
|
|
363
|
+
assert.match(auth, /signInWithGoogle/);
|
|
364
|
+
assert.match(auth, /handleOAuthRedirect/);
|
|
365
|
+
assert.match(auth, /googleAuthorizationURL/);
|
|
366
|
+
assert.match(auth, /authCapabilities/);
|
|
367
|
+
await transform(auth, { loader: "ts" });
|
|
368
|
+
} finally {
|
|
369
|
+
await rm(root, { recursive: true, force: true });
|
|
370
|
+
}
|
|
371
|
+
});
|
|
372
|
+
|
|
373
|
+
test("detectFramework identifies Vite with React", async () => {
|
|
374
|
+
const root = await tempDir();
|
|
375
|
+
try {
|
|
376
|
+
await writeFile(
|
|
377
|
+
path.join(root, "package.json"),
|
|
378
|
+
JSON.stringify({ dependencies: { react: "19.0.0" }, devDependencies: { vite: "7.0.0" } }),
|
|
379
|
+
);
|
|
380
|
+
assert.deepEqual(await detectFramework(root), {
|
|
381
|
+
id: "vite-react",
|
|
382
|
+
label: "Vite + React",
|
|
383
|
+
runtime: "vite",
|
|
384
|
+
});
|
|
385
|
+
} finally {
|
|
386
|
+
await rm(root, { recursive: true, force: true });
|
|
387
|
+
}
|
|
388
|
+
});
|
|
389
|
+
|
|
241
390
|
test("buildPlan generates only the actions selected by the developer", async () => {
|
|
242
391
|
const root = await tempDir();
|
|
243
392
|
try {
|
package/src/index.js
CHANGED
|
@@ -14,7 +14,7 @@ Usage:
|
|
|
14
14
|
baclet logout Remove local credentials
|
|
15
15
|
baclet whoami Show the authorized user
|
|
16
16
|
baclet init [--publishable-key KEY] Create baclet.config.ts (selects a project when logged in)
|
|
17
|
-
baclet setup [--yes|--preview]
|
|
17
|
+
baclet setup [--yes|--preview] Suggest models, then generate env-driven lib files and actions
|
|
18
18
|
baclet projects list List projects you can access
|
|
19
19
|
baclet db status Show the schema diff without applying it
|
|
20
20
|
baclet db push [--yes] Apply the schema to your project database
|