clawnify 0.1.16 → 0.2.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.
@@ -7,14 +7,16 @@ import {
7
7
  createArchive,
8
8
  generatePkce,
9
9
  getEmailFromToken,
10
+ getValidToken,
10
11
  listMyOrgs,
11
12
  loadAuth,
13
+ manifestKind,
12
14
  pollUntilReady,
13
15
  readManifest,
14
16
  readProject,
15
17
  saveAuth,
16
18
  saveProject
17
- } from "./chunk-CMM323B2.js";
19
+ } from "./chunk-UUTFIFKJ.js";
18
20
 
19
21
  // src/cli.ts
20
22
  import { Command } from "commander";
@@ -169,8 +171,104 @@ async function loginCommand() {
169
171
  }
170
172
 
171
173
  // src/commands/deploy.ts
172
- import path from "path";
174
+ import path2 from "path";
173
175
  import readline2 from "readline";
176
+
177
+ // src/lib/sync-schema.ts
178
+ import fs from "fs/promises";
179
+ import path from "path";
180
+ import { execSync } from "child_process";
181
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
182
+ async function resolveApp(idOrSlug, orgFilter) {
183
+ const orgs = await listMyOrgs();
184
+ if (orgs.length === 0) return null;
185
+ const candidates = orgFilter ? orgs.filter((o) => o.id === orgFilter || o.slug === orgFilter) : orgs;
186
+ if (candidates.length === 0) return null;
187
+ const isUuid = UUID_RE.test(idOrSlug);
188
+ if (isUuid) {
189
+ for (const org of candidates) {
190
+ const res = await api.get(`/v1/apps/${idOrSlug}`, { orgId: org.id });
191
+ if (res.ok) {
192
+ const app = await res.json();
193
+ return { org, appId: app.id, slug: app.slug };
194
+ }
195
+ }
196
+ return null;
197
+ }
198
+ for (const org of candidates) {
199
+ const res = await api.get(`/v1/apps`, { orgId: org.id });
200
+ if (!res.ok) continue;
201
+ const payload = await res.json();
202
+ const apps = Array.isArray(payload) ? payload : payload.apps ?? [];
203
+ const match = apps.find((a) => a.slug === idOrSlug);
204
+ if (match) return { org, appId: match.id, slug: match.slug };
205
+ }
206
+ return null;
207
+ }
208
+ async function fetchSchema(ref) {
209
+ const appId = "appId" in ref ? ref.appId : ref.appId;
210
+ const orgId = "orgId" in ref ? ref.orgId : ref.org.id;
211
+ const res = await api.get(`/v1/apps/${appId}/schema`, { orgId });
212
+ if (!res.ok) {
213
+ if (res.status === 404) return null;
214
+ const err = await res.json().catch(() => ({}));
215
+ throw new Error(`Schema fetch failed: ${err.error ?? res.statusText}`);
216
+ }
217
+ const data = await res.json();
218
+ return data.schema_sql;
219
+ }
220
+ async function writeSchema(targetPath, schema, options = {}) {
221
+ if (schema === null) {
222
+ return { status: "no-schema", path: targetPath };
223
+ }
224
+ let existing = null;
225
+ try {
226
+ existing = await fs.readFile(targetPath, "utf8");
227
+ } catch (err) {
228
+ if (err.code !== "ENOENT") throw err;
229
+ }
230
+ if (existing === schema) {
231
+ return { status: "unchanged", path: targetPath };
232
+ }
233
+ if (existing !== null && !options.force) {
234
+ const dir = path.dirname(path.resolve(targetPath));
235
+ if (isInsideGitRepo(dir)) {
236
+ if (hasUncommittedChanges(dir, targetPath)) {
237
+ return { status: "refused-uncommitted", path: targetPath };
238
+ }
239
+ } else {
240
+ return { status: "refused-different", path: targetPath };
241
+ }
242
+ }
243
+ await fs.mkdir(path.dirname(targetPath), { recursive: true });
244
+ await fs.writeFile(targetPath, schema, "utf8");
245
+ return { status: "written", path: targetPath, bytes: schema.length };
246
+ }
247
+ function isInsideGitRepo(dir) {
248
+ try {
249
+ execSync("git rev-parse --is-inside-work-tree", {
250
+ cwd: dir,
251
+ stdio: ["ignore", "pipe", "ignore"]
252
+ });
253
+ return true;
254
+ } catch {
255
+ return false;
256
+ }
257
+ }
258
+ function hasUncommittedChanges(dir, filePath) {
259
+ try {
260
+ const relative = path.relative(dir, path.resolve(filePath));
261
+ const status = execSync(`git status --porcelain -- "${relative}"`, {
262
+ cwd: dir,
263
+ stdio: ["ignore", "pipe", "ignore"]
264
+ }).toString().trim();
265
+ return status.length > 0;
266
+ } catch {
267
+ return true;
268
+ }
269
+ }
270
+
271
+ // src/commands/deploy.ts
174
272
  var EXIT_USAGE = 64;
175
273
  var EXIT_CONFLICT_NEEDS_DECISION = 75;
176
274
  function ask(question) {
@@ -301,11 +399,111 @@ function summarizeArchive(buf, files, framework, name) {
301
399
  }
302
400
  console.log();
303
401
  }
402
+ async function uploadWebsiteDeploy(archive, name, orgId) {
403
+ const formData = new FormData();
404
+ formData.append("source", new Blob([archive]), "source.tar.gz");
405
+ if (name) formData.append("name", name);
406
+ const res = await api.postForm("/v1/websites/deploy", formData, { orgId });
407
+ if (res.ok) {
408
+ const data = await res.json();
409
+ return { ok: true, data };
410
+ }
411
+ const err = await res.json().catch(() => ({}));
412
+ return { ok: false, error: err.error || res.statusText };
413
+ }
414
+ async function deployWebsite(dir, options) {
415
+ if (options.from) {
416
+ console.error("--from is app-only for now. Run `clawnify deploy` inside the website project directory.");
417
+ process.exit(EXIT_USAGE);
418
+ }
419
+ const resolvedDir = dir ? path2.resolve(dir) : process.cwd();
420
+ const manifest = readManifest(resolvedDir);
421
+ const baseName = options.name || manifest?.name || path2.basename(resolvedDir);
422
+ const linkedProject = readProject(resolvedDir);
423
+ const { archive, files } = createArchive(resolvedDir);
424
+ let orgId;
425
+ if (options.org) {
426
+ const orgs = await listMyOrgs();
427
+ const match = orgs.find((o) => o.id === options.org || o.slug === options.org);
428
+ if (!match) {
429
+ console.error(
430
+ `No org matched "${options.org}". Available: ${orgs.map((o) => o.slug).join(", ")}`
431
+ );
432
+ process.exit(EXIT_USAGE);
433
+ }
434
+ if (linkedProject?.website_id && linkedProject.org_id && linkedProject.org_id !== match.id) {
435
+ console.error(
436
+ `This project is linked to a different org (${linkedProject.org_id}).
437
+ --org ${options.org} resolves to ${match.id}.`
438
+ );
439
+ process.exit(1);
440
+ }
441
+ orgId = match.id;
442
+ } else if (linkedProject?.website_id && linkedProject.org_id) {
443
+ orgId = linkedProject.org_id;
444
+ }
445
+ if (options.dryRun) {
446
+ const sizeKB = (archive.length / 1024).toFixed(1);
447
+ console.log(`
448
+ Dry run \u2014 would deploy website '${baseName}' (astro)`);
449
+ console.log(` Archive: ${files.length} files, ${sizeKB}KB gzipped
450
+ `);
451
+ const preview = files.slice(0, 25);
452
+ for (const f of preview) console.log(` ${f}`);
453
+ if (files.length > preview.length) {
454
+ console.log(` ... and ${files.length - preview.length} more`);
455
+ }
456
+ console.log();
457
+ return;
458
+ }
459
+ console.log(linkedProject?.website_id ? `Updating ${baseName}...` : `Deploying ${baseName}...`);
460
+ const result = await uploadWebsiteDeploy(archive, baseName, orgId);
461
+ if (!result.ok) {
462
+ console.error(`Deploy failed: ${result.error}`);
463
+ process.exit(1);
464
+ }
465
+ saveProject(resolvedDir, {
466
+ kind: "website",
467
+ org_id: orgId,
468
+ website_id: result.data.website_id,
469
+ slug: result.data.slug
470
+ });
471
+ const polled = await pollUntilReady(result.data.website_id, {
472
+ kind: "website",
473
+ orgId
474
+ });
475
+ if (polled.status === "error") {
476
+ console.error(`
477
+ Deploy failed: ${polled.error || "Unknown error"}
478
+ `);
479
+ process.exit(1);
480
+ }
481
+ console.log(`
482
+ \u2713 Deployed! ${result.data.url}
483
+ `);
484
+ }
304
485
  async function deployCommand(dir, options = {}) {
305
486
  assertNodeVersion();
487
+ if (!options.from) {
488
+ const resolvedDir = dir ? path2.resolve(dir) : process.cwd();
489
+ const manifest = readManifest(resolvedDir);
490
+ if (manifest) {
491
+ try {
492
+ const kind = manifestKind(manifest);
493
+ if (kind === "website") {
494
+ return deployWebsite(dir, options);
495
+ }
496
+ } catch (err) {
497
+ console.error(`${err.message}`);
498
+ process.exit(EXIT_USAGE);
499
+ }
500
+ }
501
+ }
306
502
  let appId;
307
503
  let slug;
308
504
  let appToken;
505
+ let resolvedOrgId;
506
+ let syncTargetDir;
309
507
  if (options.from) {
310
508
  const repo = options.from.replace(/^github:/, "");
311
509
  if (options.dryRun) {
@@ -326,10 +524,12 @@ async function deployCommand(dir, options = {}) {
326
524
  appId = data.app_id;
327
525
  slug = data.slug;
328
526
  appToken = data.app_token;
527
+ resolvedOrgId = orgId;
329
528
  } else {
330
- const resolvedDir = dir ? path.resolve(dir) : process.cwd();
529
+ const resolvedDir = dir ? path2.resolve(dir) : process.cwd();
530
+ syncTargetDir = resolvedDir;
331
531
  const manifest = readManifest(resolvedDir);
332
- const baseName = options.name || manifest?.name || path.basename(resolvedDir);
532
+ const baseName = options.name || manifest?.name || path2.basename(resolvedDir);
333
533
  const framework = manifest?.app?.framework || "vite-preact";
334
534
  const linkedProject = readProject(resolvedDir);
335
535
  const { archive, files } = createArchive(resolvedDir);
@@ -392,6 +592,7 @@ async function deployCommand(dir, options = {}) {
392
592
  appToken = result2.data.app_token;
393
593
  }
394
594
  saveProject(resolvedDir, { org_id: orgId, app_id: appId, slug, app_token: appToken });
595
+ resolvedOrgId = orgId;
395
596
  }
396
597
  }
397
598
  const result = await pollUntilReady(appId);
@@ -407,6 +608,40 @@ async function deployCommand(dir, options = {}) {
407
608
  `);
408
609
  console.log(` Open: clawnify open ${slug}
409
610
  `);
611
+ if (syncTargetDir && !options.noSync && resolvedOrgId) {
612
+ try {
613
+ const schema = await fetchSchema({ appId, orgId: resolvedOrgId });
614
+ const target = path2.join(syncTargetDir, "schema.sql");
615
+ const writeResult = await writeSchema(target, schema);
616
+ const rel = path2.relative(process.cwd(), writeResult.path) || writeResult.path;
617
+ switch (writeResult.status) {
618
+ case "written":
619
+ console.log(` Synced ${rel} (${writeResult.bytes} bytes)
620
+ `);
621
+ break;
622
+ case "refused-uncommitted":
623
+ console.log(
624
+ ` ${rel} has uncommitted changes \u2014 not overwriting.
625
+ Run \`clawnify pull schema --force --from ${slug}\` to overwrite.
626
+ `
627
+ );
628
+ break;
629
+ case "refused-different":
630
+ console.log(
631
+ ` ${rel} differs from the deployed copy (not in git).
632
+ Run \`clawnify pull schema --force --from ${slug}\` to overwrite.
633
+ `
634
+ );
635
+ break;
636
+ case "no-schema":
637
+ case "unchanged":
638
+ break;
639
+ }
640
+ } catch (err) {
641
+ console.log(` (schema sync skipped: ${err.message})
642
+ `);
643
+ }
644
+ }
410
645
  }
411
646
 
412
647
  // src/commands/ls.ts
@@ -526,8 +761,8 @@ async function whoamiCommand() {
526
761
  }
527
762
 
528
763
  // src/commands/init.ts
529
- import fs from "fs";
530
- import path2 from "path";
764
+ import fs2 from "fs";
765
+ import path3 from "path";
531
766
  import readline4 from "readline";
532
767
  function ask2(question) {
533
768
  const rl = readline4.createInterface({
@@ -544,10 +779,31 @@ function ask2(question) {
544
779
  function slugify(name) {
545
780
  return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 30);
546
781
  }
782
+ async function askProjectType(opts) {
783
+ if (opts?.type === "app" || opts?.type === "website") return opts.type;
784
+ if (opts?.type) {
785
+ console.error(`Unknown --type '${opts.type}' (expected 'app' or 'website').`);
786
+ process.exit(1);
787
+ }
788
+ console.log();
789
+ console.log(" What are you creating?");
790
+ console.log(" 1) app \u2014 full-stack project (React + Hono + D1)");
791
+ console.log(" 2) website \u2014 public site (Astro)");
792
+ console.log();
793
+ const choice = await ask2("Type [1]: ") || "1";
794
+ return choice === "2" ? "website" : "app";
795
+ }
547
796
  async function initCommand(dir, opts) {
797
+ const type = await askProjectType(opts);
798
+ if (type === "website") {
799
+ return initWebsite(dir, opts);
800
+ }
801
+ return initApp(dir, opts);
802
+ }
803
+ async function initApp(dir, opts) {
548
804
  const name = opts?.name || await ask2("App name: ") || "my-app";
549
805
  const slug = slugify(name);
550
- const targetDir = dir ? path2.resolve(dir) : path2.resolve(slug);
806
+ const targetDir = dir ? path3.resolve(dir) : path3.resolve(slug);
551
807
  let template;
552
808
  if (opts?.template) {
553
809
  template = opts.template === "crud" ? "crud" : "blank";
@@ -560,12 +816,12 @@ async function initCommand(dir, opts) {
560
816
  const templateChoice = await ask2("Template [1]: ") || "1";
561
817
  template = templateChoice === "2" ? "crud" : "blank";
562
818
  }
563
- if (fs.existsSync(targetDir) && fs.readdirSync(targetDir).length > 0) {
819
+ if (fs2.existsSync(targetDir) && fs2.readdirSync(targetDir).length > 0) {
564
820
  console.error(`Directory ${targetDir} is not empty.`);
565
821
  process.exit(1);
566
822
  }
567
- fs.mkdirSync(path2.join(targetDir, "src/server"), { recursive: true });
568
- fs.mkdirSync(path2.join(targetDir, "src/client"), { recursive: true });
823
+ fs2.mkdirSync(path3.join(targetDir, "src/server"), { recursive: true });
824
+ fs2.mkdirSync(path3.join(targetDir, "src/client"), { recursive: true });
569
825
  let storage;
570
826
  if (opts?.storage !== void 0) {
571
827
  storage = opts.storage;
@@ -818,15 +1074,142 @@ createRoot(document.getElementById("app")!).render(
818
1074
  writeBlankTemplate(targetDir, name);
819
1075
  }
820
1076
  console.log();
821
- console.log(` Created ${name} in ${path2.relative(process.cwd(), targetDir)}/`);
1077
+ console.log(` Created ${name} in ${path3.relative(process.cwd(), targetDir)}/`);
822
1078
  console.log();
823
1079
  console.log(" Get started:");
824
- console.log(` cd ${path2.relative(process.cwd(), targetDir)}`);
1080
+ console.log(` cd ${path3.relative(process.cwd(), targetDir)}`);
825
1081
  console.log(" pnpm install");
826
1082
  console.log(" pnpm dev # local dev at http://localhost:5173");
827
1083
  console.log(" pnpm deploy # deploy to production");
828
1084
  console.log();
829
1085
  }
1086
+ async function initWebsite(dir, opts) {
1087
+ const name = opts?.name || await ask2("Site name: ") || "my-site";
1088
+ const slug = slugify(name);
1089
+ const targetDir = dir ? path3.resolve(dir) : path3.resolve(slug);
1090
+ if (fs2.existsSync(targetDir) && fs2.readdirSync(targetDir).length > 0) {
1091
+ console.error(`Directory ${targetDir} is not empty.`);
1092
+ process.exit(1);
1093
+ }
1094
+ fs2.mkdirSync(targetDir, { recursive: true });
1095
+ write(targetDir, "clawnify.json", JSON.stringify({
1096
+ $schema: "https://app.clawnify.com/schema/v1/clawnify.json",
1097
+ version: 1,
1098
+ name,
1099
+ description: "",
1100
+ website: { framework: "astro" }
1101
+ }, null, 2));
1102
+ write(targetDir, "package.json", JSON.stringify({
1103
+ name: slug,
1104
+ private: true,
1105
+ type: "module",
1106
+ scripts: {
1107
+ dev: "astro dev",
1108
+ build: "astro build",
1109
+ preview: "astro preview",
1110
+ deploy: "clawnify deploy"
1111
+ },
1112
+ dependencies: {
1113
+ "@astrojs/cloudflare": "^12.0.0",
1114
+ "@tailwindcss/vite": "^4.0.0",
1115
+ astro: "^5.0.0",
1116
+ tailwindcss: "^4.0.0"
1117
+ },
1118
+ devDependencies: {
1119
+ clawnify: "^0.1.15",
1120
+ "wrangler": "^4.0.0"
1121
+ },
1122
+ engines: { node: ">=22" }
1123
+ }, null, 2));
1124
+ write(targetDir, "tsconfig.json", JSON.stringify({
1125
+ extends: "astro/tsconfigs/strict",
1126
+ include: ["src/**/*", ".astro/types.d.ts"],
1127
+ exclude: ["dist", "node_modules"]
1128
+ }, null, 2));
1129
+ write(targetDir, "astro.config.mjs", `import { defineConfig } from "astro/config";
1130
+ import cloudflare from "@astrojs/cloudflare";
1131
+ import tailwindcss from "@tailwindcss/vite";
1132
+
1133
+ export default defineConfig({
1134
+ output: "server",
1135
+ adapter: cloudflare(),
1136
+ vite: {
1137
+ plugins: [tailwindcss()],
1138
+ },
1139
+ });
1140
+ `);
1141
+ write(targetDir, ".gitignore", `node_modules
1142
+ dist
1143
+ .astro
1144
+ .wrangler
1145
+ .clawnify
1146
+ .env*
1147
+ !.env.example
1148
+ .dev.vars
1149
+ `);
1150
+ write(targetDir, "src/styles/global.css", `@import "tailwindcss";
1151
+
1152
+ :root {
1153
+ --color-primary: oklch(0.55 0.18 250);
1154
+ --color-ink: oklch(0.2 0.02 250);
1155
+ --color-canvas: oklch(0.99 0 0);
1156
+ }
1157
+
1158
+ body {
1159
+ background-color: var(--color-canvas);
1160
+ color: var(--color-ink);
1161
+ font-family: ui-sans-serif, system-ui, sans-serif;
1162
+ }
1163
+ `);
1164
+ write(targetDir, "src/layouts/BaseLayout.astro", `---
1165
+ interface Props {
1166
+ title?: string;
1167
+ description?: string;
1168
+ }
1169
+
1170
+ const { title = "${name}", description = "" } = Astro.props;
1171
+ ---
1172
+ <!doctype html>
1173
+ <html lang="en">
1174
+ <head>
1175
+ <meta charset="utf-8" />
1176
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
1177
+ <title>{title}</title>
1178
+ {description && <meta name="description" content={description} />}
1179
+ <link rel="stylesheet" href="/src/styles/global.css" />
1180
+ </head>
1181
+ <body>
1182
+ <slot />
1183
+ </body>
1184
+ </html>
1185
+ `);
1186
+ write(targetDir, "src/pages/index.astro", `---
1187
+ import BaseLayout from "../layouts/BaseLayout.astro";
1188
+ ---
1189
+ <BaseLayout title="${name}">
1190
+ <main class="mx-auto max-w-3xl px-6 py-24">
1191
+ <h1 class="text-5xl font-semibold tracking-tight">${name}</h1>
1192
+ <p class="mt-4 text-lg opacity-70">
1193
+ Edit <code>src/pages/index.astro</code> to get started.
1194
+ </p>
1195
+ <p class="mt-8">
1196
+ <a class="underline" href="https://docs.astro.build" target="_blank" rel="noreferrer">
1197
+ Astro docs \u2192
1198
+ </a>
1199
+ </p>
1200
+ </main>
1201
+ </BaseLayout>
1202
+ `);
1203
+ console.log();
1204
+ console.log(` Created ${name} in ${path3.relative(process.cwd(), targetDir)}/`);
1205
+ console.log();
1206
+ console.log(" Get started:");
1207
+ console.log(` cd ${path3.relative(process.cwd(), targetDir)}`);
1208
+ console.log(" pnpm install");
1209
+ console.log(" pnpm dev # local dev at http://localhost:4321");
1210
+ console.log(" pnpm deploy # deploy as your org's website");
1211
+ console.log();
1212
+ }
830
1213
  function writeBlankTemplate(dir, name) {
831
1214
  write(dir, "src/server/schema.sql", `CREATE TABLE IF NOT EXISTS items (
832
1215
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -1100,14 +1483,14 @@ export function App() {
1100
1483
  `);
1101
1484
  }
1102
1485
  function write(dir, file, content) {
1103
- const fullPath = path2.join(dir, file);
1104
- fs.mkdirSync(path2.dirname(fullPath), { recursive: true });
1105
- fs.writeFileSync(fullPath, content);
1486
+ const fullPath = path3.join(dir, file);
1487
+ fs2.mkdirSync(path3.dirname(fullPath), { recursive: true });
1488
+ fs2.writeFileSync(fullPath, content);
1106
1489
  }
1107
1490
 
1108
1491
  // src/commands/dev.ts
1109
- import fs2 from "fs";
1110
- import path3 from "path";
1492
+ import fs3 from "fs";
1493
+ import path4 from "path";
1111
1494
  import { spawn } from "child_process";
1112
1495
  function slugify2(name) {
1113
1496
  return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 30);
@@ -1152,22 +1535,28 @@ function assertNodeVersion2() {
1152
1535
  }
1153
1536
  async function devCommand(dir, options) {
1154
1537
  assertNodeVersion2();
1155
- const resolvedDir = dir ? path3.resolve(dir) : process.cwd();
1538
+ const resolvedDir = dir ? path4.resolve(dir) : process.cwd();
1156
1539
  const manifest = readManifest(resolvedDir);
1157
1540
  if (!manifest) {
1158
1541
  console.error("No clawnify.json found. Run `clawnify init` first.");
1159
1542
  process.exit(1);
1160
1543
  }
1544
+ if (!manifest.app) {
1545
+ console.error(
1546
+ "`clawnify dev` is for app projects only. For a website, run `pnpm dev` (astro dev) directly."
1547
+ );
1548
+ process.exit(1);
1549
+ }
1161
1550
  const slug = slugify2(manifest.name);
1162
1551
  const database = manifest.app.database !== false;
1163
1552
  const storage = manifest.app.storage === true;
1164
1553
  const apiPort = options?.port || "8787";
1165
- const clawnifyDir = path3.join(resolvedDir, ".clawnify");
1166
- fs2.mkdirSync(clawnifyDir, { recursive: true });
1167
- const wranglerPath = path3.join(clawnifyDir, "wrangler.toml");
1168
- fs2.writeFileSync(wranglerPath, generateWranglerToml(slug, { database, storage }));
1169
- const schemaPath = path3.join(resolvedDir, "src/server/schema.sql");
1170
- if (database && fs2.existsSync(schemaPath)) {
1554
+ const clawnifyDir = path4.join(resolvedDir, ".clawnify");
1555
+ fs3.mkdirSync(clawnifyDir, { recursive: true });
1556
+ const wranglerPath = path4.join(clawnifyDir, "wrangler.toml");
1557
+ fs3.writeFileSync(wranglerPath, generateWranglerToml(slug, { database, storage }));
1558
+ const schemaPath = path4.join(resolvedDir, "src/server/schema.sql");
1559
+ if (database && fs3.existsSync(schemaPath)) {
1171
1560
  await runQuiet(resolvedDir, "npx", [
1172
1561
  "wrangler",
1173
1562
  "d1",
@@ -1268,8 +1657,8 @@ function runQuiet(cwd, cmd, args) {
1268
1657
  }
1269
1658
 
1270
1659
  // src/commands/link.ts
1271
- import path4 from "path";
1272
- var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1660
+ import path5 from "path";
1661
+ var UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1273
1662
  async function findByAppId(orgs, appId) {
1274
1663
  for (const org of orgs) {
1275
1664
  const res = await api.get(`/v1/apps/${appId}`, { orgId: org.id });
@@ -1307,7 +1696,7 @@ async function findBySlug(orgs, slug) {
1307
1696
  return null;
1308
1697
  }
1309
1698
  async function linkCommand(appIdOrSlug, options) {
1310
- const dir = options?.dir ? path4.resolve(options.dir) : process.cwd();
1699
+ const dir = options?.dir ? path5.resolve(options.dir) : process.cwd();
1311
1700
  const orgs = await listMyOrgs();
1312
1701
  if (orgs.length === 0) {
1313
1702
  console.error("No organizations found. Run `clawnify login` first.");
@@ -1320,7 +1709,7 @@ async function linkCommand(appIdOrSlug, options) {
1320
1709
  );
1321
1710
  process.exit(1);
1322
1711
  }
1323
- const isUuid = UUID_RE.test(appIdOrSlug);
1712
+ const isUuid = UUID_RE2.test(appIdOrSlug);
1324
1713
  const matched = isUuid ? await findByAppId(candidates, appIdOrSlug) : await findBySlug(candidates, appIdOrSlug);
1325
1714
  if (!matched) {
1326
1715
  const kind = isUuid ? "id" : "slug";
@@ -1335,12 +1724,59 @@ async function linkCommand(appIdOrSlug, options) {
1335
1724
  slug: matched.app.slug,
1336
1725
  app_token: matched.app.app_token
1337
1726
  });
1338
- const rel = path4.relative(process.cwd(), dir) || ".";
1727
+ const rel = path5.relative(process.cwd(), dir) || ".";
1339
1728
  console.log(` Linked ${matched.app.name} (${matched.app.slug}) in ${matched.org.name}`);
1340
1729
  console.log(` Wrote ${rel}/.clawnify/project.json`);
1341
1730
  console.log(` Run \`clawnify deploy\` to push the current source to this app.`);
1342
1731
  }
1343
1732
 
1733
+ // src/commands/pull.ts
1734
+ import path6 from "path";
1735
+ async function pullSchemaCommand(options) {
1736
+ if (!options.from) {
1737
+ console.error("Usage: clawnify pull schema --from <app-id-or-slug>");
1738
+ process.exit(64);
1739
+ }
1740
+ const ref = await resolveApp(options.from, options.org);
1741
+ if (!ref) {
1742
+ console.error(`App '${options.from}' not found in your orgs.`);
1743
+ process.exit(1);
1744
+ }
1745
+ let schema;
1746
+ try {
1747
+ schema = await fetchSchema(ref);
1748
+ } catch (err) {
1749
+ console.error(`Failed to fetch schema: ${err.message}`);
1750
+ process.exit(1);
1751
+ }
1752
+ const targetPath = path6.resolve(options.out ?? "schema.sql");
1753
+ const result = await writeSchema(targetPath, schema, { force: options.force });
1754
+ const rel = path6.relative(process.cwd(), result.path) || result.path;
1755
+ switch (result.status) {
1756
+ case "no-schema":
1757
+ console.log(` ${ref.slug}: no schema.sql in R2 (pre-backfill app, or no database)`);
1758
+ process.exit(0);
1759
+ case "unchanged":
1760
+ console.log(` ${rel} is already up to date`);
1761
+ process.exit(0);
1762
+ case "written":
1763
+ console.log(` \u2713 wrote ${rel} (${result.bytes} bytes, from ${ref.slug})`);
1764
+ process.exit(0);
1765
+ case "refused-uncommitted":
1766
+ console.error(
1767
+ ` ${rel} has uncommitted changes \u2014 refusing to overwrite.
1768
+ Commit/stash first, or rerun with --force.`
1769
+ );
1770
+ process.exit(1);
1771
+ case "refused-different":
1772
+ console.error(
1773
+ ` ${rel} exists locally and differs from the deployed copy.
1774
+ Not inside a git repo \u2014 can't tell intent. Rerun with --force to overwrite.`
1775
+ );
1776
+ process.exit(1);
1777
+ }
1778
+ }
1779
+
1344
1780
  // src/commands/org.ts
1345
1781
  async function orgListCommand() {
1346
1782
  const orgs = await listMyOrgs();
@@ -1378,15 +1814,204 @@ async function orgUseCommand(slugOrId) {
1378
1814
  console.log(` Active org set to ${match.name} (${match.slug})`);
1379
1815
  }
1380
1816
 
1817
+ // src/commands/execute.ts
1818
+ import fs4 from "fs";
1819
+
1820
+ // src/lib/mcp-client.ts
1821
+ var MCP_URL = "https://mcp.clawnify.com/mcp";
1822
+ async function callTool(name, args) {
1823
+ const token = await getValidToken();
1824
+ if (!token) {
1825
+ process.stderr.write("Not logged in. Run `clawnify login` first.\n");
1826
+ process.exit(1);
1827
+ }
1828
+ const auth = loadAuth();
1829
+ const headers = {
1830
+ "content-type": "application/json",
1831
+ authorization: "Bearer " + token
1832
+ };
1833
+ if (auth?.org_id) {
1834
+ headers["X-Clawnify-Org-Id"] = auth.org_id;
1835
+ }
1836
+ const res = await fetch(MCP_URL, {
1837
+ method: "POST",
1838
+ headers,
1839
+ body: JSON.stringify({
1840
+ jsonrpc: "2.0",
1841
+ id: Date.now(),
1842
+ method: "tools/call",
1843
+ params: { name, arguments: args }
1844
+ })
1845
+ });
1846
+ if (res.status === 401) {
1847
+ process.stderr.write("Authentication failed. Run `clawnify login` again.\n");
1848
+ process.exit(1);
1849
+ }
1850
+ const body = await res.json();
1851
+ if (body.error) return { error: body.error };
1852
+ if (!body.result) {
1853
+ return { error: { code: -32603, message: "Empty response from MCP gateway" } };
1854
+ }
1855
+ return { result: body.result };
1856
+ }
1857
+ function isError(resp) {
1858
+ return "error" in resp;
1859
+ }
1860
+
1861
+ // src/commands/execute.ts
1862
+ async function executeCommand(file, options) {
1863
+ let code;
1864
+ if (options.code) {
1865
+ code = options.code;
1866
+ } else if (file) {
1867
+ try {
1868
+ code = fs4.readFileSync(file, "utf-8");
1869
+ } catch (err) {
1870
+ process.stderr.write(`Failed to read ${file}: ${String(err)}
1871
+ `);
1872
+ process.exit(1);
1873
+ }
1874
+ } else {
1875
+ process.stderr.write(
1876
+ `Provide a file path or --code 'inline code'.
1877
+ Usage: clawnify execute path/to/file.ts
1878
+ clawnify execute -c "console.log(1 + 1)"
1879
+ `
1880
+ );
1881
+ process.exit(1);
1882
+ }
1883
+ const timeout_ms = options.timeout ? Math.max(1e3, parseInt(options.timeout, 10) * 1e3) : 3e4;
1884
+ const resp = await callTool("clawnify.execute", { code, timeout_ms });
1885
+ if (isError(resp)) {
1886
+ process.stderr.write(`Error ${resp.error.code}: ${resp.error.message}
1887
+ `);
1888
+ process.exit(1);
1889
+ }
1890
+ const sc = resp.result.structuredContent;
1891
+ if (sc) {
1892
+ if (sc.stdout) process.stdout.write(sc.stdout);
1893
+ if (sc.stderr) process.stderr.write(sc.stderr);
1894
+ if (sc.timed_out) {
1895
+ process.stderr.write(`
1896
+ [clawnify] timed out after ${timeout_ms}ms on ${sc.substrate_id}
1897
+ `);
1898
+ }
1899
+ process.exit(sc.exit_code ?? 0);
1900
+ }
1901
+ for (const c of resp.result.content) {
1902
+ if (c.type === "text") process.stdout.write(c.text + "\n");
1903
+ }
1904
+ process.exit(resp.result.isError ? 1 : 0);
1905
+ }
1906
+
1907
+ // src/commands/docs.ts
1908
+ var DOCS_URL = "https://clawnify-mcp-docs.workers.dev";
1909
+ async function docsCommand(slug, options) {
1910
+ const token = await getValidToken();
1911
+ if (!token) {
1912
+ process.stderr.write("Not logged in. Run `clawnify login` first.\n");
1913
+ process.exit(1);
1914
+ }
1915
+ const auth = loadAuth();
1916
+ if (!auth?.org_id) {
1917
+ process.stderr.write(
1918
+ "No active org. Pick one with `clawnify org use <slug-or-id>` first.\n"
1919
+ );
1920
+ process.exit(1);
1921
+ }
1922
+ const caller = options.caller ?? "external";
1923
+ const path7 = slug ? `/docs/${auth.org_id}/${slug}.md?caller=${caller}` : `/docs/${auth.org_id}/index.md`;
1924
+ const res = await fetch(DOCS_URL + path7, {
1925
+ headers: {
1926
+ authorization: "Bearer " + token
1927
+ }
1928
+ });
1929
+ if (!res.ok) {
1930
+ process.stderr.write(`Failed to fetch docs: ${res.status} ${res.statusText}
1931
+ `);
1932
+ process.exit(1);
1933
+ }
1934
+ const md = await res.text();
1935
+ process.stdout.write(md);
1936
+ if (!md.endsWith("\n")) process.stdout.write("\n");
1937
+ }
1938
+
1939
+ // src/commands/mcp-bridge.ts
1940
+ import readline5 from "readline";
1941
+ var MCP_URL2 = "https://mcp.clawnify.com/mcp";
1942
+ async function mcpBridgeCommand() {
1943
+ const token = await getValidToken();
1944
+ if (!token) {
1945
+ process.stderr.write("Not logged in. Run `clawnify login` first.\n");
1946
+ process.exit(1);
1947
+ }
1948
+ const auth = loadAuth();
1949
+ const baseHeaders = {
1950
+ "content-type": "application/json",
1951
+ authorization: "Bearer " + token
1952
+ };
1953
+ if (auth?.org_id) {
1954
+ baseHeaders["X-Clawnify-Org-Id"] = auth.org_id;
1955
+ }
1956
+ const rl = readline5.createInterface({ input: process.stdin, terminal: false });
1957
+ rl.on("line", async (line) => {
1958
+ const trimmed = line.trim();
1959
+ if (!trimmed) return;
1960
+ let parsedId = null;
1961
+ try {
1962
+ parsedId = JSON.parse(trimmed).id ?? null;
1963
+ } catch {
1964
+ }
1965
+ try {
1966
+ const res = await fetch(MCP_URL2, {
1967
+ method: "POST",
1968
+ headers: baseHeaders,
1969
+ body: trimmed
1970
+ });
1971
+ const text = await res.text();
1972
+ if (text.length > 0) {
1973
+ process.stdout.write(text);
1974
+ if (!text.endsWith("\n")) process.stdout.write("\n");
1975
+ }
1976
+ } catch (err) {
1977
+ const errResp = {
1978
+ jsonrpc: "2.0",
1979
+ id: parsedId,
1980
+ error: { code: -32603, message: "bridge transport error: " + String(err) }
1981
+ };
1982
+ process.stdout.write(JSON.stringify(errResp) + "\n");
1983
+ }
1984
+ });
1985
+ rl.on("close", () => {
1986
+ process.exit(0);
1987
+ });
1988
+ }
1989
+
1990
+ // src/commands/sdk.ts
1991
+ async function sdkInspectCommand(slug, options) {
1992
+ await docsCommand(slug, { caller: options.caller ?? "external" });
1993
+ }
1994
+ async function sdkLoginCommand() {
1995
+ await loginCommand();
1996
+ }
1997
+ async function sdkInstallCommand() {
1998
+ process.stderr.write(
1999
+ "`clawnify sdk install` is not yet implemented.\nIt depends on the `@clawnify/sdk` npm package being published, which depends on the build-pipeline manifest writer (template-strategy.md).\nTrack in the Phase 5 follow-up.\n"
2000
+ );
2001
+ process.exit(1);
2002
+ }
2003
+
1381
2004
  // src/cli.ts
1382
2005
  function runCli() {
1383
2006
  const program = new Command();
1384
2007
  program.name("clawnify").description("Deploy apps to Clawnify").version("0.1.0");
1385
- program.command("init [dir]").description("Scaffold a new Clawnify app").option("--name <name>", "App name (skips prompt)").option("--template <template>", "Template: blank or crud (skips prompt)").option("--storage", "Enable file uploads (R2)").action(initCommand);
2008
+ program.command("init [dir]").description("Scaffold a new Clawnify project (app or website)").option("--type <type>", "Project type: app or website (skips prompt)").option("--name <name>", "Project name (skips prompt)").option("--template <template>", "App template: blank or crud (apps only)").option("--storage", "Enable file uploads (R2) \u2014 apps only").action(initCommand);
1386
2009
  program.command("dev [dir]").description("Start local dev server").option("--port <port>", "API server port (default: 8787)").action(devCommand);
1387
2010
  program.command("login").description("Authenticate with Clawnify").action(loginCommand);
1388
- program.command("deploy [dir]").description("Deploy an app to Clawnify").option("--from <repo>", "Deploy from a GitHub repo (owner/repo)").option("--name <name>", "Override app name").option("--org <slug-or-id>", "Deploy to a specific org (overrides active org)").option("-y, --yes", "Non-interactive: on slug conflict, update existing app").option("--update-existing", "Non-interactive: on slug conflict, overwrite existing app").option("--create-new", "Non-interactive: on slug conflict, create a new app with the suggested slug").option("--dry-run", "List files that would be uploaded; do not deploy").action(deployCommand);
2011
+ program.command("deploy [dir]").description("Deploy an app or website to Clawnify").option("--from <repo>", "Deploy from a GitHub repo (owner/repo)").option("--name <name>", "Override app name").option("--org <slug-or-id>", "Deploy to a specific org (overrides active org)").option("-y, --yes", "Non-interactive: on slug conflict, update existing app").option("--update-existing", "Non-interactive: on slug conflict, overwrite existing app").option("--create-new", "Non-interactive: on slug conflict, create a new app with the suggested slug").option("--dry-run", "List files that would be uploaded; do not deploy").option("--no-sync", "Skip the post-deploy schema.sql sync into the local working directory").action(deployCommand);
1389
2012
  program.command("link <app-id-or-slug>").description("Link the current directory to an existing Clawnify app (accepts id or slug)").option("--dir <dir>", "Directory to link (default: cwd)").option("--org <slug-or-id>", "Restrict the app lookup to a specific org").action(linkCommand);
2013
+ const pull = program.command("pull").description("Pull artifacts from a deployed app into the current directory");
2014
+ pull.command("schema").description("Fetch the deployed app's current schema.sql snapshot into the local repo").option("--from <app-id-or-slug>", "App to fetch from (required)").option("--out <path>", "Where to write (default: ./schema.sql)").option("--force", "Overwrite a locally-modified or uncommitted schema.sql").option("--org <slug-or-id>", "Restrict the app lookup to a specific org").action(pullSchemaCommand);
1390
2015
  const org = program.command("org").description("Manage organizations");
1391
2016
  org.command("list").description("List orgs you belong to").action(orgListCommand);
1392
2017
  org.command("use <slug-or-id>").description("Set the active org for global commands (ls, whoami, etc.)").action(orgUseCommand);
@@ -1395,9 +2020,16 @@ function runCli() {
1395
2020
  program.command("rm <app-id>").description("Delete an app").action(rmCommand);
1396
2021
  program.command("open <slug>").description("Open an app in the browser").action(openCommand);
1397
2022
  program.command("whoami").description("Show current user info").action(whoamiCommand);
2023
+ program.command("execute [file]").description("Run TypeScript code on the active org's substrate via mcp.clawnify.com").option("-c, --code <inline>", "Inline code instead of a file path").option("--timeout <seconds>", "Execution timeout in seconds (default 30)").action(executeCommand);
2024
+ program.command("docs [slug]").description("Fetch the skill-convention README for an app (or org index if slug omitted)").option("--caller <hint>", "Caller density hint: internal | dashboard | external", "external").action(docsCommand);
2025
+ program.command("mcp").description("Run a stdio MCP bridge that proxies to mcp.clawnify.com (for Claude Desktop / ChatGPT / bash-less clients)").action(mcpBridgeCommand);
2026
+ const sdk = program.command("sdk").description("Inspect and manage the per-org SDK surface");
2027
+ sdk.command("inspect <slug>").description("Show the typed-procedure README for an app (external density)").option("--caller <hint>", "Caller density hint: internal | dashboard | external", "external").action(sdkInspectCommand);
2028
+ sdk.command("login").description("Authenticate / rotate the OAuth grant (alias of `clawnify login`)").action(sdkLoginCommand);
2029
+ sdk.command("install").description("(Deferred) Install @clawnify/sdk locally \u2014 pending Phase 5b").action(sdkInstallCommand);
1398
2030
  program.parse();
1399
2031
  }
1400
2032
  export {
1401
2033
  runCli
1402
2034
  };
1403
- //# sourceMappingURL=cli-KWGS4LVM.js.map
2035
+ //# sourceMappingURL=cli-EQWAQQTZ.js.map