@vaiftech/cli 1.6.0 → 1.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- 'use strict';var commander=require('commander'),N=require('fs'),A=require('path'),et=require('pg'),q=require('ora'),f=require('chalk'),ot=require('prettier'),Ze=require('dotenv'),pe=require('readline'),pt=require('os'),child_process=require('child_process');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var N__default=/*#__PURE__*/_interopDefault(N);var A__default=/*#__PURE__*/_interopDefault(A);var et__default=/*#__PURE__*/_interopDefault(et);var q__default=/*#__PURE__*/_interopDefault(q);var f__default=/*#__PURE__*/_interopDefault(f);var ot__default=/*#__PURE__*/_interopDefault(ot);var Ze__default=/*#__PURE__*/_interopDefault(Ze);var pe__default=/*#__PURE__*/_interopDefault(pe);var pt__default=/*#__PURE__*/_interopDefault(pt);Ze__default.default.config();async function I(t){let e=A__default.default.resolve(t);if(!N__default.default.existsSync(e))return null;try{let o=N__default.default.readFileSync(e,"utf-8"),n=JSON.parse(o);return n.database?.url&&(n.database.url=le(n.database.url)),n.api?.apiKey&&(n.api.apiKey=le(n.api.apiKey)),n}catch{throw new Error(`Failed to parse config file: ${t}`)}}function le(t){return t.replace(/\$\{([^}]+)\}/g,(e,o)=>process.env[o]||e)}async function nt(t,e){let o=await t.query(`
2
+ 'use strict';require('dotenv/config');var commander=require('commander'),N=require('fs'),A=require('path'),et=require('pg'),q=require('ora'),f=require('chalk'),ot=require('prettier'),Ze=require('dotenv'),pe=require('readline'),pt=require('os'),child_process=require('child_process');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var N__default=/*#__PURE__*/_interopDefault(N);var A__default=/*#__PURE__*/_interopDefault(A);var et__default=/*#__PURE__*/_interopDefault(et);var q__default=/*#__PURE__*/_interopDefault(q);var f__default=/*#__PURE__*/_interopDefault(f);var ot__default=/*#__PURE__*/_interopDefault(ot);var Ze__default=/*#__PURE__*/_interopDefault(Ze);var pe__default=/*#__PURE__*/_interopDefault(pe);var pt__default=/*#__PURE__*/_interopDefault(pt);Ze__default.default.config();async function I(t){let e=A__default.default.resolve(t);if(!N__default.default.existsSync(e))return null;try{let o=N__default.default.readFileSync(e,"utf-8"),n=JSON.parse(o);return n.database?.url&&(n.database.url=le(n.database.url)),n.api?.apiKey&&(n.api.apiKey=le(n.api.apiKey)),n}catch{throw new Error(`Failed to parse config file: ${t}`)}}function le(t){return t.replace(/\$\{([^}]+)\}/g,(e,o)=>process.env[o]||e)}async function nt(t,e){let o=await t.query(`
3
3
  SELECT table_name, table_type
4
4
  FROM information_schema.tables
5
5
  WHERE table_schema = $1
@@ -60,7 +60,7 @@ ${i.join(`
60
60
  `)}async function de(t){let e=q__default.default("Loading configuration...").start();try{let o=await I(t.config),n=t.connection||o?.database?.url||process.env.DATABASE_URL;n||(e.fail("No database connection string provided"),console.log(f__default.default.yellow(`
61
61
  Provide a connection string via:`)),console.log(f__default.default.gray(" --connection <url>")),console.log(f__default.default.gray(" DATABASE_URL environment variable")),console.log(f__default.default.gray(" vaif.config.json database.url")),process.exit(1)),e.text="Connecting to database...";let r=new et__default.default.Client({connectionString:n});await r.connect(),e.text="Introspecting schema...";let{tables:l,enums:i,foreignKeys:a}=await nt(r,t.schema);if(await r.end(),l.size===0){e.warn(`No tables found in schema "${t.schema}"`);return}e.text=`Generating types for ${l.size} tables...`;let s=st(l,i,a),c=await ot__default.default.format(s,{parser:"typescript",semi:!0,singleQuote:!1,trailingComma:"es5",printWidth:100});if(t.dryRun){e.succeed("Generated types (dry run):"),console.log(""),console.log(f__default.default.gray("\u2500".repeat(60))),console.log(c),console.log(f__default.default.gray("\u2500".repeat(60)));return}let d=A__default.default.resolve(t.output),u=A__default.default.dirname(d);N__default.default.existsSync(u)||N__default.default.mkdirSync(u,{recursive:!0}),N__default.default.writeFileSync(d,c,"utf-8"),e.succeed(`Generated types for ${l.size} tables \u2192 ${f__default.default.cyan(t.output)}`),console.log(""),console.log(f__default.default.green("Generated:")),console.log(f__default.default.gray(` Tables: ${l.size}`)),console.log(f__default.default.gray(` Enums: ${i.size}`)),console.log(""),console.log(f__default.default.gray("Import in your code:")),console.log(f__default.default.cyan(` import type { Database, Row, Insert, Update } from "${t.output.replace(/\.ts$/,"")}";`));}catch(o){e.fail("Failed to generate types"),o instanceof Error&&(console.error(f__default.default.red(`
62
62
  Error: ${o.message}`)),o.message.includes("ECONNREFUSED")&&console.log(f__default.default.yellow(`
63
- Make sure your database is running and accessible.`))),process.exit(1);}}var O=[{name:"database",label:"Database",description:"CRUD queries, type-safe operations"},{name:"auth",label:"Authentication",description:"login, signup, OAuth, sessions"},{name:"realtime",label:"Realtime",description:"live subscriptions, presence"},{name:"storage",label:"Storage",description:"file uploads, signed URLs"},{name:"functions",label:"Functions",description:"serverless function calls"}],ue={"nextjs-fullstack":{name:"Next.js Full-Stack",description:"Next.js app with server/client VAIF client, auth middleware, and React hooks",tag:"Next.js",defaultFeatures:["database","auth"],files:[{path:"package.json",content:`{
63
+ Make sure your database is running and accessible.`))),process.exit(1);}}var $=[{name:"database",label:"Database",description:"CRUD queries, type-safe operations"},{name:"auth",label:"Authentication",description:"login, signup, OAuth, sessions"},{name:"realtime",label:"Realtime",description:"live subscriptions, presence"},{name:"storage",label:"Storage",description:"file uploads, signed URLs"},{name:"functions",label:"Functions",description:"serverless function calls"}],ue={"nextjs-fullstack":{name:"Next.js Full-Stack",description:"Next.js app with server/client VAIF client, auth middleware, and React hooks",tag:"Next.js",defaultFeatures:["database","auth"],files:[{path:"package.json",content:`{
64
64
  "name": "my-vaif-app",
65
65
  "private": true,
66
66
  "version": "0.1.0",
@@ -82,6 +82,7 @@ Make sure your database is running and accessible.`))),process.exit(1);}}var O=[
82
82
  "@types/node": "^22.0.0",
83
83
  "@types/react": "^19.0.0",
84
84
  "@types/react-dom": "^19.0.0",
85
+ "drizzle-kit": "^0.30.0",
85
86
  "typescript": "^5.7.0"
86
87
  }
87
88
  }
@@ -151,18 +152,17 @@ body {
151
152
  -webkit-font-smoothing: antialiased;
152
153
  -moz-osx-font-smoothing: grayscale;
153
154
  }
154
- `},{path:"lib/vaif.ts",content:`import { createClient } from "@vaiftech/client";
155
- import { createServerClient } from "@vaiftech/client/server";
155
+ `},{path:"lib/vaif.ts",content:`import { createVaifClient } from "@vaiftech/client";
156
156
 
157
157
  // Browser client \u2013 safe to use in Client Components
158
- export const vaif = createClient({
158
+ export const vaif = createVaifClient({
159
159
  projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID!,
160
160
  apiKey: process.env.NEXT_PUBLIC_VAIF_API_KEY!,
161
161
  });
162
162
 
163
163
  // Server client \u2013 use in Server Components, Route Handlers, Server Actions
164
164
  export function createVaifServer() {
165
- return createServerClient({
165
+ return createVaifClient({
166
166
  projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID!,
167
167
  secretKey: process.env.VAIF_SECRET_KEY!,
168
168
  });
@@ -173,6 +173,9 @@ export function createVaifServer() {
173
173
  NEXT_PUBLIC_VAIF_PROJECT_ID=your-project-id
174
174
  NEXT_PUBLIC_VAIF_API_KEY=your-anon-key
175
175
  VAIF_SECRET_KEY=your-secret-key
176
+
177
+ # CLI uses these (non-prefixed) for vaif db push, vaif secrets, etc.
178
+ VAIF_PROJECT_ID=your-project-id
176
179
  `},{path:".gitignore",content:`node_modules
177
180
  .next
178
181
  out
@@ -275,7 +278,7 @@ A full-stack Next.js application powered by [VAIF Studio](https://vaif.studio),
275
278
 
276
279
  Full documentation is available at <https://docs.vaif.studio>.
277
280
  `}],featureFiles:{auth:[{path:"middleware.ts",content:`import { NextResponse, type NextRequest } from "next/server";
278
- import { createServerClient } from "@vaiftech/client/server";
281
+ import { createVaifClient } from "@vaiftech/client";
279
282
  import { authMiddleware } from "@vaiftech/auth/nextjs";
280
283
 
281
284
  const protectedRoutes = ["/dashboard", "/settings", "/api/protected"];
@@ -285,7 +288,7 @@ export async function middleware(request: NextRequest) {
285
288
  const isProtected = protectedRoutes.some((route) => pathname.startsWith(route));
286
289
  if (!isProtected) return NextResponse.next();
287
290
 
288
- const vaif = createServerClient({
291
+ const vaif = createVaifClient({
289
292
  projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID!,
290
293
  secretKey: process.env.VAIF_SECRET_KEY!,
291
294
  });
@@ -553,9 +556,11 @@ export const posts = pgTable("posts", {
553
556
  "react-router-dom": "^7.0.0"
554
557
  },
555
558
  "devDependencies": {
559
+ "@types/node": "^22.0.0",
556
560
  "@types/react": "^19.0.0",
557
561
  "@types/react-dom": "^19.0.0",
558
562
  "@vitejs/plugin-react": "^4.4.0",
563
+ "drizzle-kit": "^0.30.0",
559
564
  "typescript": "^5.7.0",
560
565
  "vite": "^6.0.0"
561
566
  }
@@ -643,9 +648,9 @@ function Home() {
643
648
  </div>
644
649
  );
645
650
  }
646
- `},{path:"src/lib/vaif.ts",content:`import { createClient } from "@vaiftech/client";
651
+ `},{path:"src/lib/vaif.ts",content:`import { createVaifClient } from "@vaiftech/client";
647
652
 
648
- export const vaif = createClient({
653
+ export const vaif = createVaifClient({
649
654
  projectId: import.meta.env.VITE_VAIF_PROJECT_ID,
650
655
  apiKey: import.meta.env.VITE_VAIF_API_KEY,
651
656
  });
@@ -664,6 +669,9 @@ interface ImportMeta {
664
669
 
665
670
  VITE_VAIF_PROJECT_ID=your-project-id
666
671
  VITE_VAIF_API_KEY=your-anon-key
672
+
673
+ # CLI uses these (non-prefixed) for vaif db push, vaif secrets, etc.
674
+ VAIF_PROJECT_ID=your-project-id
667
675
  `},{path:".gitignore",content:`node_modules
668
676
  dist
669
677
  .env
@@ -1270,7 +1278,9 @@ Full documentation is available at <https://docs.vaif.studio>.
1270
1278
  "react-native": "~0.76.0"
1271
1279
  },
1272
1280
  "devDependencies": {
1281
+ "@types/node": "^22.0.0",
1273
1282
  "@types/react": "^19.0.0",
1283
+ "drizzle-kit": "^0.30.0",
1274
1284
  "typescript": "^5.7.0"
1275
1285
  }
1276
1286
  }
@@ -1327,6 +1337,9 @@ export const vaif = createExpoClient({
1327
1337
 
1328
1338
  EXPO_PUBLIC_VAIF_PROJECT_ID=your-project-id
1329
1339
  EXPO_PUBLIC_VAIF_API_KEY=your-anon-key
1340
+
1341
+ # CLI uses these (non-prefixed) for vaif db push, vaif secrets, etc.
1342
+ VAIF_PROJECT_ID=your-project-id
1330
1343
  `},{path:".gitignore",content:`node_modules
1331
1344
  .expo
1332
1345
  dist
@@ -2594,9 +2607,9 @@ func HelloHandler(w http.ResponseWriter, r *http.Request) {
2594
2607
  Message: fmt.Sprintf("Hello, %s!", req.Name),
2595
2608
  })
2596
2609
  }
2597
- `}]},postInstructions:["go mod tidy","# Copy .env.example to .env and add your VAIF credentials","go run main.go"]},"todo-app":{name:"Todo App",description:"Simple React todo app \u2013 great for learning VAIF basics",tag:"React Starter",defaultFeatures:["database"],files:[{path:"src/lib/vaif.ts",content:`import { createClient } from "@vaiftech/client";
2610
+ `}]},postInstructions:["go mod tidy","# Copy .env.example to .env and add your VAIF credentials","go run main.go"]},"todo-app":{name:"Todo App",description:"Simple React todo app \u2013 great for learning VAIF basics",tag:"React Starter",defaultFeatures:["database"],files:[{path:"src/lib/vaif.ts",content:`import { createVaifClient } from "@vaiftech/client";
2598
2611
 
2599
- export const vaif = createClient({
2612
+ export const vaif = createVaifClient({
2600
2613
  projectId: import.meta.env.VITE_VAIF_PROJECT_ID,
2601
2614
  apiKey: import.meta.env.VITE_VAIF_API_KEY,
2602
2615
  });
@@ -2653,6 +2666,9 @@ export async function deleteTodo(id: string): Promise<void> {
2653
2666
 
2654
2667
  VITE_VAIF_PROJECT_ID=your-project-id
2655
2668
  VITE_VAIF_API_KEY=your-anon-key
2669
+
2670
+ # CLI uses these (non-prefixed) for vaif db push, vaif secrets, etc.
2671
+ VAIF_PROJECT_ID=your-project-id
2656
2672
  `},{path:"README.md",content:`# Todo App \u2014 VAIF Starter
2657
2673
 
2658
2674
  A simple React todo application for learning [VAIF Studio](https://vaif.studio) basics, including typed database queries and CRUD operations.
@@ -2785,9 +2801,9 @@ export const posts = pgTable("posts", {
2785
2801
 
2786
2802
  return Response.json({ message: \`Hello, \${name}!\` });
2787
2803
  }
2788
- `}]},dependencies:["@vaiftech/client","@vaiftech/react"],postInstructions:["Copy .env.example to .env and fill in your project credentials","Create a 'todos' table in your VAIF dashboard with columns: id (uuid), title (text), done (boolean), created_at (timestamptz)","Import helpers from './lib/vaif' in your components","Run: npx vaif generate to generate TypeScript types"]},"realtime-chat":{name:"Realtime Chat",description:"React chat app with VAIF realtime subscriptions for live messaging",tag:"React + Realtime",defaultFeatures:["database","realtime","auth"],files:[{path:"src/lib/vaif.ts",content:`import { createClient } from "@vaiftech/client";
2804
+ `}]},dependencies:["@vaiftech/client","@vaiftech/react"],postInstructions:["Copy .env.example to .env and fill in your project credentials","Create a 'todos' table in your VAIF dashboard with columns: id (uuid), title (text), done (boolean), created_at (timestamptz)","Import helpers from './lib/vaif' in your components","Run: npx vaif generate to generate TypeScript types"]},"realtime-chat":{name:"Realtime Chat",description:"React chat app with VAIF realtime subscriptions for live messaging",tag:"React + Realtime",defaultFeatures:["database","realtime","auth"],files:[{path:"src/lib/vaif.ts",content:`import { createVaifClient } from "@vaiftech/client";
2789
2805
 
2790
- export const vaif = createClient({
2806
+ export const vaif = createVaifClient({
2791
2807
  projectId: import.meta.env.VITE_VAIF_PROJECT_ID,
2792
2808
  apiKey: import.meta.env.VITE_VAIF_API_KEY,
2793
2809
  realtime: {
@@ -2938,6 +2954,9 @@ export function useRealtimeMessages({
2938
2954
 
2939
2955
  VITE_VAIF_PROJECT_ID=your-project-id
2940
2956
  VITE_VAIF_API_KEY=your-anon-key
2957
+
2958
+ # CLI uses these (non-prefixed) for vaif db push, vaif secrets, etc.
2959
+ VAIF_PROJECT_ID=your-project-id
2941
2960
  `},{path:"README.md",content:`# Realtime Chat \u2014 VAIF Starter
2942
2961
 
2943
2962
  A React chat application with live messaging powered by [VAIF Studio](https://vaif.studio) realtime subscriptions.
@@ -3084,18 +3103,17 @@ export const posts = pgTable("posts", {
3084
3103
 
3085
3104
  return Response.json({ message: \`Hello, \${name}!\` });
3086
3105
  }
3087
- `}]},dependencies:["@vaiftech/client","@vaiftech/react"],postInstructions:["Copy .env.example to .env and fill in your project credentials","Create a 'messages' table with columns: id (uuid), content (text), user_id (text), username (text), channel_id (text), created_at (timestamptz)","Enable Realtime on the messages table in your VAIF dashboard","Use the useRealtimeMessages hook in your components","Run: npx vaif generate to generate TypeScript types"]},"saas-starter":{name:"SaaS Starter",description:"Full SaaS starter with VAIF auth, team/org support, and server-side helpers",tag:"Next.js SaaS",defaultFeatures:["database","auth","functions"],files:[{path:"lib/vaif.ts",content:`import { createClient } from "@vaiftech/client";
3088
- import { createServerClient } from "@vaiftech/client/server";
3106
+ `}]},dependencies:["@vaiftech/client","@vaiftech/react"],postInstructions:["Copy .env.example to .env and fill in your project credentials","Create a 'messages' table with columns: id (uuid), content (text), user_id (text), username (text), channel_id (text), created_at (timestamptz)","Enable Realtime on the messages table in your VAIF dashboard","Use the useRealtimeMessages hook in your components","Run: npx vaif generate to generate TypeScript types"]},"saas-starter":{name:"SaaS Starter",description:"Full SaaS starter with VAIF auth, team/org support, and server-side helpers",tag:"Next.js SaaS",defaultFeatures:["database","auth","functions"],files:[{path:"lib/vaif.ts",content:`import { createVaifClient } from "@vaiftech/client";
3089
3107
 
3090
3108
  // Browser client \u2013 use in Client Components
3091
- export const vaif = createClient({
3109
+ export const vaif = createVaifClient({
3092
3110
  projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID!,
3093
3111
  apiKey: process.env.NEXT_PUBLIC_VAIF_API_KEY!,
3094
3112
  });
3095
3113
 
3096
3114
  // Server client \u2013 use in Server Components, Route Handlers, Server Actions
3097
3115
  export function createVaifServer() {
3098
- return createServerClient({
3116
+ return createVaifClient({
3099
3117
  projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID!,
3100
3118
  secretKey: process.env.VAIF_SECRET_KEY!,
3101
3119
  });
@@ -3253,6 +3271,9 @@ export async function requireTeamRole(
3253
3271
  NEXT_PUBLIC_VAIF_PROJECT_ID=your-project-id
3254
3272
  NEXT_PUBLIC_VAIF_API_KEY=your-anon-key
3255
3273
  VAIF_SECRET_KEY=your-secret-key
3274
+
3275
+ # CLI uses these (non-prefixed) for vaif db push, vaif secrets, etc.
3276
+ VAIF_PROJECT_ID=your-project-id
3256
3277
  `},{path:"README.md",content:`# SaaS Starter \u2014 VAIF Studio
3257
3278
 
3258
3279
  A full SaaS starter kit powered by [VAIF Studio](https://vaif.studio) with authentication, team/organization support, role-based access control, and server-side helpers.
@@ -3395,18 +3416,17 @@ export const posts = pgTable("posts", {
3395
3416
 
3396
3417
  return Response.json({ message: \`Hello, \${name}!\` });
3397
3418
  }
3398
- `}]},dependencies:["@vaiftech/client","@vaiftech/auth","@vaiftech/react"],postInstructions:["Copy .env.example to .env.local and fill in your project credentials","Create 'teams' and 'team_members' tables in your VAIF dashboard","Import auth helpers from '@/lib/auth' in your Server Components/Actions","Use requireUser() for authenticated routes and requireTeamRole() for role checks","Run: npx vaif generate to generate TypeScript types"]},"ecommerce-api":{name:"E-commerce API",description:"API-first e-commerce setup with VAIF storage for product images",tag:"Next.js E-commerce",defaultFeatures:["database","auth","storage"],files:[{path:"lib/vaif.ts",content:`import { createClient } from "@vaiftech/client";
3399
- import { createServerClient } from "@vaiftech/client/server";
3419
+ `}]},dependencies:["@vaiftech/client","@vaiftech/auth","@vaiftech/react"],postInstructions:["Copy .env.example to .env.local and fill in your project credentials","Create 'teams' and 'team_members' tables in your VAIF dashboard","Import auth helpers from '@/lib/auth' in your Server Components/Actions","Use requireUser() for authenticated routes and requireTeamRole() for role checks","Run: npx vaif generate to generate TypeScript types"]},"ecommerce-api":{name:"E-commerce API",description:"API-first e-commerce setup with VAIF storage for product images",tag:"Next.js E-commerce",defaultFeatures:["database","auth","storage"],files:[{path:"lib/vaif.ts",content:`import { createVaifClient } from "@vaiftech/client";
3400
3420
 
3401
3421
  // Browser client
3402
- export const vaif = createClient({
3422
+ export const vaif = createVaifClient({
3403
3423
  projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID!,
3404
3424
  apiKey: process.env.NEXT_PUBLIC_VAIF_API_KEY!,
3405
3425
  });
3406
3426
 
3407
3427
  // Server client
3408
3428
  export function createVaifServer() {
3409
- return createServerClient({
3429
+ return createVaifClient({
3410
3430
  projectId: process.env.NEXT_PUBLIC_VAIF_PROJECT_ID!,
3411
3431
  secretKey: process.env.VAIF_SECRET_KEY!,
3412
3432
  });
@@ -3526,6 +3546,9 @@ function getContentType(fileName: string): string {
3526
3546
  NEXT_PUBLIC_VAIF_PROJECT_ID=your-project-id
3527
3547
  NEXT_PUBLIC_VAIF_API_KEY=your-anon-key
3528
3548
  VAIF_SECRET_KEY=your-secret-key
3549
+
3550
+ # CLI uses these (non-prefixed) for vaif db push, vaif secrets, etc.
3551
+ VAIF_PROJECT_ID=your-project-id
3529
3552
  `},{path:"README.md",content:`# E-commerce API \u2014 VAIF Studio
3530
3553
 
3531
3554
  An API-first e-commerce setup powered by [VAIF Studio](https://vaif.studio) with product image storage, signed URLs, and server-side helpers.
@@ -3666,54 +3689,54 @@ export const posts = pgTable("posts", {
3666
3689
 
3667
3690
  return Response.json({ message: \`Hello, \${name}!\` });
3668
3691
  }
3669
- `}]},dependencies:["@vaiftech/client","@vaiftech/auth"],postInstructions:["Copy .env.example to .env.local and fill in your project credentials","Create a 'product-images' storage bucket in your VAIF dashboard","Import storage helpers from '@/lib/storage' in your API routes","Use uploadProductImage() in your product creation flow","Run: npx vaif generate to generate TypeScript types"]}};function fe(){console.log(""),console.log(f__default.default.bold("Available project templates")),console.log("");let t=26,e=22;console.log(` ${f__default.default.gray("Template".padEnd(t))}${f__default.default.gray("Stack".padEnd(e))}${f__default.default.gray("Description")}`),console.log(f__default.default.gray(" "+"-".repeat(t+e+40)));for(let[o,n]of Object.entries(ue))console.log(` ${f__default.default.cyan(o.padEnd(t))}${f__default.default.yellow(n.tag.padEnd(e))}${f__default.default.white(n.description)}`);console.log(""),console.log(f__default.default.gray("Usage:")),console.log(f__default.default.gray(" npx @vaiftech/cli init --template <name>")),console.log(f__default.default.gray(" npx @vaiftech/cli init -t nextjs-fullstack")),console.log(f__default.default.gray(" npx @vaiftech/cli init -t react-spa --features auth,database,realtime")),console.log(""),console.log(f__default.default.gray("Available features: auth, database, realtime, storage, functions")),console.log("");}async function lt(t){if(!process.stdin.isTTY||!process.stdout.isTTY)return t;let e=new Set(t.map(n=>O.findIndex(r=>r.name===n)).filter(n=>n>=0)),o=0;return new Promise(n=>{let r=pe__default.default.createInterface({input:process.stdin,output:process.stdout});pe__default.default.emitKeypressEvents(process.stdin,r),process.stdin.setRawMode&&process.stdin.setRawMode(true);function l(){let a=O.length+2;process.stdout.write(`\x1B[${a}A`),i();}function i(){console.log(f__default.default.bold(`
3670
- ? Which VAIF features do you want to include?`)),O.forEach((a,s)=>{let c=e.has(s)?f__default.default.green("[x]"):"[ ]",d=s===o?f__default.default.cyan("> "):" ";console.log(`${d}${c} ${a.label} ${f__default.default.gray(`(${a.description})`)}`);}),console.log(f__default.default.gray(" (up/down to move, space to toggle, enter to confirm)"));}i(),process.stdin.on("keypress",(a,s)=>{if(s.name==="up"&&o>0)o--,l();else if(s.name==="down"&&o<O.length-1)o++,l();else if(s.name==="space")e.has(o)?e.delete(o):e.add(o),l();else if(s.name==="return"){process.stdin.setRawMode&&process.stdin.setRawMode(false),r.close();let c=[...e].sort().map(d=>O[d].name);n(c.length>0?c:t);}else s.name==="c"&&s.ctrl&&(process.stdin.setRawMode&&process.stdin.setRawMode(false),r.close(),process.exit(0));});})}async function ge(t,e={}){let o=ue[t];o||(console.log(f__default.default.red(`
3692
+ `}]},dependencies:["@vaiftech/client","@vaiftech/auth"],postInstructions:["Copy .env.example to .env.local and fill in your project credentials","Create a 'product-images' storage bucket in your VAIF dashboard","Import storage helpers from '@/lib/storage' in your API routes","Use uploadProductImage() in your product creation flow","Run: npx vaif generate to generate TypeScript types"]}};function fe(){console.log(""),console.log(f__default.default.bold("Available project templates")),console.log("");let t=26,e=22;console.log(` ${f__default.default.gray("Template".padEnd(t))}${f__default.default.gray("Stack".padEnd(e))}${f__default.default.gray("Description")}`),console.log(f__default.default.gray(" "+"-".repeat(t+e+40)));for(let[o,n]of Object.entries(ue))console.log(` ${f__default.default.cyan(o.padEnd(t))}${f__default.default.yellow(n.tag.padEnd(e))}${f__default.default.white(n.description)}`);console.log(""),console.log(f__default.default.gray("Usage:")),console.log(f__default.default.gray(" npx @vaiftech/cli init --template <name>")),console.log(f__default.default.gray(" npx @vaiftech/cli init -t nextjs-fullstack")),console.log(f__default.default.gray(" npx @vaiftech/cli init -t react-spa --features auth,database,realtime")),console.log(""),console.log(f__default.default.gray("Available features: auth, database, realtime, storage, functions")),console.log("");}async function lt(t){if(!process.stdin.isTTY||!process.stdout.isTTY)return t;let e=new Set(t.map(n=>$.findIndex(r=>r.name===n)).filter(n=>n>=0)),o=0;return new Promise(n=>{let r=pe__default.default.createInterface({input:process.stdin,output:process.stdout});pe__default.default.emitKeypressEvents(process.stdin,r),process.stdin.setRawMode&&process.stdin.setRawMode(true);function l(){let a=$.length+2;process.stdout.write(`\x1B[${a}A`),i();}function i(){console.log(f__default.default.bold(`
3693
+ ? Which VAIF features do you want to include?`)),$.forEach((a,s)=>{let c=e.has(s)?f__default.default.green("[x]"):"[ ]",d=s===o?f__default.default.cyan("> "):" ";console.log(`${d}${c} ${a.label} ${f__default.default.gray(`(${a.description})`)}`);}),console.log(f__default.default.gray(" (up/down to move, space to toggle, enter to confirm)"));}i(),process.stdin.on("keypress",(a,s)=>{if(s.name==="up"&&o>0)o--,l();else if(s.name==="down"&&o<$.length-1)o++,l();else if(s.name==="space")e.has(o)?e.delete(o):e.add(o),l();else if(s.name==="return"){process.stdin.setRawMode&&process.stdin.setRawMode(false),r.close();let c=[...e].sort().map(d=>$[d].name);n(c.length>0?c:t);}else s.name==="c"&&s.ctrl&&(process.stdin.setRawMode&&process.stdin.setRawMode(false),r.close(),process.exit(0));});})}async function ge(t,e={}){let o=ue[t];o||(console.log(f__default.default.red(`
3671
3694
  Unknown template: ${t}`)),console.log(f__default.default.yellow(`Run 'vaif templates' to see available templates.
3672
- `)),process.exit(1));let n;e.features&&e.features.length>0?n=e.features.filter(c=>O.some(d=>d.name===c)):o.featureFiles&&Object.keys(o.featureFiles).length>0?n=await lt(o.defaultFeatures??["database","auth"]):n=o.defaultFeatures??[],console.log(""),console.log(f__default.default.bold(`Scaffolding ${f__default.default.cyan(o.name)} template...`)),n.length>0&&console.log(f__default.default.gray(` Features: ${n.join(", ")}`)),console.log("");let r=[...o.files];if(o.featureFiles)for(let c of n){let d=o.featureFiles[c];d&&r.push(...d);}let l=0,i=0;for(let c of r){let d=A__default.default.resolve(c.path),u=A__default.default.dirname(d);if(N__default.default.existsSync(u)||N__default.default.mkdirSync(u,{recursive:true}),c.path==="package.json"&&N__default.default.existsSync(d)&&!e.force)try{let p=JSON.parse(N__default.default.readFileSync(d,"utf-8")),g=JSON.parse(c.content),b=C=>{if(!C)return {};let $={};for(let[Xe,K]of Object.entries(C))!K.startsWith("workspace:")&&!K.startsWith("link:")&&!K.startsWith("file:")&&($[Xe]=K);return $};p.dependencies={...b(p.dependencies),...g.dependencies||{}},p.devDependencies={...b(p.devDependencies),...g.devDependencies||{}},g.scripts&&(p.scripts={...p.scripts||{},...g.scripts}),N__default.default.writeFileSync(d,JSON.stringify(p,null,2)+`
3695
+ `)),process.exit(1));let n;e.features&&e.features.length>0?n=e.features.filter(c=>$.some(d=>d.name===c)):o.featureFiles&&Object.keys(o.featureFiles).length>0?n=await lt(o.defaultFeatures??["database","auth"]):n=o.defaultFeatures??[],console.log(""),console.log(f__default.default.bold(`Scaffolding ${f__default.default.cyan(o.name)} template...`)),n.length>0&&console.log(f__default.default.gray(` Features: ${n.join(", ")}`)),console.log("");let r=[...o.files];if(o.featureFiles)for(let c of n){let d=o.featureFiles[c];d&&r.push(...d);}let l=0,i=0;for(let c of r){let d=A__default.default.resolve(c.path),u=A__default.default.dirname(d);if(N__default.default.existsSync(u)||N__default.default.mkdirSync(u,{recursive:true}),c.path==="package.json"&&N__default.default.existsSync(d)&&!e.force)try{let p=JSON.parse(N__default.default.readFileSync(d,"utf-8")),g=JSON.parse(c.content),b=C=>{if(!C)return {};let O={};for(let[Xe,z]of Object.entries(C))!z.startsWith("workspace:")&&!z.startsWith("link:")&&!z.startsWith("file:")&&(O[Xe]=z);return O};p.dependencies={...b(p.dependencies),...g.dependencies||{}},p.devDependencies={...b(p.devDependencies),...g.devDependencies||{}},g.scripts&&(p.scripts={...p.scripts||{},...g.scripts}),N__default.default.writeFileSync(d,JSON.stringify(p,null,2)+`
3673
3696
  `,"utf-8"),console.log(f__default.default.green(` merge ${c.path} (added dependencies)`)),l++;continue}catch{}if(N__default.default.existsSync(d)&&!e.force){console.log(f__default.default.yellow(` skip ${c.path} (already exists)`)),i++;continue}N__default.default.writeFileSync(d,c.content,"utf-8"),console.log(f__default.default.green(` create ${c.path}`)),l++;}console.log(""),l>0&&console.log(f__default.default.green(`Created ${l} file${l!==1?"s":""}.`)),i>0&&console.log(f__default.default.yellow(`Skipped ${i} file${i!==1?"s":""} (use --force to overwrite).`));let a={auth:{"@vaiftech/auth":"^1.0.0"},database:{},realtime:{},storage:{},functions:{}},s=A__default.default.resolve("package.json");if(N__default.default.existsSync(s)&&n.length>0)try{let c=JSON.parse(N__default.default.readFileSync(s,"utf-8")),d=!1;for(let u of n){let p=a[u];if(p)for(let[g,b]of Object.entries(p))c.dependencies?.[g]||(c.dependencies=c.dependencies||{},c.dependencies[g]=b,d=!0);}d&&N__default.default.writeFileSync(s,JSON.stringify(c,null,2)+`
3674
3697
  `,"utf-8");}catch{}(o.dependencies?.length||o.devDependencies?.length)&&(console.log(""),console.log(f__default.default.bold("Install dependencies:")),o.dependencies?.length&&console.log(f__default.default.cyan(` npm install ${o.dependencies.join(" ")}`)),o.devDependencies?.length&&console.log(f__default.default.cyan(` npm install -D ${o.devDependencies.join(" ")}`))),console.log(""),console.log(f__default.default.bold.green("Project scaffolded successfully!")),console.log(""),console.log(f__default.default.bold(" Next steps:")),o.postInstructions.forEach(c=>{console.log(f__default.default.gray(` ${c}`));}),console.log(""),console.log(f__default.default.gray(" Get your project credentials at https://vaif.studio/app/security/api-keys")),console.log("");}var dt={$schema:"https://vaif.studio/schemas/config.json",projectId:"",database:{url:"${DATABASE_URL}",schema:"public"},types:{output:"./src/types/database.ts"},api:{baseUrl:"https://api.vaif.studio"}};async function me(t){let e=q__default.default("Initializing VAIF configuration...").start(),o=A__default.default.resolve("vaif.config.json");N__default.default.existsSync(o)&&!t.force&&(e.fail("vaif.config.json already exists"),console.log(f__default.default.yellow(`
3675
3698
  Use --force to overwrite existing configuration.`)),process.exit(1));try{if(N__default.default.writeFileSync(o,JSON.stringify(dt,null,2),"utf-8"),e.succeed("Created vaif.config.json"),t.template){let n=t.features?t.features.split(",").map(r=>r.trim()):void 0;await ge(t.template,{force:t.force,features:n});}else {let n=A__default.default.resolve(".env.example");if(N__default.default.existsSync(n)||(N__default.default.writeFileSync(n,`# VAIF Configuration
3676
3699
  DATABASE_URL=postgresql://user:password@localhost:5432/database
3677
3700
  VAIF_API_KEY=your-api-key
3678
3701
  `,"utf-8"),console.log(f__default.default.gray("Created .env.example"))),t.typescript){let r=A__default.default.resolve("src/types");N__default.default.existsSync(r)||(N__default.default.mkdirSync(r,{recursive:!0}),console.log(f__default.default.gray("Created src/types directory")));}console.log(""),console.log(f__default.default.green("VAIF initialized successfully!")),console.log(""),console.log(f__default.default.gray("Next steps:")),console.log(f__default.default.gray(" 1. Update vaif.config.json with your project ID")),console.log(f__default.default.gray(" 2. Set DATABASE_URL in your environment")),console.log(f__default.default.gray(" 3. Run: npx vaif generate")),console.log("");}}catch(n){e.fail("Failed to initialize"),n instanceof Error&&console.error(f__default.default.red(`
3679
- Error: ${n.message}`)),process.exit(1);}}var ae=A__default.default.join(pt__default.default.homedir(),".vaif"),V=A__default.default.join(ae,"auth.json"),z=process.env.VAIF_API_URL||"https://api.vaif.studio";function ft(){N__default.default.existsSync(ae)||N__default.default.mkdirSync(ae,{recursive:true});}function ve(t){ft(),N__default.default.writeFileSync(V,JSON.stringify(t,null,2),"utf-8"),N__default.default.chmodSync(V,384);}function w(){if(!N__default.default.existsSync(V))return null;try{let t=N__default.default.readFileSync(V,"utf-8");return JSON.parse(t)}catch{return null}}function gt(t){let e=pe__default.default.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(t,n=>{e.close(),o(n);});})}function mt(t){return new Promise(e=>{let o=pe__default.default.createInterface({input:process.stdin,output:process.stdout});process.stdin;let r=process.stdout.write.bind(process.stdout),l=false;process.stdout.write=((...i)=>l?true:r(...i)),o.question(t,i=>{l=false,process.stdout.write=r,console.log(""),o.close(),e(i);}),l=true;})}function ht(t){let e=process.platform,o;e==="darwin"?o=`open "${t}"`:e==="win32"?o=`start "" "${t}"`:o=`xdg-open "${t}"`,child_process.exec(o,n=>{});}function yt(t){return new Promise(e=>setTimeout(e,t))}async function vt(t){try{let e=await fetch(`${z}/auth/me`,{headers:{Authorization:`Bearer ${t}`}});if(e.ok){let o=await e.json();return {valid:!0,email:o.user?.email||o.email}}return {valid:!1}}catch{return {valid:false}}}async function bt(t){let e=q__default.default();e.start("Setting up authentication...");let o,n;try{let a=await fetch(`${z}/auth/cli/authorize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})});a.ok||(e.fail("Failed to initiate authentication"),console.log(f__default.default.red(`
3702
+ Error: ${n.message}`)),process.exit(1);}}var ae=A__default.default.join(pt__default.default.homedir(),".vaif"),k=A__default.default.join(ae,"auth.json"),K=process.env.VAIF_API_URL||"https://api.vaif.studio";function ft(){N__default.default.existsSync(ae)||N__default.default.mkdirSync(ae,{recursive:true});}function ve(t){ft(),N__default.default.writeFileSync(k,JSON.stringify(t,null,2),"utf-8"),N__default.default.chmodSync(k,384);}function w(){if(!N__default.default.existsSync(k))return null;try{let t=N__default.default.readFileSync(k,"utf-8");return JSON.parse(t)}catch{return null}}function gt(t){let e=pe__default.default.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(t,n=>{e.close(),o(n);});})}function mt(t){return new Promise(e=>{let o=pe__default.default.createInterface({input:process.stdin,output:process.stdout});process.stdin;let r=process.stdout.write.bind(process.stdout),l=false;process.stdout.write=((...i)=>l?true:r(...i)),o.question(t,i=>{l=false,process.stdout.write=r,console.log(""),o.close(),e(i);}),l=true;})}function ht(t){let e=process.platform,o;e==="darwin"?o=`open "${t}"`:e==="win32"?o=`start "" "${t}"`:o=`xdg-open "${t}"`,child_process.exec(o,n=>{});}function yt(t){return new Promise(e=>setTimeout(e,t))}async function vt(t){try{let e=await fetch(`${K}/auth/me`,{headers:{Authorization:`Bearer ${t}`}});if(e.ok){let o=await e.json();return {valid:!0,email:o.user?.email||o.email}}return {valid:!1}}catch{return {valid:false}}}async function bt(t){let e=q__default.default();e.start("Setting up authentication...");let o,n;try{let a=await fetch(`${K}/auth/cli/authorize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})});a.ok||(e.fail("Failed to initiate authentication"),console.log(f__default.default.red(`
3680
3703
  Could not connect to VAIF API. Please try again later.`)),process.exit(1));let s=await a.json();o=s.code,n=s.url;}catch{e.fail("Failed to connect to VAIF API"),console.log(f__default.default.red(`
3681
- Could not connect to VAIF API.`)),console.log(f__default.default.gray("Check your internet connection or try: vaif login --email")),process.exit(1);}e.stop(),console.log(f__default.default.cyan(" Opening browser for authentication...")),console.log(""),console.log(f__default.default.gray(" If the browser doesn't open, visit this URL:")),console.log(f__default.default.white(` ${n}`)),console.log(""),ht(n),e.start("Waiting for browser authentication...");let r=12e4,l=2e3,i=Date.now();for(;Date.now()-i<r;){await yt(l);try{let a=await fetch(`${z}/auth/cli/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:o})});if(!a.ok){let c=await a.json();(c.error==="ExpiredCode"||c.error==="InvalidCode")&&(e.fail("Authentication expired"),console.log(f__default.default.red(`
3682
- The authentication session expired. Please try again.`)),process.exit(1));continue}let s=await a.json();if(s.ok&&s.accessToken){let c={token:s.accessToken,email:s.user?.email,projectId:t,expiresAt:new Date(Date.now()+s.expiresIn*1e3).toISOString()};ve(c),e.succeed("Logged in successfully"),console.log(""),s.user?.email&&console.log(f__default.default.green(` Authenticated as: ${s.user.email}`)),console.log(f__default.default.gray(` Config saved to: ${V}`)),console.log("");return}}catch{}}e.fail("Authentication timed out"),console.log(f__default.default.red(`
3704
+ Could not connect to VAIF API.`)),console.log(f__default.default.gray("Check your internet connection or try: vaif login --email")),process.exit(1);}e.stop(),console.log(f__default.default.cyan(" Opening browser for authentication...")),console.log(""),console.log(f__default.default.gray(" If the browser doesn't open, visit this URL:")),console.log(f__default.default.white(` ${n}`)),console.log(""),ht(n),e.start("Waiting for browser authentication...");let r=12e4,l=2e3,i=Date.now();for(;Date.now()-i<r;){await yt(l);try{let a=await fetch(`${K}/auth/cli/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:o})});if(!a.ok){let c=await a.json();(c.error==="ExpiredCode"||c.error==="InvalidCode")&&(e.fail("Authentication expired"),console.log(f__default.default.red(`
3705
+ The authentication session expired. Please try again.`)),process.exit(1));continue}let s=await a.json();if(s.ok&&s.accessToken){let c={token:s.accessToken,email:s.user?.email,projectId:t,expiresAt:new Date(Date.now()+s.expiresIn*1e3).toISOString()};ve(c),e.succeed("Logged in successfully"),console.log(""),s.user?.email&&console.log(f__default.default.green(` Authenticated as: ${s.user.email}`)),console.log(f__default.default.gray(` Config saved to: ${k}`)),console.log("");return}}catch{}}e.fail("Authentication timed out"),console.log(f__default.default.red(`
3683
3706
  Timed out waiting for browser authentication.`)),console.log(f__default.default.gray("Try again or use: vaif login --email")),process.exit(1);}async function It(t){console.log(""),console.log(f__default.default.bold("VAIF CLI Login")),console.log(f__default.default.gray("Enter your VAIF account credentials")),console.log("");let e=await gt(f__default.default.cyan(" Email: "));(!e||e.trim()==="")&&(console.log(f__default.default.red(`
3684
3707
  No email provided. Login cancelled.`)),process.exit(1));let o=await mt(f__default.default.cyan(" Password: "));(!o||o.trim()==="")&&(console.log(f__default.default.red(`
3685
- No password provided. Login cancelled.`)),process.exit(1));let n=q__default.default("Authenticating...").start();try{let r=await fetch(`${z}/auth/cli/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e.trim(),password:o})}),l=await r.json();(!r.ok||!l.ok)&&(n.fail("Login failed"),console.log(f__default.default.red(`
3686
- ${l.message||"Invalid email or password."}`)),process.exit(1));let i={token:l.accessToken,email:l.user?.email,projectId:t,expiresAt:new Date(Date.now()+l.expiresIn*1e3).toISOString()};ve(i),n.succeed("Logged in successfully"),console.log(""),l.user?.email&&console.log(f__default.default.green(` Authenticated as: ${l.user.email}`)),console.log(f__default.default.gray(` Config saved to: ${V}`)),console.log("");}catch{n.fail("Failed to connect to VAIF API"),console.log(f__default.default.red(`
3687
- Could not connect to VAIF API. Please try again later.`)),process.exit(1);}}async function be(t){console.log(""),console.log(f__default.default.bold("Welcome to VAIF CLI")),console.log(f__default.default.gray("Authenticate to access your VAIF projects")),console.log(""),t.email?await It(t.projectId):await bt(t.projectId),console.log(f__default.default.gray("You can now use VAIF CLI commands like:")),console.log(f__default.default.gray(" vaif pull - Pull remote schema")),console.log(f__default.default.gray(" vaif push - Push schema changes")),console.log(f__default.default.gray(" vaif generate - Generate TypeScript types")),console.log("");}async function Ie(){N__default.default.existsSync(V)?(N__default.default.unlinkSync(V),console.log(f__default.default.green("Logged out successfully"))):console.log(f__default.default.yellow("Not currently logged in"));}async function Ae(){let t=w();(!t||!t.token)&&(console.log(f__default.default.yellow("Not logged in")),console.log(f__default.default.gray("Run `vaif login` to authenticate")),process.exit(1));let e=q__default.default("Checking authentication...").start(),{valid:o,email:n}=await vt(t.token);o||(e.fail("Session expired"),console.log(f__default.default.yellow(`
3688
- Your session has expired. Please login again.`)),process.exit(1)),e.succeed("Authenticated"),console.log(""),console.log(f__default.default.green(` Email: ${n||t.email||"Unknown"}`)),t.projectId&&console.log(f__default.default.green(` Project: ${t.projectId}`)),console.log("");}var Et=process.env.VAIF_API_URL||"https://api.vaif.studio";async function xt(t,e,o="public"){let n=await fetch(`${Et}/v1/projects/${e}/schema?schema=${o}`,{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}});if(!n.ok){let r=await n.text();throw new Error(`Failed to fetch schema: ${r}`)}return n.json()}async function we(t){let e=q__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;e.start("Loading configuration...");try{r=await I(n);}catch(i){e.fail("Failed to load config"),console.log(f__default.default.red(`
3689
- Error: ${i}`)),process.exit(1);}r||(e.fail("No configuration found"),console.log(f__default.default.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let l=t.projectId||r.projectId||o.projectId;l||(e.fail("No project ID specified"),console.log(f__default.default.yellow(`
3690
- Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1)),e.text="Fetching remote schema...";try{let i=t.schema||r.database?.schema||"public",a=await xt(o.token,l,i);e.succeed("Schema fetched successfully");let s=t.output||A__default.default.resolve("vaif.schema.json"),c={$schema:"https://vaif.studio/schemas/schema.json",projectId:l,schema:i,pulledAt:new Date().toISOString(),...a};N__default.default.writeFileSync(s,JSON.stringify(c,null,2),"utf-8"),console.log(""),console.log(f__default.default.green(`Schema saved to: ${s}`)),console.log(""),console.log(f__default.default.gray("Schema summary:")),console.log(f__default.default.gray(` Tables: ${(a.tables||[]).length}`)),console.log(f__default.default.gray(` Enums: ${(a.enums||[]).length}`)),console.log(f__default.default.gray(` Functions: ${(a.functions||[]).length}`)),console.log(""),console.log(f__default.default.gray("Next steps:")),console.log(f__default.default.gray(" - Run `vaif generate` to generate TypeScript types")),console.log(f__default.default.gray(" - Edit the schema and run `vaif push` to deploy changes")),console.log("");}catch(i){e.fail("Failed to fetch schema"),i instanceof Error&&console.log(f__default.default.red(`
3691
- Error: ${i.message}`)),process.exit(1);}}var Ee=process.env.VAIF_API_URL||"https://api.vaif.studio";function Ft(t){let e=pe__default.default.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(t,n=>{e.close(),o(n);});})}async function jt(t,e,o){let n=await fetch(`${Ee}/v1/projects/${e}/schema/preview`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({schema:o})});if(!n.ok){let r=await n.text();throw new Error(`Failed to preview changes: ${r}`)}return n.json()}async function Ct(t,e,o){let n=await fetch(`${Ee}/v1/projects/${e}/schema/apply`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({schema:o})});if(!n.ok){let r=await n.text();throw new Error(`Failed to apply changes: ${r}`)}return n.json()}function Rt(t){if(console.log(""),console.log(f__default.default.bold("Schema Changes:")),console.log(""),t.added.length===0&&t.modified.length===0&&t.removed.length===0){console.log(f__default.default.gray(" No changes detected. Schema is up to date."));return}if(t.added.length>0){console.log(f__default.default.green.bold(" + Added:"));for(let e of t.added)console.log(f__default.default.green(` + ${e.type}: ${e.name}`));console.log("");}if(t.modified.length>0){console.log(f__default.default.yellow.bold(" ~ Modified:"));for(let e of t.modified){console.log(f__default.default.yellow(` ~ ${e.type}: ${e.name}`));for(let o of e.changes)console.log(f__default.default.gray(` ${o}`));}console.log("");}if(t.removed.length>0){console.log(f__default.default.red.bold(" - Removed:"));for(let e of t.removed)console.log(f__default.default.red(` - ${e.type}: ${e.name}`));console.log("");}}async function xe(t){let e=q__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;e.start("Loading configuration...");try{r=await I(n);}catch(s){e.fail("Failed to load config"),console.log(f__default.default.red(`
3692
- Error: ${s}`)),process.exit(1);}r||(e.fail("No configuration found"),console.log(f__default.default.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let l=t.projectId||r.projectId||o.projectId;l||(e.fail("No project ID specified"),console.log(f__default.default.yellow(`
3708
+ No password provided. Login cancelled.`)),process.exit(1));let n=q__default.default("Authenticating...").start();try{let r=await fetch(`${K}/auth/cli/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e.trim(),password:o})}),l=await r.json();(!r.ok||!l.ok)&&(n.fail("Login failed"),console.log(f__default.default.red(`
3709
+ ${l.message||"Invalid email or password."}`)),process.exit(1));let i={token:l.accessToken,email:l.user?.email,projectId:t,expiresAt:new Date(Date.now()+l.expiresIn*1e3).toISOString()};ve(i),n.succeed("Logged in successfully"),console.log(""),l.user?.email&&console.log(f__default.default.green(` Authenticated as: ${l.user.email}`)),console.log(f__default.default.gray(` Config saved to: ${k}`)),console.log("");}catch{n.fail("Failed to connect to VAIF API"),console.log(f__default.default.red(`
3710
+ Could not connect to VAIF API. Please try again later.`)),process.exit(1);}}async function be(t){console.log(""),console.log(f__default.default.bold("Welcome to VAIF CLI")),console.log(f__default.default.gray("Authenticate to access your VAIF projects")),console.log(""),t.email?await It(t.projectId):await bt(t.projectId),console.log(f__default.default.gray("You can now use VAIF CLI commands like:")),console.log(f__default.default.gray(" vaif pull - Pull remote schema")),console.log(f__default.default.gray(" vaif push - Push schema changes")),console.log(f__default.default.gray(" vaif generate - Generate TypeScript types")),console.log("");}async function Ie(){N__default.default.existsSync(k)?(N__default.default.unlinkSync(k),console.log(f__default.default.green("Logged out successfully"))):console.log(f__default.default.yellow("Not currently logged in"));}async function Ae(){let t=w();(!t||!t.token)&&(console.log(f__default.default.yellow("Not logged in")),console.log(f__default.default.gray("Run `vaif login` to authenticate")),process.exit(1));let e=q__default.default("Checking authentication...").start(),{valid:o,email:n}=await vt(t.token);o||(e.fail("Session expired"),console.log(f__default.default.yellow(`
3711
+ Your session has expired. Please login again.`)),process.exit(1)),e.succeed("Authenticated"),console.log(""),console.log(f__default.default.green(` Email: ${n||t.email||"Unknown"}`)),t.projectId&&console.log(f__default.default.green(` Project: ${t.projectId}`)),console.log("");}var Et=process.env.VAIF_API_URL||"https://api.vaif.studio";async function _t(t,e,o="public"){let n=await fetch(`${Et}/v1/projects/${e}/schema?schema=${o}`,{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}});if(!n.ok){let r=await n.text();throw new Error(`Failed to fetch schema: ${r}`)}return n.json()}async function we(t){let e=q__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;e.start("Loading configuration...");try{r=await I(n);}catch(i){e.fail("Failed to load config"),console.log(f__default.default.red(`
3712
+ Error: ${i}`)),process.exit(1);}r||(e.fail("No configuration found"),console.log(f__default.default.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let l=t.projectId||r.projectId||process.env.VAIF_PROJECT_ID||o.projectId;l||(e.fail("No project ID specified"),console.log(f__default.default.yellow(`
3713
+ Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1)),e.text="Fetching remote schema...";try{let i=t.schema||r.database?.schema||"public",a=await _t(o.token,l,i);e.succeed("Schema fetched successfully");let s=t.output||A__default.default.resolve("vaif.schema.json"),c={$schema:"https://vaif.studio/schemas/schema.json",projectId:l,schema:i,pulledAt:new Date().toISOString(),...a};N__default.default.writeFileSync(s,JSON.stringify(c,null,2),"utf-8"),console.log(""),console.log(f__default.default.green(`Schema saved to: ${s}`)),console.log(""),console.log(f__default.default.gray("Schema summary:")),console.log(f__default.default.gray(` Tables: ${(a.tables||[]).length}`)),console.log(f__default.default.gray(` Enums: ${(a.enums||[]).length}`)),console.log(f__default.default.gray(` Functions: ${(a.functions||[]).length}`)),console.log(""),console.log(f__default.default.gray("Next steps:")),console.log(f__default.default.gray(" - Run `vaif generate` to generate TypeScript types")),console.log(f__default.default.gray(" - Edit the schema and run `vaif push` to deploy changes")),console.log("");}catch(i){e.fail("Failed to fetch schema"),i instanceof Error&&console.log(f__default.default.red(`
3714
+ Error: ${i.message}`)),process.exit(1);}}var Ee=process.env.VAIF_API_URL||"https://api.vaif.studio";function Ft(t){let e=pe__default.default.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(t,n=>{e.close(),o(n);});})}async function jt(t,e,o){let n=await fetch(`${Ee}/v1/projects/${e}/schema/preview`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({schema:o})});if(!n.ok){let r=await n.text();throw new Error(`Failed to preview changes: ${r}`)}return n.json()}async function Ct(t,e,o){let n=await fetch(`${Ee}/v1/projects/${e}/schema/apply`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({schema:o})});if(!n.ok){let r=await n.text();throw new Error(`Failed to apply changes: ${r}`)}return n.json()}function Rt(t){if(console.log(""),console.log(f__default.default.bold("Schema Changes:")),console.log(""),t.added.length===0&&t.modified.length===0&&t.removed.length===0){console.log(f__default.default.gray(" No changes detected. Schema is up to date."));return}if(t.added.length>0){console.log(f__default.default.green.bold(" + Added:"));for(let e of t.added)console.log(f__default.default.green(` + ${e.type}: ${e.name}`));console.log("");}if(t.modified.length>0){console.log(f__default.default.yellow.bold(" ~ Modified:"));for(let e of t.modified){console.log(f__default.default.yellow(` ~ ${e.type}: ${e.name}`));for(let o of e.changes)console.log(f__default.default.gray(` ${o}`));}console.log("");}if(t.removed.length>0){console.log(f__default.default.red.bold(" - Removed:"));for(let e of t.removed)console.log(f__default.default.red(` - ${e.type}: ${e.name}`));console.log("");}}async function _e(t){let e=q__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;e.start("Loading configuration...");try{r=await I(n);}catch(s){e.fail("Failed to load config"),console.log(f__default.default.red(`
3715
+ Error: ${s}`)),process.exit(1);}r||(e.fail("No configuration found"),console.log(f__default.default.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let l=t.projectId||r.projectId||process.env.VAIF_PROJECT_ID||o.projectId;l||(e.fail("No project ID specified"),console.log(f__default.default.yellow(`
3693
3716
  Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1));let i=t.schema||A__default.default.resolve("vaif.schema.json");N__default.default.existsSync(i)||(e.fail("No local schema found"),console.log(f__default.default.yellow(`
3694
3717
  Expected schema file at: ${i}`)),console.log(f__default.default.gray("Run `vaif pull` first to fetch the current schema.")),process.exit(1));let a;try{let s=N__default.default.readFileSync(i,"utf-8");a=JSON.parse(s);}catch(s){e.fail("Failed to parse schema file"),s instanceof Error&&console.log(f__default.default.red(`
3695
3718
  Error: ${s.message}`)),process.exit(1);}e.text="Calculating schema changes...";try{let{diff:s,sql:c}=await jt(o.token,l,a);if(e.stop(),Rt(s),s.added.length===0&&s.modified.length===0&&s.removed.length===0){console.log("");return}if(c.length>0){console.log(f__default.default.bold("SQL Migrations:")),console.log("");for(let u of c)console.log(f__default.default.gray(` ${u}`));console.log("");}if(t.dryRun){console.log(f__default.default.yellow("Dry run mode - no changes applied.")),console.log(f__default.default.gray("Remove --dry-run to apply these changes."));return}if(!t.force){s.removed.length>0&&(console.log(f__default.default.red.bold("\u26A0\uFE0F Warning: This will remove tables/columns from your database.")),console.log(f__default.default.red(" This action cannot be undone!")),console.log(""));let p=await Ft(f__default.default.cyan("Apply these changes? [y/N] "));if(p.toLowerCase()!=="y"&&p.toLowerCase()!=="yes"){console.log(f__default.default.yellow(`
3696
3719
  Cancelled. No changes applied.`));return}}e.start("Applying schema changes...");let d=await Ct(o.token,l,a);if(d.success){if(e.succeed("Schema changes applied successfully"),console.log(""),d.migrations.length>0){console.log(f__default.default.gray("Migrations applied:"));for(let u of d.migrations)console.log(f__default.default.gray(` - ${u}`));console.log("");}console.log(f__default.default.green("Your database schema is now up to date.")),console.log(f__default.default.gray("Run `vaif generate` to update your TypeScript types.")),console.log("");}else e.fail("Failed to apply some changes");}catch(s){e.fail("Failed to push schema changes"),s instanceof Error&&console.log(f__default.default.red(`
3697
- Error: ${s.message}`)),process.exit(1);}}var Fe=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Nt(t,e,o){let n=await fetch(`${Fe}/v1/projects/${e}/functions`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({name:o.name,runtime:o.runtime,entrypoint:o.entrypoint,code:o.code,envId:o.envId})});if(!n.ok){let r=await n.text();throw new Error(`Failed to deploy function: ${r}`)}return n.json()}async function Dt(t,e,o){let n=new URL(`${Fe}/v1/projects/${e}/functions`);o&&n.searchParams.set("envId",o);let r=await fetch(n.toString(),{headers:{Authorization:`Bearer ${t}`}});if(!r.ok){let l=await r.text();throw new Error(`Failed to list functions: ${l}`)}return r.json()}function _e(t){switch(A__default.default.extname(t).toLowerCase()){case ".ts":return "typescript";case ".js":case ".mjs":return "nodejs";case ".py":return "python";case ".go":return "go";case ".rs":return "rust";default:return "nodejs"}}function Te(t){let e=[],o=[".ts",".js",".mjs",".py",".go",".rs"];function n(r){if(!N__default.default.existsSync(r))return;let l=N__default.default.readdirSync(r,{withFileTypes:true});for(let i of l){let a=A__default.default.join(r,i.name);if(i.isDirectory())i.name!=="node_modules"&&!i.name.startsWith(".")&&n(a);else if(i.isFile()){let s=A__default.default.extname(i.name).toLowerCase();o.includes(s)&&(i.name==="index.ts"||i.name==="index.js"||i.name.includes("function")||i.name.includes("handler"))&&e.push(a);}}}return n(t),e}async function je(t){let e=q__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let l=t.projectId||r?.projectId||o.projectId;l||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(f__default.default.bold("VAIF Functions Deploy")),console.log(""),e.start("Scanning for function files...");let i=A__default.default.resolve("functions"),a=A__default.default.resolve("src/functions"),s=[];if(t.entrypoint){let p=A__default.default.resolve(t.entrypoint);N__default.default.existsSync(p)||(e.fail(`File not found: ${t.entrypoint}`),process.exit(1)),s=[p];}else s=[...Te(i),...Te(a)];s.length===0&&(e.fail("No function files found"),console.log(f__default.default.yellow(`
3720
+ Error: ${s.message}`)),process.exit(1);}}var Fe=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Nt(t,e,o){let n=await fetch(`${Fe}/v1/projects/${e}/functions`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({name:o.name,runtime:o.runtime,entrypoint:o.entrypoint,code:o.code,envId:o.envId})});if(!n.ok){let r=await n.text();throw new Error(`Failed to deploy function: ${r}`)}return n.json()}async function Dt(t,e,o){let n=new URL(`${Fe}/v1/projects/${e}/functions`);o&&n.searchParams.set("envId",o);let r=await fetch(n.toString(),{headers:{Authorization:`Bearer ${t}`}});if(!r.ok){let l=await r.text();throw new Error(`Failed to list functions: ${l}`)}return r.json()}function xe(t){switch(A__default.default.extname(t).toLowerCase()){case ".ts":return "typescript";case ".js":case ".mjs":return "nodejs";case ".py":return "python";case ".go":return "go";case ".rs":return "rust";default:return "nodejs"}}function Te(t){let e=[],o=[".ts",".js",".mjs",".py",".go",".rs"];function n(r){if(!N__default.default.existsSync(r))return;let l=N__default.default.readdirSync(r,{withFileTypes:true});for(let i of l){let a=A__default.default.join(r,i.name);if(i.isDirectory())i.name!=="node_modules"&&!i.name.startsWith(".")&&n(a);else if(i.isFile()){let s=A__default.default.extname(i.name).toLowerCase();o.includes(s)&&(i.name==="index.ts"||i.name==="index.js"||i.name.includes("function")||i.name.includes("handler"))&&e.push(a);}}}return n(t),e}async function je(t){let e=q__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let l=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;l||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(f__default.default.bold("VAIF Functions Deploy")),console.log(""),e.start("Scanning for function files...");let i=A__default.default.resolve("functions"),a=A__default.default.resolve("src/functions"),s=[];if(t.entrypoint){let p=A__default.default.resolve(t.entrypoint);N__default.default.existsSync(p)||(e.fail(`File not found: ${t.entrypoint}`),process.exit(1)),s=[p];}else s=[...Te(i),...Te(a)];s.length===0&&(e.fail("No function files found"),console.log(f__default.default.yellow(`
3698
3721
  Place your functions in:`)),console.log(f__default.default.gray(" - ./functions/")),console.log(f__default.default.gray(" - ./src/functions/")),console.log(f__default.default.gray(`
3699
3722
  Or specify an entrypoint with --entrypoint`)),process.exit(1)),e.succeed(`Found ${s.length} function(s)`),t.name&&(s=s.filter(p=>A__default.default.basename(p,A__default.default.extname(p)).includes(t.name)),s.length===0&&(console.log(f__default.default.yellow(`
3700
- No functions matching "${t.name}" found`)),process.exit(1))),console.log(""),console.log(f__default.default.gray("Functions to deploy:"));for(let p of s){let g=A__default.default.basename(A__default.default.dirname(p))||A__default.default.basename(p,A__default.default.extname(p)),b=t.runtime||_e(p);console.log(f__default.default.gray(` - ${g} (${b})`));}if(console.log(""),t.dryRun){console.log(f__default.default.yellow("Dry run mode - no functions deployed."));return}let c=[];for(let p of s){let g=A__default.default.basename(A__default.default.dirname(p))||A__default.default.basename(p,A__default.default.extname(p)),b=t.runtime||_e(p);e.start(`Deploying ${g}...`);try{let C=N__default.default.readFileSync(p,"utf-8"),$=await Nt(o.token,l,{name:g,runtime:b,entrypoint:A__default.default.basename(p),code:C,envId:t.envId});e.succeed(`Deployed ${g} (v${$.version})`),c.push({name:g,success:!0,version:$.version});}catch(C){let $=C instanceof Error?C.message:"Unknown error";e.fail(`Failed to deploy ${g}`),c.push({name:g,success:false,error:$});}}console.log("");let d=c.filter(p=>p.success).length;if(c.filter(p=>!p.success).length===0)console.log(f__default.default.green(`\u2713 Successfully deployed ${d} function(s)`));else {console.log(f__default.default.yellow(`Deployed ${d}/${c.length} function(s)`)),console.log(""),console.log(f__default.default.red("Failed deployments:"));for(let p of c.filter(g=>!g.success))console.log(f__default.default.red(` - ${p.name}: ${p.error}`));}console.log("");}async function Ce(t){let e=q__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let l=t.projectId||r?.projectId||o.projectId;l||(console.log(f__default.default.red("No project ID specified")),process.exit(1)),e.start("Fetching functions...");try{let i=await Dt(o.token,l,t.envId);if(e.stop(),i.length===0){console.log(f__default.default.yellow(`
3723
+ No functions matching "${t.name}" found`)),process.exit(1))),console.log(""),console.log(f__default.default.gray("Functions to deploy:"));for(let p of s){let g=A__default.default.basename(A__default.default.dirname(p))||A__default.default.basename(p,A__default.default.extname(p)),b=t.runtime||xe(p);console.log(f__default.default.gray(` - ${g} (${b})`));}if(console.log(""),t.dryRun){console.log(f__default.default.yellow("Dry run mode - no functions deployed."));return}let c=[];for(let p of s){let g=A__default.default.basename(A__default.default.dirname(p))||A__default.default.basename(p,A__default.default.extname(p)),b=t.runtime||xe(p);e.start(`Deploying ${g}...`);try{let C=N__default.default.readFileSync(p,"utf-8"),O=await Nt(o.token,l,{name:g,runtime:b,entrypoint:A__default.default.basename(p),code:C,envId:t.envId});e.succeed(`Deployed ${g} (v${O.version})`),c.push({name:g,success:!0,version:O.version});}catch(C){let O=C instanceof Error?C.message:"Unknown error";e.fail(`Failed to deploy ${g}`),c.push({name:g,success:false,error:O});}}console.log("");let d=c.filter(p=>p.success).length;if(c.filter(p=>!p.success).length===0)console.log(f__default.default.green(`\u2713 Successfully deployed ${d} function(s)`));else {console.log(f__default.default.yellow(`Deployed ${d}/${c.length} function(s)`)),console.log(""),console.log(f__default.default.red("Failed deployments:"));for(let p of c.filter(g=>!g.success))console.log(f__default.default.red(` - ${p.name}: ${p.error}`));}console.log("");}async function Ce(t){let e=q__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let l=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;l||(console.log(f__default.default.red("No project ID specified")),process.exit(1)),e.start("Fetching functions...");try{let i=await Dt(o.token,l,t.envId);if(e.stop(),i.length===0){console.log(f__default.default.yellow(`
3701
3724
  No functions found`)),console.log(f__default.default.gray("Deploy your first function with: vaif functions deploy"));return}console.log(""),console.log(f__default.default.bold(`Functions (${i.length}):`)),console.log(""),console.log(f__default.default.gray(" "+"NAME".padEnd(25)+"RUNTIME".padEnd(15)+"VERSION".padEnd(10)+"STATUS".padEnd(12)+"LAST DEPLOYED")),console.log(f__default.default.gray(" "+"-".repeat(80)));for(let a of i){let s=a.status==="active"?f__default.default.green:a.status==="deploying"?f__default.default.yellow:f__default.default.red;console.log(" "+a.name.padEnd(25)+a.runtime.padEnd(15)+`v${a.version}`.padEnd(10)+s(a.status.padEnd(12))+(a.lastDeployed?new Date(a.lastDeployed).toLocaleDateString():"-"));}console.log("");}catch(i){e.fail("Failed to fetch functions"),i instanceof Error&&console.log(f__default.default.red(`
3702
- Error: ${i.message}`)),process.exit(1);}}var Y=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Lt(t,e,o,n,r){let l=await fetch(`${Y}/v1/projects/${e}/db/seed`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({table:o,records:n,truncate:r?.truncate??false})});if(!l.ok){let i=await l.text();throw new Error(`Failed to seed ${o}: ${i}`)}return l.json()}async function kt(t,e){let o=await fetch(`${Y}/v1/projects/${e}/db/reset`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}});if(!o.ok){let n=await o.text();throw new Error(`Failed to reset database: ${n}`)}return o.json()}function re(t){let e=[];if(!N__default.default.existsSync(t))return e;let o=N__default.default.readdirSync(t,{withFileTypes:true});for(let n of o)if(n.isFile()){let r=A__default.default.extname(n.name).toLowerCase();(r===".json"||r===".ts"||r===".js")&&e.push(A__default.default.join(t,n.name));}return e.sort()}async function Re(t){let e=A__default.default.extname(t).toLowerCase();if(e===".json"){let o=N__default.default.readFileSync(t,"utf-8"),n=JSON.parse(o);return Array.isArray(n)?[{table:A__default.default.basename(t,e),data:n}]:n.table&&n.data?[n]:Object.entries(n).map(([r,l])=>({table:r,data:l}))}else if(e===".ts"||e===".js"){let o=await import(t),n=o.default||o;return typeof n=="function"?n():n}throw new Error(`Unsupported file format: ${e}`)}async function Ne(t){let e=q__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let l=t.projectId||r?.projectId||o.projectId;l||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(f__default.default.bold("VAIF Database Seed")),console.log("");let i=[];if(t.file){let d=A__default.default.resolve(t.file);N__default.default.existsSync(d)||(console.log(f__default.default.red(`File not found: ${t.file}`)),process.exit(1)),i=[d];}else {let d=A__default.default.resolve("seeds"),u=A__default.default.resolve("prisma/seed"),p=A__default.default.resolve("db/seeds");i=[...re(d),...re(u),...re(p)];}i.length===0&&(console.log(f__default.default.yellow("No seed files found")),console.log(f__default.default.gray(`
3725
+ Error: ${i.message}`)),process.exit(1);}}var Y=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Vt(t,e,o,n,r){let l=await fetch(`${Y}/v1/projects/${e}/db/seed`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({table:o,records:n,truncate:r?.truncate??false})});if(!l.ok){let i=await l.text();throw new Error(`Failed to seed ${o}: ${i}`)}return l.json()}async function Lt(t,e){let o=await fetch(`${Y}/v1/projects/${e}/db/reset`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}});if(!o.ok){let n=await o.text();throw new Error(`Failed to reset database: ${n}`)}return o.json()}function re(t){let e=[];if(!N__default.default.existsSync(t))return e;let o=N__default.default.readdirSync(t,{withFileTypes:true});for(let n of o)if(n.isFile()){let r=A__default.default.extname(n.name).toLowerCase();(r===".json"||r===".ts"||r===".js")&&e.push(A__default.default.join(t,n.name));}return e.sort()}async function Re(t){let e=A__default.default.extname(t).toLowerCase();if(e===".json"){let o=N__default.default.readFileSync(t,"utf-8"),n=JSON.parse(o);return Array.isArray(n)?[{table:A__default.default.basename(t,e),data:n}]:n.table&&n.data?[n]:Object.entries(n).map(([r,l])=>({table:r,data:l}))}else if(e===".ts"||e===".js"){let o=await import(t),n=o.default||o;return typeof n=="function"?n():n}throw new Error(`Unsupported file format: ${e}`)}async function Ne(t){let e=q__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let l=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;l||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(f__default.default.bold("VAIF Database Seed")),console.log("");let i=[];if(t.file){let d=A__default.default.resolve(t.file);N__default.default.existsSync(d)||(console.log(f__default.default.red(`File not found: ${t.file}`)),process.exit(1)),i=[d];}else {let d=A__default.default.resolve("seeds"),u=A__default.default.resolve("prisma/seed"),p=A__default.default.resolve("db/seeds");i=[...re(d),...re(u),...re(p)];}i.length===0&&(console.log(f__default.default.yellow("No seed files found")),console.log(f__default.default.gray(`
3703
3726
  Place your seed files in one of these directories:`)),console.log(f__default.default.gray(" - ./seeds/")),console.log(f__default.default.gray(" - ./prisma/seed/")),console.log(f__default.default.gray(" - ./db/seeds/")),console.log(f__default.default.gray(`
3704
3727
  Or specify a file with --file`)),console.log(f__default.default.gray(`
3705
- Example seed file (seeds/users.json):`)),console.log(f__default.default.gray(" [")),console.log(f__default.default.gray(' { "name": "John Doe", "email": "john@example.com" },')),console.log(f__default.default.gray(' { "name": "Jane Doe", "email": "jane@example.com" }')),console.log(f__default.default.gray(" ]")),process.exit(1)),console.log(f__default.default.gray("Seed files found:"));for(let d of i)console.log(f__default.default.gray(` - ${A__default.default.relative(process.cwd(),d)}`));if(console.log(""),t.truncate&&(console.log(f__default.default.yellow("\u26A0\uFE0F Tables will be truncated before seeding")),console.log("")),t.dryRun){console.log(f__default.default.yellow("Dry run mode - no data will be inserted.")),console.log("");for(let d of i){e.start(`Loading ${A__default.default.basename(d)}...`);try{let u=await Re(d);e.stop();for(let p of u)t.table&&p.table!==t.table||(console.log(f__default.default.cyan(`Table: ${p.table}`)),console.log(f__default.default.gray(` Records: ${p.data.length}`)),p.data.length>0&&console.log(f__default.default.gray(` Sample: ${JSON.stringify(p.data[0],null,2).slice(0,100)}...`)),console.log(""));}catch(u){e.fail(`Failed to load ${A__default.default.basename(d)}`),u instanceof Error&&console.log(f__default.default.red(` Error: ${u.message}`));}}return}let a=[];for(let d of i){e.start(`Processing ${A__default.default.basename(d)}...`);try{let u=await Re(d);e.stop();for(let p of u)if(!(t.table&&p.table!==t.table)){if(p.data.length===0){console.log(f__default.default.gray(` Skipping ${p.table} (no records)`));continue}e.start(`Seeding ${p.table} (${p.data.length} records)...`);try{let g=await Lt(o.token,l,p.table,p.data,{truncate:t.truncate});e.succeed(`Seeded ${p.table}: ${g.inserted} records`),a.push({table:p.table,inserted:g.inserted});}catch(g){let b=g instanceof Error?g.message:"Unknown error";e.fail(`Failed to seed ${p.table}`),a.push({table:p.table,inserted:0,error:b});}}}catch(u){e.fail(`Failed to load ${A__default.default.basename(d)}`),u instanceof Error&&console.log(f__default.default.red(` Error: ${u.message}`));}}console.log("");let s=a.reduce((d,u)=>d+u.inserted,0),c=a.filter(d=>d.error).length;if(c===0)console.log(f__default.default.green(`\u2713 Successfully seeded ${s} records across ${a.length} table(s)`));else {console.log(f__default.default.yellow(`Seeded ${s} records with ${c} error(s)`)),console.log(""),console.log(f__default.default.red("Errors:"));for(let d of a.filter(u=>u.error))console.log(f__default.default.red(` - ${d.table}: ${d.error}`));}console.log("");}async function De(t){let e=q__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let l=t.projectId||r?.projectId||o.projectId;l||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=A__default.default.resolve(t.dir||"./drizzle");if(console.log(""),console.log(f__default.default.bold("VAIF Database Push")),console.log(""),!N__default.default.existsSync(i)){let u=A__default.default.resolve("./migrations");N__default.default.existsSync(u)?console.log(f__default.default.gray(`Using migrations from: ${u}`)):(console.log(f__default.default.red(`Migrations directory not found: ${i}`)),console.log(f__default.default.gray(`
3728
+ Example seed file (seeds/users.json):`)),console.log(f__default.default.gray(" [")),console.log(f__default.default.gray(' { "name": "John Doe", "email": "john@example.com" },')),console.log(f__default.default.gray(' { "name": "Jane Doe", "email": "jane@example.com" }')),console.log(f__default.default.gray(" ]")),process.exit(1)),console.log(f__default.default.gray("Seed files found:"));for(let d of i)console.log(f__default.default.gray(` - ${A__default.default.relative(process.cwd(),d)}`));if(console.log(""),t.truncate&&(console.log(f__default.default.yellow("\u26A0\uFE0F Tables will be truncated before seeding")),console.log("")),t.dryRun){console.log(f__default.default.yellow("Dry run mode - no data will be inserted.")),console.log("");for(let d of i){e.start(`Loading ${A__default.default.basename(d)}...`);try{let u=await Re(d);e.stop();for(let p of u)t.table&&p.table!==t.table||(console.log(f__default.default.cyan(`Table: ${p.table}`)),console.log(f__default.default.gray(` Records: ${p.data.length}`)),p.data.length>0&&console.log(f__default.default.gray(` Sample: ${JSON.stringify(p.data[0],null,2).slice(0,100)}...`)),console.log(""));}catch(u){e.fail(`Failed to load ${A__default.default.basename(d)}`),u instanceof Error&&console.log(f__default.default.red(` Error: ${u.message}`));}}return}let a=[];for(let d of i){e.start(`Processing ${A__default.default.basename(d)}...`);try{let u=await Re(d);e.stop();for(let p of u)if(!(t.table&&p.table!==t.table)){if(p.data.length===0){console.log(f__default.default.gray(` Skipping ${p.table} (no records)`));continue}e.start(`Seeding ${p.table} (${p.data.length} records)...`);try{let g=await Vt(o.token,l,p.table,p.data,{truncate:t.truncate});e.succeed(`Seeded ${p.table}: ${g.inserted} records`),a.push({table:p.table,inserted:g.inserted});}catch(g){let b=g instanceof Error?g.message:"Unknown error";e.fail(`Failed to seed ${p.table}`),a.push({table:p.table,inserted:0,error:b});}}}catch(u){e.fail(`Failed to load ${A__default.default.basename(d)}`),u instanceof Error&&console.log(f__default.default.red(` Error: ${u.message}`));}}console.log("");let s=a.reduce((d,u)=>d+u.inserted,0),c=a.filter(d=>d.error).length;if(c===0)console.log(f__default.default.green(`\u2713 Successfully seeded ${s} records across ${a.length} table(s)`));else {console.log(f__default.default.yellow(`Seeded ${s} records with ${c} error(s)`)),console.log(""),console.log(f__default.default.red("Errors:"));for(let d of a.filter(u=>u.error))console.log(f__default.default.red(` - ${d.table}: ${d.error}`));}console.log("");}async function De(t){let e=q__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let l=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;l||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=A__default.default.resolve(t.dir||"./drizzle");if(console.log(""),console.log(f__default.default.bold("VAIF Database Push")),console.log(""),!N__default.default.existsSync(i)){let u=A__default.default.resolve("./migrations");N__default.default.existsSync(u)?console.log(f__default.default.gray(`Using migrations from: ${u}`)):(console.log(f__default.default.red(`Migrations directory not found: ${i}`)),console.log(f__default.default.gray(`
3706
3729
  Expected one of:`)),console.log(f__default.default.gray(" - ./drizzle/")),console.log(f__default.default.gray(" - ./migrations/")),console.log(f__default.default.gray(`
3707
- Or specify with: vaif db push --dir <path>`)),process.exit(1));}let a=[],s=N__default.default.readdirSync(i,{withFileTypes:true});for(let u of s)if(u.isFile()&&u.name.endsWith(".sql"))a.push(A__default.default.join(i,u.name));else if(u.isDirectory()){let p=N__default.default.readdirSync(A__default.default.join(i,u.name),{withFileTypes:true});for(let g of p)g.isFile()&&g.name.endsWith(".sql")&&a.push(A__default.default.join(i,u.name,g.name));}a.sort(),a.length===0&&(console.log(f__default.default.yellow("No SQL migration files found")),process.exit(1)),console.log(f__default.default.gray(`Found ${a.length} migration(s):`));for(let u of a)console.log(f__default.default.gray(` - ${A__default.default.relative(process.cwd(),u)}`));if(console.log(""),t.dryRun){console.log(f__default.default.yellow("Dry run mode - no migrations will be applied.")),console.log("");for(let u of a){let p=N__default.default.readFileSync(u,"utf-8");console.log(f__default.default.cyan(`--- ${A__default.default.basename(u)} ---`)),console.log(f__default.default.gray(p.slice(0,500))),p.length>500&&console.log(f__default.default.gray("...")),console.log("");}return}let c=0,d=0;for(let u of a){let p=N__default.default.readFileSync(u,"utf-8"),g=A__default.default.relative(process.cwd(),u);e.start(`Applying ${g}...`);try{let b=await fetch(`${Y}/v1/projects/${l}/schema/execute`,{method:"POST",headers:{Authorization:`Bearer ${o.token}`,"Content-Type":"application/json"},body:JSON.stringify({sql:p})});if(!b.ok){let C=await b.text();throw new Error(C)}e.succeed(`Applied ${g}`),c++;}catch(b){let C=b instanceof Error?b.message:"Unknown error";e.fail(`Failed ${g}: ${C}`),d++;}}console.log(""),console.log(d===0?f__default.default.green(`Successfully applied ${c} migration(s)`):f__default.default.yellow(`Applied ${c}, failed ${d} migration(s)`)),console.log("");}async function Le(t){let e=q__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let l=t.projectId||r?.projectId||o.projectId;l||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=A__default.default.resolve(t.output||"vaif.schema.json");console.log(""),console.log(f__default.default.bold("VAIF Database Pull")),console.log(""),e.start("Pulling schema from remote...");try{let a=await fetch(`${Y}/v1/projects/${l}/schema`,{headers:{Authorization:`Bearer ${o.token}`}});if(!a.ok){let d=await a.text();throw new Error(`Failed to pull schema: ${d}`)}let s=await a.json();N__default.default.writeFileSync(i,JSON.stringify(s,null,2),"utf-8"),e.succeed(`Schema written to ${A__default.default.relative(process.cwd(),i)}`);let c=s.tables?.length??Object.keys(s).length;console.log(f__default.default.gray(` ${c} table(s) pulled`)),console.log("");}catch(a){e.fail("Failed to pull schema"),a instanceof Error&&console.log(f__default.default.red(`
3708
- Error: ${a.message}`)),process.exit(1);}}async function ke(t){let e=q__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let l=t.projectId||r?.projectId||o.projectId;l||(console.log(f__default.default.red("No project ID specified")),process.exit(1)),console.log(""),console.log(f__default.default.red.bold("\u26A0\uFE0F DATABASE RESET")),console.log(""),console.log(f__default.default.red("This will:")),console.log(f__default.default.red(" - Drop all tables")),console.log(f__default.default.red(" - Delete all data")),console.log(f__default.default.red(" - Reset migrations")),console.log(""),console.log(f__default.default.red.bold("This action cannot be undone!")),console.log(""),t.force||(console.log(f__default.default.yellow("Use --force to confirm this action.")),process.exit(1)),e.start("Resetting database...");try{await kt(o.token,l),e.succeed("Database reset complete"),console.log(""),console.log(f__default.default.gray("Your database is now empty.")),console.log(f__default.default.gray("Run `vaif push` to apply your schema, then `vaif db seed` to seed data.")),console.log("");}catch(i){e.fail("Failed to reset database"),i instanceof Error&&console.log(f__default.default.red(`
3709
- Error: ${i.message}`)),process.exit(1);}}var Ue=process.env.VAIF_API_URL||"https://api.vaif.studio";function $e(t,e,o){return t.projectId||e?.projectId||o.projectId||null}async function Oe(t){let e=q__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let l=$e(t,r,o);l||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=t.name||`cli-key-${Date.now()}`;console.log(""),console.log(f__default.default.bold("VAIF Generate API Key")),console.log(""),e.start("Generating API key...");try{let a=await fetch(`${Ue}/v1/projects/${l}/api-keys`,{method:"POST",headers:{Authorization:`Bearer ${o.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:i})});if(!a.ok){let c=await a.text();throw new Error(`Failed to generate key: ${c}`)}let s=await a.json();e.succeed("API key generated"),console.log(""),console.log(f__default.default.green(` Name: ${s.name}`)),console.log(f__default.default.green(` Key: ${s.key}`)),console.log(""),console.log(f__default.default.yellow.bold(" Save this key now - it will not be shown again!")),console.log("");}catch(a){e.fail("Failed to generate API key"),a instanceof Error&&console.log(f__default.default.red(`
3710
- Error: ${a.message}`)),process.exit(1);}}async function Me(t){let e=q__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let l=$e(t,r,o);l||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(f__default.default.bold("VAIF API Keys")),console.log(""),e.start("Fetching API keys...");try{let i=await fetch(`${Ue}/v1/projects/${l}/api-keys`,{headers:{Authorization:`Bearer ${o.token}`}});if(!i.ok){let u=await i.text();throw new Error(`Failed to list keys: ${u}`)}let a=await i.json(),s=a.keys||a;if(e.stop(),!Array.isArray(s)||s.length===0){console.log(f__default.default.yellow("No API keys found")),console.log(f__default.default.gray(`
3730
+ Or specify with: vaif db push --dir <path>`)),process.exit(1));}let a=[],s=N__default.default.readdirSync(i,{withFileTypes:true});for(let u of s)if(u.isFile()&&u.name.endsWith(".sql"))a.push(A__default.default.join(i,u.name));else if(u.isDirectory()){let p=N__default.default.readdirSync(A__default.default.join(i,u.name),{withFileTypes:true});for(let g of p)g.isFile()&&g.name.endsWith(".sql")&&a.push(A__default.default.join(i,u.name,g.name));}a.sort(),a.length===0&&(console.log(f__default.default.yellow("No SQL migration files found")),process.exit(1)),console.log(f__default.default.gray(`Found ${a.length} migration(s):`));for(let u of a)console.log(f__default.default.gray(` - ${A__default.default.relative(process.cwd(),u)}`));if(console.log(""),t.dryRun){console.log(f__default.default.yellow("Dry run mode - no migrations will be applied.")),console.log("");for(let u of a){let p=N__default.default.readFileSync(u,"utf-8");console.log(f__default.default.cyan(`--- ${A__default.default.basename(u)} ---`)),console.log(f__default.default.gray(p.slice(0,500))),p.length>500&&console.log(f__default.default.gray("...")),console.log("");}return}let c=0,d=0;for(let u of a){let p=N__default.default.readFileSync(u,"utf-8"),g=A__default.default.relative(process.cwd(),u);e.start(`Applying ${g}...`);try{let b=await fetch(`${Y}/schema-engine/query/${l}`,{method:"POST",headers:{Authorization:`Bearer ${o.token}`,"Content-Type":"application/json"},body:JSON.stringify({sql:p})});if(!b.ok){let C=await b.text();throw new Error(C)}e.succeed(`Applied ${g}`),c++;}catch(b){let C=b instanceof Error?b.message:"Unknown error";e.fail(`Failed ${g}: ${C}`),d++;}}console.log(""),console.log(d===0?f__default.default.green(`Successfully applied ${c} migration(s)`):f__default.default.yellow(`Applied ${c}, failed ${d} migration(s)`)),console.log("");}async function Ve(t){let e=q__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let l=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;l||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=A__default.default.resolve(t.output||"vaif.schema.json");console.log(""),console.log(f__default.default.bold("VAIF Database Pull")),console.log(""),e.start("Pulling schema from remote...");try{let a=await fetch(`${Y}/schema-engine/introspect/${l}`,{headers:{Authorization:`Bearer ${o.token}`}});if(!a.ok){let d=await a.text();throw new Error(`Failed to pull schema: ${d}`)}let s=await a.json();N__default.default.writeFileSync(i,JSON.stringify(s,null,2),"utf-8"),e.succeed(`Schema written to ${A__default.default.relative(process.cwd(),i)}`);let c=s.tables?.length??Object.keys(s).length;console.log(f__default.default.gray(` ${c} table(s) pulled`)),console.log("");}catch(a){e.fail("Failed to pull schema"),a instanceof Error&&console.log(f__default.default.red(`
3731
+ Error: ${a.message}`)),process.exit(1);}}async function Le(t){let e=q__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let l=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;l||(console.log(f__default.default.red("No project ID specified")),process.exit(1)),console.log(""),console.log(f__default.default.red.bold("\u26A0\uFE0F DATABASE RESET")),console.log(""),console.log(f__default.default.red("This will:")),console.log(f__default.default.red(" - Drop all tables")),console.log(f__default.default.red(" - Delete all data")),console.log(f__default.default.red(" - Reset migrations")),console.log(""),console.log(f__default.default.red.bold("This action cannot be undone!")),console.log(""),t.force||(console.log(f__default.default.yellow("Use --force to confirm this action.")),process.exit(1)),e.start("Resetting database...");try{await Lt(o.token,l),e.succeed("Database reset complete"),console.log(""),console.log(f__default.default.gray("Your database is now empty.")),console.log(f__default.default.gray("Run `vaif push` to apply your schema, then `vaif db seed` to seed data.")),console.log("");}catch(i){e.fail("Failed to reset database"),i instanceof Error&&console.log(f__default.default.red(`
3732
+ Error: ${i.message}`)),process.exit(1);}}var Ue=process.env.VAIF_API_URL||"https://api.vaif.studio";function Oe(t,e,o){return t.projectId||e?.projectId||process.env.VAIF_PROJECT_ID||o.projectId||null}async function $e(t){let e=q__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let l=Oe(t,r,o);l||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=t.name||`cli-key-${Date.now()}`;console.log(""),console.log(f__default.default.bold("VAIF Generate API Key")),console.log(""),e.start("Generating API key...");try{let a=await fetch(`${Ue}/v1/projects/${l}/api-keys`,{method:"POST",headers:{Authorization:`Bearer ${o.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:i})});if(!a.ok){let c=await a.text();throw new Error(`Failed to generate key: ${c}`)}let s=await a.json();e.succeed("API key generated"),console.log(""),console.log(f__default.default.green(` Name: ${s.name}`)),console.log(f__default.default.green(` Key: ${s.key}`)),console.log(""),console.log(f__default.default.yellow.bold(" Save this key now - it will not be shown again!")),console.log("");}catch(a){e.fail("Failed to generate API key"),a instanceof Error&&console.log(f__default.default.red(`
3733
+ Error: ${a.message}`)),process.exit(1);}}async function Me(t){let e=q__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let l=Oe(t,r,o);l||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(f__default.default.bold("VAIF API Keys")),console.log(""),e.start("Fetching API keys...");try{let i=await fetch(`${Ue}/v1/projects/${l}/api-keys`,{headers:{Authorization:`Bearer ${o.token}`}});if(!i.ok){let u=await i.text();throw new Error(`Failed to list keys: ${u}`)}let a=await i.json(),s=a.keys||a;if(e.stop(),!Array.isArray(s)||s.length===0){console.log(f__default.default.yellow("No API keys found")),console.log(f__default.default.gray(`
3711
3734
  Generate one with: vaif keys generate`));return}let c=Math.max(8,...s.map(u=>(u.name||"").length)),d=` ${"Name".padEnd(c)} ${"Key".padEnd(24)} Created`;console.log(f__default.default.gray(d)),console.log(f__default.default.gray(" "+"-".repeat(d.length-2)));for(let u of s){let p=(u.name||"unnamed").padEnd(c),g=u.maskedKey||u.prefix||`${(u.key||"").slice(0,12)}...`,b=u.createdAt?new Date(u.createdAt).toLocaleDateString():"N/A";console.log(` ${p} ${g.padEnd(24)} ${b}`);}console.log(""),console.log(f__default.default.gray(` ${s.length} key(s) total`)),console.log("");}catch(i){e.fail("Failed to list API keys"),i instanceof Error&&console.log(f__default.default.red(`
3712
- Error: ${i.message}`)),process.exit(1);}}var U=process.env.VAIF_API_URL||"https://api.vaif.studio";function Ut(t,e,o){return t.projectId||e?.projectId||o.projectId||null}function J(){let t=w();return (!t||!t.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1)),t}async function H(t){try{return await I(t||"vaif.config.json")}catch{return null}}function W(t,e,o){let n=Ut(t,e,o);return n||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),n}async function Ke(t,e,o){let n=q__default.default(),r=J(),l=await H(o.config),i=W(o,l,r),a=e;if(o.fromFile)try{a=N__default.default.readFileSync(o.fromFile,"utf-8");}catch(s){console.log(f__default.default.red(`Failed to read file: ${o.fromFile}`)),s instanceof Error&&console.log(f__default.default.gray(s.message)),process.exit(1);}a||(console.log(f__default.default.red("No value provided")),console.log(f__default.default.gray("Provide a value as argument or use --from-file <path>")),process.exit(1)),console.log(""),console.log(f__default.default.bold("VAIF Set Secret")),console.log(""),n.start("Checking for existing secret...");try{let s=new URL(`${U}/functions/secrets/project/${i}`);o.envId&&s.searchParams.set("envId",o.envId);let c=await fetch(s.toString(),{headers:{Authorization:`Bearer ${r.token}`}});if(!c.ok)throw new Error(`Failed to check existing secrets: ${await c.text()}`);let u=(await c.json()).find(p=>p.key===t);if(u){n.text=`Updating secret "${t}"...`;let p=await fetch(`${U}/functions/secrets/${u.id}`,{method:"PUT",headers:{Authorization:`Bearer ${r.token}`,"Content-Type":"application/json"},body:JSON.stringify({value:a})});if(!p.ok)throw new Error(`Failed to update secret: ${await p.text()}`);n.succeed(`Updated secret "${t}"`);}else {n.text=`Creating secret "${t}"...`;let p=await fetch(`${U}/functions/secrets`,{method:"POST",headers:{Authorization:`Bearer ${r.token}`,"Content-Type":"application/json"},body:JSON.stringify({projectId:i,envId:o.envId,key:t,value:a})});if(!p.ok)throw new Error(`Failed to create secret: ${await p.text()}`);n.succeed(`Created secret "${t}"`);}console.log("");}catch(s){n.fail("Failed to set secret"),s instanceof Error&&console.log(f__default.default.red(`
3713
- Error: ${s.message}`)),process.exit(1);}}async function ze(t){let e=q__default.default(),o=J(),n=await H(t.config),r=W(t,n,o);console.log(""),console.log(f__default.default.bold("VAIF Secrets")),console.log(""),e.start("Fetching secrets...");try{let l=new URL(`${U}/functions/secrets/project/${r}`);t.envId&&l.searchParams.set("envId",t.envId);let i=await fetch(l.toString(),{headers:{Authorization:`Bearer ${o.token}`}});if(!i.ok)throw new Error(`Failed to list secrets: ${await i.text()}`);let a=await i.json();if(e.stop(),a.length===0){console.log(f__default.default.yellow("No secrets found")),console.log(f__default.default.gray(`
3735
+ Error: ${i.message}`)),process.exit(1);}}var U=process.env.VAIF_API_URL||"https://api.vaif.studio";function Ut(t,e,o){return t.projectId||e?.projectId||process.env.VAIF_PROJECT_ID||o.projectId||null}function G(){let t=w();return (!t||!t.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1)),t}async function H(t){try{return await I(t||"vaif.config.json")}catch{return null}}function W(t,e,o){let n=Ut(t,e,o);return n||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),n}async function ze(t,e,o){let n=q__default.default(),r=G(),l=await H(o.config),i=W(o,l,r),a=e;if(o.fromFile)try{a=N__default.default.readFileSync(o.fromFile,"utf-8");}catch(s){console.log(f__default.default.red(`Failed to read file: ${o.fromFile}`)),s instanceof Error&&console.log(f__default.default.gray(s.message)),process.exit(1);}a||(console.log(f__default.default.red("No value provided")),console.log(f__default.default.gray("Provide a value as argument or use --from-file <path>")),process.exit(1)),console.log(""),console.log(f__default.default.bold("VAIF Set Secret")),console.log(""),n.start("Checking for existing secret...");try{let s=new URL(`${U}/functions/secrets/project/${i}`);o.envId&&s.searchParams.set("envId",o.envId);let c=await fetch(s.toString(),{headers:{Authorization:`Bearer ${r.token}`}});if(!c.ok)throw new Error(`Failed to check existing secrets: ${await c.text()}`);let u=(await c.json()).find(p=>p.key===t);if(u){n.text=`Updating secret "${t}"...`;let p=await fetch(`${U}/functions/secrets/${u.id}`,{method:"PUT",headers:{Authorization:`Bearer ${r.token}`,"Content-Type":"application/json"},body:JSON.stringify({value:a})});if(!p.ok)throw new Error(`Failed to update secret: ${await p.text()}`);n.succeed(`Updated secret "${t}"`);}else {n.text=`Creating secret "${t}"...`;let p=await fetch(`${U}/functions/secrets`,{method:"POST",headers:{Authorization:`Bearer ${r.token}`,"Content-Type":"application/json"},body:JSON.stringify({projectId:i,envId:o.envId,key:t,value:a})});if(!p.ok)throw new Error(`Failed to create secret: ${await p.text()}`);n.succeed(`Created secret "${t}"`);}console.log("");}catch(s){n.fail("Failed to set secret"),s instanceof Error&&console.log(f__default.default.red(`
3736
+ Error: ${s.message}`)),process.exit(1);}}async function Ke(t){let e=q__default.default(),o=G(),n=await H(t.config),r=W(t,n,o);console.log(""),console.log(f__default.default.bold("VAIF Secrets")),console.log(""),e.start("Fetching secrets...");try{let l=new URL(`${U}/functions/secrets/project/${r}`);t.envId&&l.searchParams.set("envId",t.envId);let i=await fetch(l.toString(),{headers:{Authorization:`Bearer ${o.token}`}});if(!i.ok)throw new Error(`Failed to list secrets: ${await i.text()}`);let a=await i.json();if(e.stop(),a.length===0){console.log(f__default.default.yellow("No secrets found")),console.log(f__default.default.gray(`
3714
3737
  Create one with: vaif secrets set <name> <value>`));return}let s=Math.max(8,...a.map(d=>d.key.length)),c=` ${"Name".padEnd(s)} Created`;console.log(f__default.default.gray(c)),console.log(f__default.default.gray(" "+"-".repeat(c.length-2)));for(let d of a){let u=d.key.padEnd(s),p=d.createdAt?new Date(d.createdAt).toLocaleDateString():"N/A";console.log(` ${u} ${p}`);}console.log(""),console.log(f__default.default.gray(` ${a.length} secret(s) total`)),console.log(f__default.default.gray(" Values are hidden. Use `vaif secrets get <name>` to reveal.")),console.log("");}catch(l){e.fail("Failed to list secrets"),l instanceof Error&&console.log(f__default.default.red(`
3715
- Error: ${l.message}`)),process.exit(1);}}async function Be(t,e){let o=q__default.default(),n=J(),r=await H(e.config),l=W(e,r,n);console.log(""),o.start("Fetching secret...");try{let i=new URL(`${U}/functions/secrets/project/${l}`);e.envId&&i.searchParams.set("envId",e.envId);let a=await fetch(i.toString(),{headers:{Authorization:`Bearer ${n.token}`}});if(!a.ok)throw new Error(`Failed to fetch secrets: ${await a.text()}`);let c=(await a.json()).find(p=>p.key===t);c||(o.fail(`Secret "${t}" not found`),process.exit(1));let d=await fetch(`${U}/functions/secrets/${c.id}/value`,{headers:{Authorization:`Bearer ${n.token}`}});if(!d.ok)throw new Error(`Failed to get secret value: ${await d.text()}`);let u=await d.json();o.stop(),console.log(u.value);}catch(i){o.fail("Failed to get secret"),i instanceof Error&&console.log(f__default.default.red(`
3716
- Error: ${i.message}`)),process.exit(1);}}async function qe(t,e){let o=q__default.default(),n=J(),r=await H(e.config),l=W(e,r,n);console.log(""),console.log(f__default.default.bold("VAIF Delete Secret")),console.log(""),o.start("Finding secret...");try{let i=new URL(`${U}/functions/secrets/project/${l}`);e.envId&&i.searchParams.set("envId",e.envId);let a=await fetch(i.toString(),{headers:{Authorization:`Bearer ${n.token}`}});if(!a.ok)throw new Error(`Failed to fetch secrets: ${await a.text()}`);let c=(await a.json()).find(u=>u.key===t);c||(o.fail(`Secret "${t}" not found`),process.exit(1)),o.text=`Deleting secret "${t}"...`;let d=await fetch(`${U}/functions/secrets/${c.id}`,{method:"DELETE",headers:{Authorization:`Bearer ${n.token}`}});if(!d.ok)throw new Error(`Failed to delete secret: ${await d.text()}`);o.succeed(`Deleted secret "${t}"`),console.log("");}catch(i){o.fail("Failed to delete secret"),i instanceof Error&&console.log(f__default.default.red(`
3717
- Error: ${i.message}`)),process.exit(1);}}var Ye=process.env.VAIF_API_URL||"https://api.vaif.studio";function Ot(t){try{let e=new URL(t);return e.password&&(e.password="****"),e.toString()}catch{return t.replace(/:[^@/]+@/,":****@")}}async function Ge(t){let e=q__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let l=t.projectId||r?.projectId||o.projectId;l||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),e.start("Fetching project info...");try{let i=await fetch(`${Ye}/v1/projects/${l}`,{headers:{Authorization:`Bearer ${o.token}`}});if(!i.ok){let d=await i.text();throw new Error(`Failed to fetch project: ${d}`)}let a=await i.json();e.stop(),console.log(""),console.log(f__default.default.bold("VAIF Project Info")),console.log("");let s=16,c=(d,u)=>{console.log(` ${f__default.default.gray(d.padEnd(s))} ${u}`);};c("Name:",f__default.default.white(a.name||"N/A")),c("Project ID:",f__default.default.white(l)),c("Region:",f__default.default.white(a.region||"us-east-1")),c("Plan:",f__default.default.white(a.plan||a.tier||"free")),c("Created:",f__default.default.white(a.createdAt?new Date(a.createdAt).toLocaleDateString():"N/A")),console.log(""),c("API URL:",f__default.default.cyan(a.apiUrl||`${Ye}/v1`)),c("WS URL:",f__default.default.cyan(a.wsUrl||a.realtimeUrl||"N/A")),c("DB URL:",f__default.default.cyan(a.databaseUrl?Ot(a.databaseUrl):"N/A")),c("Storage URL:",f__default.default.cyan(a.storageUrl||"N/A")),console.log("");}catch(i){e.fail("Failed to fetch project info"),i instanceof Error&&console.log(f__default.default.red(`
3718
- Error: ${i.message}`)),process.exit(1);}}var Kt=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Je(t){let e=q__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let l=t.projectId||r?.projectId||o.projectId;l||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),e.start("Fetching project status...");try{let i=await fetch(`${Kt}/v1/projects/${l}?include=tables,functions,storage,connections`,{headers:{Authorization:`Bearer ${o.token}`}});if(!i.ok){let b=await i.text();throw new Error(`Failed to fetch project status: ${b}`)}let a=await i.json();e.stop(),console.log(""),console.log(f__default.default.bold("VAIF Project Status")),console.log("");let s=22,c=(b,C)=>{console.log(` ${f__default.default.gray(b.padEnd(s))} ${C}`);};c("Project:",f__default.default.white(a.name||l)),c("Plan:",f__default.default.white(a.plan||a.tier||"free")),console.log(""),console.log(f__default.default.gray(" --- Resources ---")),console.log("");let d=a.tableCount??a.tables?.length??"N/A",u=a.functionCount??a.functions?.length??"N/A",p=a.bucketCount??a.storage?.buckets?.length??"N/A",g=a.activeConnections??a.connections??"N/A";c("Tables:",f__default.default.white(String(d))),c("Functions:",f__default.default.white(String(u))),c("Storage Buckets:",f__default.default.white(String(p))),c("Active Connections:",f__default.default.white(String(g))),a.usage&&(console.log(""),console.log(f__default.default.gray(" --- Usage ---")),console.log(""),a.usage.dbSize&&c("Database Size:",f__default.default.white(a.usage.dbSize)),a.usage.storageSize&&c("Storage Size:",f__default.default.white(a.usage.storageSize)),a.usage.bandwidth&&c("Bandwidth:",f__default.default.white(a.usage.bandwidth)),a.usage.functionInvocations!=null&&c("Function Invocations:",f__default.default.white(String(a.usage.functionInvocations)))),console.log("");}catch(i){e.fail("Failed to fetch project status"),i instanceof Error&&console.log(f__default.default.red(`
3719
- Error: ${i.message}`)),process.exit(1);}}commander.program.name("vaif").description("VAIF CLI - Type generation and development tools").version("1.6.0");commander.program.command("login").description("Authenticate with VAIF (opens browser)").option("-e, --email","Login with email/password instead of browser").option("-p, --project-id <id>","Default project ID").action(be);commander.program.command("logout").description("Log out and remove stored credentials").action(Ie);commander.program.command("whoami").description("Show current authenticated user").action(Ae);commander.program.command("init").description("Initialize VAIF configuration in your project").option("--typescript","Setup for TypeScript project").option("-f, --force","Overwrite existing config").option("-t, --template <name>","Scaffold from a template (run vaif templates for list)").option("--features <features>","Comma-separated features to include: auth,database,realtime,storage,functions").action(me);commander.program.command("templates").alias("tpl").description("List available project templates").action(fe);commander.program.command("info").description("Show project information (name, region, URLs)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").action(Ge);commander.program.command("status").description("Show project status (tables, functions, storage, connections)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").action(Je);commander.program.command("pull").description("Pull database schema from your VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-o, --output <path>","Output file path","vaif.schema.json").option("-s, --schema <name>","Schema name","public").option("-p, --project-id <id>","Project ID (overrides config)").action(we);commander.program.command("push").description("Push local schema changes to your VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-s, --schema <path>","Schema file path","vaif.schema.json").option("-p, --project-id <id>","Project ID (overrides config)").option("--dry-run","Preview changes without applying").option("-f, --force","Apply changes without confirmation").action(xe);commander.program.command("generate").alias("gen").description("Generate TypeScript types from your database schema").option("-c, --connection <url>","Database connection string").option("-o, --output <path>","Output file path","./src/types/database.ts").option("--schema <name>","Schema name","public").option("--config <path>","Config file path","vaif.config.json").option("--dry-run","Preview generated types without writing").action(de);var He=commander.program.command("functions").alias("fn").description("Manage serverless functions");He.command("deploy").description("Deploy functions to your VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID").option("-n, --name <name>","Function name filter").option("-r, --runtime <runtime>","Runtime (nodejs, typescript, python)").option("--entrypoint <file>","Specific entrypoint file").option("--dry-run","Preview deployment without deploying").action(je);He.command("list").alias("ls").description("List deployed functions").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID").action(Ce);var X=commander.program.command("db").description("Database management commands");X.command("push").description("Push local Drizzle migrations to VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-d, --dir <path>","Migrations directory","./drizzle").option("--dry-run","Preview without applying").action(De);X.command("pull").description("Pull schema from VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-o, --output <path>","Output file","vaif.schema.json").action(Le);X.command("seed").description("Seed your database with test data").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-f, --file <path>","Specific seed file").option("-t, --table <name>","Seed specific table only").option("--truncate","Truncate tables before seeding").option("--dry-run","Preview seeding without inserting data").action(Ne);X.command("reset").description("Reset database (drop all tables and data)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-f, --force","Confirm reset (required)").action(ke);var We=commander.program.command("keys").description("Manage API keys");We.command("generate").description("Generate a new API key").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-n, --name <name>","Key name").action(Oe);We.command("list").alias("ls").description("List API keys").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").action(Me);var Q=commander.program.command("secrets").alias("sec").description("Manage function secrets");Q.command("set <name> [value]").description("Create or update a secret").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").option("--from-file <path>","Read secret value from a file").action(Ke);Q.command("list").alias("ls").description("List all secrets (names only)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").action(ze);Q.command("get <name>").description("Reveal a secret value").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").action(Be);Q.command("delete <name>").description("Delete a secret").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").action(qe);commander.program.parse(process.argv);process.argv.slice(2).length||commander.program.outputHelp();
3738
+ Error: ${l.message}`)),process.exit(1);}}async function Be(t,e){let o=q__default.default(),n=G(),r=await H(e.config),l=W(e,r,n);console.log(""),o.start("Fetching secret...");try{let i=new URL(`${U}/functions/secrets/project/${l}`);e.envId&&i.searchParams.set("envId",e.envId);let a=await fetch(i.toString(),{headers:{Authorization:`Bearer ${n.token}`}});if(!a.ok)throw new Error(`Failed to fetch secrets: ${await a.text()}`);let c=(await a.json()).find(p=>p.key===t);c||(o.fail(`Secret "${t}" not found`),process.exit(1));let d=await fetch(`${U}/functions/secrets/${c.id}/value`,{headers:{Authorization:`Bearer ${n.token}`}});if(!d.ok)throw new Error(`Failed to get secret value: ${await d.text()}`);let u=await d.json();o.stop(),console.log(u.value);}catch(i){o.fail("Failed to get secret"),i instanceof Error&&console.log(f__default.default.red(`
3739
+ Error: ${i.message}`)),process.exit(1);}}async function qe(t,e){let o=q__default.default(),n=G(),r=await H(e.config),l=W(e,r,n);console.log(""),console.log(f__default.default.bold("VAIF Delete Secret")),console.log(""),o.start("Finding secret...");try{let i=new URL(`${U}/functions/secrets/project/${l}`);e.envId&&i.searchParams.set("envId",e.envId);let a=await fetch(i.toString(),{headers:{Authorization:`Bearer ${n.token}`}});if(!a.ok)throw new Error(`Failed to fetch secrets: ${await a.text()}`);let c=(await a.json()).find(u=>u.key===t);c||(o.fail(`Secret "${t}" not found`),process.exit(1)),o.text=`Deleting secret "${t}"...`;let d=await fetch(`${U}/functions/secrets/${c.id}`,{method:"DELETE",headers:{Authorization:`Bearer ${n.token}`}});if(!d.ok)throw new Error(`Failed to delete secret: ${await d.text()}`);o.succeed(`Deleted secret "${t}"`),console.log("");}catch(i){o.fail("Failed to delete secret"),i instanceof Error&&console.log(f__default.default.red(`
3740
+ Error: ${i.message}`)),process.exit(1);}}var Ye=process.env.VAIF_API_URL||"https://api.vaif.studio";function $t(t){try{let e=new URL(t);return e.password&&(e.password="****"),e.toString()}catch{return t.replace(/:[^@/]+@/,":****@")}}async function Je(t){let e=q__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let l=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;l||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),e.start("Fetching project info...");try{let i=await fetch(`${Ye}/v1/projects/${l}`,{headers:{Authorization:`Bearer ${o.token}`}});if(!i.ok){let d=await i.text();throw new Error(`Failed to fetch project: ${d}`)}let a=await i.json();e.stop(),console.log(""),console.log(f__default.default.bold("VAIF Project Info")),console.log("");let s=16,c=(d,u)=>{console.log(` ${f__default.default.gray(d.padEnd(s))} ${u}`);};c("Name:",f__default.default.white(a.name||"N/A")),c("Project ID:",f__default.default.white(l)),c("Region:",f__default.default.white(a.region||"us-east-1")),c("Plan:",f__default.default.white(a.plan||a.tier||"free")),c("Created:",f__default.default.white(a.createdAt?new Date(a.createdAt).toLocaleDateString():"N/A")),console.log(""),c("API URL:",f__default.default.cyan(a.apiUrl||`${Ye}/v1`)),c("WS URL:",f__default.default.cyan(a.wsUrl||a.realtimeUrl||"N/A")),c("DB URL:",f__default.default.cyan(a.databaseUrl?$t(a.databaseUrl):"N/A")),c("Storage URL:",f__default.default.cyan(a.storageUrl||"N/A")),console.log("");}catch(i){e.fail("Failed to fetch project info"),i instanceof Error&&console.log(f__default.default.red(`
3741
+ Error: ${i.message}`)),process.exit(1);}}var zt=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Ge(t){let e=q__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let l=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;l||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),e.start("Fetching project status...");try{let i=await fetch(`${zt}/v1/projects/${l}?include=tables,functions,storage,connections`,{headers:{Authorization:`Bearer ${o.token}`}});if(!i.ok){let b=await i.text();throw new Error(`Failed to fetch project status: ${b}`)}let a=await i.json();e.stop(),console.log(""),console.log(f__default.default.bold("VAIF Project Status")),console.log("");let s=22,c=(b,C)=>{console.log(` ${f__default.default.gray(b.padEnd(s))} ${C}`);};c("Project:",f__default.default.white(a.name||l)),c("Plan:",f__default.default.white(a.plan||a.tier||"free")),console.log(""),console.log(f__default.default.gray(" --- Resources ---")),console.log("");let d=a.tableCount??a.tables?.length??"N/A",u=a.functionCount??a.functions?.length??"N/A",p=a.bucketCount??a.storage?.buckets?.length??"N/A",g=a.activeConnections??a.connections??"N/A";c("Tables:",f__default.default.white(String(d))),c("Functions:",f__default.default.white(String(u))),c("Storage Buckets:",f__default.default.white(String(p))),c("Active Connections:",f__default.default.white(String(g))),a.usage&&(console.log(""),console.log(f__default.default.gray(" --- Usage ---")),console.log(""),a.usage.dbSize&&c("Database Size:",f__default.default.white(a.usage.dbSize)),a.usage.storageSize&&c("Storage Size:",f__default.default.white(a.usage.storageSize)),a.usage.bandwidth&&c("Bandwidth:",f__default.default.white(a.usage.bandwidth)),a.usage.functionInvocations!=null&&c("Function Invocations:",f__default.default.white(String(a.usage.functionInvocations)))),console.log("");}catch(i){e.fail("Failed to fetch project status"),i instanceof Error&&console.log(f__default.default.red(`
3742
+ Error: ${i.message}`)),process.exit(1);}}commander.program.name("vaif").description("VAIF CLI - Type generation and development tools").version("1.6.2");commander.program.command("login").description("Authenticate with VAIF (opens browser)").option("-e, --email","Login with email/password instead of browser").option("-p, --project-id <id>","Default project ID").action(be);commander.program.command("logout").description("Log out and remove stored credentials").action(Ie);commander.program.command("whoami").description("Show current authenticated user").action(Ae);commander.program.command("init").description("Initialize VAIF configuration in your project").option("--typescript","Setup for TypeScript project").option("-f, --force","Overwrite existing config").option("-t, --template <name>","Scaffold from a template (run vaif templates for list)").option("--features <features>","Comma-separated features to include: auth,database,realtime,storage,functions").action(me);commander.program.command("templates").alias("tpl").description("List available project templates").action(fe);commander.program.command("info").description("Show project information (name, region, URLs)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").action(Je);commander.program.command("status").description("Show project status (tables, functions, storage, connections)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").action(Ge);commander.program.command("pull").description("Pull database schema from your VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-o, --output <path>","Output file path","vaif.schema.json").option("-s, --schema <name>","Schema name","public").option("-p, --project-id <id>","Project ID (overrides config)").action(we);commander.program.command("push").description("Push local schema changes to your VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-s, --schema <path>","Schema file path","vaif.schema.json").option("-p, --project-id <id>","Project ID (overrides config)").option("--dry-run","Preview changes without applying").option("-f, --force","Apply changes without confirmation").action(_e);commander.program.command("generate").alias("gen").description("Generate TypeScript types from your database schema").option("-c, --connection <url>","Database connection string").option("-o, --output <path>","Output file path","./src/types/database.ts").option("--schema <name>","Schema name","public").option("--config <path>","Config file path","vaif.config.json").option("--dry-run","Preview generated types without writing").action(de);var He=commander.program.command("functions").alias("fn").description("Manage serverless functions");He.command("deploy").description("Deploy functions to your VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID").option("-n, --name <name>","Function name filter").option("-r, --runtime <runtime>","Runtime (nodejs, typescript, python)").option("--entrypoint <file>","Specific entrypoint file").option("--dry-run","Preview deployment without deploying").action(je);He.command("list").alias("ls").description("List deployed functions").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID").action(Ce);var X=commander.program.command("db").description("Database management commands");X.command("push").description("Push local Drizzle migrations to VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-d, --dir <path>","Migrations directory","./drizzle").option("--dry-run","Preview without applying").action(De);X.command("pull").description("Pull schema from VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-o, --output <path>","Output file","vaif.schema.json").action(Ve);X.command("seed").description("Seed your database with test data").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-f, --file <path>","Specific seed file").option("-t, --table <name>","Seed specific table only").option("--truncate","Truncate tables before seeding").option("--dry-run","Preview seeding without inserting data").action(Ne);X.command("reset").description("Reset database (drop all tables and data)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-f, --force","Confirm reset (required)").action(Le);var We=commander.program.command("keys").description("Manage API keys");We.command("generate").description("Generate a new API key").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-n, --name <name>","Key name").action($e);We.command("list").alias("ls").description("List API keys").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").action(Me);var Q=commander.program.command("secrets").alias("sec").description("Manage function secrets");Q.command("set <name> [value]").description("Create or update a secret").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").option("--from-file <path>","Read secret value from a file").action(ze);Q.command("list").alias("ls").description("List all secrets (names only)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").action(Ke);Q.command("get <name>").description("Reveal a secret value").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").action(Be);Q.command("delete <name>").description("Delete a secret").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").action(qe);commander.program.parse(process.argv);process.argv.slice(2).length||commander.program.outputHelp();