@alori/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 +16 -2
- package/bin/alori.mjs +67 -0
- package/lib/auth.mjs +197 -0
- package/lib/folder.mjs +65 -0
- package/lib/guide.mjs +34 -0
- package/lib/sync.mjs +232 -0
- package/package.json +25 -4
package/README.md
CHANGED
|
@@ -1,3 +1,17 @@
|
|
|
1
|
-
#
|
|
1
|
+
# alori
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Build your Alori app with your own Claude Code.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npm install -g @alori/cli # once
|
|
7
|
+
alori login # connect this computer to your Alori account
|
|
8
|
+
alori pull my-app # download your app's code
|
|
9
|
+
cd my-app && pnpm install
|
|
10
|
+
claude # change it with Claude Code
|
|
11
|
+
alori push -m "New pricing page"
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
Alori builds each push, shows it in your workspace preview and saves it as a version. Publish it from Alori when it
|
|
15
|
+
looks right. How it works: `docs/CLAUDE_CODE.md` in Alori's repository.
|
|
16
|
+
|
|
17
|
+
No dependencies; Node 20 or newer, and `tar`.
|
package/bin/alori.mjs
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* `alori`: build your Alori app with your own Claude Code. Pull its code into a folder, change it, push it back:
|
|
4
|
+
* Alori builds it, deploys it to the preview and saves it as a version, with no AI from Alori.
|
|
5
|
+
*/
|
|
6
|
+
import { resolve } from "node:path";
|
|
7
|
+
import { apiBase, call, forget, login, SignedOut } from "../lib/auth.mjs";
|
|
8
|
+
import { pull, push, status } from "../lib/sync.mjs";
|
|
9
|
+
|
|
10
|
+
const help = `alori: build your Alori app with Claude Code
|
|
11
|
+
|
|
12
|
+
alori login Connect this computer to your Alori account
|
|
13
|
+
alori pull [folder] Download your app's code (or bring the latest into a pulled folder)
|
|
14
|
+
alori status What changed since the last pull or push
|
|
15
|
+
alori push -m "message" Send your changes: Alori builds them and saves a new version
|
|
16
|
+
alori whoami Which app you're connected to
|
|
17
|
+
alori logout Forget this computer's sign-in
|
|
18
|
+
|
|
19
|
+
Set ALORI_API to use another Alori than ${apiBase()}.`;
|
|
20
|
+
|
|
21
|
+
function messageOf(args) {
|
|
22
|
+
const index = args.findIndex((arg) => arg === "-m" || arg === "--message");
|
|
23
|
+
return index >= 0 ? args[index + 1] : undefined;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async function main() {
|
|
27
|
+
const [command, ...args] = process.argv.slice(2);
|
|
28
|
+
switch (command) {
|
|
29
|
+
case "login": {
|
|
30
|
+
await login();
|
|
31
|
+
const me = await call("/code/me");
|
|
32
|
+
if (!me.ok) {
|
|
33
|
+
console.log(me.body?.error === "cantBuild" ? "Connected, but your role doesn't build this app." : "Connected.");
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
console.log(`Connected to ${me.body.app} as ${me.body.email ?? "you"}. Next: alori pull <folder>`);
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
case "logout":
|
|
40
|
+
forget();
|
|
41
|
+
console.log("Signed out on this computer.");
|
|
42
|
+
return;
|
|
43
|
+
case "whoami": {
|
|
44
|
+
const me = await call("/code/me");
|
|
45
|
+
if (!me.ok) throw Object.assign(new Error(me.body?.error === "cantBuild" ? "Your role doesn't build this app." : "Run: alori login"), { plain: true });
|
|
46
|
+
console.log(`${me.body.app} (version ${me.body.version ?? "none"}), signed in as ${me.body.email ?? "you"}.`);
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
case "pull":
|
|
50
|
+
await pull(resolve(args.find((arg) => !arg.startsWith("-")) ?? "."));
|
|
51
|
+
return;
|
|
52
|
+
case "status":
|
|
53
|
+
status(resolve("."));
|
|
54
|
+
return;
|
|
55
|
+
case "push":
|
|
56
|
+
await push(resolve("."), messageOf(args));
|
|
57
|
+
return;
|
|
58
|
+
default:
|
|
59
|
+
console.log(help);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
main().catch((error) => {
|
|
64
|
+
if (error instanceof SignedOut || error?.plain) console.error(error.message);
|
|
65
|
+
else console.error(error);
|
|
66
|
+
process.exit(1);
|
|
67
|
+
});
|
package/lib/auth.mjs
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Signing in to Alori the way Claude does (apps/platform/convex/mcp/oauth.ts): the command registers as "Alori CLI",
|
|
3
|
+
* opens the Allow screen in the browser, catches the code on this computer, and trades it for tokens. The tokens are
|
|
4
|
+
* kept in ~/.alori/credentials.json (readable by this user only), one entry per Alori address.
|
|
5
|
+
*/
|
|
6
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
7
|
+
import { spawn } from "node:child_process";
|
|
8
|
+
import { mkdirSync, readFileSync, writeFileSync, chmodSync, existsSync } from "node:fs";
|
|
9
|
+
import { createServer } from "node:http";
|
|
10
|
+
import { homedir } from "node:os";
|
|
11
|
+
import { join } from "node:path";
|
|
12
|
+
|
|
13
|
+
/** The name the platform knows the command by (`codeClientName` in convex/lib/mcp/oauth.ts). */
|
|
14
|
+
const clientName = "Alori CLI";
|
|
15
|
+
const credentialsFile = join(homedir(), ".alori", "credentials.json");
|
|
16
|
+
|
|
17
|
+
/** Where Alori answers: production, unless ALORI_API names another (a dev deployment's `.convex.site`). */
|
|
18
|
+
export function apiBase() {
|
|
19
|
+
return (process.env.ALORI_API || "https://api.alori.dev").replace(/\/+$/, "");
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function readAll() {
|
|
23
|
+
if (!existsSync(credentialsFile)) return {};
|
|
24
|
+
try {
|
|
25
|
+
const parsed = JSON.parse(readFileSync(credentialsFile, "utf8"));
|
|
26
|
+
return typeof parsed === "object" && parsed !== null ? parsed : {};
|
|
27
|
+
} catch {
|
|
28
|
+
return {};
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function writeAll(all) {
|
|
33
|
+
mkdirSync(join(homedir(), ".alori"), { recursive: true, mode: 0o700 });
|
|
34
|
+
writeFileSync(credentialsFile, `${JSON.stringify(all, null, 2)}\n`, { mode: 0o600 });
|
|
35
|
+
chmodSync(credentialsFile, 0o600);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function saved() {
|
|
39
|
+
const entry = readAll()[apiBase()];
|
|
40
|
+
return entry && typeof entry.accessToken === "string" && typeof entry.refreshToken === "string" && typeof entry.clientId === "string" ? entry : null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function save(entry) {
|
|
44
|
+
const all = readAll();
|
|
45
|
+
all[apiBase()] = entry;
|
|
46
|
+
writeAll(all);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function forget() {
|
|
50
|
+
const all = readAll();
|
|
51
|
+
delete all[apiBase()];
|
|
52
|
+
writeAll(all);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const base64Url = (buffer) => buffer.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
56
|
+
|
|
57
|
+
function openBrowser(url) {
|
|
58
|
+
const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
|
|
59
|
+
const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
|
|
60
|
+
try {
|
|
61
|
+
spawn(command, args, { stdio: "ignore", detached: true }).unref();
|
|
62
|
+
} catch {
|
|
63
|
+
// The link is printed too.
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function postForm(url, fields) {
|
|
68
|
+
const response = await fetch(url, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams(fields).toString() });
|
|
69
|
+
const body = await response.json().catch(() => ({}));
|
|
70
|
+
return { ok: response.ok, body };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function tokensEntry(clientId, body) {
|
|
74
|
+
return {
|
|
75
|
+
clientId,
|
|
76
|
+
accessToken: body.access_token,
|
|
77
|
+
refreshToken: body.refresh_token,
|
|
78
|
+
expiresAt: Date.now() + (Number(body.expires_in) || 3600) * 1000,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Listens on this computer for the Allow screen to send the browser back. Answers the port it took and the code it
|
|
84
|
+
* will receive.
|
|
85
|
+
*/
|
|
86
|
+
async function callbackServer(state) {
|
|
87
|
+
let settle;
|
|
88
|
+
const code = new Promise((resolve, reject) => (settle = { resolve, reject }));
|
|
89
|
+
const server = createServer((request, response) => {
|
|
90
|
+
const url = new URL(request.url ?? "/", "http://127.0.0.1");
|
|
91
|
+
if (url.pathname !== "/callback") {
|
|
92
|
+
response.writeHead(404).end();
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
const received = url.searchParams.get("code");
|
|
96
|
+
const ok = Boolean(received) && url.searchParams.get("state") === state;
|
|
97
|
+
response.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
|
98
|
+
response.end(
|
|
99
|
+
`<!doctype html><meta charset="utf-8"><title>Alori</title><body style="font-family:system-ui;display:grid;place-items:center;height:90vh"><p>${
|
|
100
|
+
ok ? "Connected. You can close this tab and go back to your terminal." : "That didn't work. Run alori login again."
|
|
101
|
+
}</p></body>`,
|
|
102
|
+
);
|
|
103
|
+
server.close();
|
|
104
|
+
if (ok) settle.resolve(received);
|
|
105
|
+
else settle.reject(new Error(url.searchParams.get("error") === "access_denied" ? "You cancelled the connection." : "The sign-in didn't come back right."));
|
|
106
|
+
});
|
|
107
|
+
const port = await new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve(server.address().port)));
|
|
108
|
+
return { port, code };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Signs in through the browser and keeps the tokens. */
|
|
112
|
+
export async function login() {
|
|
113
|
+
const api = apiBase();
|
|
114
|
+
const discovery = await fetch(`${api}/.well-known/oauth-authorization-server`).then((response) => response.json());
|
|
115
|
+
const state = base64Url(randomBytes(16));
|
|
116
|
+
const verifier = base64Url(randomBytes(32));
|
|
117
|
+
const challenge = base64Url(createHash("sha256").update(verifier).digest());
|
|
118
|
+
|
|
119
|
+
const { port, code: codePromise } = await callbackServer(state);
|
|
120
|
+
const redirectUri = `http://127.0.0.1:${port}/callback`;
|
|
121
|
+
|
|
122
|
+
const registered = await fetch(discovery.registration_endpoint, {
|
|
123
|
+
method: "POST",
|
|
124
|
+
headers: { "Content-Type": "application/json" },
|
|
125
|
+
body: JSON.stringify({ client_name: clientName, redirect_uris: [redirectUri] }),
|
|
126
|
+
}).then((response) => response.json());
|
|
127
|
+
if (!registered.client_id) throw new Error("Alori didn't accept the sign-in. Try again.");
|
|
128
|
+
|
|
129
|
+
const allow = new URL(discovery.authorization_endpoint);
|
|
130
|
+
for (const [key, value] of Object.entries({
|
|
131
|
+
response_type: "code",
|
|
132
|
+
client_id: registered.client_id,
|
|
133
|
+
redirect_uri: redirectUri,
|
|
134
|
+
code_challenge: challenge,
|
|
135
|
+
code_challenge_method: "S256",
|
|
136
|
+
state,
|
|
137
|
+
})) {
|
|
138
|
+
allow.searchParams.set(key, value);
|
|
139
|
+
}
|
|
140
|
+
// On a machine with no browser of its own (SSH), ALORI_NO_BROWSER=1 only prints the link.
|
|
141
|
+
const opens = process.env.ALORI_NO_BROWSER !== "1";
|
|
142
|
+
console.log(opens ? "Opening your browser to connect Alori. If it doesn't open, go to:" : "Open this link to connect Alori:");
|
|
143
|
+
console.log(` ${allow}`);
|
|
144
|
+
if (opens) openBrowser(allow.toString());
|
|
145
|
+
|
|
146
|
+
const code = await codePromise;
|
|
147
|
+
const answer = await postForm(discovery.token_endpoint, {
|
|
148
|
+
grant_type: "authorization_code",
|
|
149
|
+
code,
|
|
150
|
+
client_id: registered.client_id,
|
|
151
|
+
redirect_uri: redirectUri,
|
|
152
|
+
code_verifier: verifier,
|
|
153
|
+
});
|
|
154
|
+
if (!answer.ok || !answer.body.access_token) throw new Error("Alori didn't give a sign-in. Run alori login again.");
|
|
155
|
+
save({ ...tokensEntry(registered.client_id, answer.body), tokenEndpoint: discovery.token_endpoint });
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** A fresh access token, renewing it when it is about to end. Null when signed out. */
|
|
159
|
+
async function accessToken({ renew = false } = {}) {
|
|
160
|
+
const entry = saved();
|
|
161
|
+
if (!entry) return null;
|
|
162
|
+
if (!renew && entry.expiresAt > Date.now() + 60_000) return entry.accessToken;
|
|
163
|
+
const answer = await postForm(entry.tokenEndpoint ?? `${apiBase()}/oauth/token`, { grant_type: "refresh_token", refresh_token: entry.refreshToken, client_id: entry.clientId });
|
|
164
|
+
if (!answer.ok || !answer.body.access_token) {
|
|
165
|
+
forget();
|
|
166
|
+
return null;
|
|
167
|
+
}
|
|
168
|
+
save({ ...tokensEntry(entry.clientId, answer.body), tokenEndpoint: entry.tokenEndpoint });
|
|
169
|
+
return answer.body.access_token;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export class SignedOut extends Error {
|
|
173
|
+
constructor() {
|
|
174
|
+
super("You're not signed in. Run: alori login");
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Calls Alori's code routes as the signed-in person. Renews the token once on a 401. */
|
|
179
|
+
export async function call(path, { method = "GET", body } = {}) {
|
|
180
|
+
for (const renew of [false, true]) {
|
|
181
|
+
const token = await accessToken({ renew });
|
|
182
|
+
if (!token) throw new SignedOut();
|
|
183
|
+
const response = await fetch(`${apiBase()}${path}`, {
|
|
184
|
+
method,
|
|
185
|
+
headers: { Authorization: `Bearer ${token}`, ...(body === undefined ? {} : { "Content-Type": "application/json" }) },
|
|
186
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
187
|
+
});
|
|
188
|
+
if (response.status === 401 && !renew) continue;
|
|
189
|
+
if (response.status === 401) {
|
|
190
|
+
forget();
|
|
191
|
+
throw new SignedOut();
|
|
192
|
+
}
|
|
193
|
+
const answer = await response.json().catch(() => ({}));
|
|
194
|
+
return { status: response.status, ok: response.ok, body: answer };
|
|
195
|
+
}
|
|
196
|
+
throw new SignedOut();
|
|
197
|
+
}
|
package/lib/folder.mjs
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The pulled folder: which of its files are the app's code, and the snapshot of them as they were at the last pull or
|
|
3
|
+
* push (`.alori/state.json`), which tells what changed since.
|
|
4
|
+
*/
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
6
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { join, relative, sep } from "node:path";
|
|
8
|
+
|
|
9
|
+
export const stateDir = ".alori";
|
|
10
|
+
const stateFile = join(stateDir, "state.json");
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* The app's own code lives under `src/` and `convex/`. Generated files never travel: Alori writes them on each build.
|
|
14
|
+
* Everything else (package.json, vite.config.ts, public/) is Alori's template and comes fresh with each pull.
|
|
15
|
+
*/
|
|
16
|
+
export function isAppCode(path) {
|
|
17
|
+
return (path.startsWith("src/") || path.startsWith("convex/")) && !path.startsWith("convex/_generated/") && path !== "src/routeTree.gen.ts" && !path.endsWith(".alori-theirs");
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const skipped = new Set(["node_modules", ".git", stateDir, "dist", ".output", ".tanstack", ".vercel", ".DS_Store"]);
|
|
21
|
+
|
|
22
|
+
/** Every file under `dir`, as paths with forward slashes. */
|
|
23
|
+
export function walk(dir, under = dir) {
|
|
24
|
+
if (!existsSync(dir)) return [];
|
|
25
|
+
return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
|
|
26
|
+
if (skipped.has(entry.name)) return [];
|
|
27
|
+
const path = join(dir, entry.name);
|
|
28
|
+
if (entry.isDirectory()) return walk(path, under);
|
|
29
|
+
if (!entry.isFile()) return [];
|
|
30
|
+
return [relative(under, path).split(sep).join("/")];
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export const hashOf = (content) => createHash("sha256").update(content).digest("hex");
|
|
35
|
+
|
|
36
|
+
/** The app's code in `dir`, by path, with each file's hash. */
|
|
37
|
+
export function codeHashes(dir) {
|
|
38
|
+
const hashes = {};
|
|
39
|
+
for (const path of walk(dir).filter(isAppCode)) hashes[path] = hashOf(readFileSync(join(dir, path)));
|
|
40
|
+
return hashes;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function readState(dir) {
|
|
44
|
+
const file = join(dir, stateFile);
|
|
45
|
+
if (!existsSync(file)) return null;
|
|
46
|
+
try {
|
|
47
|
+
const state = JSON.parse(readFileSync(file, "utf8"));
|
|
48
|
+
return typeof state.version === "number" && typeof state.hashes === "object" ? state : null;
|
|
49
|
+
} catch {
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function writeState(dir, state) {
|
|
55
|
+
mkdirSync(join(dir, stateDir), { recursive: true });
|
|
56
|
+
writeFileSync(join(dir, stateFile), `${JSON.stringify(state, null, 2)}\n`);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** What changed in `dir` since its snapshot: files changed or added, and files removed. */
|
|
60
|
+
export function changesOf(dir, state) {
|
|
61
|
+
const now = codeHashes(dir);
|
|
62
|
+
const changed = Object.keys(now).filter((path) => now[path] !== state.hashes[path]).sort();
|
|
63
|
+
const deleted = Object.keys(state.hashes).filter((path) => !(path in now)).sort();
|
|
64
|
+
return { changed, deleted, now };
|
|
65
|
+
}
|
package/lib/guide.mjs
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/** The CLAUDE.md a pull writes at the folder's root, so Claude Code knows how this folder works. */
|
|
2
|
+
export function claudeGuide(app) {
|
|
3
|
+
return `# ${app}: an Alori app
|
|
4
|
+
|
|
5
|
+
This folder is the code of ${app}, pulled from Alori with the \`alori\` command. Change it here, then send the changes back
|
|
6
|
+
with \`alori push\`. Alori builds them, deploys them, and shows them in the workspace preview. Publish stays in Alori.
|
|
7
|
+
|
|
8
|
+
## Rules
|
|
9
|
+
|
|
10
|
+
- **Only \`src/\` and \`convex/\` travel.** Everything else (package.json, vite.config.ts, public/) is Alori's template and
|
|
11
|
+
comes back fresh with each pull, so a change there is lost.
|
|
12
|
+
- **Some files under \`src/\` and \`convex/\` are Alori's too** (the platform-owned files: the shell, auth, booking, Team chat,
|
|
13
|
+
the schema files under \`convex/schema/\` and more). They are here so the code typechecks. \`alori push\` refuses a change
|
|
14
|
+
to one of them and names it: put the change in the app's own files instead (for tables, \`convex/schema.ts\`).
|
|
15
|
+
- **The backend is live.** The app has one Convex deployment with real data. A pushed change to \`convex/\` reaches it at once,
|
|
16
|
+
even before Publish. Never drop a table or a field that holds data.
|
|
17
|
+
- \`convex/_generated/\` and \`src/routeTree.gen.ts\` are generated: never edit them.
|
|
18
|
+
|
|
19
|
+
## Commands
|
|
20
|
+
|
|
21
|
+
\`\`\`bash
|
|
22
|
+
pnpm install # once, after a pull
|
|
23
|
+
pnpm typecheck # before each push
|
|
24
|
+
pnpm lint
|
|
25
|
+
alori status # what changed since the last pull or push
|
|
26
|
+
alori push -m "What changed, in one line"
|
|
27
|
+
alori pull # brings changes saved since (the builder's, a teammate's), keeping yours
|
|
28
|
+
\`\`\`
|
|
29
|
+
|
|
30
|
+
A push that someone else's change overlaps (the same file, saved since your pull) is refused: run \`alori pull\`, which
|
|
31
|
+
keeps your changes and writes their version beside each overlapping file as \`<file>.alori-theirs\`. Merge them, delete the
|
|
32
|
+
\`.alori-theirs\` files, then push again.
|
|
33
|
+
`;
|
|
34
|
+
}
|
package/lib/sync.mjs
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `alori pull` and `alori push` (apps/platform/convex/codeSync/http.ts). A pull packs the app's latest saved code on
|
|
3
|
+
* Alori's build machine and unpacks it here; a push sends the files changed since, which Alori builds, deploys to
|
|
4
|
+
* the preview and saves as a new version.
|
|
5
|
+
*/
|
|
6
|
+
import { execFileSync } from "node:child_process";
|
|
7
|
+
import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
|
|
8
|
+
import { tmpdir } from "node:os";
|
|
9
|
+
import { dirname, join } from "node:path";
|
|
10
|
+
import { apiBase, call } from "./auth.mjs";
|
|
11
|
+
import { changesOf, codeHashes, isAppCode, readState, stateDir, walk, writeState } from "./folder.mjs";
|
|
12
|
+
import { claudeGuide } from "./guide.mjs";
|
|
13
|
+
|
|
14
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
15
|
+
|
|
16
|
+
const errors = {
|
|
17
|
+
signIn: "You're not signed in. Run: alori login",
|
|
18
|
+
notCodeClient: "This sign-in can't change code. Run: alori login",
|
|
19
|
+
cantBuild: "Your role in this app doesn't build it. Ask an admin to change your role.",
|
|
20
|
+
noApp: "Your Alori account has no app yet.",
|
|
21
|
+
rateLimited: "Too many calls in a minute. Wait a moment and try again.",
|
|
22
|
+
noCode: "This app has no saved code yet.",
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
function fail(message) {
|
|
26
|
+
const error = new Error(message);
|
|
27
|
+
error.plain = true;
|
|
28
|
+
throw error;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function failOn(answer) {
|
|
32
|
+
fail(errors[answer.body?.error] ?? `Alori answered ${answer.status}: ${JSON.stringify(answer.body)}`);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Packs the app's latest code on Alori and unpacks it into a new temporary folder. */
|
|
36
|
+
async function download() {
|
|
37
|
+
const started = await call("/code/pull", { method: "POST" });
|
|
38
|
+
if (!started.ok) failOn(started);
|
|
39
|
+
process.stdout.write("Packing your app's code");
|
|
40
|
+
const until = Date.now() + 10 * 60_000;
|
|
41
|
+
let job;
|
|
42
|
+
for (;;) {
|
|
43
|
+
await sleep(2000);
|
|
44
|
+
process.stdout.write(".");
|
|
45
|
+
const answer = await call(`/code/pull?job=${encodeURIComponent(started.body.jobId)}`);
|
|
46
|
+
if (!answer.ok) failOn(answer);
|
|
47
|
+
job = answer.body;
|
|
48
|
+
if (job.status === "succeeded" || job.status === "failed") break;
|
|
49
|
+
if (Date.now() > until) fail("\nPacking took too long. Try again.");
|
|
50
|
+
}
|
|
51
|
+
process.stdout.write("\n");
|
|
52
|
+
if (job.status === "failed" || !job.url || typeof job.version !== "number") fail(`Packing failed. Try again.${job.log ? `\n${job.log.slice(-2000)}` : ""}`);
|
|
53
|
+
const temp = mkdtempSync(join(tmpdir(), "alori-pull-"));
|
|
54
|
+
const tarball = join(temp, "code.tar.gz");
|
|
55
|
+
const response = await fetch(job.url);
|
|
56
|
+
if (!response.ok) fail("The download failed. Try again.");
|
|
57
|
+
writeFileSync(tarball, Buffer.from(await response.arrayBuffer()));
|
|
58
|
+
const folder = join(temp, "code");
|
|
59
|
+
mkdirSync(folder);
|
|
60
|
+
execFileSync("tar", ["-xzf", tarball, "-C", folder]);
|
|
61
|
+
unlinkSync(tarball);
|
|
62
|
+
return { folder, temp, version: job.version };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The template's own notes for Alori's developers: the folder gets the owner's guide (`guide.mjs`) instead. */
|
|
66
|
+
const templateNotes = new Set(["CLAUDE.md", "AGENTS.md"]);
|
|
67
|
+
|
|
68
|
+
function copyInto(from, to, path) {
|
|
69
|
+
mkdirSync(dirname(join(to, path)), { recursive: true });
|
|
70
|
+
copyFileSync(join(from, path), join(to, path));
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const ignoreFile = `node_modules/
|
|
74
|
+
${stateDir}/
|
|
75
|
+
dist/
|
|
76
|
+
.output/
|
|
77
|
+
.tanstack/
|
|
78
|
+
.env*
|
|
79
|
+
*.alori-theirs
|
|
80
|
+
`;
|
|
81
|
+
|
|
82
|
+
/** A first pull into an empty folder. */
|
|
83
|
+
async function pullFresh(dir, me) {
|
|
84
|
+
const { folder, temp, version } = await download();
|
|
85
|
+
mkdirSync(dir, { recursive: true });
|
|
86
|
+
for (const path of walk(folder).filter((path) => !templateNotes.has(path))) copyInto(folder, dir, path);
|
|
87
|
+
rmSync(temp, { recursive: true, force: true });
|
|
88
|
+
writeFileSync(join(dir, "CLAUDE.md"), claudeGuide(me.app));
|
|
89
|
+
if (!existsSync(join(dir, ".gitignore"))) writeFileSync(join(dir, ".gitignore"), ignoreFile);
|
|
90
|
+
writeState(dir, { api: apiBase(), appId: me.appId, app: me.app, version, hashes: codeHashes(dir) });
|
|
91
|
+
console.log(`Pulled ${me.app}, version ${version}, into ${dir}`);
|
|
92
|
+
console.log("Next: pnpm install, then change it with Claude Code, then: alori push -m \"what changed\"");
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* A pull into a folder already pulled: Alori's latest code comes in, and the person's changes stay. A file both sides
|
|
97
|
+
* changed keeps the person's version and gets Alori's beside it as `<file>.alori-theirs`.
|
|
98
|
+
*/
|
|
99
|
+
async function pullOver(dir, state, me) {
|
|
100
|
+
const { folder, temp, version } = await download();
|
|
101
|
+
const remote = codeHashes(folder);
|
|
102
|
+
const local = codeHashes(dir);
|
|
103
|
+
const overlaps = [];
|
|
104
|
+
for (const path of new Set([...Object.keys(remote), ...Object.keys(local), ...Object.keys(state.hashes)])) {
|
|
105
|
+
const base = state.hashes[path];
|
|
106
|
+
const mine = local[path];
|
|
107
|
+
const theirs = remote[path];
|
|
108
|
+
if (mine === theirs) continue;
|
|
109
|
+
if (mine === base) {
|
|
110
|
+
// Unchanged here: take Alori's.
|
|
111
|
+
if (theirs === undefined) rmSync(join(dir, path), { force: true });
|
|
112
|
+
else copyInto(folder, dir, path);
|
|
113
|
+
} else if (theirs !== base) {
|
|
114
|
+
// Changed on both sides.
|
|
115
|
+
if (theirs === undefined) overlaps.push(`${path} (removed in Alori)`);
|
|
116
|
+
else {
|
|
117
|
+
writeFileSync(join(dir, `${path}.alori-theirs`), readFileSync(join(folder, path)));
|
|
118
|
+
overlaps.push(path);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
// Alori's template files (package.json, vite.config.ts, public/…) always come fresh.
|
|
123
|
+
for (const path of walk(folder).filter((path) => !isAppCode(path) && !templateNotes.has(path))) copyInto(folder, dir, path);
|
|
124
|
+
rmSync(temp, { recursive: true, force: true });
|
|
125
|
+
writeState(dir, { api: apiBase(), appId: me.appId, app: me.app, version, hashes: remote });
|
|
126
|
+
console.log(`Pulled ${me.app}, version ${version}.`);
|
|
127
|
+
if (overlaps.length > 0) {
|
|
128
|
+
console.log("\nThese files changed both here and in Alori. Yours are kept; Alori's are beside them as .alori-theirs:");
|
|
129
|
+
for (const path of overlaps) console.log(` ${path}`);
|
|
130
|
+
console.log("Merge each one, delete the .alori-theirs files, then push.");
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async function whoAmI() {
|
|
135
|
+
const me = await call("/code/me");
|
|
136
|
+
if (!me.ok) failOn(me);
|
|
137
|
+
return me.body;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function checkSameApp(state, me) {
|
|
141
|
+
if (state.appId && state.appId !== me.appId) fail(`This folder holds ${state.app}, but you're signed in to ${me.app}. Run alori login with the right account.`);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export async function pull(dir) {
|
|
145
|
+
const me = await whoAmI();
|
|
146
|
+
const state = readState(dir);
|
|
147
|
+
if (state) {
|
|
148
|
+
checkSameApp(state, me);
|
|
149
|
+
await pullOver(dir, state, me);
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
if (existsSync(dir) && readdirSync(dir).some((name) => name !== ".DS_Store")) fail(`${dir} isn't empty. Pull into a new folder: alori pull <folder>`);
|
|
153
|
+
await pullFresh(dir, me);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export function status(dir) {
|
|
157
|
+
const state = readState(dir);
|
|
158
|
+
if (!state) fail("This folder wasn't pulled from Alori. Run: alori pull <folder>");
|
|
159
|
+
const { changed, deleted } = changesOf(dir, state);
|
|
160
|
+
console.log(`${state.app}, pulled at version ${state.version}.`);
|
|
161
|
+
if (changed.length + deleted.length === 0) {
|
|
162
|
+
console.log("Nothing changed since.");
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
for (const path of changed) console.log(` ${state.hashes[path] ? "changed" : "new "} ${path}`);
|
|
166
|
+
for (const path of deleted) console.log(` removed ${path}`);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const stageWords = {
|
|
170
|
+
checkCode: "Checking the code",
|
|
171
|
+
liveCheck: "Checking it against the live app",
|
|
172
|
+
backend: "Deploying the backend",
|
|
173
|
+
upload: "Uploading the screens",
|
|
174
|
+
openPages: "Opening the pages",
|
|
175
|
+
preview: "Updating the preview",
|
|
176
|
+
};
|
|
177
|
+
|
|
178
|
+
export async function push(dir, message) {
|
|
179
|
+
const state = readState(dir);
|
|
180
|
+
if (!state) fail("This folder wasn't pulled from Alori. Run: alori pull <folder>");
|
|
181
|
+
const leftovers = walk(dir).filter((path) => path.endsWith(".alori-theirs"));
|
|
182
|
+
if (leftovers.length > 0) fail(`Merge and delete these first:\n${leftovers.map((path) => ` ${path}`).join("\n")}`);
|
|
183
|
+
if (state.needsPull) fail("Someone else saved changes while your last push built. Run alori pull first, then push.");
|
|
184
|
+
const me = await whoAmI();
|
|
185
|
+
checkSameApp(state, me);
|
|
186
|
+
const { changed, deleted, now } = changesOf(dir, state);
|
|
187
|
+
if (changed.length + deleted.length === 0) {
|
|
188
|
+
console.log("Nothing changed since the last pull or push.");
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
const files = changed.map((path) => ({ path, content: readFileSync(join(dir, path), "utf8") }));
|
|
192
|
+
console.log(`Sending ${changed.length} changed and ${deleted.length} removed file${changed.length + deleted.length === 1 ? "" : "s"}…`);
|
|
193
|
+
const sent = await call("/code/push", { method: "POST", body: { baseVersion: state.version, message: message ?? "", files, deletedPaths: deleted } });
|
|
194
|
+
if (!sent.ok) {
|
|
195
|
+
const error = sent.body?.error;
|
|
196
|
+
if (error === "conflicts") fail(`Someone saved changes to these files since your pull:\n${sent.body.paths.map((path) => ` ${path}`).join("\n")}\nRun alori pull, merge, then push again.`);
|
|
197
|
+
if (error === "notEditable") fail(`These files are Alori's and change for every app, so they can't be pushed:\n${sent.body.paths.map((path) => ` ${path}`).join("\n")}\nPut the change in the app's own files instead.`);
|
|
198
|
+
if (error === "busy") fail("Alori is already building this app (the builder or another push). Try again in a minute.");
|
|
199
|
+
if (error === "noCredits") fail("You're out of credits. Add credits in Alori, then push again.");
|
|
200
|
+
if (error === "unknownVersion") fail("The version you pulled is gone. Run alori pull, then push again.");
|
|
201
|
+
if (error === "tooBig") fail("That's too much at once. Push fewer files at a time.");
|
|
202
|
+
failOn(sent);
|
|
203
|
+
}
|
|
204
|
+
const pushId = sent.body.pushId;
|
|
205
|
+
let shown = "";
|
|
206
|
+
for (;;) {
|
|
207
|
+
await sleep(2000);
|
|
208
|
+
const answer = await call(`/code/push?id=${encodeURIComponent(pushId)}`);
|
|
209
|
+
if (!answer.ok) failOn(answer);
|
|
210
|
+
const pushed = answer.body;
|
|
211
|
+
// A push deploys from its first moment; the build machine names a stage once it takes the job.
|
|
212
|
+
const line = pushed.stage ? (stageWords[pushed.stage] ?? "Building") : "Waiting for a build machine";
|
|
213
|
+
if (line !== shown && (pushed.status === "queued" || pushed.status === "deploying")) {
|
|
214
|
+
console.log(`${line}…`);
|
|
215
|
+
shown = line;
|
|
216
|
+
}
|
|
217
|
+
if (pushed.status === "saved") {
|
|
218
|
+
// The snapshot moves to what was just saved: only what was sent counts as Alori's now.
|
|
219
|
+
const hashes = { ...state.hashes };
|
|
220
|
+
for (const path of changed) hashes[path] = now[path];
|
|
221
|
+
for (const path of deleted) delete hashes[path];
|
|
222
|
+
// Others saved too between the pull and this save: this folder lacks their changes, so the next push pulls first.
|
|
223
|
+
writeState(dir, { ...state, version: pushed.version, hashes, ...(pushed.behind ? { needsPull: true } : {}) });
|
|
224
|
+
console.log(`Saved as version ${pushed.version}. It's in the preview: publish it in Alori when you're ready.`);
|
|
225
|
+
if (pushed.behind) console.log("Someone else saved changes since your pull too. Run alori pull to bring them here.");
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
if (pushed.status === "refused") fail(`Someone saved changes to the same files while this built: ${pushed.conflicts.join(", ")}\nNothing was saved. Run alori pull, merge, then push again.`);
|
|
229
|
+
if (pushed.status === "failed") fail(`The build failed, so nothing was saved:\n${pushed.error ?? ""}`);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
package/package.json
CHANGED
|
@@ -1,6 +1,27 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alori/cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Build your Alori app with your own Claude Code: pull its code, change it, push it back.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"alori": "bin/alori.mjs"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"bin",
|
|
11
|
+
"lib",
|
|
12
|
+
"README.md"
|
|
13
|
+
],
|
|
14
|
+
"engines": {
|
|
15
|
+
"node": ">=20"
|
|
16
|
+
},
|
|
17
|
+
"license": "UNLICENSED",
|
|
18
|
+
"publishConfig": {
|
|
19
|
+
"access": "public"
|
|
20
|
+
},
|
|
21
|
+
"homepage": "https://alori.dev",
|
|
22
|
+
"keywords": [
|
|
23
|
+
"alori",
|
|
24
|
+
"claude-code",
|
|
25
|
+
"cli"
|
|
26
|
+
]
|
|
27
|
+
}
|