@baclet/cli 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +89 -2
- package/package.json +24 -4
- package/src/commands/auth.js +79 -0
- package/src/commands/project.js +124 -0
- package/src/config.js +96 -0
- package/src/config.test.js +53 -0
- package/src/credentials.js +32 -0
- package/src/http.js +48 -0
- package/src/index.js +50 -0
- package/src/paths.js +7 -0
package/README.md
CHANGED
|
@@ -1,3 +1,90 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @baclet/cli
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Command line tool for authorizing a machine with BACLET and pushing TypeScript models to a connected project database.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
Globally, when you want one command for all projects:
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install --global @baclet/cli
|
|
11
|
+
baclet --help
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
Locally, when a repository should pin the version:
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
npm install --save-dev @baclet/cli
|
|
18
|
+
npx baclet --help
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Node.js 18 or later is required.
|
|
22
|
+
|
|
23
|
+
## Commands
|
|
24
|
+
|
|
25
|
+
| Command | Description |
|
|
26
|
+
| --- | --- |
|
|
27
|
+
| `baclet login [--qr\|--link]` | Authorize this machine with a QR code, a link, or both. |
|
|
28
|
+
| `baclet logout` | Remove local credentials and revoke the CLI token. |
|
|
29
|
+
| `baclet whoami` | Show the authorized account. |
|
|
30
|
+
| `baclet init [--publishable-key KEY]` | Create `baclet.config.ts`, selecting a project when logged in. |
|
|
31
|
+
| `baclet projects list` | List projects you can access. |
|
|
32
|
+
| `baclet db status` | Print the schema diff without applying it. |
|
|
33
|
+
| `baclet db push [--yes]` | Apply the schema diff after confirmation. |
|
|
34
|
+
| `baclet db migrate [--yes]` | Alias for `db push`. |
|
|
35
|
+
|
|
36
|
+
## Login
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
baclet login
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
The CLI prints an activation link, a verification code, and a QR code. Open the link or scan the QR code, sign in, and approve the code. Use `--link` or `--qr` to show only one option.
|
|
43
|
+
|
|
44
|
+
Tokens are stored in `~/.config/baclet/credentials.json` with `0600` permissions. `XDG_CONFIG_HOME` changes the parent directory. Tokens are valid for 30 days and `baclet logout` revokes them.
|
|
45
|
+
|
|
46
|
+
## Schema push
|
|
47
|
+
|
|
48
|
+
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.
|
|
49
|
+
|
|
50
|
+
Otherwise, create `baclet.config.ts` in your project:
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
import { defineConfig } from "@baclet/sdk";
|
|
54
|
+
|
|
55
|
+
export default defineConfig({
|
|
56
|
+
publishableKey: "pb_45a8d1b2-3da5-4e1a-9435-ec40b58ee68b_...",
|
|
57
|
+
schema: { models: "./src/models/**/*.ts" },
|
|
58
|
+
});
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Export a model from each matched file:
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
import { defineModel } from "@baclet/sdk";
|
|
65
|
+
|
|
66
|
+
export const Product = defineModel({
|
|
67
|
+
name: "products",
|
|
68
|
+
fields: {
|
|
69
|
+
name: { type: "string", required: true },
|
|
70
|
+
price: { type: "decimal", required: true, precision: 12, scale: 2 },
|
|
71
|
+
},
|
|
72
|
+
});
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Then preview and apply:
|
|
76
|
+
|
|
77
|
+
```bash
|
|
78
|
+
baclet db status
|
|
79
|
+
baclet db push
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Pushes are additive: new tables, columns, constraints, and indexes are applied in one transaction. Columns that exist in the database but not in your models are reported as warnings and are never dropped.
|
|
83
|
+
|
|
84
|
+
## Environment
|
|
85
|
+
|
|
86
|
+
| Variable | Default | Purpose |
|
|
87
|
+
| --- | --- | --- |
|
|
88
|
+
| `BACLET_API_URL` | `https://api.baclet.com` | API host. |
|
|
89
|
+
| `BACLET_DASHBOARD_URL` | `https://app.baclet.com` | Fallback activation link host. |
|
|
90
|
+
| `XDG_CONFIG_HOME` | `~/.config` | Parent directory for credentials. |
|
package/package.json
CHANGED
|
@@ -1,6 +1,26 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@baclet/cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "BACLET command line tool for authentication and schema pushes",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"baclet": "./src/index.js"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"src",
|
|
11
|
+
"README.md"
|
|
12
|
+
],
|
|
13
|
+
"scripts": {
|
|
14
|
+
"test": "node --test"
|
|
15
|
+
},
|
|
16
|
+
"dependencies": {
|
|
17
|
+
"@inquirer/prompts": "^7.5.0",
|
|
18
|
+
"esbuild": "^0.25.0",
|
|
19
|
+
"fast-glob": "^3.3.2",
|
|
20
|
+
"qrcode": "^1.5.4"
|
|
21
|
+
},
|
|
22
|
+
"engines": {
|
|
23
|
+
"node": ">=18"
|
|
24
|
+
},
|
|
25
|
+
"license": "MIT"
|
|
26
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import os from "node:os";
|
|
2
|
+
import QRCode from "qrcode";
|
|
3
|
+
import { request, apiUrl, dashboardUrl } from "../http.js";
|
|
4
|
+
import { loadCredentials, requireCredentials, saveCredentials, clearCredentials } from "../credentials.js";
|
|
5
|
+
|
|
6
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
7
|
+
|
|
8
|
+
export async function login(args = []) {
|
|
9
|
+
const method = args.find((arg) => arg === "--qr" || arg === "--link")?.slice(2) || "both";
|
|
10
|
+
const device = await request({
|
|
11
|
+
method: "POST",
|
|
12
|
+
path: "/api/v1/cli/devices",
|
|
13
|
+
body: { name: os.hostname(), method },
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
const { device_code: deviceCode, user_code: userCode, verification_url: verificationUrl, expires_in: expiresIn = 600, interval = 5 } = device;
|
|
17
|
+
const url = verificationUrl || `${dashboardUrl()}/cli/activate?code=${encodeURIComponent(userCode)}`;
|
|
18
|
+
|
|
19
|
+
console.log(`\nOpen this link to authorize BACLET CLI:\n ${url}\n`);
|
|
20
|
+
if (method !== "link") {
|
|
21
|
+
const qr = await QRCode.toString(url, { type: "terminal", small: true });
|
|
22
|
+
console.log(qr);
|
|
23
|
+
console.log("Or scan the QR code above with your phone.\n");
|
|
24
|
+
}
|
|
25
|
+
console.log(`Verification code: ${userCode}\n`);
|
|
26
|
+
console.log(`Waiting for authorization (expires in ${Math.round(expiresIn / 60)} minutes)...`);
|
|
27
|
+
console.log("Press Ctrl+C to cancel.\n");
|
|
28
|
+
|
|
29
|
+
const deadline = Date.now() + expiresIn * 1000;
|
|
30
|
+
let pending = 0;
|
|
31
|
+
while (Date.now() < deadline) {
|
|
32
|
+
await sleep(interval * 1000);
|
|
33
|
+
try {
|
|
34
|
+
const result = await request({
|
|
35
|
+
method: "POST",
|
|
36
|
+
path: "/api/v1/cli/devices/token",
|
|
37
|
+
body: { device_code: deviceCode },
|
|
38
|
+
});
|
|
39
|
+
await saveCredentials({
|
|
40
|
+
accessToken: result.token,
|
|
41
|
+
user: result.user,
|
|
42
|
+
apiUrl: apiUrl(),
|
|
43
|
+
obtainedAt: new Date().toISOString(),
|
|
44
|
+
});
|
|
45
|
+
console.log(`\nLogged in as ${result.user.email}.`);
|
|
46
|
+
return;
|
|
47
|
+
} catch (error) {
|
|
48
|
+
if (error.status === 409) {
|
|
49
|
+
pending += 1;
|
|
50
|
+
if (pending % 12 === 0) process.stdout.write(" still waiting...\n");
|
|
51
|
+
else process.stdout.write(".");
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
throw error;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
throw new Error("Authorization request expired. Run `baclet login` to try again.");
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export async function logout() {
|
|
61
|
+
const creds = await loadCredentials();
|
|
62
|
+
if (creds?.accessToken) {
|
|
63
|
+
try {
|
|
64
|
+
await request({ method: "POST", path: "/api/v1/cli/logout", token: creds.accessToken });
|
|
65
|
+
} catch {
|
|
66
|
+
// Local logout still succeeds when the API is unreachable.
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
await clearCredentials();
|
|
70
|
+
console.log("Logged out of BACLET CLI.");
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export async function whoami() {
|
|
74
|
+
const creds = await requireCredentials();
|
|
75
|
+
const payload = await request({ method: "GET", path: "/api/v1/me", token: creds.accessToken });
|
|
76
|
+
const profile = payload.user || payload;
|
|
77
|
+
console.log(`${profile.fullName || profile.email} <${profile.email}>`);
|
|
78
|
+
console.log(`User ID: ${profile.id}`);
|
|
79
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { access, writeFile } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { confirm, select } from "@inquirer/prompts";
|
|
4
|
+
import { request } from "../http.js";
|
|
5
|
+
import { requireCredentials } from "../credentials.js";
|
|
6
|
+
import { loadProject } from "../config.js";
|
|
7
|
+
|
|
8
|
+
export async function init(args = []) {
|
|
9
|
+
const keyIndex = args.findIndex((arg) => ["--publishable-key", "--key", "--project"].includes(arg));
|
|
10
|
+
let publishableKey = keyIndex >= 0 ? args[keyIndex + 1] : null;
|
|
11
|
+
|
|
12
|
+
if (!publishableKey) {
|
|
13
|
+
const creds = await requireCredentials();
|
|
14
|
+
const payload = await request({ method: "GET", path: "/api/v1/me/projects", token: creds.accessToken });
|
|
15
|
+
const projects = payload.projects || [];
|
|
16
|
+
if (!projects.length) throw new Error("No projects found. Create one in the BACLET dashboard first.");
|
|
17
|
+
|
|
18
|
+
const selected = await select({
|
|
19
|
+
message: "Select a project:",
|
|
20
|
+
choices: projects.map((project) => ({
|
|
21
|
+
name: `${project.name} (${project.workspace_slug}/${project.slug})`,
|
|
22
|
+
value: project,
|
|
23
|
+
})),
|
|
24
|
+
});
|
|
25
|
+
const settings = await request({
|
|
26
|
+
method: "GET",
|
|
27
|
+
path: `/api/v1/workspaces/${selected.workspace_slug}/projects/${selected.slug}/auth/settings`,
|
|
28
|
+
token: creds.accessToken,
|
|
29
|
+
});
|
|
30
|
+
publishableKey = settings.publishable_key;
|
|
31
|
+
console.log(`Using ${selected.name}.`);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const key = publishableKey?.trim();
|
|
35
|
+
if (!key || !/^pb_[0-9a-fA-F-]{36}_/.test(key)) {
|
|
36
|
+
throw new Error("A valid publishable key (pb_<uuid>_...) is required. Copy it from Dashboard → API Keys.");
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const file = path.join(process.cwd(), "baclet.config.ts");
|
|
40
|
+
try {
|
|
41
|
+
await access(file);
|
|
42
|
+
throw new Error("baclet.config.ts already exists in this directory.");
|
|
43
|
+
} catch (error) {
|
|
44
|
+
if (error.code !== "ENOENT") throw error;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
await writeFile(file, `import { defineConfig } from "@baclet/sdk";
|
|
48
|
+
|
|
49
|
+
export default defineConfig({
|
|
50
|
+
publishableKey: ${JSON.stringify(key)},
|
|
51
|
+
schema: {
|
|
52
|
+
models: "./src/models/**/*.ts",
|
|
53
|
+
},
|
|
54
|
+
});
|
|
55
|
+
`);
|
|
56
|
+
console.log(`Created ${file}`);
|
|
57
|
+
console.log("Add your models under src/models and export each one with defineModel(...).");
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export async function listProjects() {
|
|
61
|
+
const creds = await requireCredentials();
|
|
62
|
+
const payload = await request({ method: "GET", path: "/api/v1/me/projects", token: creds.accessToken });
|
|
63
|
+
const projects = payload.projects || [];
|
|
64
|
+
if (!projects.length) {
|
|
65
|
+
console.log("No projects found. Create one in the BACLET dashboard first.");
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
for (const project of projects) {
|
|
69
|
+
console.log(`${project.name} ${project.workspace_slug}/${project.slug} ${project.id}`);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function printDiff(result) {
|
|
74
|
+
const statements = result?.diff?.statements || [];
|
|
75
|
+
const warnings = result?.diff?.warnings || [];
|
|
76
|
+
console.log(`Project: ${result.project}`);
|
|
77
|
+
if (!statements.length) {
|
|
78
|
+
console.log("No changes detected. Your database matches the schema.");
|
|
79
|
+
} else {
|
|
80
|
+
console.log(`\n${statements.length} change${statements.length === 1 ? "" : "s"}:\n`);
|
|
81
|
+
for (const statement of statements) console.log(` + ${statement}`);
|
|
82
|
+
}
|
|
83
|
+
for (const warning of warnings) console.log(`\n ! ${warning}`);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async function push(args, apply) {
|
|
87
|
+
const creds = await requireCredentials();
|
|
88
|
+
const { models, projectId } = await loadProject();
|
|
89
|
+
console.log(`Loaded ${models.length} model${models.length === 1 ? "" : "s"} from project ${projectId}.`);
|
|
90
|
+
|
|
91
|
+
const result = await request({
|
|
92
|
+
method: "POST",
|
|
93
|
+
path: `/api/v1/cli/schema/${apply ? "push" : "status"}`,
|
|
94
|
+
token: creds.accessToken,
|
|
95
|
+
body: { projectId, models },
|
|
96
|
+
});
|
|
97
|
+
printDiff(result);
|
|
98
|
+
|
|
99
|
+
if (apply) {
|
|
100
|
+
if (!result.diff.statements.length) return;
|
|
101
|
+
if (!args.includes("--yes")) {
|
|
102
|
+
const ok = await confirm({ message: "Apply these changes to your project database?", default: false });
|
|
103
|
+
if (!ok) {
|
|
104
|
+
console.log("Cancelled.");
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
const applied = await request({
|
|
109
|
+
method: "POST",
|
|
110
|
+
path: "/api/v1/cli/schema/push",
|
|
111
|
+
token: creds.accessToken,
|
|
112
|
+
body: { projectId, models, apply: true },
|
|
113
|
+
});
|
|
114
|
+
console.log(`\nSchema applied. Version ${applied.version} saved.`);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export async function dbStatus() {
|
|
119
|
+
await push([], false);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export async function dbPush(args = []) {
|
|
123
|
+
await push(args, true);
|
|
124
|
+
}
|
package/src/config.js
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { mkdtemp, rm, stat } from "node:fs/promises";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { pathToFileURL } from "node:url";
|
|
5
|
+
import { build } from "esbuild";
|
|
6
|
+
import fg from "fast-glob";
|
|
7
|
+
|
|
8
|
+
const configNames = [
|
|
9
|
+
"baclet.config.ts",
|
|
10
|
+
"baclet.config.mts",
|
|
11
|
+
"baclet.config.js",
|
|
12
|
+
"baclet.config.mjs",
|
|
13
|
+
];
|
|
14
|
+
|
|
15
|
+
async function findConfig(cwd) {
|
|
16
|
+
for (let dir = cwd; ; dir = path.dirname(dir)) {
|
|
17
|
+
for (const name of configNames) {
|
|
18
|
+
const candidate = path.join(dir, name);
|
|
19
|
+
try {
|
|
20
|
+
if ((await stat(candidate)).isFile()) return candidate;
|
|
21
|
+
} catch {
|
|
22
|
+
// keep searching
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
if (dir === path.dirname(dir)) break;
|
|
26
|
+
}
|
|
27
|
+
throw new Error("No baclet.config.ts found. Run `baclet init` first.");
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function isModel(value) {
|
|
31
|
+
return !!value && typeof value === "object" && typeof value.name === "string" && !!value.fields && typeof value.fields === "object";
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export async function loadProject(cwd = process.cwd()) {
|
|
35
|
+
const configPath = await findConfig(cwd);
|
|
36
|
+
const root = path.dirname(configPath);
|
|
37
|
+
const temp = await mkdtemp(path.join(os.tmpdir(), "baclet-cli-"));
|
|
38
|
+
|
|
39
|
+
try {
|
|
40
|
+
const configOut = path.join(temp, "config.mjs");
|
|
41
|
+
await build({
|
|
42
|
+
entryPoints: [configPath],
|
|
43
|
+
bundle: true,
|
|
44
|
+
format: "esm",
|
|
45
|
+
platform: "node",
|
|
46
|
+
target: "node18",
|
|
47
|
+
outfile: configOut,
|
|
48
|
+
logLevel: "silent",
|
|
49
|
+
});
|
|
50
|
+
const config = (await import(pathToFileURL(configOut).href)).default;
|
|
51
|
+
if (!config || typeof config.publishableKey !== "string" || !config.publishableKey.trim()) {
|
|
52
|
+
throw new Error("baclet.config.ts must export a publishableKey.");
|
|
53
|
+
}
|
|
54
|
+
const match = config.publishableKey.trim().match(/^pb_([0-9a-fA-F-]{36})_/);
|
|
55
|
+
if (!match) {
|
|
56
|
+
throw new Error("Invalid BACLET publishable key. Expected pb_<uuid>_... from your project API Keys page.");
|
|
57
|
+
}
|
|
58
|
+
const projectId = match[1];
|
|
59
|
+
const patterns = Array.isArray(config.schema?.models)
|
|
60
|
+
? config.schema.models
|
|
61
|
+
: [config.schema?.models].filter(Boolean);
|
|
62
|
+
if (!patterns.length) throw new Error("baclet.config.ts must define schema.models.");
|
|
63
|
+
|
|
64
|
+
const files = await fg(patterns, { cwd: root, absolute: true, onlyFiles: true });
|
|
65
|
+
if (!files.length) throw new Error(`No model files matched ${patterns.join(", ")}.`);
|
|
66
|
+
|
|
67
|
+
const entry = files.map((file, index) => `export * as model_${index} from ${JSON.stringify(file)};`).join("\n");
|
|
68
|
+
const modelsOut = path.join(temp, "models.mjs");
|
|
69
|
+
await build({
|
|
70
|
+
stdin: { contents: entry, resolveDir: root, sourcefile: "baclet-models.ts", loader: "ts" },
|
|
71
|
+
bundle: true,
|
|
72
|
+
format: "esm",
|
|
73
|
+
platform: "node",
|
|
74
|
+
target: "node18",
|
|
75
|
+
outfile: modelsOut,
|
|
76
|
+
logLevel: "silent",
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
const namespace = await import(pathToFileURL(modelsOut).href);
|
|
80
|
+
const models = [];
|
|
81
|
+
const seen = new Set();
|
|
82
|
+
for (const module of Object.values(namespace)) {
|
|
83
|
+
for (const value of Object.values(module)) {
|
|
84
|
+
if (!isModel(value)) continue;
|
|
85
|
+
if (seen.has(value.name)) throw new Error(`Duplicate model name "${value.name}".`);
|
|
86
|
+
seen.add(value.name);
|
|
87
|
+
models.push(value);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
if (!models.length) throw new Error("No models found. Export defineModel(...) objects from your model files.");
|
|
91
|
+
|
|
92
|
+
return { config, models, root, projectId };
|
|
93
|
+
} finally {
|
|
94
|
+
await rm(temp, { recursive: true, force: true });
|
|
95
|
+
}
|
|
96
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { mkdtemp, mkdir, writeFile, stat, rm } from "node:fs/promises";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import test from "node:test";
|
|
6
|
+
import { loadProject } from "./config.js";
|
|
7
|
+
|
|
8
|
+
test("loadProject bundles config and model files", async () => {
|
|
9
|
+
const dir = await mkdtemp(path.join(os.tmpdir(), "baclet-test-"));
|
|
10
|
+
try {
|
|
11
|
+
await mkdir(path.join(dir, "models"), { recursive: true });
|
|
12
|
+
await writeFile(path.join(dir, "baclet.config.ts"), `export default { publishableKey: "pb_45a8d1b2-3da5-4e1a-9435-ec40b58ee68b_demo", schema: { models: "./models/*.js" } };`);
|
|
13
|
+
await writeFile(path.join(dir, "models", "product.js"), `export const Product = { name: "products", fields: { name: { type: "string" } } };`);
|
|
14
|
+
const project = await loadProject(dir);
|
|
15
|
+
assert.equal(project.config.publishableKey, "pb_45a8d1b2-3da5-4e1a-9435-ec40b58ee68b_demo");
|
|
16
|
+
assert.equal(project.projectId, "45a8d1b2-3da5-4e1a-9435-ec40b58ee68b");
|
|
17
|
+
assert.equal(project.models.length, 1);
|
|
18
|
+
assert.equal(project.models[0].name, "products");
|
|
19
|
+
} finally {
|
|
20
|
+
await rm(dir, { recursive: true, force: true });
|
|
21
|
+
}
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
test("loadProject rejects an invalid publishable key", async () => {
|
|
25
|
+
const dir = await mkdtemp(path.join(os.tmpdir(), "baclet-test-"));
|
|
26
|
+
try {
|
|
27
|
+
await writeFile(path.join(dir, "baclet.config.ts"), `export default { publishableKey: "not-a-key", schema: { models: "./models/*.js" } };`);
|
|
28
|
+
await assert.rejects(() => loadProject(dir), /Invalid BACLET publishable key/);
|
|
29
|
+
} finally {
|
|
30
|
+
await rm(dir, { recursive: true, force: true });
|
|
31
|
+
}
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
test("credentials are written with owner-only permissions", async () => {
|
|
35
|
+
const dir = await mkdtemp(path.join(os.tmpdir(), "baclet-test-"));
|
|
36
|
+
const previous = process.env.XDG_CONFIG_HOME;
|
|
37
|
+
process.env.XDG_CONFIG_HOME = dir;
|
|
38
|
+
try {
|
|
39
|
+
const suffix = `?test=${Date.now()}`;
|
|
40
|
+
const paths = await import(`./paths.js${suffix}`);
|
|
41
|
+
const credentials = await import(`./credentials.js${suffix}`);
|
|
42
|
+
await credentials.saveCredentials({ accessToken: "token", user: { email: "a@example.com" } });
|
|
43
|
+
const info = await stat(paths.credentialsFile);
|
|
44
|
+
assert.equal(info.mode & 0o777, 0o600);
|
|
45
|
+
assert.equal((await credentials.loadCredentials()).accessToken, "token");
|
|
46
|
+
await credentials.clearCredentials();
|
|
47
|
+
assert.equal(await credentials.loadCredentials(), null);
|
|
48
|
+
} finally {
|
|
49
|
+
if (previous === undefined) delete process.env.XDG_CONFIG_HOME;
|
|
50
|
+
else process.env.XDG_CONFIG_HOME = previous;
|
|
51
|
+
await rm(dir, { recursive: true, force: true });
|
|
52
|
+
}
|
|
53
|
+
});
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { mkdir, readFile, rename, rm, writeFile, chmod } from "node:fs/promises";
|
|
2
|
+
import { configDir, credentialsFile } from "./paths.js";
|
|
3
|
+
|
|
4
|
+
export async function loadCredentials() {
|
|
5
|
+
try {
|
|
6
|
+
const raw = await readFile(credentialsFile, "utf8");
|
|
7
|
+
const data = JSON.parse(raw);
|
|
8
|
+
if (!data || typeof data.accessToken !== "string" || !data.accessToken) return null;
|
|
9
|
+
return data;
|
|
10
|
+
} catch {
|
|
11
|
+
return null;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export async function requireCredentials() {
|
|
16
|
+
const creds = await loadCredentials();
|
|
17
|
+
if (!creds) throw new Error("You are not logged in. Run `baclet login` first.");
|
|
18
|
+
return creds;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export async function saveCredentials(data) {
|
|
22
|
+
await mkdir(configDir, { recursive: true, mode: 0o700 });
|
|
23
|
+
const temp = `${credentialsFile}.${process.pid}.${Date.now()}.tmp`;
|
|
24
|
+
await writeFile(temp, JSON.stringify(data, null, 2), { mode: 0o600 });
|
|
25
|
+
await chmod(temp, 0o600);
|
|
26
|
+
await rename(temp, credentialsFile);
|
|
27
|
+
await chmod(credentialsFile, 0o600);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export async function clearCredentials() {
|
|
31
|
+
await rm(credentialsFile, { force: true });
|
|
32
|
+
}
|
package/src/http.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
export class APIError extends Error {
|
|
2
|
+
constructor(status, message, data) {
|
|
3
|
+
super(message);
|
|
4
|
+
this.name = "APIError";
|
|
5
|
+
this.status = status;
|
|
6
|
+
this.data = data;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function apiUrl() {
|
|
11
|
+
return (process.env.BACLET_API_URL || "https://api.baclet.com").replace(/\/$/, "");
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function dashboardUrl() {
|
|
15
|
+
return (process.env.BACLET_DASHBOARD_URL || "https://app.baclet.com").replace(/\/$/, "");
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export async function request({ method = "GET", path, body, token } = {}) {
|
|
19
|
+
const headers = { Accept: "application/json" };
|
|
20
|
+
if (body !== undefined) headers["Content-Type"] = "application/json";
|
|
21
|
+
if (token) headers.Authorization = `Bearer ${token}`;
|
|
22
|
+
|
|
23
|
+
let response;
|
|
24
|
+
try {
|
|
25
|
+
response = await fetch(`${apiUrl()}${path}`, {
|
|
26
|
+
method,
|
|
27
|
+
headers,
|
|
28
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
29
|
+
});
|
|
30
|
+
} catch (error) {
|
|
31
|
+
throw new Error(`Could not reach BACLET at ${apiUrl()}: ${error.message}`);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const text = await response.text();
|
|
35
|
+
let data = null;
|
|
36
|
+
if (text) {
|
|
37
|
+
try {
|
|
38
|
+
data = JSON.parse(text);
|
|
39
|
+
} catch {
|
|
40
|
+
data = null;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
if (!response.ok) {
|
|
44
|
+
const message = data?.error?.message || data?.message || text || response.statusText;
|
|
45
|
+
throw new APIError(response.status, message, data);
|
|
46
|
+
}
|
|
47
|
+
return data;
|
|
48
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { login, logout, whoami } from "./commands/auth.js";
|
|
3
|
+
import { init, listProjects, dbStatus, dbPush } from "./commands/project.js";
|
|
4
|
+
|
|
5
|
+
const help = `BACLET CLI
|
|
6
|
+
|
|
7
|
+
Usage:
|
|
8
|
+
baclet login [--qr|--link] Authorize this machine with your BACLET account
|
|
9
|
+
baclet logout Remove local credentials
|
|
10
|
+
baclet whoami Show the authorized user
|
|
11
|
+
baclet init [--publishable-key KEY] Create baclet.config.ts (selects a project when logged in)
|
|
12
|
+
baclet projects list List projects you can access
|
|
13
|
+
baclet db status Show the schema diff without applying it
|
|
14
|
+
baclet db push [--yes] Apply the schema to your project database
|
|
15
|
+
baclet db migrate [--yes] Alias for db push
|
|
16
|
+
baclet --help Show this message
|
|
17
|
+
|
|
18
|
+
Environment:
|
|
19
|
+
BACLET_API_URL API base URL (default https://api.baclet.com)
|
|
20
|
+
BACLET_DASHBOARD_URL Dashboard URL (default https://app.baclet.com)
|
|
21
|
+
`;
|
|
22
|
+
|
|
23
|
+
async function main() {
|
|
24
|
+
const [command, ...args] = process.argv.slice(2);
|
|
25
|
+
switch (command) {
|
|
26
|
+
case "login": return login(args);
|
|
27
|
+
case "logout": return logout();
|
|
28
|
+
case "whoami": return whoami();
|
|
29
|
+
case "init": return init(args);
|
|
30
|
+
case "projects":
|
|
31
|
+
if (args[0] === "list") return listProjects();
|
|
32
|
+
throw new Error("Usage: baclet projects list");
|
|
33
|
+
case "db":
|
|
34
|
+
if (args[0] === "status") return dbStatus();
|
|
35
|
+
if (args[0] === "push" || args[0] === "migrate") return dbPush(args.slice(1));
|
|
36
|
+
throw new Error("Usage: baclet db status|push|migrate");
|
|
37
|
+
case "--help":
|
|
38
|
+
case "-h":
|
|
39
|
+
case undefined:
|
|
40
|
+
process.stdout.write(help);
|
|
41
|
+
return;
|
|
42
|
+
default:
|
|
43
|
+
throw new Error(`Unknown command "${command}". Run \`baclet --help\`.`);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
main().catch((error) => {
|
|
48
|
+
console.error(`error: ${error.message}`);
|
|
49
|
+
process.exitCode = 1;
|
|
50
|
+
});
|
package/src/paths.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import os from "node:os";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
|
|
4
|
+
const root = process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");
|
|
5
|
+
|
|
6
|
+
export const configDir = path.join(root, "baclet");
|
|
7
|
+
export const credentialsFile = path.join(configDir, "credentials.json");
|