@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.
@@ -0,0 +1,361 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import test from "node:test";
6
+ import { transform } from "esbuild";
7
+ import { loadConfig, loadModels, loadProject } from "../config.js";
8
+ import {
9
+ buildPlan,
10
+ defaultIntent,
11
+ describePlanItem,
12
+ detectDefaults,
13
+ normalizeIntent,
14
+ mergeEnvExample,
15
+ mergeGitignore,
16
+ resolveInside,
17
+ reviewSource,
18
+ writePlan,
19
+ writeWithBackup,
20
+ } from "./setup.js";
21
+
22
+ const sampleModels = [
23
+ {
24
+ name: "products",
25
+ fields: {
26
+ name: { type: "string", required: true },
27
+ price: { type: "decimal", required: true, precision: 10, scale: 2 },
28
+ created_at: { type: "timestamp", default: { expr: "now()" } },
29
+ },
30
+ },
31
+ {
32
+ name: "user profiles",
33
+ fields: {
34
+ email: { type: "string", required: true, unique: true },
35
+ role: { type: "enum", required: true, values: ["admin", "user"] },
36
+ },
37
+ },
38
+ ];
39
+
40
+ async function tempDir() {
41
+ return mkdtemp(path.join(os.tmpdir(), "baclet-setup-test-"));
42
+ }
43
+
44
+ test("buildPlan generates env-driven TypeScript files for every feature", async () => {
45
+ const root = await tempDir();
46
+ try {
47
+ const plan = buildPlan({
48
+ root,
49
+ libDir: "src/lib",
50
+ language: "ts",
51
+ runtime: "vite",
52
+ features: ["auth", "storage", "database"],
53
+ models: sampleModels,
54
+ });
55
+ const code = plan.filter((item) => item.merge === null);
56
+ assert.deepEqual(
57
+ code.map((item) => path.relative(root, item.path)),
58
+ [
59
+ "src/lib/baclet.ts",
60
+ "src/lib/actions/auth.ts",
61
+ "src/lib/actions/storage.ts",
62
+ "src/lib/actions/products.ts",
63
+ "src/lib/actions/user-profiles.ts",
64
+ "src/lib/index.ts",
65
+ ],
66
+ );
67
+
68
+ const contents = new Map(code.map((item) => [path.relative(root, item.path), item.content]));
69
+ const client = contents.get("src/lib/baclet.ts");
70
+ assert.match(client, /env\.VITE_BACLET_PUBLISHABLE_KEY/);
71
+ assert.match(client, /apiUrl: env\.VITE_BACLET_API_URL \|\| "https:\/\/api\.baclet\.app"/);
72
+ assert.match(client, /enableDatabasePersistence\(\);/);
73
+ assert.doesNotMatch(client, /secretKey|sk_[A-Za-z0-9_-]{43}/);
74
+
75
+ const products = contents.get("src/lib/actions/products.ts");
76
+ assert.match(products, /const collection = "products";/);
77
+ assert.match(products, /export type ProductsRecord = \{/);
78
+ assert.match(products, /name: string;/);
79
+ assert.match(products, /price: number;/);
80
+ assert.match(products, /created_at\?: string;/);
81
+ assert.match(products, /assertKey\(key\)/);
82
+ assert.match(products, /assertValues\(values, true\)/);
83
+ assert.match(products, /Missing required field/);
84
+ assert.match(products, /Unknown field/);
85
+
86
+ const roles = contents.get("src/lib/actions/user-profiles.ts");
87
+ assert.match(roles, /role: "admin" \| "user";/);
88
+
89
+ const index = contents.get("src/lib/index.ts");
90
+ assert.match(index, /export \{ authActions \} from "\.\/actions\/auth\.js";/);
91
+ assert.match(index, /export \{ storageActions \} from "\.\/actions\/storage\.js";/);
92
+ assert.match(index, /export \{ productsActions \} from "\.\/actions\/products\.js";/);
93
+ assert.match(index, /export type \{ ProductsInput, ProductsRecord \}/);
94
+
95
+ for (const item of code) {
96
+ await transform(item.content, { loader: "ts" });
97
+ assert.doesNotMatch(item.content, /sk_[A-Za-z0-9_-]{43}/);
98
+ }
99
+
100
+ const env = plan.find((item) => item.merge === "env");
101
+ assert.equal(env.path, path.join(root, ".env.example"));
102
+ assert.deepEqual(env.keys.map((key) => key.name), [
103
+ "VITE_BACLET_PUBLISHABLE_KEY",
104
+ "VITE_BACLET_API_URL",
105
+ "VITE_BACLET_STORAGE_BUCKET",
106
+ ]);
107
+ const gitignore = plan.find((item) => item.merge === "gitignore");
108
+ assert.deepEqual(gitignore.entries, [".env", ".env.local", ".env.*.local"]);
109
+ } finally {
110
+ await rm(root, { recursive: true, force: true });
111
+ }
112
+ });
113
+
114
+ test("buildPlan emits JavaScript with process env for Node and skips unused features", async () => {
115
+ const root = await tempDir();
116
+ try {
117
+ const plan = buildPlan({
118
+ root,
119
+ libDir: "lib",
120
+ language: "js",
121
+ runtime: "node",
122
+ features: ["auth"],
123
+ models: sampleModels,
124
+ });
125
+ const code = plan.filter((item) => item.merge === null);
126
+ assert.deepEqual(
127
+ code.map((item) => path.relative(root, item.path)),
128
+ ["lib/baclet.js", "lib/actions/auth.js", "lib/index.js"],
129
+ );
130
+ const client = code[0].content;
131
+ assert.match(client, /globalThis\.process\?\.env/);
132
+ assert.match(client, /env\.BACLET_PUBLISHABLE_KEY/);
133
+ assert.doesNotMatch(client, /import\.meta/);
134
+ for (const item of code) await transform(item.content, { loader: "js" });
135
+ assert.deepEqual(
136
+ plan.find((item) => item.merge === "env").keys.map((key) => key.name),
137
+ ["BACLET_PUBLISHABLE_KEY", "BACLET_API_URL"],
138
+ );
139
+ } finally {
140
+ await rm(root, { recursive: true, force: true });
141
+ }
142
+ });
143
+
144
+ test("buildPlan rejects paths outside the project and database without models", () => {
145
+ const root = path.join(os.tmpdir(), `baclet-setup-root-${Date.now()}`);
146
+ assert.throws(() => resolveInside(root, "../elsewhere"), /inside the project root/);
147
+ assert.throws(
148
+ () =>
149
+ buildPlan({
150
+ root,
151
+ libDir: "lib",
152
+ language: "ts",
153
+ runtime: "node",
154
+ features: ["database"],
155
+ models: [],
156
+ }),
157
+ /require at least one model/,
158
+ );
159
+ });
160
+
161
+ test("env and gitignore merges preserve existing values and avoid duplicates", () => {
162
+ const keys = [
163
+ { name: "BACLET_PUBLISHABLE_KEY", value: "pb_placeholder" },
164
+ { name: "BACLET_API_URL", value: "https://api.baclet.app" },
165
+ ];
166
+ const first = mergeEnvExample("BACLET_PUBLISHABLE_KEY=pb_existing\n", keys);
167
+ assert.equal(first.changed, true);
168
+ assert.match(first.content, /BACLET_PUBLISHABLE_KEY=pb_existing/);
169
+ assert.match(first.content, /BACLET_API_URL=https:\/\/api\.baclet\.app/);
170
+ assert.equal(mergeEnvExample(first.content, keys).changed, false);
171
+
172
+ const gitignore = mergeGitignore("node_modules\n", [".env", ".env.local", ".env.*.local"]);
173
+ assert.match(gitignore.content, /node_modules\n\.env\n\.env\.local\n\.env\.\*\.local\n/);
174
+ assert.equal(mergeGitignore(gitignore.content, [".env"]).changed, false);
175
+ });
176
+
177
+ test("writePlan skips existing files and backs up files on confirmed overwrite", async () => {
178
+ const root = await tempDir();
179
+ try {
180
+ const plan = buildPlan({
181
+ root,
182
+ libDir: "lib",
183
+ language: "js",
184
+ runtime: "node",
185
+ features: ["auth"],
186
+ models: [],
187
+ });
188
+ const first = await writePlan(plan);
189
+ assert.equal(first.created.length, 5);
190
+ const index = plan.find((item) => item.path.endsWith("index.js"));
191
+ assert.match(await readFile(index.path, "utf8"), /authActions/);
192
+
193
+ const second = await writePlan(plan);
194
+ assert.equal(second.created.length, 0);
195
+ assert.equal(second.skipped.length, 5);
196
+ assert.equal(await readFile(`${index.path}.bak`, "utf8").catch(() => null), null);
197
+
198
+ await writeFile(index.path, "custom content\n");
199
+ const third = await writePlan(plan, { overwrite: true });
200
+ assert.equal(third.updated.length, 3);
201
+ assert.equal(await readFile(`${index.path}.bak`, "utf8"), "custom content\n");
202
+ assert.match(await readFile(index.path, "utf8"), /authActions/);
203
+
204
+ await writeFile(path.join(root, ".env.example"), "BACLET_PUBLISHABLE_KEY=pb_real\n");
205
+ await writePlan(plan);
206
+ assert.match(await readFile(path.join(root, ".env.example"), "utf8"), /BACLET_PUBLISHABLE_KEY=pb_real/);
207
+ } finally {
208
+ await rm(root, { recursive: true, force: true });
209
+ }
210
+ });
211
+
212
+ test("detectDefaults uses package metadata and project layout", async () => {
213
+ const root = await tempDir();
214
+ try {
215
+ await mkdir(path.join(root, "src"), { recursive: true });
216
+ await writeFile(path.join(root, "package.json"), JSON.stringify({ dependencies: { next: "15.0.0" } }));
217
+ await writeFile(path.join(root, "tsconfig.json"), "{}");
218
+ const defaults = await detectDefaults({
219
+ root,
220
+ configPath: path.join(root, "baclet.config.ts"),
221
+ models: [],
222
+ });
223
+ assert.deepEqual(defaults, {
224
+ runtime: "next",
225
+ language: "ts",
226
+ libDir: "src/lib",
227
+ hasModels: false,
228
+ });
229
+ } finally {
230
+ await rm(root, { recursive: true, force: true });
231
+ }
232
+ });
233
+
234
+ test("normalizeIntent validates options and keeps safe defaults", () => {
235
+ assert.deepEqual(normalizeIntent(), defaultIntent);
236
+ assert.throws(() => normalizeIntent({ authMethods: ["nope"] }), /Unknown authMethods/);
237
+ assert.throws(() => normalizeIntent({ validation: "unsafe" }), /Unknown validation mode/);
238
+ assert.throws(() => normalizeIntent({ queryOptions: "yes" }), /must be a boolean/);
239
+ });
240
+
241
+ test("buildPlan generates only the actions selected by the developer", async () => {
242
+ const root = await tempDir();
243
+ try {
244
+ const plan = buildPlan({
245
+ root,
246
+ libDir: "lib",
247
+ language: "ts",
248
+ runtime: "node",
249
+ features: ["auth", "storage", "database"],
250
+ models: [sampleModels[0]],
251
+ intent: {
252
+ authMethods: ["email"],
253
+ storageOps: ["url"],
254
+ databaseOps: ["list", "get"],
255
+ queryOptions: false,
256
+ validation: "none",
257
+ },
258
+ });
259
+ const contents = new Map(plan.map((item) => [path.relative(root, item.path), item]));
260
+
261
+ const auth = contents.get("lib/actions/auth.ts").content;
262
+ assert.match(auth, /signIn:/);
263
+ assert.match(auth, /signUp:/);
264
+ assert.doesNotMatch(auth, /signInAsGuest|forgotPassword|getIdToken/);
265
+
266
+ const storage = contents.get("lib/actions/storage.ts").content;
267
+ assert.match(storage, /url:/);
268
+ assert.doesNotMatch(storage, /uploadBytes|deleteObject|UploadMetadata/);
269
+
270
+ const model = contents.get("lib/actions/products.ts").content;
271
+ assert.match(model, /list: async \(\) =>/);
272
+ assert.match(model, /get: async/);
273
+ assert.doesNotMatch(model, /assertValues|create:|set:|update:|remove:/);
274
+ assert.doesNotMatch(model, /QueryConstraint|orderByChild/);
275
+
276
+ for (const item of plan.filter((entry) => entry.merge === null)) {
277
+ await transform(item.content, { loader: "ts" });
278
+ }
279
+ } finally {
280
+ await rm(root, { recursive: true, force: true });
281
+ }
282
+ });
283
+
284
+ test("describePlanItem reports exports, actions, env keys, and ignore entries", () => {
285
+ const root = path.join(os.tmpdir(), `baclet-plan-${Date.now()}`);
286
+ const plan = buildPlan({
287
+ root,
288
+ libDir: "lib",
289
+ language: "js",
290
+ runtime: "node",
291
+ features: ["auth"],
292
+ models: [],
293
+ });
294
+ const auth = describePlanItem(plan.find((item) => item.path.endsWith("auth.js")));
295
+ assert.deepEqual(auth.exports, ["authActions"]);
296
+ assert.match(auth.actions.join(","), /signIn/);
297
+ assert.equal(describePlanItem(plan.find((item) => item.merge === "env")).details[0], "BACLET_PUBLISHABLE_KEY");
298
+ assert.equal(describePlanItem(plan.find((item) => item.merge === "gitignore")).details[0], ".env");
299
+ });
300
+
301
+ test("writeWithBackup preserves the previous file before replacing it", async () => {
302
+ const root = await tempDir();
303
+ try {
304
+ const file = path.join(root, "models", "product.ts");
305
+ await mkdir(path.dirname(file), { recursive: true });
306
+ await writeFile(file, "original\n");
307
+ await writeWithBackup(file, "corrected\n");
308
+ assert.equal(await readFile(file, "utf8"), "corrected\n");
309
+ assert.equal(await readFile(`${file}.bak`, "utf8"), "original\n");
310
+
311
+ const fresh = path.join(root, "models", "fresh.ts");
312
+ await writeWithBackup(fresh, "new\n");
313
+ assert.equal(await readFile(fresh, "utf8"), "new\n");
314
+ assert.equal(await readFile(`${fresh}.bak`, "utf8").catch(() => null), null);
315
+ } finally {
316
+ await rm(root, { recursive: true, force: true });
317
+ }
318
+ });
319
+
320
+ test("reviewSource applies fixes only after confirmation", async () => {
321
+ const root = await tempDir();
322
+ const original = 'export const Product = { name: "products", fields: { count: { type: "int" } } };\n';
323
+ try {
324
+ const file = path.join(root, "product.ts");
325
+ await writeFile(file, original);
326
+
327
+ const skipped = await reviewSource(file, "model", false, async () => false, () => {});
328
+ assert.equal(skipped, false);
329
+ assert.equal(await readFile(file, "utf8"), original);
330
+ assert.equal(await readFile(`${file}.bak`, "utf8").catch(() => null), null);
331
+
332
+ const defaults = await reviewSource(file, "model", true, async () => {
333
+ throw new Error("should not ask in --yes mode");
334
+ }, () => {});
335
+ assert.equal(defaults, false);
336
+ assert.equal(await readFile(file, "utf8"), original);
337
+
338
+ const applied = await reviewSource(file, "model", false, async () => true, () => {});
339
+ assert.equal(applied, true);
340
+ assert.match(await readFile(file, "utf8"), /type: "integer"/);
341
+ assert.equal(await readFile(`${file}.bak`, "utf8"), original);
342
+ } finally {
343
+ await rm(root, { recursive: true, force: true });
344
+ }
345
+ });
346
+
347
+ test("setup can load a project before any model files exist", async () => {
348
+ const root = await tempDir();
349
+ try {
350
+ await writeFile(
351
+ path.join(root, "baclet.config.ts"),
352
+ 'export default { publishableKey: "pb_45a8d1b2-3da5-4e1a-9435-ec40b58ee68b_demo", schema: { models: "./models/*.ts" } };',
353
+ );
354
+ const project = await loadConfig(root);
355
+ assert.equal(project.projectId, "45a8d1b2-3da5-4e1a-9435-ec40b58ee68b");
356
+ assert.deepEqual(await loadModels(project, { allowEmpty: true }), []);
357
+ await assert.rejects(() => loadProject(root), /No model files matched/);
358
+ } finally {
359
+ await rm(root, { recursive: true, force: true });
360
+ }
361
+ });
package/src/config.js CHANGED
@@ -12,7 +12,7 @@ const configNames = [
12
12
  "baclet.config.mjs",
13
13
  ];
14
14
 
15
- async function findConfig(cwd) {
15
+ export async function findConfig(cwd) {
16
16
  for (let dir = cwd; ; dir = path.dirname(dir)) {
17
17
  for (const name of configNames) {
18
18
  const candidate = path.join(dir, name);
@@ -46,7 +46,7 @@ function normalizeModel(model) {
46
46
  return { ...model, fields };
47
47
  }
48
48
 
49
- export async function loadProject(cwd = process.cwd()) {
49
+ export async function loadConfig(cwd = process.cwd()) {
50
50
  const configPath = await findConfig(cwd);
51
51
  const root = path.dirname(configPath);
52
52
  const temp = await mkdtemp(path.join(os.tmpdir(), "baclet-cli-"));
@@ -70,14 +70,31 @@ export async function loadProject(cwd = process.cwd()) {
70
70
  if (!match) {
71
71
  throw new Error("Invalid BACLET publishable key. Expected pb_<uuid>_... from your project API Keys page.");
72
72
  }
73
- const projectId = match[1];
74
73
  const patterns = Array.isArray(config.schema?.models)
75
74
  ? config.schema.models
76
75
  : [config.schema?.models].filter(Boolean);
77
76
  if (!patterns.length) throw new Error("baclet.config.ts must define schema.models.");
78
77
 
78
+ return { config, root, projectId: match[1], configPath, patterns };
79
+ } finally {
80
+ await rm(temp, { recursive: true, force: true });
81
+ }
82
+ }
83
+
84
+ export async function loadModels({ root, patterns }, options = {}) {
85
+ const allowEmpty = options.allowEmpty === true;
86
+ if (!patterns.length) {
87
+ if (allowEmpty) return [];
88
+ throw new Error("baclet.config.ts must define schema.models.");
89
+ }
90
+
91
+ const temp = await mkdtemp(path.join(os.tmpdir(), "baclet-cli-"));
92
+ try {
79
93
  const files = await fg(patterns, { cwd: root, absolute: true, onlyFiles: true });
80
- if (!files.length) throw new Error(`No model files matched ${patterns.join(", ")}.`);
94
+ if (!files.length) {
95
+ if (allowEmpty) return [];
96
+ throw new Error(`No model files matched ${patterns.join(", ")}.`);
97
+ }
81
98
 
82
99
  const entry = files.map((file, index) => `export * as model_${index} from ${JSON.stringify(file)};`).join("\n");
83
100
  const modelsOut = path.join(temp, "models.mjs");
@@ -103,10 +120,18 @@ export async function loadProject(cwd = process.cwd()) {
103
120
  models.push(model);
104
121
  }
105
122
  }
106
- if (!models.length) throw new Error("No models found. Export defineModel(...) objects from your model files.");
123
+ if (!models.length && !allowEmpty) {
124
+ throw new Error("No models found. Export defineModel(...) objects from your model files.");
125
+ }
107
126
 
108
- return { config, models, root, projectId };
127
+ return models;
109
128
  } finally {
110
129
  await rm(temp, { recursive: true, force: true });
111
130
  }
112
131
  }
132
+
133
+ export async function loadProject(cwd = process.cwd()) {
134
+ const project = await loadConfig(cwd);
135
+ const models = await loadModels(project);
136
+ return { ...project, models };
137
+ }
package/src/index.js CHANGED
@@ -2,6 +2,7 @@
2
2
  import { readFileSync } from "node:fs";
3
3
  import { login, logout, whoami } from "./commands/auth.js";
4
4
  import { init, listProjects, dbStatus, dbPush } from "./commands/project.js";
5
+ import { setup } from "./commands/setup.js";
5
6
  import { upgrade, maybeNotifyUpdate } from "./update.js";
6
7
 
7
8
  const { version } = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
@@ -13,6 +14,7 @@ Usage:
13
14
  baclet logout Remove local credentials
14
15
  baclet whoami Show the authorized user
15
16
  baclet init [--publishable-key KEY] Create baclet.config.ts (selects a project when logged in)
17
+ baclet setup [--yes|--preview] Generate env-driven lib files and actions from your models
16
18
  baclet projects list List projects you can access
17
19
  baclet db status Show the schema diff without applying it
18
20
  baclet db push [--yes] Apply the schema to your project database
@@ -31,6 +33,7 @@ async function main() {
31
33
  case "logout": return logout();
32
34
  case "whoami": return whoami();
33
35
  case "init": return init(args);
36
+ case "setup": return setup(args);
34
37
  case "projects":
35
38
  if (args[0] === "list") return listProjects();
36
39
  throw new Error("Usage: baclet projects list");