clawnify 0.3.0 → 0.5.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.
@@ -16,7 +16,7 @@ import {
16
16
  readProject,
17
17
  saveAuth,
18
18
  saveProject
19
- } from "./chunk-UUTFIFKJ.js";
19
+ } from "./chunk-3HQ3VZOS.js";
20
20
 
21
21
  // src/cli.ts
22
22
  import { Command } from "commander";
@@ -171,8 +171,10 @@ async function loginCommand() {
171
171
  }
172
172
 
173
173
  // src/commands/deploy.ts
174
+ import fs2 from "fs";
174
175
  import path2 from "path";
175
176
  import readline2 from "readline";
177
+ import { spawn } from "child_process";
176
178
 
177
179
  // src/lib/sync-schema.ts
178
180
  import fs from "fs/promises";
@@ -532,6 +534,7 @@ async function deployCommand(dir, options = {}) {
532
534
  const baseName = options.name || manifest?.name || path2.basename(resolvedDir);
533
535
  const framework = manifest?.app?.framework || "vite-preact";
534
536
  const linkedProject = readProject(resolvedDir);
537
+ await regenerateDrizzleMigrations(resolvedDir);
535
538
  const { archive, files } = createArchive(resolvedDir);
536
539
  const orgId = await resolveOrgId(options, linkedProject);
537
540
  if (options.dryRun) {
@@ -643,6 +646,31 @@ async function deployCommand(dir, options = {}) {
643
646
  }
644
647
  }
645
648
  }
649
+ async function regenerateDrizzleMigrations(resolvedDir) {
650
+ const schemaTs = path2.join(resolvedDir, "src/server/schema.ts");
651
+ const drizzleConfig = path2.join(resolvedDir, "drizzle.config.ts");
652
+ if (!fs2.existsSync(schemaTs) || !fs2.existsSync(drizzleConfig)) return;
653
+ await new Promise((resolve) => {
654
+ const proc = spawn("npx", ["drizzle-kit", "generate"], {
655
+ cwd: resolvedDir,
656
+ stdio: ["ignore", "pipe", "pipe"],
657
+ env: { ...process.env }
658
+ });
659
+ let stderr = "";
660
+ proc.stderr?.on("data", (d) => {
661
+ stderr += d.toString();
662
+ });
663
+ proc.on("exit", (code) => {
664
+ if (code !== 0) {
665
+ console.warn(
666
+ ` warning: drizzle-kit generate failed (${stderr.trim().slice(0, 200)}). Continuing with existing .clawnify/drizzle/ contents.`
667
+ );
668
+ }
669
+ resolve();
670
+ });
671
+ proc.on("error", () => resolve());
672
+ });
673
+ }
646
674
 
647
675
  // src/commands/ls.ts
648
676
  async function lsCommand() {
@@ -761,7 +789,7 @@ async function whoamiCommand() {
761
789
  }
762
790
 
763
791
  // src/commands/init.ts
764
- import fs2 from "fs";
792
+ import fs3 from "fs";
765
793
  import path3 from "path";
766
794
  import readline4 from "readline";
767
795
  function ask2(question) {
@@ -785,6 +813,7 @@ async function askProjectType(opts) {
785
813
  console.error(`Unknown --type '${opts.type}' (expected 'app' or 'website').`);
786
814
  process.exit(1);
787
815
  }
816
+ if (opts?.yes) return "app";
788
817
  console.log();
789
818
  console.log(" What are you creating?");
790
819
  console.log(" 1) app \u2014 full-stack project (React + Hono + D1)");
@@ -793,6 +822,13 @@ async function askProjectType(opts) {
793
822
  const choice = await ask2("Type [1]: ") || "1";
794
823
  return choice === "2" ? "website" : "app";
795
824
  }
825
+ function detectPackageManager() {
826
+ const ua = process.env.npm_config_user_agent ?? "";
827
+ if (ua.startsWith("pnpm")) return "pnpm";
828
+ if (ua.startsWith("yarn")) return "yarn";
829
+ if (ua.startsWith("bun")) return "bun";
830
+ return "npm";
831
+ }
796
832
  async function initCommand(dir, opts) {
797
833
  const type = await askProjectType(opts);
798
834
  if (type === "website") {
@@ -801,12 +837,16 @@ async function initCommand(dir, opts) {
801
837
  return initApp(dir, opts);
802
838
  }
803
839
  async function initApp(dir, opts) {
804
- const name = opts?.name || await ask2("App name: ") || "my-app";
840
+ const yes = !!opts?.yes;
841
+ const dirArgName = dir ? path3.basename(path3.resolve(dir)) : void 0;
842
+ const name = opts?.name || (yes ? dirArgName ?? "my-app" : await ask2("App name: ") || "my-app");
805
843
  const slug = slugify(name);
806
844
  const targetDir = dir ? path3.resolve(dir) : path3.resolve(slug);
807
845
  let template;
808
846
  if (opts?.template) {
809
847
  template = opts.template === "crud" ? "crud" : "blank";
848
+ } else if (yes) {
849
+ template = "blank";
810
850
  } else {
811
851
  console.log();
812
852
  console.log(" Templates:");
@@ -816,15 +856,17 @@ async function initApp(dir, opts) {
816
856
  const templateChoice = await ask2("Template [1]: ") || "1";
817
857
  template = templateChoice === "2" ? "crud" : "blank";
818
858
  }
819
- if (fs2.existsSync(targetDir) && fs2.readdirSync(targetDir).length > 0) {
859
+ if (fs3.existsSync(targetDir) && fs3.readdirSync(targetDir).length > 0) {
820
860
  console.error(`Directory ${targetDir} is not empty.`);
821
861
  process.exit(1);
822
862
  }
823
- fs2.mkdirSync(path3.join(targetDir, "src/server"), { recursive: true });
824
- fs2.mkdirSync(path3.join(targetDir, "src/client"), { recursive: true });
863
+ fs3.mkdirSync(path3.join(targetDir, "src/server"), { recursive: true });
864
+ fs3.mkdirSync(path3.join(targetDir, "src/client"), { recursive: true });
825
865
  let storage;
826
866
  if (opts?.storage !== void 0) {
827
867
  storage = opts.storage;
868
+ } else if (yes) {
869
+ storage = false;
828
870
  } else {
829
871
  const storageChoice = await ask2("Enable file uploads? [y/N]: ") || "n";
830
872
  storage = storageChoice.toLowerCase() === "y";
@@ -842,10 +884,11 @@ async function initApp(dir, opts) {
842
884
  "@types/react": "^19.0.0",
843
885
  "@types/react-dom": "^19.0.0",
844
886
  "@vitejs/plugin-react": "^4.0.0",
845
- "clawnify": "^0.1.15",
846
- "tailwindcss": "^4.0.0",
847
- "vite": "^6.0.0",
848
- "wrangler": "^4.0.0"
887
+ clawnify: "^0.3.0",
888
+ "drizzle-kit": "^0.31.0",
889
+ tailwindcss: "^4.0.0",
890
+ vite: "^6.0.0",
891
+ wrangler: "^4.0.0"
849
892
  };
850
893
  write(targetDir, "package.json", JSON.stringify({
851
894
  name: slug,
@@ -857,6 +900,7 @@ async function initApp(dir, opts) {
857
900
  deploy: "clawnify deploy"
858
901
  },
859
902
  dependencies: {
903
+ "@clawnify/db": "^0.4.1",
860
904
  "@hono/zod-openapi": "^0.19.0",
861
905
  hono: "^4.0.0",
862
906
  react: "^19.0.0",
@@ -929,45 +973,31 @@ data.db-shm
929
973
  `);
930
974
  write(targetDir, "src/server/worker-env.d.ts", `/// <reference types="@cloudflare/workers-types" />
931
975
  `);
932
- write(targetDir, "src/server/db.ts", `let _db: D1Database;
933
-
934
- export function initDB(db: D1Database) {
935
- _db = db;
936
- }
937
-
938
- export async function query<T = Record<string, unknown>>(
939
- sql: string,
940
- params: unknown[] = [],
941
- ): Promise<T[]> {
942
- const stmt = _db.prepare(sql).bind(...params);
943
- const { results } = await stmt.all<T>();
944
- return results ?? [];
945
- }
946
-
947
- export async function get<T = Record<string, unknown>>(
948
- sql: string,
949
- params: unknown[] = [],
950
- ): Promise<T | undefined> {
951
- const stmt = _db.prepare(sql).bind(...params);
952
- const row = await stmt.first<T>();
953
- return row ?? undefined;
954
- }
976
+ write(targetDir, "src/server/schema.ts", `import { sqliteTable, text, integer } from "@clawnify/db";
977
+
978
+ /**
979
+ * Example table. Replace with your own.
980
+ *
981
+ * Multi-tenancy reminder: every user-facing table should carry an
982
+ * \`org_id\` column and every query should filter by the X-Clawnify-Org-Id
983
+ * header. See docs/build-a-clawnify-app.md.
984
+ */
985
+ export const items = sqliteTable("items", {
986
+ id: integer("id").primaryKey({ autoIncrement: true }),
987
+ name: text("name").notNull(),
988
+ createdAt: text("created_at").notNull().$default(() => new Date().toISOString()),
989
+ });
990
+ `);
991
+ write(targetDir, "drizzle.config.ts", `import { defineConfig } from "drizzle-kit";
955
992
 
956
- export async function run(
957
- sql: string,
958
- params: unknown[] = [],
959
- ): Promise<{ changes: number; lastInsertRowid: number }> {
960
- const stmt = _db.prepare(sql).bind(...params);
961
- const result = await stmt.run();
962
- return {
963
- changes: result.meta?.changes ?? 0,
964
- lastInsertRowid: Number(result.meta?.last_row_id ?? 0),
965
- };
966
- }
993
+ export default defineConfig({
994
+ schema: "./src/server/schema.ts",
995
+ out: "./.clawnify/drizzle",
996
+ dialect: "sqlite",
997
+ });
967
998
  `);
968
999
  if (storage) {
969
1000
  write(targetDir, "src/server/index.ts", `import { OpenAPIHono } from "@hono/zod-openapi";
970
- import { initDB } from "./db";
971
1001
  import { initUploads } from "./uploads";
972
1002
  import api from "./routes";
973
1003
 
@@ -976,7 +1006,6 @@ type Env = { Bindings: { DB: D1Database; UPLOADS: R2Bucket } };
976
1006
  const app = new OpenAPIHono<Env>();
977
1007
 
978
1008
  app.use("*", async (c, next) => {
979
- initDB(c.env.DB);
980
1009
  initUploads(c.env.UPLOADS);
981
1010
  await next();
982
1011
  });
@@ -1033,18 +1062,12 @@ export async function readUploadAsBase64DataUrl(
1033
1062
  `);
1034
1063
  } else {
1035
1064
  write(targetDir, "src/server/index.ts", `import { OpenAPIHono } from "@hono/zod-openapi";
1036
- import { initDB } from "./db";
1037
1065
  import api from "./routes";
1038
1066
 
1039
1067
  type Env = { Bindings: { DB: D1Database } };
1040
1068
 
1041
1069
  const app = new OpenAPIHono<Env>();
1042
1070
 
1043
- app.use("*", async (c, next) => {
1044
- initDB(c.env.DB);
1045
- await next();
1046
- });
1047
-
1048
1071
  app.route("/", api);
1049
1072
 
1050
1073
  app.doc("/api/openapi.json", {
@@ -1073,25 +1096,26 @@ createRoot(document.getElementById("app")!).render(
1073
1096
  } else {
1074
1097
  writeBlankTemplate(targetDir, name);
1075
1098
  }
1099
+ const pm = detectPackageManager();
1076
1100
  console.log();
1077
1101
  console.log(` Created ${name} in ${path3.relative(process.cwd(), targetDir)}/`);
1078
1102
  console.log();
1079
1103
  console.log(" Get started:");
1080
1104
  console.log(` cd ${path3.relative(process.cwd(), targetDir)}`);
1081
- console.log(" pnpm install");
1082
- console.log(" pnpm dev # local dev at http://localhost:5173");
1083
- console.log(" pnpm deploy # deploy to production");
1105
+ console.log(` ${pm} install`);
1106
+ console.log(` ${pm} ${pm === "npm" ? "run " : ""}dev # local dev at http://localhost:5173`);
1107
+ console.log(` ${pm} ${pm === "npm" ? "run " : ""}deploy # deploy to production`);
1084
1108
  console.log();
1085
1109
  }
1086
1110
  async function initWebsite(dir, opts) {
1087
1111
  const name = opts?.name || await ask2("Site name: ") || "my-site";
1088
1112
  const slug = slugify(name);
1089
1113
  const targetDir = dir ? path3.resolve(dir) : path3.resolve(slug);
1090
- if (fs2.existsSync(targetDir) && fs2.readdirSync(targetDir).length > 0) {
1114
+ if (fs3.existsSync(targetDir) && fs3.readdirSync(targetDir).length > 0) {
1091
1115
  console.error(`Directory ${targetDir} is not empty.`);
1092
1116
  process.exit(1);
1093
1117
  }
1094
- fs2.mkdirSync(targetDir, { recursive: true });
1118
+ fs3.mkdirSync(targetDir, { recursive: true });
1095
1119
  write(targetDir, "clawnify.json", JSON.stringify({
1096
1120
  $schema: "https://app.clawnify.com/schema/v1/clawnify.json",
1097
1121
  version: 1,
@@ -1211,21 +1235,17 @@ import BaseLayout from "../layouts/BaseLayout.astro";
1211
1235
  console.log();
1212
1236
  }
1213
1237
  function writeBlankTemplate(dir, name) {
1214
- write(dir, "schema.sql", `CREATE TABLE IF NOT EXISTS items (
1215
- id INTEGER PRIMARY KEY AUTOINCREMENT,
1216
- name TEXT NOT NULL,
1217
- created_at TEXT NOT NULL DEFAULT (datetime('now'))
1218
- );
1219
- `);
1220
1238
  write(dir, "src/server/routes.ts", `import { OpenAPIHono, createRoute, z } from "@hono/zod-openapi";
1221
- import { query } from "./db";
1239
+ import { getDB, desc } from "@clawnify/db";
1240
+ import * as schema from "./schema";
1222
1241
 
1223
- const api = new OpenAPIHono();
1242
+ type Env = { Bindings: { DB: D1Database } };
1243
+ const api = new OpenAPIHono<Env>();
1224
1244
 
1225
1245
  const ItemSchema = z.object({
1226
1246
  id: z.number(),
1227
1247
  name: z.string(),
1228
- created_at: z.string(),
1248
+ createdAt: z.string(),
1229
1249
  }).openapi("Item");
1230
1250
 
1231
1251
  api.openapi(
@@ -1241,58 +1261,80 @@ api.openapi(
1241
1261
  },
1242
1262
  }),
1243
1263
  async (c) => {
1244
- const items = await query("SELECT * FROM items ORDER BY created_at DESC");
1264
+ const db = getDB(c.env, { schema });
1265
+ const items = await db
1266
+ .select()
1267
+ .from(schema.items)
1268
+ .orderBy(desc(schema.items.createdAt));
1245
1269
  return c.json(items);
1246
1270
  },
1247
1271
  );
1248
1272
 
1249
1273
  export default api;
1250
1274
  `);
1251
- write(dir, "src/client/app.tsx", `import { useState, useEffect } from "react";
1252
-
1253
- export function App() {
1254
- const [items, setItems] = useState<any[]>([]);
1255
-
1256
- useEffect(() => {
1257
- fetch("/api/items").then((r) => r.json()).then(setItems);
1258
- }, []);
1259
-
1275
+ write(dir, "src/client/app.tsx", `export function App() {
1260
1276
  return (
1261
- <div className="max-w-xl mx-auto mt-10 px-4">
1262
- <h1 className="text-2xl font-semibold mb-4">${name}</h1>
1263
- <ul className="space-y-2">
1264
- {items.map((item: any) => (
1265
- <li key={item.id} className="p-3 rounded-lg border border-gray-200 text-sm">
1266
- {item.name}
1277
+ <main className="min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 to-slate-100 px-6">
1278
+ <div className="max-w-xl w-full text-center">
1279
+ <div className="inline-flex items-center gap-2 rounded-full bg-white/80 backdrop-blur px-3 py-1 text-xs font-medium text-slate-600 ring-1 ring-slate-200">
1280
+ <span className="size-1.5 rounded-full bg-emerald-500" />
1281
+ Clawnify \xB7 live
1282
+ </div>
1283
+
1284
+ <h1 className="mt-6 text-4xl font-semibold tracking-tight text-slate-900">
1285
+ Welcome to ${name}
1286
+ </h1>
1287
+ <p className="mt-3 text-base text-slate-600">
1288
+ Edit <code className="rounded bg-slate-200/70 px-1.5 py-0.5 text-sm">src/client/app.tsx</code> to get started.
1289
+ </p>
1290
+
1291
+ <ul className="mt-8 grid gap-3 text-left text-sm text-slate-700">
1292
+ <li className="rounded-lg border border-slate-200 bg-white px-4 py-3">
1293
+ <span className="font-medium text-slate-900">Try the API.</span> Open <code>/api/items</code> \u2014 empty list to start.
1267
1294
  </li>
1268
- ))}
1269
- </ul>
1270
- {items.length === 0 && (
1271
- <p className="text-gray-400 mt-4 text-sm">No items yet.</p>
1272
- )}
1273
- </div>
1295
+ <li className="rounded-lg border border-slate-200 bg-white px-4 py-3">
1296
+ <span className="font-medium text-slate-900">Evolve the schema.</span> Edit <code>src/server/schema.ts</code>, then run <code>pnpm db:generate</code>.
1297
+ </li>
1298
+ <li className="rounded-lg border border-slate-200 bg-white px-4 py-3">
1299
+ <span className="font-medium text-slate-900">Deploy.</span> Run <code>pnpm deploy</code> to push live.
1300
+ </li>
1301
+ </ul>
1302
+
1303
+ <p className="mt-8 text-xs text-slate-500">
1304
+ Read{" "}
1305
+ <a href="https://github.com/clawnify/clawnify/blob/main/docs/build-a-clawnify-app.md" target="_blank" rel="noreferrer" className="underline underline-offset-2">
1306
+ docs/build-a-clawnify-app.md
1307
+ </a>{" "}
1308
+ for the full gold-standard guide.
1309
+ </p>
1310
+ </div>
1311
+ </main>
1274
1312
  );
1275
1313
  }
1276
1314
  `);
1277
1315
  }
1278
1316
  function writeCrudTemplate(dir, name) {
1279
- write(dir, "schema.sql", `CREATE TABLE IF NOT EXISTS items (
1280
- id INTEGER PRIMARY KEY AUTOINCREMENT,
1281
- title TEXT NOT NULL,
1282
- status TEXT NOT NULL DEFAULT 'active',
1283
- created_at TEXT NOT NULL DEFAULT (datetime('now'))
1284
- );
1317
+ write(dir, "src/server/schema.ts", `import { sqliteTable, text, integer } from "@clawnify/db";
1318
+
1319
+ export const items = sqliteTable("items", {
1320
+ id: integer("id").primaryKey({ autoIncrement: true }),
1321
+ title: text("title").notNull(),
1322
+ status: text("status").notNull().default("active"),
1323
+ createdAt: text("created_at").notNull().$default(() => new Date().toISOString()),
1324
+ });
1285
1325
  `);
1286
1326
  write(dir, "src/server/routes.ts", `import { OpenAPIHono, createRoute, z } from "@hono/zod-openapi";
1287
- import { query, run } from "./db";
1327
+ import { getDB, eq, desc } from "@clawnify/db";
1328
+ import * as schema from "./schema";
1288
1329
 
1289
- const api = new OpenAPIHono();
1330
+ type Env = { Bindings: { DB: D1Database } };
1331
+ const api = new OpenAPIHono<Env>();
1290
1332
 
1291
1333
  const ItemSchema = z.object({
1292
1334
  id: z.number(),
1293
1335
  title: z.string(),
1294
1336
  status: z.string(),
1295
- created_at: z.string(),
1337
+ createdAt: z.string(),
1296
1338
  }).openapi("Item");
1297
1339
 
1298
1340
  const CreateItemSchema = z.object({ title: z.string().min(1) }).openapi("CreateItem");
@@ -1316,7 +1358,11 @@ api.openapi(
1316
1358
  },
1317
1359
  }),
1318
1360
  async (c) => {
1319
- const items = await query("SELECT * FROM items ORDER BY created_at DESC");
1361
+ const db = getDB(c.env, { schema });
1362
+ const items = await db
1363
+ .select()
1364
+ .from(schema.items)
1365
+ .orderBy(desc(schema.items.createdAt));
1320
1366
  return c.json(items);
1321
1367
  },
1322
1368
  );
@@ -1336,8 +1382,12 @@ api.openapi(
1336
1382
  }),
1337
1383
  async (c) => {
1338
1384
  const { title } = c.req.valid("json");
1339
- const result = await run("INSERT INTO items (title) VALUES (?)", [title.trim()]);
1340
- return c.json({ id: result.lastInsertRowid, title: title.trim(), status: "active", created_at: new Date().toISOString() }, 201);
1385
+ const db = getDB(c.env, { schema });
1386
+ const [row] = await db
1387
+ .insert(schema.items)
1388
+ .values({ title: title.trim() })
1389
+ .returning();
1390
+ return c.json(row, 201);
1341
1391
  },
1342
1392
  );
1343
1393
 
@@ -1357,13 +1407,12 @@ api.openapi(
1357
1407
  async (c) => {
1358
1408
  const { id } = c.req.valid("param");
1359
1409
  const body = c.req.valid("json");
1360
- const sets: string[] = [];
1361
- const params: unknown[] = [];
1362
- if (body.title !== undefined) { sets.push("title = ?"); params.push(body.title); }
1363
- if (body.status !== undefined) { sets.push("status = ?"); params.push(body.status); }
1364
- if (sets.length === 0) return c.json({ ok: false }, 400);
1365
- params.push(id);
1366
- await run(\`UPDATE items SET \${sets.join(", ")} WHERE id = ?\`, params);
1410
+ const patch: Partial<typeof schema.items.$inferInsert> = {};
1411
+ if (body.title !== undefined) patch.title = body.title;
1412
+ if (body.status !== undefined) patch.status = body.status;
1413
+ if (Object.keys(patch).length === 0) return c.json({ ok: false }, 400);
1414
+ const db = getDB(c.env, { schema });
1415
+ await db.update(schema.items).set(patch).where(eq(schema.items.id, Number(id)));
1367
1416
  return c.json({ ok: true });
1368
1417
  },
1369
1418
  );
@@ -1380,7 +1429,8 @@ api.openapi(
1380
1429
  }),
1381
1430
  async (c) => {
1382
1431
  const { id } = c.req.valid("param");
1383
- await run("DELETE FROM items WHERE id = ?", [id]);
1432
+ const db = getDB(c.env, { schema });
1433
+ await db.delete(schema.items).where(eq(schema.items.id, Number(id)));
1384
1434
  return c.json({ ok: true });
1385
1435
  },
1386
1436
  );
@@ -1393,7 +1443,7 @@ interface Item {
1393
1443
  id: number;
1394
1444
  title: string;
1395
1445
  status: string;
1396
- created_at: string;
1446
+ createdAt: string;
1397
1447
  }
1398
1448
 
1399
1449
  export function App() {
@@ -1484,14 +1534,14 @@ export function App() {
1484
1534
  }
1485
1535
  function write(dir, file, content) {
1486
1536
  const fullPath = path3.join(dir, file);
1487
- fs2.mkdirSync(path3.dirname(fullPath), { recursive: true });
1488
- fs2.writeFileSync(fullPath, content);
1537
+ fs3.mkdirSync(path3.dirname(fullPath), { recursive: true });
1538
+ fs3.writeFileSync(fullPath, content);
1489
1539
  }
1490
1540
 
1491
1541
  // src/commands/dev.ts
1492
- import fs3 from "fs";
1542
+ import fs4 from "fs";
1493
1543
  import path4 from "path";
1494
- import { spawn } from "child_process";
1544
+ import { spawn as spawn2 } from "child_process";
1495
1545
  function slugify2(name) {
1496
1546
  return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 30);
1497
1547
  }
@@ -1552,24 +1602,32 @@ async function devCommand(dir, options) {
1552
1602
  const storage = manifest.app.storage === true;
1553
1603
  const apiPort = options?.port || "8787";
1554
1604
  const clawnifyDir = path4.join(resolvedDir, ".clawnify");
1555
- fs3.mkdirSync(clawnifyDir, { recursive: true });
1605
+ fs4.mkdirSync(clawnifyDir, { recursive: true });
1556
1606
  const wranglerPath = path4.join(clawnifyDir, "wrangler.toml");
1557
- fs3.writeFileSync(wranglerPath, generateWranglerToml(slug, { database, storage }));
1558
- const schemaCandidates = [
1559
- path4.join(resolvedDir, "schema.sql"),
1560
- path4.join(resolvedDir, "src/server/schema.sql")
1561
- ];
1562
- const schemaPath = schemaCandidates.find((p) => fs3.existsSync(p));
1563
- if (database && schemaPath) {
1564
- await runQuiet(resolvedDir, "npx", [
1565
- "wrangler",
1566
- "d1",
1567
- "execute",
1568
- `${slug}-db`,
1569
- "--local",
1570
- `--file=${schemaPath}`,
1571
- `--config=${wranglerPath}`
1572
- ]);
1607
+ fs4.writeFileSync(wranglerPath, generateWranglerToml(slug, { database, storage }));
1608
+ if (database) {
1609
+ const schemaTsPath = path4.join(resolvedDir, "src/server/schema.ts");
1610
+ const drizzleConfigPath = path4.join(resolvedDir, "drizzle.config.ts");
1611
+ if (fs4.existsSync(schemaTsPath) && fs4.existsSync(drizzleConfigPath)) {
1612
+ await syncDrizzleToLocalD1(resolvedDir, clawnifyDir, slug, wranglerPath);
1613
+ } else {
1614
+ const schemaCandidates = [
1615
+ path4.join(resolvedDir, "schema.sql"),
1616
+ path4.join(resolvedDir, "src/server/schema.sql")
1617
+ ];
1618
+ const schemaPath = schemaCandidates.find((p) => fs4.existsSync(p));
1619
+ if (schemaPath) {
1620
+ await runQuiet(resolvedDir, "npx", [
1621
+ "wrangler",
1622
+ "d1",
1623
+ "execute",
1624
+ `${slug}-db`,
1625
+ "--local",
1626
+ `--file=${schemaPath}`,
1627
+ `--config=${wranglerPath}`
1628
+ ]);
1629
+ }
1630
+ }
1573
1631
  }
1574
1632
  console.log();
1575
1633
  console.log(` ${manifest.name} dev server`);
@@ -1577,12 +1635,12 @@ async function devCommand(dir, options) {
1577
1635
  console.log(` UI: http://localhost:5173`);
1578
1636
  console.log(` API: http://localhost:${apiPort}`);
1579
1637
  console.log();
1580
- const vite = spawn("npx", ["vite"], {
1638
+ const vite = spawn2("npx", ["vite"], {
1581
1639
  cwd: resolvedDir,
1582
1640
  stdio: ["ignore", "pipe", "pipe"],
1583
1641
  env: { ...process.env }
1584
1642
  });
1585
- const wrangler = spawn("npx", [
1643
+ const wrangler = spawn2("npx", [
1586
1644
  "wrangler",
1587
1645
  "dev",
1588
1646
  `--port=${apiPort}`,
@@ -1641,7 +1699,7 @@ function createFilter(label) {
1641
1699
  }
1642
1700
  function runQuiet(cwd, cmd, args) {
1643
1701
  return new Promise((resolve, reject) => {
1644
- const proc = spawn(cmd, args, {
1702
+ const proc = spawn2(cmd, args, {
1645
1703
  cwd,
1646
1704
  stdio: ["ignore", "pipe", "pipe"],
1647
1705
  env: { ...process.env }
@@ -1659,6 +1717,47 @@ function runQuiet(cwd, cmd, args) {
1659
1717
  });
1660
1718
  });
1661
1719
  }
1720
+ async function syncDrizzleToLocalD1(resolvedDir, clawnifyDir, slug, wranglerPath) {
1721
+ try {
1722
+ await runQuiet(resolvedDir, "npx", ["drizzle-kit", "generate"]);
1723
+ } catch (err) {
1724
+ console.error(
1725
+ ` drizzle-kit generate failed. Is \`drizzle-kit\` in devDependencies?
1726
+ ${err.message}`
1727
+ );
1728
+ throw err;
1729
+ }
1730
+ const drizzleDir = path4.join(clawnifyDir, "drizzle");
1731
+ if (!fs4.existsSync(drizzleDir)) return;
1732
+ const sqlFiles = fs4.readdirSync(drizzleDir).filter((name) => name.endsWith(".sql")).sort();
1733
+ if (sqlFiles.length === 0) return;
1734
+ const appliedPath = path4.join(clawnifyDir, "applied-migrations.json");
1735
+ let applied = [];
1736
+ if (fs4.existsSync(appliedPath)) {
1737
+ try {
1738
+ applied = JSON.parse(fs4.readFileSync(appliedPath, "utf8"));
1739
+ if (!Array.isArray(applied)) applied = [];
1740
+ } catch {
1741
+ applied = [];
1742
+ }
1743
+ }
1744
+ const appliedSet = new Set(applied);
1745
+ for (const file of sqlFiles) {
1746
+ if (appliedSet.has(file)) continue;
1747
+ const filePath = path4.join(drizzleDir, file);
1748
+ await runQuiet(resolvedDir, "npx", [
1749
+ "wrangler",
1750
+ "d1",
1751
+ "execute",
1752
+ `${slug}-db`,
1753
+ "--local",
1754
+ `--file=${filePath}`,
1755
+ `--config=${wranglerPath}`
1756
+ ]);
1757
+ applied.push(file);
1758
+ }
1759
+ fs4.writeFileSync(appliedPath, JSON.stringify(applied, null, 2) + "\n");
1760
+ }
1662
1761
 
1663
1762
  // src/commands/link.ts
1664
1763
  import path5 from "path";
@@ -1819,7 +1918,7 @@ async function orgUseCommand(slugOrId) {
1819
1918
  }
1820
1919
 
1821
1920
  // src/commands/execute.ts
1822
- import fs4 from "fs";
1921
+ import fs5 from "fs";
1823
1922
 
1824
1923
  // src/lib/mcp-client.ts
1825
1924
  var MCP_URL = "https://mcp.clawnify.com/mcp";
@@ -1869,7 +1968,7 @@ async function executeCommand(file, options) {
1869
1968
  code = options.code;
1870
1969
  } else if (file) {
1871
1970
  try {
1872
- code = fs4.readFileSync(file, "utf-8");
1971
+ code = fs5.readFileSync(file, "utf-8");
1873
1972
  } catch (err) {
1874
1973
  process.stderr.write(`Failed to read ${file}: ${String(err)}
1875
1974
  `);
@@ -2006,7 +2105,7 @@ async function sdkInstallCommand() {
2006
2105
  }
2007
2106
 
2008
2107
  // src/lib/skills/content.gen.ts
2009
- var CLI_VERSION = "0.3.0";
2108
+ var CLI_VERSION = "0.5.0";
2010
2109
  var BUNDLED_SKILLS = [
2011
2110
  {
2012
2111
  name: "build-a-clawnify-app",
@@ -2342,7 +2441,7 @@ Valid: ${ALL_AGENTS.join(", ")}`
2342
2441
  function runCli() {
2343
2442
  const program = new Command();
2344
2443
  program.name("clawnify").description("Deploy apps to Clawnify").version("0.1.0");
2345
- 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);
2444
+ 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").option("-y, --yes", "Non-interactive: use all defaults (app, blank, no storage)").action(initCommand);
2346
2445
  program.command("dev [dir]").description("Start local dev server").option("--port <port>", "API server port (default: 8787)").action(devCommand);
2347
2446
  program.command("login").description("Authenticate with Clawnify").action(loginCommand);
2348
2447
  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);
@@ -2373,4 +2472,4 @@ function runCli() {
2373
2472
  export {
2374
2473
  runCli
2375
2474
  };
2376
- //# sourceMappingURL=cli-P6F6JKMF.js.map
2475
+ //# sourceMappingURL=cli-XYGLEX6Q.js.map