@camox/cli 0.4.2 → 0.5.1

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,62 @@
1
+ #!/usr/bin/env node
2
+ import { createORPCClient } from "@orpc/client";
3
+ import { RPCLink } from "@orpc/client/fetch";
4
+ //#region src/lib/api.ts
5
+ const CAMOX_API_URL = process.env.CAMOX_API_URL || "https://api.camox.ai";
6
+ function authHeaders(token) {
7
+ return {
8
+ Authorization: `Bearer ${token}`,
9
+ "Content-Type": "application/json"
10
+ };
11
+ }
12
+ function createRpcClient(token) {
13
+ return createORPCClient(new RPCLink({
14
+ url: `${CAMOX_API_URL}/rpc`,
15
+ headers: { Authorization: `Bearer ${token}` }
16
+ }));
17
+ }
18
+ async function verifySession(token) {
19
+ return (await fetch(`${CAMOX_API_URL}/api/auth/get-session`, {
20
+ method: "GET",
21
+ headers: authHeaders(token)
22
+ })).ok;
23
+ }
24
+ async function listOrganizations(token) {
25
+ const res = await fetch(`${CAMOX_API_URL}/api/auth/organization/list`, {
26
+ method: "GET",
27
+ headers: authHeaders(token)
28
+ });
29
+ if (!res.ok) throw new Error(`Failed to list organizations: ${res.status}`);
30
+ return res.json();
31
+ }
32
+ async function createOrganization(token, name, slug) {
33
+ const res = await fetch(`${CAMOX_API_URL}/api/auth/organization/create`, {
34
+ method: "POST",
35
+ headers: authHeaders(token),
36
+ body: JSON.stringify({
37
+ name,
38
+ slug
39
+ })
40
+ });
41
+ if (!res.ok) {
42
+ const text = await res.text();
43
+ throw new Error(`Failed to create organization: ${res.status} ${text}`);
44
+ }
45
+ return res.json();
46
+ }
47
+ async function setActiveOrganization(token, organizationId) {
48
+ const res = await fetch(`${CAMOX_API_URL}/api/auth/organization/set-active`, {
49
+ method: "POST",
50
+ headers: authHeaders(token),
51
+ body: JSON.stringify({ organizationId })
52
+ });
53
+ if (!res.ok) throw new Error(`Failed to set active organization: ${res.status}`);
54
+ }
55
+ async function createProject(token, name, organizationId) {
56
+ return await createRpcClient(token).projects.create({
57
+ name,
58
+ organizationId
59
+ });
60
+ }
61
+ //#endregion
62
+ export { verifySession as a, setActiveOrganization as i, createProject as n, listOrganizations as r, createOrganization as t };
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import { a as verifySession } from "./api-57fjJbHn.mjs";
3
+ export { verifySession };
package/dist/index.mjs ADDED
@@ -0,0 +1,441 @@
1
+ #!/usr/bin/env node
2
+ import { i as setActiveOrganization, n as createProject, r as listOrganizations, t as createOrganization } from "./api-57fjJbHn.mjs";
3
+ import { object, or } from "@optique/core/constructs";
4
+ import { message } from "@optique/core/message";
5
+ import { defineProgram } from "@optique/core/program";
6
+ import { run } from "@optique/run";
7
+ import { execSync, spawn, spawnSync } from "node:child_process";
8
+ import fs from "node:fs";
9
+ import path from "node:path";
10
+ import { fileURLToPath } from "node:url";
11
+ import * as p from "@clack/prompts";
12
+ import { command, constant } from "@optique/core/primitives";
13
+ import http from "node:http";
14
+ import os from "node:os";
15
+ //#region \0rolldown/runtime.js
16
+ var __defProp = Object.defineProperty;
17
+ var __exportAll = (all, no_symbols) => {
18
+ let target = {};
19
+ for (var name in all) __defProp(target, name, {
20
+ get: all[name],
21
+ enumerable: true
22
+ });
23
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
24
+ return target;
25
+ };
26
+ //#endregion
27
+ //#region src/lib/auth.ts
28
+ const CAMOX_URL = process.env.CAMOX_URL || "https://camox.ai";
29
+ const CAMOX_API_URL = process.env.CAMOX_API_URL || "https://api.camox.ai";
30
+ const AUTH_TIMEOUT_MS = 300 * 1e3;
31
+ const AUTH_DIR = path.join(os.homedir(), ".camox");
32
+ const AUTH_FILE = path.join(AUTH_DIR, "auth.json");
33
+ function readAuthToken() {
34
+ try {
35
+ const data = JSON.parse(fs.readFileSync(AUTH_FILE, "utf-8"));
36
+ if (data?.token && data?.name) return data;
37
+ return null;
38
+ } catch {
39
+ return null;
40
+ }
41
+ }
42
+ function writeAuthToken(token) {
43
+ fs.mkdirSync(AUTH_DIR, { recursive: true });
44
+ fs.writeFileSync(AUTH_FILE, JSON.stringify(token, null, 2), { mode: 384 });
45
+ }
46
+ function removeAuthToken() {
47
+ try {
48
+ fs.unlinkSync(AUTH_FILE);
49
+ } catch {}
50
+ }
51
+ function openBrowser(url) {
52
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
53
+ try {
54
+ execSync(`${cmd} ${JSON.stringify(url)}`, { stdio: "ignore" });
55
+ } catch {}
56
+ }
57
+ function startCallbackServer() {
58
+ return new Promise((resolve, reject) => {
59
+ let resolveOtt;
60
+ const ottPromise = new Promise((res) => {
61
+ resolveOtt = res;
62
+ });
63
+ const server = http.createServer((req, res) => {
64
+ const url = new URL(req.url ?? "/", `http://localhost`);
65
+ if (url.pathname !== "/callback") {
66
+ res.writeHead(404);
67
+ res.end();
68
+ return;
69
+ }
70
+ const ott = url.searchParams.get("ott");
71
+ if (!ott) {
72
+ res.writeHead(400, { "Content-Type": "text/html" });
73
+ res.end("<html><body><h2>Missing token. Please try again.</h2></body></html>");
74
+ return;
75
+ }
76
+ res.writeHead(302, { Location: `${CAMOX_URL}/cli-authorized` });
77
+ res.end();
78
+ resolveOtt(ott);
79
+ });
80
+ server.listen(0, () => {
81
+ const addr = server.address();
82
+ if (!addr || typeof addr === "string") {
83
+ reject(/* @__PURE__ */ new Error("Failed to start callback server"));
84
+ return;
85
+ }
86
+ resolve({
87
+ port: addr.port,
88
+ ottPromise,
89
+ close: () => server.close()
90
+ });
91
+ });
92
+ server.on("error", reject);
93
+ });
94
+ }
95
+ async function verifyOtt(token) {
96
+ const res = await fetch(`${CAMOX_API_URL}/api/auth/one-time-token/verify`, {
97
+ method: "POST",
98
+ headers: { "Content-Type": "application/json" },
99
+ body: JSON.stringify({ token })
100
+ });
101
+ if (!res.ok) throw new Error(`OTT verification failed: ${res.status}`);
102
+ const data = await res.json();
103
+ const user = data.user;
104
+ if (!user?.name) throw new Error("No user info in verification response");
105
+ const sessionToken = data.session?.token;
106
+ if (!sessionToken) throw new Error("No session token in verification response");
107
+ return {
108
+ name: user.name,
109
+ email: user.email ?? "",
110
+ sessionToken
111
+ };
112
+ }
113
+ async function authenticateUser() {
114
+ const { port, ottPromise, close } = await startCallbackServer();
115
+ const loginUrl = `${CAMOX_URL}/cli-authorize?callback=${encodeURIComponent(`http://localhost:${port}/callback`)}`;
116
+ const action = await p.select({
117
+ message: "Log in to Camox",
118
+ options: [{
119
+ value: "open",
120
+ label: "Open browser"
121
+ }, {
122
+ value: "copy",
123
+ label: "Copy URL"
124
+ }]
125
+ });
126
+ if (p.isCancel(action)) {
127
+ close();
128
+ throw new Error("Authentication cancelled");
129
+ }
130
+ if (action === "open") openBrowser(loginUrl);
131
+ else p.log.info(loginUrl);
132
+ const s = p.spinner();
133
+ s.start("Waiting for authentication...");
134
+ try {
135
+ const ott = await Promise.race([ottPromise, new Promise((_, reject) => setTimeout(() => reject(/* @__PURE__ */ new Error("Authentication timed out")), AUTH_TIMEOUT_MS))]);
136
+ s.message("Verifying...");
137
+ const result = await verifyOtt(ott);
138
+ const authToken = {
139
+ token: result.sessionToken,
140
+ name: result.name,
141
+ email: result.email
142
+ };
143
+ writeAuthToken(authToken);
144
+ s.stop(`Authenticated as ${result.name}`);
145
+ return authToken;
146
+ } catch (err) {
147
+ s.stop("Authentication failed.");
148
+ throw err;
149
+ } finally {
150
+ close();
151
+ }
152
+ }
153
+ /**
154
+ * Returns a stored auth token if available and valid, otherwise runs the interactive login flow.
155
+ */
156
+ async function getOrAuthenticate() {
157
+ const stored = readAuthToken();
158
+ if (stored) {
159
+ const { verifySession } = await import("./api-BB93iDN7.mjs");
160
+ if (await verifySession(stored.token)) {
161
+ p.log.info(`Authenticated as ${stored.name}`);
162
+ return stored;
163
+ }
164
+ removeAuthToken();
165
+ p.log.warn("Session expired. Please log in again.");
166
+ } else p.log.info("Please authenticate to create a Camox project.");
167
+ return authenticateUser();
168
+ }
169
+ //#endregion
170
+ //#region src/lib/utils.ts
171
+ const pmCommands = {
172
+ pnpm: {
173
+ install: "pnpm install",
174
+ dev: "pnpm dev"
175
+ },
176
+ bun: {
177
+ install: "bun install",
178
+ dev: "bun dev"
179
+ },
180
+ npm: {
181
+ install: "npm install",
182
+ dev: "npm run dev"
183
+ },
184
+ yarn: {
185
+ install: "yarn install",
186
+ dev: "yarn dev"
187
+ }
188
+ };
189
+ function slugify(name) {
190
+ return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
191
+ }
192
+ function copyDir(src, dest, replacements) {
193
+ fs.mkdirSync(dest, { recursive: true });
194
+ for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
195
+ const srcPath = path.join(src, entry.name);
196
+ const destPath = path.join(dest, entry.name);
197
+ if (entry.isDirectory()) {
198
+ copyDir(srcPath, destPath, replacements);
199
+ continue;
200
+ }
201
+ let content = fs.readFileSync(srcPath, "utf-8");
202
+ for (const [key, value] of Object.entries(replacements)) content = content.replaceAll(key, value);
203
+ fs.writeFileSync(destPath, content);
204
+ }
205
+ }
206
+ //#endregion
207
+ //#region src/commands/init.ts
208
+ var init_exports = /* @__PURE__ */ __exportAll({
209
+ handler: () => handler$2,
210
+ init: () => init,
211
+ parser: () => parser$2
212
+ });
213
+ const parser$2 = command("init", object({ command: constant("init") }));
214
+ const handler$2 = init;
215
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
216
+ const ownPkg = JSON.parse(fs.readFileSync(path.resolve(__dirname, "..", "package.json"), "utf-8"));
217
+ function onCancel() {
218
+ p.cancel("Cancelled.");
219
+ process.exit(0);
220
+ }
221
+ const CREATE_NEW_ORG = "__create_new__";
222
+ async function selectOrCreateOrganization(token) {
223
+ const orgs = await listOrganizations(token);
224
+ if (orgs.length === 0) {
225
+ p.log.info("You don't have any organizations yet. Let's create one.");
226
+ return promptCreateOrganization(token);
227
+ }
228
+ const selected = await p.select({
229
+ message: "Select an organization for your new project",
230
+ options: [...orgs.map((org) => ({
231
+ value: org.id,
232
+ label: `${org.name} (${org.slug})`
233
+ })), {
234
+ value: CREATE_NEW_ORG,
235
+ label: "Create a new organization"
236
+ }]
237
+ });
238
+ if (p.isCancel(selected)) return onCancel();
239
+ if (selected === CREATE_NEW_ORG) return promptCreateOrganization(token);
240
+ const org = orgs.find((o) => o.id === selected);
241
+ await setActiveOrganization(token, org.id);
242
+ return org.id;
243
+ }
244
+ async function promptCreateOrganization(token) {
245
+ const orgName = await p.text({
246
+ message: "Organization name",
247
+ placeholder: "My Company",
248
+ validate: (value) => {
249
+ if (!value.trim()) return "Organization name is required";
250
+ }
251
+ });
252
+ if (p.isCancel(orgName)) return onCancel();
253
+ const org = await createOrganization(token, orgName, slugify(orgName));
254
+ p.log.success(`Created organization: ${org.name}`);
255
+ return org.id;
256
+ }
257
+ async function init() {
258
+ p.intro(`Camox v${ownPkg.version}`);
259
+ const stored = readAuthToken();
260
+ if (stored) p.log.info(`Welcome back, ${stored.name}!`);
261
+ p.log.info("Let's create your Camox application.");
262
+ const result = await p.group({
263
+ name: () => p.text({
264
+ message: "Project display name",
265
+ placeholder: "My Website",
266
+ validate: (value) => {
267
+ if (!value.trim()) return "Project name is required";
268
+ }
269
+ }),
270
+ path: ({ results }) => p.text({
271
+ message: "Project path",
272
+ initialValue: `./${slugify(results.name ?? "") || "my-site"}`,
273
+ validate: (value) => {
274
+ if (!value.trim()) return "Path is required";
275
+ }
276
+ })
277
+ }, { onCancel });
278
+ const targetDir = path.resolve(result.path);
279
+ const auth = await getOrAuthenticate();
280
+ const orgId = await selectOrCreateOrganization(auth.token);
281
+ const s0 = p.spinner();
282
+ s0.start("Creating project...");
283
+ let project;
284
+ try {
285
+ project = await createProject(auth.token, result.name, orgId);
286
+ s0.stop(`Project created with slug: ${project.slug}`);
287
+ } catch (err) {
288
+ s0.stop("Failed to create project.");
289
+ p.log.error(err instanceof Error ? err.message : "Unknown error");
290
+ process.exit(1);
291
+ }
292
+ if (fs.existsSync(targetDir) && fs.readdirSync(targetDir).length > 0) {
293
+ p.cancel(`Directory ${targetDir} is not empty.`);
294
+ process.exit(1);
295
+ }
296
+ const selected = await p.select({
297
+ message: "Which package manager?",
298
+ options: [
299
+ {
300
+ value: "pnpm",
301
+ label: "pnpm (recommended)"
302
+ },
303
+ {
304
+ value: "bun",
305
+ label: "bun"
306
+ },
307
+ {
308
+ value: "npm",
309
+ label: "npm"
310
+ },
311
+ {
312
+ value: "yarn",
313
+ label: "yarn"
314
+ }
315
+ ]
316
+ });
317
+ if (p.isCancel(selected)) return onCancel();
318
+ const pm = selected;
319
+ const s = p.spinner();
320
+ s.start("Scaffolding project...");
321
+ copyDir(path.resolve(__dirname, "..", "template"), targetDir, {
322
+ "{{projectName}}": result.name,
323
+ "{{projectSlug}}": project.slug,
324
+ "{{camoxVersion}}": ownPkg.version
325
+ });
326
+ fs.writeFileSync(path.join(targetDir, ".env"), `CAMOX_SYNC_SECRET=${project.syncSecret}\n`);
327
+ fs.writeFileSync(path.join(targetDir, ".gitignore"), `node_modules
328
+ .DS_Store
329
+ dist
330
+ dist-ssr
331
+ *.local
332
+ count.txt
333
+ .env
334
+ .nitro
335
+ .tanstack
336
+ .output
337
+ .vinxi
338
+
339
+ # Auto generated by Camox
340
+ src/camox/app.ts
341
+ src/routes/_camox.tsx
342
+ src/routes/_camox/
343
+
344
+ # Auto generated by Tanstack Router
345
+ src/routeTree.gen.ts
346
+ `);
347
+ s.stop("Project scaffolded!");
348
+ function dropIntoProject() {
349
+ const shell = process.env.SHELL || "/bin/bash";
350
+ p.log.info(`Dropping you into ${result.path}`);
351
+ spawnSync(shell, [], {
352
+ cwd: targetDir,
353
+ stdio: "inherit"
354
+ });
355
+ process.exit(0);
356
+ }
357
+ const { install: installCmd, dev: devCmd } = pmCommands[pm];
358
+ const [installBin, ...installArgs] = installCmd.split(" ");
359
+ const s2 = p.spinner();
360
+ s2.start(`Running ${installCmd}...`);
361
+ try {
362
+ await new Promise((resolve, reject) => {
363
+ const child = spawn(installBin, installArgs, {
364
+ cwd: targetDir,
365
+ stdio: "ignore"
366
+ });
367
+ child.on("close", (code) => {
368
+ if (code === 0) resolve();
369
+ else reject(/* @__PURE__ */ new Error(`Exit code ${code}`));
370
+ });
371
+ child.on("error", reject);
372
+ });
373
+ s2.stop("Dependencies installed!");
374
+ } catch {
375
+ s2.stop("Install failed.");
376
+ p.log.error(`Failed to install dependencies. Run "${installCmd}" manually.`);
377
+ dropIntoProject();
378
+ }
379
+ p.outro(`Starting dev server...`);
380
+ const [cmd, ...args] = devCmd.split(" ");
381
+ process.on("SIGINT", () => {});
382
+ spawn(cmd, args, {
383
+ cwd: targetDir,
384
+ stdio: "inherit"
385
+ }).on("close", () => {
386
+ dropIntoProject();
387
+ });
388
+ }
389
+ //#endregion
390
+ //#region src/commands/login.ts
391
+ var login_exports = /* @__PURE__ */ __exportAll({
392
+ handler: () => handler$1,
393
+ login: () => login,
394
+ parser: () => parser$1
395
+ });
396
+ const parser$1 = command("login", object({ command: constant("login") }));
397
+ const handler$1 = login;
398
+ async function login() {
399
+ p.intro("camox login");
400
+ try {
401
+ await getOrAuthenticate();
402
+ } catch {
403
+ p.log.error("Authentication failed.");
404
+ process.exit(1);
405
+ }
406
+ p.outro("You're all set!");
407
+ process.exit(0);
408
+ }
409
+ //#endregion
410
+ //#region src/commands/logout.ts
411
+ var logout_exports = /* @__PURE__ */ __exportAll({
412
+ handler: () => handler,
413
+ logout: () => logout,
414
+ parser: () => parser
415
+ });
416
+ const parser = command("logout", object({ command: constant("logout") }));
417
+ const handler = logout;
418
+ function logout() {
419
+ const token = readAuthToken();
420
+ if (!token) {
421
+ console.log("Not logged in.");
422
+ return;
423
+ }
424
+ removeAuthToken();
425
+ console.log(`Logged out from ${token.name}.`);
426
+ }
427
+ //#endregion
428
+ //#region src/index.ts
429
+ await {
430
+ init: init_exports,
431
+ login: login_exports,
432
+ logout: logout_exports
433
+ }[run(defineProgram({
434
+ parser: or(parser$2, parser$1, parser),
435
+ metadata: {
436
+ name: "camox",
437
+ brief: message`Camox CLI`
438
+ }
439
+ }), { help: "both" }).command].handler();
440
+ //#endregion
441
+ export {};
package/package.json CHANGED
@@ -1,17 +1,17 @@
1
1
  {
2
2
  "name": "@camox/cli",
3
- "version": "0.4.2",
3
+ "version": "0.5.1",
4
4
  "bin": {
5
- "camox": "./dist/index.js"
5
+ "camox": "./dist/index.mjs"
6
6
  },
7
7
  "files": [
8
8
  "dist",
9
9
  "template"
10
10
  ],
11
11
  "type": "module",
12
- "main": "./dist/index.js",
12
+ "main": "./dist/index.mjs",
13
13
  "exports": {
14
- ".": "./dist/index.js"
14
+ ".": "./dist/index.mjs"
15
15
  },
16
16
  "dependencies": {
17
17
  "@clack/prompts": "^0.10.0",
@@ -24,12 +24,12 @@
24
24
  "@types/node": "^24.12.2",
25
25
  "@typescript/native-preview": "7.0.0-dev.20260412.1",
26
26
  "oxlint": "^0.15.0",
27
- "tsup": "^8.4.0",
28
- "@camox/api": "0.4.2"
27
+ "tsdown": "^0.21.8",
28
+ "@camox/api": "0.5.1"
29
29
  },
30
30
  "scripts": {
31
- "build": "tsup",
32
- "dev": "tsup --watch",
31
+ "build": "tsdown",
32
+ "dev": "tsdown --watch",
33
33
  "lint": "oxlint",
34
34
  "check": "tsgo --noEmit && oxlint --fix"
35
35
  }
@@ -3,12 +3,13 @@
3
3
  "private": true,
4
4
  "type": "module",
5
5
  "scripts": {
6
- "dev": "vite dev --port 7400",
6
+ "dev": "vp dev --port 7400",
7
7
  "start": "node .output/server/index.mjs",
8
- "build": "vite build",
9
- "serve": "vite preview",
10
- "lint": "oxlint",
11
- "check": "tsgo --noEmit && oxlint --fix"
8
+ "build": "vp build",
9
+ "serve": "vp preview",
10
+ "lint": "vp lint",
11
+ "check": "vp check",
12
+ "prepare": "vp config"
12
13
  },
13
14
  "dependencies": {
14
15
  "@radix-ui/react-slot": "^1.2.4",
@@ -36,8 +37,7 @@
36
37
  "@typescript/native-preview": "^7.0.0-dev",
37
38
  "@vitejs/plugin-react": "^6.0.1",
38
39
  "babel-plugin-react-compiler": "^1.0.0",
39
- "oxlint": "^0.15.15",
40
40
  "tw-animate-css": "^1.4.0",
41
- "vite": "8.0.1"
41
+ "vite-plus": "^0.1.16"
42
42
  }
43
43
  }
@@ -3,7 +3,7 @@ import tailwindcss from "@tailwindcss/vite";
3
3
  import { tanstackStart } from "@tanstack/react-start/plugin/vite";
4
4
  import react, { reactCompilerPreset } from "@vitejs/plugin-react";
5
5
  import { camox } from "camox/vite";
6
- import { defineConfig, loadEnv } from "vite";
6
+ import { defineConfig, loadEnv } from "vite-plus";
7
7
 
8
8
  export default defineConfig(({ mode }) => {
9
9
  const env = loadEnv(mode, process.cwd(), "CAMOX_");
@@ -1,15 +0,0 @@
1
- #!/usr/bin/env node
2
- import {
3
- createOrganization,
4
- createProject,
5
- listOrganizations,
6
- setActiveOrganization,
7
- verifySession
8
- } from "./chunk-5VGGMUU6.js";
9
- export {
10
- createOrganization,
11
- createProject,
12
- listOrganizations,
13
- setActiveOrganization,
14
- verifySession
15
- };
@@ -1,77 +0,0 @@
1
- #!/usr/bin/env node
2
- var __defProp = Object.defineProperty;
3
- var __export = (target, all) => {
4
- for (var name in all)
5
- __defProp(target, name, { get: all[name], enumerable: true });
6
- };
7
-
8
- // src/lib/api.ts
9
- import { createORPCClient } from "@orpc/client";
10
- import { RPCLink } from "@orpc/client/fetch";
11
- var CAMOX_API_URL = process.env.CAMOX_API_URL || "https://api.camox.ai";
12
- function authHeaders(token) {
13
- return {
14
- Authorization: `Bearer ${token}`,
15
- "Content-Type": "application/json"
16
- };
17
- }
18
- function createRpcClient(token) {
19
- const link = new RPCLink({
20
- url: `${CAMOX_API_URL}/rpc`,
21
- headers: { Authorization: `Bearer ${token}` }
22
- });
23
- return createORPCClient(link);
24
- }
25
- async function verifySession(token) {
26
- const res = await fetch(`${CAMOX_API_URL}/api/auth/get-session`, {
27
- method: "GET",
28
- headers: authHeaders(token)
29
- });
30
- return res.ok;
31
- }
32
- async function listOrganizations(token) {
33
- const res = await fetch(`${CAMOX_API_URL}/api/auth/organization/list`, {
34
- method: "GET",
35
- headers: authHeaders(token)
36
- });
37
- if (!res.ok) {
38
- throw new Error(`Failed to list organizations: ${res.status}`);
39
- }
40
- return res.json();
41
- }
42
- async function createOrganization(token, name, slug) {
43
- const res = await fetch(`${CAMOX_API_URL}/api/auth/organization/create`, {
44
- method: "POST",
45
- headers: authHeaders(token),
46
- body: JSON.stringify({ name, slug })
47
- });
48
- if (!res.ok) {
49
- const text = await res.text();
50
- throw new Error(`Failed to create organization: ${res.status} ${text}`);
51
- }
52
- return res.json();
53
- }
54
- async function setActiveOrganization(token, organizationId) {
55
- const res = await fetch(`${CAMOX_API_URL}/api/auth/organization/set-active`, {
56
- method: "POST",
57
- headers: authHeaders(token),
58
- body: JSON.stringify({ organizationId })
59
- });
60
- if (!res.ok) {
61
- throw new Error(`Failed to set active organization: ${res.status}`);
62
- }
63
- }
64
- async function createProject(token, name, organizationId) {
65
- const client = createRpcClient(token);
66
- const result = await client.projects.create({ name, organizationId });
67
- return result;
68
- }
69
-
70
- export {
71
- __export,
72
- verifySession,
73
- listOrganizations,
74
- createOrganization,
75
- setActiveOrganization,
76
- createProject
77
- };
package/dist/index.js DELETED
@@ -1,456 +0,0 @@
1
- #!/usr/bin/env node
2
- import {
3
- __export,
4
- createOrganization,
5
- createProject,
6
- listOrganizations,
7
- setActiveOrganization
8
- } from "./chunk-5VGGMUU6.js";
9
-
10
- // src/index.ts
11
- import { or } from "@optique/core/constructs";
12
- import { message } from "@optique/core/message";
13
- import { defineProgram } from "@optique/core/program";
14
- import { run } from "@optique/run";
15
-
16
- // src/commands/init.ts
17
- var init_exports = {};
18
- __export(init_exports, {
19
- handler: () => handler,
20
- init: () => init,
21
- parser: () => parser
22
- });
23
- import { spawn, spawnSync } from "child_process";
24
- import fs3 from "fs";
25
- import path3 from "path";
26
- import { fileURLToPath } from "url";
27
- import * as p2 from "@clack/prompts";
28
- import { object } from "@optique/core/constructs";
29
- import { command, constant } from "@optique/core/primitives";
30
-
31
- // src/lib/auth.ts
32
- import { execSync } from "child_process";
33
- import fs from "fs";
34
- import http from "http";
35
- import os from "os";
36
- import path from "path";
37
- import * as p from "@clack/prompts";
38
- var CAMOX_URL = process.env.CAMOX_URL || "https://camox.ai";
39
- var CAMOX_API_URL = process.env.CAMOX_API_URL || "https://api.camox.ai";
40
- var AUTH_TIMEOUT_MS = 12e4;
41
- var AUTH_DIR = path.join(os.homedir(), ".camox");
42
- var AUTH_FILE = path.join(AUTH_DIR, "auth.json");
43
- function readAuthToken() {
44
- try {
45
- const data = JSON.parse(fs.readFileSync(AUTH_FILE, "utf-8"));
46
- if (data?.token && data?.name) return data;
47
- return null;
48
- } catch {
49
- return null;
50
- }
51
- }
52
- function writeAuthToken(token) {
53
- fs.mkdirSync(AUTH_DIR, { recursive: true });
54
- fs.writeFileSync(AUTH_FILE, JSON.stringify(token, null, 2), { mode: 384 });
55
- }
56
- function removeAuthToken() {
57
- try {
58
- fs.unlinkSync(AUTH_FILE);
59
- } catch {
60
- }
61
- }
62
- function openBrowser(url) {
63
- const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
64
- try {
65
- execSync(`${cmd} ${JSON.stringify(url)}`, { stdio: "ignore" });
66
- } catch {
67
- }
68
- }
69
- function startCallbackServer() {
70
- return new Promise((resolve, reject) => {
71
- let resolveOtt;
72
- const ottPromise = new Promise((res) => {
73
- resolveOtt = res;
74
- });
75
- const server = http.createServer((req, res) => {
76
- const url = new URL(req.url ?? "/", `http://localhost`);
77
- if (url.pathname !== "/callback") {
78
- res.writeHead(404);
79
- res.end();
80
- return;
81
- }
82
- const ott = url.searchParams.get("ott");
83
- if (!ott) {
84
- res.writeHead(400, { "Content-Type": "text/html" });
85
- res.end("<html><body><h2>Missing token. Please try again.</h2></body></html>");
86
- return;
87
- }
88
- res.writeHead(302, { Location: `${CAMOX_URL}/cli-authorized` });
89
- res.end();
90
- resolveOtt(ott);
91
- });
92
- server.listen(0, () => {
93
- const addr = server.address();
94
- if (!addr || typeof addr === "string") {
95
- reject(new Error("Failed to start callback server"));
96
- return;
97
- }
98
- resolve({
99
- port: addr.port,
100
- ottPromise,
101
- close: () => server.close()
102
- });
103
- });
104
- server.on("error", reject);
105
- });
106
- }
107
- async function verifyOtt(token) {
108
- const res = await fetch(`${CAMOX_API_URL}/api/auth/one-time-token/verify`, {
109
- method: "POST",
110
- headers: { "Content-Type": "application/json" },
111
- body: JSON.stringify({ token })
112
- });
113
- if (!res.ok) {
114
- throw new Error(`OTT verification failed: ${res.status}`);
115
- }
116
- const data = await res.json();
117
- const user = data.user;
118
- if (!user?.name) {
119
- throw new Error("No user info in verification response");
120
- }
121
- const sessionToken = data.session?.token;
122
- if (!sessionToken) {
123
- throw new Error("No session token in verification response");
124
- }
125
- return { name: user.name, email: user.email ?? "", sessionToken };
126
- }
127
- async function authenticateUser() {
128
- const { port, ottPromise, close } = await startCallbackServer();
129
- const loginUrl = `${CAMOX_URL}/cli-authorize?callback=${encodeURIComponent(`http://localhost:${port}/callback`)}`;
130
- const action = await p.select({
131
- message: "Log in to Camox",
132
- options: [
133
- { value: "open", label: "Open browser" },
134
- { value: "copy", label: "Copy URL" }
135
- ]
136
- });
137
- if (p.isCancel(action)) {
138
- close();
139
- throw new Error("Authentication cancelled");
140
- }
141
- if (action === "open") {
142
- openBrowser(loginUrl);
143
- } else {
144
- p.log.info(loginUrl);
145
- }
146
- const s = p.spinner();
147
- s.start("Waiting for authentication...");
148
- try {
149
- const ott = await Promise.race([
150
- ottPromise,
151
- new Promise(
152
- (_, reject) => setTimeout(() => reject(new Error("Authentication timed out")), AUTH_TIMEOUT_MS)
153
- )
154
- ]);
155
- s.message("Verifying...");
156
- const result2 = await verifyOtt(ott);
157
- const authToken = {
158
- token: result2.sessionToken,
159
- name: result2.name,
160
- email: result2.email
161
- };
162
- writeAuthToken(authToken);
163
- s.stop(`Authenticated as ${result2.name}`);
164
- return authToken;
165
- } catch (err) {
166
- s.stop("Authentication failed.");
167
- throw err;
168
- } finally {
169
- close();
170
- }
171
- }
172
- async function getOrAuthenticate() {
173
- const stored = readAuthToken();
174
- if (stored) {
175
- const { verifySession } = await import("./api-C4HUA6JP.js");
176
- const valid = await verifySession(stored.token);
177
- if (valid) {
178
- p.log.info(`Authenticated as ${stored.name}`);
179
- return stored;
180
- }
181
- removeAuthToken();
182
- p.log.warn("Session expired. Please log in again.");
183
- } else {
184
- p.log.info("Please authenticate to create a Camox project.");
185
- }
186
- return authenticateUser();
187
- }
188
-
189
- // src/lib/utils.ts
190
- import fs2 from "fs";
191
- import path2 from "path";
192
- var pmCommands = {
193
- pnpm: { install: "pnpm install", dev: "pnpm dev" },
194
- bun: { install: "bun install", dev: "bun dev" },
195
- npm: { install: "npm install", dev: "npm run dev" },
196
- yarn: { install: "yarn install", dev: "yarn dev" }
197
- };
198
- function slugify(name) {
199
- return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
200
- }
201
- function copyDir(src, dest, replacements) {
202
- fs2.mkdirSync(dest, { recursive: true });
203
- for (const entry of fs2.readdirSync(src, { withFileTypes: true })) {
204
- const srcPath = path2.join(src, entry.name);
205
- const destPath = path2.join(dest, entry.name);
206
- if (entry.isDirectory()) {
207
- copyDir(srcPath, destPath, replacements);
208
- continue;
209
- }
210
- let content = fs2.readFileSync(srcPath, "utf-8");
211
- for (const [key, value] of Object.entries(replacements)) {
212
- content = content.replaceAll(key, value);
213
- }
214
- fs2.writeFileSync(destPath, content);
215
- }
216
- }
217
-
218
- // src/commands/init.ts
219
- var parser = command(
220
- "init",
221
- object({
222
- command: constant("init")
223
- })
224
- );
225
- var handler = init;
226
- var __dirname = path3.dirname(fileURLToPath(import.meta.url));
227
- var ownPkg = JSON.parse(fs3.readFileSync(path3.resolve(__dirname, "..", "package.json"), "utf-8"));
228
- function onCancel() {
229
- p2.cancel("Cancelled.");
230
- process.exit(0);
231
- }
232
- var CREATE_NEW_ORG = "__create_new__";
233
- async function selectOrCreateOrganization(token) {
234
- const orgs = await listOrganizations(token);
235
- if (orgs.length === 0) {
236
- p2.log.info("You don't have any organizations yet. Let's create one.");
237
- return promptCreateOrganization(token);
238
- }
239
- const selected = await p2.select({
240
- message: "Select an organization for your new project",
241
- options: [
242
- ...orgs.map((org2) => ({ value: org2.id, label: `${org2.name} (${org2.slug})` })),
243
- { value: CREATE_NEW_ORG, label: "Create a new organization" }
244
- ]
245
- });
246
- if (p2.isCancel(selected)) return onCancel();
247
- if (selected === CREATE_NEW_ORG) {
248
- return promptCreateOrganization(token);
249
- }
250
- const org = orgs.find((o) => o.id === selected);
251
- await setActiveOrganization(token, org.id);
252
- return org.id;
253
- }
254
- async function promptCreateOrganization(token) {
255
- const orgName = await p2.text({
256
- message: "Organization name",
257
- placeholder: "My Company",
258
- validate: (value) => {
259
- if (!value.trim()) return "Organization name is required";
260
- }
261
- });
262
- if (p2.isCancel(orgName)) return onCancel();
263
- const orgSlug = slugify(orgName);
264
- const org = await createOrganization(token, orgName, orgSlug);
265
- p2.log.success(`Created organization: ${org.name}`);
266
- return org.id;
267
- }
268
- async function init() {
269
- p2.intro("camox init");
270
- const result2 = await p2.group(
271
- {
272
- name: () => p2.text({
273
- message: "Project display name",
274
- placeholder: "My Website",
275
- validate: (value) => {
276
- if (!value.trim()) return "Project name is required";
277
- }
278
- }),
279
- path: ({ results }) => p2.text({
280
- message: "Project path",
281
- initialValue: `./${slugify(results.name ?? "") || "my-site"}`,
282
- validate: (value) => {
283
- if (!value.trim()) return "Path is required";
284
- }
285
- })
286
- },
287
- { onCancel }
288
- );
289
- const targetDir = path3.resolve(result2.path);
290
- const auth = await getOrAuthenticate();
291
- const orgId = await selectOrCreateOrganization(auth.token);
292
- const s0 = p2.spinner();
293
- s0.start("Creating project...");
294
- let project;
295
- try {
296
- project = await createProject(auth.token, result2.name, orgId);
297
- s0.stop(`Project created with slug: ${project.slug}`);
298
- } catch (err) {
299
- s0.stop("Failed to create project.");
300
- p2.log.error(err instanceof Error ? err.message : "Unknown error");
301
- process.exit(1);
302
- }
303
- if (fs3.existsSync(targetDir) && fs3.readdirSync(targetDir).length > 0) {
304
- p2.cancel(`Directory ${targetDir} is not empty.`);
305
- process.exit(1);
306
- }
307
- const selected = await p2.select({
308
- message: "Which package manager?",
309
- options: [
310
- { value: "pnpm", label: "pnpm (recommended)" },
311
- { value: "bun", label: "bun" },
312
- { value: "npm", label: "npm" },
313
- { value: "yarn", label: "yarn" }
314
- ]
315
- });
316
- if (p2.isCancel(selected)) return onCancel();
317
- const pm = selected;
318
- const s = p2.spinner();
319
- s.start("Scaffolding project...");
320
- const templateDir = path3.resolve(__dirname, "..", "template");
321
- copyDir(templateDir, targetDir, {
322
- "{{projectName}}": result2.name,
323
- "{{projectSlug}}": project.slug,
324
- "{{camoxVersion}}": ownPkg.version
325
- });
326
- fs3.writeFileSync(path3.join(targetDir, ".env"), `CAMOX_SYNC_SECRET=${project.syncSecret}
327
- `);
328
- fs3.writeFileSync(
329
- path3.join(targetDir, ".gitignore"),
330
- `node_modules
331
- .DS_Store
332
- dist
333
- dist-ssr
334
- *.local
335
- count.txt
336
- .env
337
- .nitro
338
- .tanstack
339
- .output
340
- .vinxi
341
-
342
- # Auto generated by Camox
343
- src/camox/app.ts
344
- src/routes/_camox.tsx
345
- src/routes/_camox/
346
-
347
- # Auto generated by Tanstack Router
348
- src/routeTree.gen.ts
349
- `
350
- );
351
- s.stop("Project scaffolded!");
352
- function dropIntoProject() {
353
- const shell = process.env.SHELL || "/bin/bash";
354
- p2.log.info(`Dropping you into ${result2.path}`);
355
- spawnSync(shell, [], { cwd: targetDir, stdio: "inherit" });
356
- process.exit(0);
357
- }
358
- const { install: installCmd, dev: devCmd } = pmCommands[pm];
359
- const [installBin, ...installArgs] = installCmd.split(" ");
360
- const s2 = p2.spinner();
361
- s2.start(`Running ${installCmd}...`);
362
- try {
363
- await new Promise((resolve, reject) => {
364
- const child2 = spawn(installBin, installArgs, {
365
- cwd: targetDir,
366
- stdio: "ignore"
367
- });
368
- child2.on("close", (code) => {
369
- if (code === 0) resolve();
370
- else reject(new Error(`Exit code ${code}`));
371
- });
372
- child2.on("error", reject);
373
- });
374
- s2.stop("Dependencies installed!");
375
- } catch {
376
- s2.stop("Install failed.");
377
- p2.log.error(`Failed to install dependencies. Run "${installCmd}" manually.`);
378
- dropIntoProject();
379
- }
380
- p2.outro(`Starting dev server...`);
381
- const [cmd, ...args] = devCmd.split(" ");
382
- const child = spawn(cmd, args, {
383
- cwd: targetDir,
384
- stdio: "inherit"
385
- });
386
- child.on("close", () => {
387
- dropIntoProject();
388
- });
389
- }
390
-
391
- // src/commands/login.ts
392
- var login_exports = {};
393
- __export(login_exports, {
394
- handler: () => handler2,
395
- login: () => login,
396
- parser: () => parser2
397
- });
398
- import * as p3 from "@clack/prompts";
399
- import { object as object2 } from "@optique/core/constructs";
400
- import { command as command2, constant as constant2 } from "@optique/core/primitives";
401
- var parser2 = command2(
402
- "login",
403
- object2({
404
- command: constant2("login")
405
- })
406
- );
407
- var handler2 = login;
408
- async function login() {
409
- p3.intro("camox login");
410
- try {
411
- await getOrAuthenticate();
412
- } catch {
413
- p3.log.error("Authentication failed.");
414
- process.exit(1);
415
- }
416
- p3.outro("You're all set!");
417
- process.exit(0);
418
- }
419
-
420
- // src/commands/logout.ts
421
- var logout_exports = {};
422
- __export(logout_exports, {
423
- handler: () => handler3,
424
- logout: () => logout,
425
- parser: () => parser3
426
- });
427
- import { object as object3 } from "@optique/core/constructs";
428
- import { command as command3, constant as constant3 } from "@optique/core/primitives";
429
- var parser3 = command3(
430
- "logout",
431
- object3({
432
- command: constant3("logout")
433
- })
434
- );
435
- var handler3 = logout;
436
- function logout() {
437
- const token = readAuthToken();
438
- if (!token) {
439
- console.log("Not logged in.");
440
- return;
441
- }
442
- removeAuthToken();
443
- console.log(`Logged out from ${token.name}.`);
444
- }
445
-
446
- // src/index.ts
447
- var commands = { init: init_exports, login: login_exports, logout: logout_exports };
448
- var program = defineProgram({
449
- parser: or(parser, parser2, parser3),
450
- metadata: {
451
- name: "camox",
452
- brief: message`Camox CLI`
453
- }
454
- });
455
- var result = run(program, { help: "both" });
456
- await commands[result.command].handler();