@vaiftech/cli 1.5.1 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- 'use strict';var commander=require('commander'),R=require('fs'),I=require('path'),Ke=require('pg'),K=require('ora'),p=require('chalk'),qe=require('prettier'),ze=require('dotenv'),ae=require('readline'),et=require('os'),child_process=require('child_process');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var R__default=/*#__PURE__*/_interopDefault(R);var I__default=/*#__PURE__*/_interopDefault(I);var Ke__default=/*#__PURE__*/_interopDefault(Ke);var K__default=/*#__PURE__*/_interopDefault(K);var p__default=/*#__PURE__*/_interopDefault(p);var qe__default=/*#__PURE__*/_interopDefault(qe);var ze__default=/*#__PURE__*/_interopDefault(ze);var ae__default=/*#__PURE__*/_interopDefault(ae);var et__default=/*#__PURE__*/_interopDefault(et);ze__default.default.config();async function A(t){let e=I__default.default.resolve(t);if(!R__default.default.existsSync(e))return null;try{let o=R__default.default.readFileSync(e,"utf-8"),n=JSON.parse(o);return n.database?.url&&(n.database.url=te(n.database.url)),n.api?.apiKey&&(n.api.apiKey=te(n.api.apiKey)),n}catch{throw new Error(`Failed to parse config file: ${t}`)}}function te(t){return t.replace(/\$\{([^}]+)\}/g,(e,o)=>process.env[o]||e)}async function Ye(t,e){let o=await t.query(`
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(`
3
3
  SELECT table_name, table_type
4
4
  FROM information_schema.tables
5
5
  WHERE table_schema = $1
@@ -36,7 +36,7 @@
36
36
  AND ccu.table_schema = tc.table_schema
37
37
  WHERE tc.constraint_type = 'FOREIGN KEY'
38
38
  AND tc.table_schema = $1
39
- `,[e]),s=await t.query(`
39
+ `,[e]),l=await t.query(`
40
40
  SELECT
41
41
  t.typname as enum_name,
42
42
  e.enumlabel as enum_value
@@ -45,22 +45,22 @@
45
45
  JOIN pg_namespace n ON n.oid = t.typnamespace
46
46
  WHERE n.nspname = $1
47
47
  ORDER BY t.typname, e.enumsortorder
48
- `,[e]),i=new Map;for(let l of o.rows)i.set(l.table_name,[]);for(let l of n.rows){let c=i.get(l.table_name);c&&c.push(l);}let a=new Map;for(let l of s.rows){let c=a.get(l.enum_name)||[];c.push(l.enum_value),a.set(l.enum_name,c);}return {tables:i,enums:a,foreignKeys:r.rows}}var G={smallint:"number",integer:"number",bigint:"string",int2:"number",int4:"number",int8:"string",decimal:"string",numeric:"string",real:"number",float4:"number",float8:"number","double precision":"number",money:"string",boolean:"boolean",bool:"boolean",text:"string",varchar:"string",char:"string",character:"string","character varying":"string",name:"string",citext:"string",date:"string",time:"string",timetz:"string","time without time zone":"string","time with time zone":"string",timestamp:"string",timestamptz:"string","timestamp without time zone":"string","timestamp with time zone":"string",interval:"string",bytea:"Buffer",uuid:"string",json:"unknown",jsonb:"unknown",inet:"string",cidr:"string",macaddr:"string",macaddr8:"string",point:"{ x: number; y: number }",line:"string",lseg:"string",box:"string",path:"string",polygon:"string",circle:"string",ARRAY:"unknown[]"};function Ge(t,e){let{data_type:o,udt_name:n,is_nullable:r}=t;if(e.has(n)){let a=e.get(n).map(l=>`"${l}"`).join(" | ");return r==="YES"?`(${a}) | null`:a}if(o==="ARRAY"){let i=n.replace(/^_/,"");if(e.has(i)){let c=e.get(i).map(u=>`"${u}"`).join(" | ");return r==="YES"?`(${c})[] | null`:`(${c})[]`}let a=G[i]||"unknown";return r==="YES"?`${a}[] | null`:`${a}[]`}let s=G[o]||G[n]||"unknown";return r==="YES"&&(s=`${s} | null`),s}function J(t){return t.split(/[_\-\s]+/).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}function Je(t,e){let o=J(t),n=e.map(r=>` | "${r}"`).join(`
48
+ `,[e]),i=new Map;for(let s of o.rows)i.set(s.table_name,[]);for(let s of n.rows){let c=i.get(s.table_name);c&&c.push(s);}let a=new Map;for(let s of l.rows){let c=a.get(s.enum_name)||[];c.push(s.enum_value),a.set(s.enum_name,c);}return {tables:i,enums:a,foreignKeys:r.rows}}var ee={smallint:"number",integer:"number",bigint:"string",int2:"number",int4:"number",int8:"string",decimal:"string",numeric:"string",real:"number",float4:"number",float8:"number","double precision":"number",money:"string",boolean:"boolean",bool:"boolean",text:"string",varchar:"string",char:"string",character:"string","character varying":"string",name:"string",citext:"string",date:"string",time:"string",timetz:"string","time without time zone":"string","time with time zone":"string",timestamp:"string",timestamptz:"string","timestamp without time zone":"string","timestamp with time zone":"string",interval:"string",bytea:"Buffer",uuid:"string",json:"unknown",jsonb:"unknown",inet:"string",cidr:"string",macaddr:"string",macaddr8:"string",point:"{ x: number; y: number }",line:"string",lseg:"string",box:"string",path:"string",polygon:"string",circle:"string",ARRAY:"unknown[]"};function at(t,e){let{data_type:o,udt_name:n,is_nullable:r}=t;if(e.has(n)){let a=e.get(n).map(s=>`"${s}"`).join(" | ");return r==="YES"?`(${a}) | null`:a}if(o==="ARRAY"){let i=n.replace(/^_/,"");if(e.has(i)){let c=e.get(i).map(d=>`"${d}"`).join(" | ");return r==="YES"?`(${c})[] | null`:`(${c})[]`}let a=ee[i]||"unknown";return r==="YES"?`${a}[] | null`:`${a}[]`}let l=ee[o]||ee[n]||"unknown";return r==="YES"&&(l=`${l} | null`),l}function te(t){return t.split(/[_\-\s]+/).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}function it(t,e){let o=te(t),n=e.map(r=>` | "${r}"`).join(`
49
49
  `);return `export type ${o} =
50
- ${n};`}function He(t,e,o){let n=J(t),r=[],s=[],i=[];for(let u of e){let f=Ge(u,o),d=u.column_name,m=u.column_default!==null||u.is_identity==="YES",b=u.is_nullable==="YES";r.push(` ${d}: ${f};`),m||u.column_name==="id"?s.push(` ${d}?: ${f.replace(" | null","")} | null;`):b?s.push(` ${d}?: ${f};`):s.push(` ${d}: ${f.replace(" | null","")};`),i.push(` ${d}?: ${f.replace(" | null","")} | null;`);}let a=`export interface ${n} {
50
+ ${n};`}function rt(t,e,o){let n=te(t),r=[],l=[],i=[];for(let d of e){let u=at(d,o),p=d.column_name,g=d.column_default!==null||d.is_identity==="YES",b=d.is_nullable==="YES";r.push(` ${p}: ${u};`),g||d.column_name==="id"?l.push(` ${p}?: ${u.replace(" | null","")} | null;`):b?l.push(` ${p}?: ${u};`):l.push(` ${p}: ${u.replace(" | null","")};`),i.push(` ${p}?: ${u.replace(" | null","")} | null;`);}let a=`export interface ${n} {
51
51
  ${r.join(`
52
52
  `)}
53
- }`,l=`export interface ${n}Insert {
54
- ${s.join(`
53
+ }`,s=`export interface ${n}Insert {
54
+ ${l.join(`
55
55
  `)}
56
56
  }`,c=`export interface ${n}Update {
57
57
  ${i.join(`
58
58
  `)}
59
- }`;return {base:a,insert:l,update:c}}function We(t,e,o){let n=["/**"," * Auto-generated TypeScript types from database schema"," * Generated by @vaiftech/cli",` * Generated at: ${new Date().toISOString()}`," * "," * DO NOT EDIT MANUALLY - changes will be overwritten"," */",""];if(e.size>0){n.push("// ============ ENUMS ============"),n.push("");for(let[s,i]of e)n.push(Je(s,i)),n.push("");}n.push("// ============ TABLES ============"),n.push("");let r=[];for(let[s,i]of t){let{base:a,insert:l,update:c}=He(s,i,e);r.push(s),n.push(a),n.push(""),n.push(l),n.push(""),n.push(c),n.push("");}n.push("// ============ DATABASE SCHEMA ============"),n.push(""),n.push("export interface Database {");for(let s of r){let i=J(s);n.push(` ${s}: {`),n.push(` Row: ${i};`),n.push(` Insert: ${i}Insert;`),n.push(` Update: ${i}Update;`),n.push(" };");}return n.push("}"),n.push(""),n.push("export type TableName = keyof Database;"),n.push(""),n.push("// ============ HELPER TYPES ============"),n.push(""),n.push('export type Row<T extends TableName> = Database[T]["Row"];'),n.push('export type Insert<T extends TableName> = Database[T]["Insert"];'),n.push('export type Update<T extends TableName> = Database[T]["Update"];'),n.push(""),n.join(`
60
- `)}async function ne(t){let e=K__default.default("Loading configuration...").start();try{let o=await A(t.config),n=t.connection||o?.database?.url||process.env.DATABASE_URL;n||(e.fail("No database connection string provided"),console.log(p__default.default.yellow(`
61
- Provide a connection string via:`)),console.log(p__default.default.gray(" --connection <url>")),console.log(p__default.default.gray(" DATABASE_URL environment variable")),console.log(p__default.default.gray(" vaif.config.json database.url")),process.exit(1)),e.text="Connecting to database...";let r=new Ke__default.default.Client({connectionString:n});await r.connect(),e.text="Introspecting schema...";let{tables:s,enums:i,foreignKeys:a}=await Ye(r,t.schema);if(await r.end(),s.size===0){e.warn(`No tables found in schema "${t.schema}"`);return}e.text=`Generating types for ${s.size} tables...`;let l=We(s,i,a),c=await qe__default.default.format(l,{parser:"typescript",semi:!0,singleQuote:!1,trailingComma:"es5",printWidth:100});if(t.dryRun){e.succeed("Generated types (dry run):"),console.log(""),console.log(p__default.default.gray("\u2500".repeat(60))),console.log(c),console.log(p__default.default.gray("\u2500".repeat(60)));return}let u=I__default.default.resolve(t.output),f=I__default.default.dirname(u);R__default.default.existsSync(f)||R__default.default.mkdirSync(f,{recursive:!0}),R__default.default.writeFileSync(u,c,"utf-8"),e.succeed(`Generated types for ${s.size} tables \u2192 ${p__default.default.cyan(t.output)}`),console.log(""),console.log(p__default.default.green("Generated:")),console.log(p__default.default.gray(` Tables: ${s.size}`)),console.log(p__default.default.gray(` Enums: ${i.size}`)),console.log(""),console.log(p__default.default.gray("Import in your code:")),console.log(p__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(p__default.default.red(`
62
- Error: ${o.message}`)),o.message.includes("ECONNREFUSED")&&console.log(p__default.default.yellow(`
63
- Make sure your database is running and accessible.`))),process.exit(1);}}var k=[{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"}],ie={"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:`{
59
+ }`;return {base:a,insert:s,update:c}}function st(t,e,o){let n=["/**"," * Auto-generated TypeScript types from database schema"," * Generated by @vaiftech/cli",` * Generated at: ${new Date().toISOString()}`," * "," * DO NOT EDIT MANUALLY - changes will be overwritten"," */",""];if(e.size>0){n.push("// ============ ENUMS ============"),n.push("");for(let[l,i]of e)n.push(it(l,i)),n.push("");}n.push("// ============ TABLES ============"),n.push("");let r=[];for(let[l,i]of t){let{base:a,insert:s,update:c}=rt(l,i,e);r.push(l),n.push(a),n.push(""),n.push(s),n.push(""),n.push(c),n.push("");}n.push("// ============ DATABASE SCHEMA ============"),n.push(""),n.push("export interface Database {");for(let l of r){let i=te(l);n.push(` ${l}: {`),n.push(` Row: ${i};`),n.push(` Insert: ${i}Insert;`),n.push(` Update: ${i}Update;`),n.push(" };");}return n.push("}"),n.push(""),n.push("export type TableName = keyof Database;"),n.push(""),n.push("// ============ HELPER TYPES ============"),n.push(""),n.push('export type Row<T extends TableName> = Database[T]["Row"];'),n.push('export type Insert<T extends TableName> = Database[T]["Insert"];'),n.push('export type Update<T extends TableName> = Database[T]["Update"];'),n.push(""),n.join(`
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
+ 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
+ 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:`{
64
64
  "name": "my-vaif-app",
65
65
  "private": true,
66
66
  "version": "0.1.0",
@@ -528,6 +528,11 @@ export const posts = pgTable("posts", {
528
528
  });
529
529
  `}],functions:[{path:"functions/hello.ts",content:`export default async function handler(req: Request): Promise<Response> {
530
530
  const { name } = await req.json().catch(() => ({ name: "World" }));
531
+
532
+ // Secrets set via \\\`vaif secrets set\\\` or the Security > Secrets page
533
+ // are available as environment variables at runtime:
534
+ // const apiKey = process.env.MY_API_KEY;
535
+
531
536
  return Response.json({ message: \`Hello, \${name}!\` });
532
537
  }
533
538
  `}]},dependencies:["@vaiftech/client","@vaiftech/auth","@vaiftech/react","next","react","react-dom"],devDependencies:["@types/node","@types/react","@types/react-dom","typescript"],postInstructions:["cd my-vaif-app","npm install","# Copy .env.local.example to .env.local and add your VAIF credentials","npm run dev"]},"react-spa":{name:"React SPA",description:"Single-page React app with Vite, VAIF client, and provider wrapper",tag:"React + Vite",defaultFeatures:["database","auth"],files:[{path:"package.json",content:`{
@@ -1037,6 +1042,11 @@ export const posts = pgTable("posts", {
1037
1042
  });
1038
1043
  `}],functions:[{path:"functions/hello.ts",content:`export default async function handler(req: Request): Promise<Response> {
1039
1044
  const { name } = await req.json().catch(() => ({ name: "World" }));
1045
+
1046
+ // Secrets set via \\\`vaif secrets set\\\` or the Security > Secrets page
1047
+ // are available as environment variables at runtime:
1048
+ // const apiKey = process.env.MY_API_KEY;
1049
+
1040
1050
  return Response.json({ message: \`Hello, \${name}!\` });
1041
1051
  }
1042
1052
  `}]},dependencies:["@vaiftech/client","@vaiftech/react","react","react-dom","react-router-dom"],devDependencies:["@types/react","@types/react-dom","@vitejs/plugin-react","typescript","vite"],postInstructions:["cd my-vaif-app","npm install","# Copy .env.example to .env and add your VAIF credentials","npm run dev"]},"ios-swift-app":{name:"iOS Swift App",description:"Swift client manager for iOS/macOS apps using Swift Package Manager",tag:"Swift / iOS",defaultFeatures:["database","auth"],files:[{path:"VaifManager.swift",content:`import Foundation
@@ -1626,6 +1636,11 @@ export const posts = pgTable("posts", {
1626
1636
  });
1627
1637
  `}],functions:[{path:"functions/hello.ts",content:`export default async function handler(req: Request): Promise<Response> {
1628
1638
  const { name } = await req.json().catch(() => ({ name: "World" }));
1639
+
1640
+ // Secrets set via \\\`vaif secrets set\\\` or the Security > Secrets page
1641
+ // are available as environment variables at runtime:
1642
+ // const apiKey = process.env.MY_API_KEY;
1643
+
1629
1644
  return Response.json({ message: \`Hello, \${name}!\` });
1630
1645
  }
1631
1646
  `}]},dependencies:["@vaiftech/sdk-expo","@react-native-async-storage/async-storage","expo","expo-router","react","react-native"],postInstructions:["cd my-vaif-app","npm install","# Copy .env.example to .env and add your VAIF credentials","npx expo start"]},"flutter-app":{name:"Flutter App",description:"Dart/Flutter client setup with environment configuration",tag:"Flutter / Dart",defaultFeatures:["database","auth"],files:[{path:"lib/main.dart",content:`import 'package:flutter/material.dart';
@@ -2237,6 +2252,7 @@ async def invoke_function(function_name: str, payload: dict = {}):
2237
2252
  `},{path:"functions/hello.py",content:`"""Example VAIF serverless function."""
2238
2253
 
2239
2254
  import json
2255
+ import os
2240
2256
 
2241
2257
 
2242
2258
  def handler(request):
@@ -2244,6 +2260,10 @@ def handler(request):
2244
2260
 
2245
2261
  Deploy with: vaif functions deploy
2246
2262
  """
2263
+ # Secrets set via \\\`vaif secrets set\\\` or the Security > Secrets page
2264
+ # are available as environment variables at runtime:
2265
+ # api_key = os.environ.get("MY_API_KEY")
2266
+
2247
2267
  try:
2248
2268
  body = json.loads(request.body) if request.body else {}
2249
2269
  name = body.get("name", "World")
@@ -2558,6 +2578,11 @@ type HelloResponse struct {
2558
2578
  }
2559
2579
 
2560
2580
  // HelloHandler is an example VAIF serverless function.
2581
+ //
2582
+ // Secrets set via \\\`vaif secrets set\\\` or the Security > Secrets page
2583
+ // are available as environment variables at runtime:
2584
+ //
2585
+ // apiKey := os.Getenv("MY_API_KEY") // import "os"
2561
2586
  func HelloHandler(w http.ResponseWriter, r *http.Request) {
2562
2587
  var req HelloRequest
2563
2588
  if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Name == "" {
@@ -2753,6 +2778,11 @@ export const posts = pgTable("posts", {
2753
2778
  });
2754
2779
  `}],functions:[{path:"functions/hello.ts",content:`export default async function handler(req: Request): Promise<Response> {
2755
2780
  const { name } = await req.json().catch(() => ({ name: "World" }));
2781
+
2782
+ // Secrets set via \\\`vaif secrets set\\\` or the Security > Secrets page
2783
+ // are available as environment variables at runtime:
2784
+ // const apiKey = process.env.MY_API_KEY;
2785
+
2756
2786
  return Response.json({ message: \`Hello, \${name}!\` });
2757
2787
  }
2758
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";
@@ -3047,6 +3077,11 @@ export const posts = pgTable("posts", {
3047
3077
  });
3048
3078
  `}],functions:[{path:"functions/hello.ts",content:`export default async function handler(req: Request): Promise<Response> {
3049
3079
  const { name } = await req.json().catch(() => ({ name: "World" }));
3080
+
3081
+ // Secrets set via \\\`vaif secrets set\\\` or the Security > Secrets page
3082
+ // are available as environment variables at runtime:
3083
+ // const apiKey = process.env.MY_API_KEY;
3084
+
3050
3085
  return Response.json({ message: \`Hello, \${name}!\` });
3051
3086
  }
3052
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";
@@ -3353,6 +3388,11 @@ export const posts = pgTable("posts", {
3353
3388
  });
3354
3389
  `}],functions:[{path:"functions/hello.ts",content:`export default async function handler(req: Request): Promise<Response> {
3355
3390
  const { name } = await req.json().catch(() => ({ name: "World" }));
3391
+
3392
+ // Secrets set via \\\`vaif secrets set\\\` or the Security > Secrets page
3393
+ // are available as environment variables at runtime:
3394
+ // const apiKey = process.env.MY_API_KEY;
3395
+
3356
3396
  return Response.json({ message: \`Hello, \${name}!\` });
3357
3397
  }
3358
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";
@@ -3619,51 +3659,61 @@ export const posts = pgTable("posts", {
3619
3659
  });
3620
3660
  `}],functions:[{path:"functions/hello.ts",content:`export default async function handler(req: Request): Promise<Response> {
3621
3661
  const { name } = await req.json().catch(() => ({ name: "World" }));
3662
+
3663
+ // Secrets set via \\\`vaif secrets set\\\` or the Security > Secrets page
3664
+ // are available as environment variables at runtime:
3665
+ // const apiKey = process.env.MY_API_KEY;
3666
+
3622
3667
  return Response.json({ message: \`Hello, \${name}!\` });
3623
3668
  }
3624
- `}]},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 re(){console.log(""),console.log(p__default.default.bold("Available project templates")),console.log("");let t=26,e=22;console.log(` ${p__default.default.gray("Template".padEnd(t))}${p__default.default.gray("Stack".padEnd(e))}${p__default.default.gray("Description")}`),console.log(p__default.default.gray(" "+"-".repeat(t+e+40)));for(let[o,n]of Object.entries(ie))console.log(` ${p__default.default.cyan(o.padEnd(t))}${p__default.default.yellow(n.tag.padEnd(e))}${p__default.default.white(n.description)}`);console.log(""),console.log(p__default.default.gray("Usage:")),console.log(p__default.default.gray(" npx @vaiftech/cli init --template <name>")),console.log(p__default.default.gray(" npx @vaiftech/cli init -t nextjs-fullstack")),console.log(p__default.default.gray(" npx @vaiftech/cli init -t react-spa --features auth,database,realtime")),console.log(""),console.log(p__default.default.gray("Available features: auth, database, realtime, storage, functions")),console.log("");}async function Xe(t){if(!process.stdin.isTTY||!process.stdout.isTTY)return t;let e=new Set(t.map(n=>k.findIndex(r=>r.name===n)).filter(n=>n>=0)),o=0;return new Promise(n=>{let r=ae__default.default.createInterface({input:process.stdin,output:process.stdout});ae__default.default.emitKeypressEvents(process.stdin,r),process.stdin.setRawMode&&process.stdin.setRawMode(true);function s(){let a=k.length+2;process.stdout.write(`\x1B[${a}A`),i();}function i(){console.log(p__default.default.bold(`
3625
- ? Which VAIF features do you want to include?`)),k.forEach((a,l)=>{let c=e.has(l)?p__default.default.green("[x]"):"[ ]",u=l===o?p__default.default.cyan("> "):" ";console.log(`${u}${c} ${a.label} ${p__default.default.gray(`(${a.description})`)}`);}),console.log(p__default.default.gray(" (up/down to move, space to toggle, enter to confirm)"));}i(),process.stdin.on("keypress",(a,l)=>{if(l.name==="up"&&o>0)o--,s();else if(l.name==="down"&&o<k.length-1)o++,s();else if(l.name==="space")e.has(o)?e.delete(o):e.add(o),s();else if(l.name==="return"){process.stdin.setRawMode&&process.stdin.setRawMode(false),r.close();let c=[...e].sort().map(u=>k[u].name);n(c.length>0?c:t);}else l.name==="c"&&l.ctrl&&(process.stdin.setRawMode&&process.stdin.setRawMode(false),r.close(),process.exit(0));});})}async function se(t,e={}){let o=ie[t];o||(console.log(p__default.default.red(`
3626
- Unknown template: ${t}`)),console.log(p__default.default.yellow(`Run 'vaif templates' to see available templates.
3627
- `)),process.exit(1));let n;e.features&&e.features.length>0?n=e.features.filter(c=>k.some(u=>u.name===c)):o.featureFiles&&Object.keys(o.featureFiles).length>0?n=await Xe(o.defaultFeatures??["database","auth"]):n=o.defaultFeatures??[],console.log(""),console.log(p__default.default.bold(`Scaffolding ${p__default.default.cyan(o.name)} template...`)),n.length>0&&console.log(p__default.default.gray(` Features: ${n.join(", ")}`)),console.log("");let r=[...o.files];if(o.featureFiles)for(let c of n){let u=o.featureFiles[c];u&&r.push(...u);}let s=0,i=0;for(let c of r){let u=I__default.default.resolve(c.path),f=I__default.default.dirname(u);if(R__default.default.existsSync(f)||R__default.default.mkdirSync(f,{recursive:true}),c.path==="package.json"&&R__default.default.existsSync(u)&&!e.force)try{let d=JSON.parse(R__default.default.readFileSync(u,"utf-8")),m=JSON.parse(c.content),b=C=>{if(!C)return {};let U={};for(let[$e,$]of Object.entries(C))!$.startsWith("workspace:")&&!$.startsWith("link:")&&!$.startsWith("file:")&&(U[$e]=$);return U};d.dependencies={...b(d.dependencies),...m.dependencies||{}},d.devDependencies={...b(d.devDependencies),...m.devDependencies||{}},m.scripts&&(d.scripts={...d.scripts||{},...m.scripts}),R__default.default.writeFileSync(u,JSON.stringify(d,null,2)+`
3628
- `,"utf-8"),console.log(p__default.default.green(` merge ${c.path} (added dependencies)`)),s++;continue}catch{}if(R__default.default.existsSync(u)&&!e.force){console.log(p__default.default.yellow(` skip ${c.path} (already exists)`)),i++;continue}R__default.default.writeFileSync(u,c.content,"utf-8"),console.log(p__default.default.green(` create ${c.path}`)),s++;}console.log(""),s>0&&console.log(p__default.default.green(`Created ${s} file${s!==1?"s":""}.`)),i>0&&console.log(p__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:{}},l=I__default.default.resolve("package.json");if(R__default.default.existsSync(l)&&n.length>0)try{let c=JSON.parse(R__default.default.readFileSync(l,"utf-8")),u=!1;for(let f of n){let d=a[f];if(d)for(let[m,b]of Object.entries(d))c.dependencies?.[m]||(c.dependencies=c.dependencies||{},c.dependencies[m]=b,u=!0);}u&&R__default.default.writeFileSync(l,JSON.stringify(c,null,2)+`
3629
- `,"utf-8");}catch{}(o.dependencies?.length||o.devDependencies?.length)&&(console.log(""),console.log(p__default.default.bold("Install dependencies:")),o.dependencies?.length&&console.log(p__default.default.cyan(` npm install ${o.dependencies.join(" ")}`)),o.devDependencies?.length&&console.log(p__default.default.cyan(` npm install -D ${o.devDependencies.join(" ")}`))),console.log(""),console.log(p__default.default.bold.green("Project scaffolded successfully!")),console.log(""),console.log(p__default.default.bold(" Next steps:")),o.postInstructions.forEach(c=>{console.log(p__default.default.gray(` ${c}`));}),console.log(""),console.log(p__default.default.gray(" Get your project credentials at https://vaif.studio/app/security/api-keys")),console.log("");}var Ze={$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 le(t){let e=K__default.default("Initializing VAIF configuration...").start(),o=I__default.default.resolve("vaif.config.json");R__default.default.existsSync(o)&&!t.force&&(e.fail("vaif.config.json already exists"),console.log(p__default.default.yellow(`
3630
- Use --force to overwrite existing configuration.`)),process.exit(1));try{if(R__default.default.writeFileSync(o,JSON.stringify(Ze,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 se(t.template,{force:t.force,features:n});}else {let n=I__default.default.resolve(".env.example");if(R__default.default.existsSync(n)||(R__default.default.writeFileSync(n,`# VAIF Configuration
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(`
3671
+ 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)+`
3673
+ `,"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
+ `,"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
+ 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
3631
3676
  DATABASE_URL=postgresql://user:password@localhost:5432/database
3632
3677
  VAIF_API_KEY=your-api-key
3633
- `,"utf-8"),console.log(p__default.default.gray("Created .env.example"))),t.typescript){let r=I__default.default.resolve("src/types");R__default.default.existsSync(r)||(R__default.default.mkdirSync(r,{recursive:!0}),console.log(p__default.default.gray("Created src/types directory")));}console.log(""),console.log(p__default.default.green("VAIF initialized successfully!")),console.log(""),console.log(p__default.default.gray("Next steps:")),console.log(p__default.default.gray(" 1. Update vaif.config.json with your project ID")),console.log(p__default.default.gray(" 2. Set DATABASE_URL in your environment")),console.log(p__default.default.gray(" 3. Run: npx vaif generate")),console.log("");}}catch(n){e.fail("Failed to initialize"),n instanceof Error&&console.error(p__default.default.red(`
3634
- Error: ${n.message}`)),process.exit(1);}}var X=I__default.default.join(et__default.default.homedir(),".vaif"),V=I__default.default.join(X,"auth.json"),M=process.env.VAIF_API_URL||"https://api.vaif.studio";function ot(){R__default.default.existsSync(X)||R__default.default.mkdirSync(X,{recursive:true});}function ue(t){ot(),R__default.default.writeFileSync(V,JSON.stringify(t,null,2),"utf-8"),R__default.default.chmodSync(V,384);}function w(){if(!R__default.default.existsSync(V))return null;try{let t=R__default.default.readFileSync(V,"utf-8");return JSON.parse(t)}catch{return null}}function nt(t){let e=ae__default.default.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(t,n=>{e.close(),o(n);});})}function at(t){return new Promise(e=>{let o=ae__default.default.createInterface({input:process.stdin,output:process.stdout});process.stdin;let r=process.stdout.write.bind(process.stdout),s=false;process.stdout.write=((...i)=>s?true:r(...i)),o.question(t,i=>{s=false,process.stdout.write=r,console.log(""),o.close(),e(i);}),s=true;})}function it(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 rt(t){return new Promise(e=>setTimeout(e,t))}async function st(t){try{let e=await fetch(`${M}/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 lt(t){let e=K__default.default();e.start("Setting up authentication...");let o,n;try{let a=await fetch(`${M}/auth/cli/authorize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})});a.ok||(e.fail("Failed to initiate authentication"),console.log(p__default.default.red(`
3635
- Could not connect to VAIF API. Please try again later.`)),process.exit(1));let l=await a.json();o=l.code,n=l.url;}catch{e.fail("Failed to connect to VAIF API"),console.log(p__default.default.red(`
3636
- Could not connect to VAIF API.`)),console.log(p__default.default.gray("Check your internet connection or try: vaif login --email")),process.exit(1);}e.stop(),console.log(p__default.default.cyan(" Opening browser for authentication...")),console.log(""),console.log(p__default.default.gray(" If the browser doesn't open, visit this URL:")),console.log(p__default.default.white(` ${n}`)),console.log(""),it(n),e.start("Waiting for browser authentication...");let r=12e4,s=2e3,i=Date.now();for(;Date.now()-i<r;){await rt(s);try{let a=await fetch(`${M}/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(p__default.default.red(`
3637
- The authentication session expired. Please try again.`)),process.exit(1));continue}let l=await a.json();if(l.ok&&l.accessToken){let c={token:l.accessToken,email:l.user?.email,projectId:t,expiresAt:new Date(Date.now()+l.expiresIn*1e3).toISOString()};ue(c),e.succeed("Logged in successfully"),console.log(""),l.user?.email&&console.log(p__default.default.green(` Authenticated as: ${l.user.email}`)),console.log(p__default.default.gray(` Config saved to: ${V}`)),console.log("");return}}catch{}}e.fail("Authentication timed out"),console.log(p__default.default.red(`
3638
- Timed out waiting for browser authentication.`)),console.log(p__default.default.gray("Try again or use: vaif login --email")),process.exit(1);}async function ct(t){console.log(""),console.log(p__default.default.bold("VAIF CLI Login")),console.log(p__default.default.gray("Enter your VAIF account credentials")),console.log("");let e=await nt(p__default.default.cyan(" Email: "));(!e||e.trim()==="")&&(console.log(p__default.default.red(`
3639
- No email provided. Login cancelled.`)),process.exit(1));let o=await at(p__default.default.cyan(" Password: "));(!o||o.trim()==="")&&(console.log(p__default.default.red(`
3640
- No password provided. Login cancelled.`)),process.exit(1));let n=K__default.default("Authenticating...").start();try{let r=await fetch(`${M}/auth/cli/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e.trim(),password:o})}),s=await r.json();(!r.ok||!s.ok)&&(n.fail("Login failed"),console.log(p__default.default.red(`
3641
- ${s.message||"Invalid email or password."}`)),process.exit(1));let i={token:s.accessToken,email:s.user?.email,projectId:t,expiresAt:new Date(Date.now()+s.expiresIn*1e3).toISOString()};ue(i),n.succeed("Logged in successfully"),console.log(""),s.user?.email&&console.log(p__default.default.green(` Authenticated as: ${s.user.email}`)),console.log(p__default.default.gray(` Config saved to: ${V}`)),console.log("");}catch{n.fail("Failed to connect to VAIF API"),console.log(p__default.default.red(`
3642
- Could not connect to VAIF API. Please try again later.`)),process.exit(1);}}async function pe(t){console.log(""),console.log(p__default.default.bold("Welcome to VAIF CLI")),console.log(p__default.default.gray("Authenticate to access your VAIF projects")),console.log(""),t.email?await ct(t.projectId):await lt(t.projectId),console.log(p__default.default.gray("You can now use VAIF CLI commands like:")),console.log(p__default.default.gray(" vaif pull - Pull remote schema")),console.log(p__default.default.gray(" vaif push - Push schema changes")),console.log(p__default.default.gray(" vaif generate - Generate TypeScript types")),console.log("");}async function fe(){R__default.default.existsSync(V)?(R__default.default.unlinkSync(V),console.log(p__default.default.green("Logged out successfully"))):console.log(p__default.default.yellow("Not currently logged in"));}async function me(){let t=w();(!t||!t.token)&&(console.log(p__default.default.yellow("Not logged in")),console.log(p__default.default.gray("Run `vaif login` to authenticate")),process.exit(1));let e=K__default.default("Checking authentication...").start(),{valid:o,email:n}=await st(t.token);o||(e.fail("Session expired"),console.log(p__default.default.yellow(`
3643
- Your session has expired. Please login again.`)),process.exit(1)),e.succeed("Authenticated"),console.log(""),console.log(p__default.default.green(` Email: ${n||t.email||"Unknown"}`)),t.projectId&&console.log(p__default.default.green(` Project: ${t.projectId}`)),console.log("");}var ft=process.env.VAIF_API_URL||"https://api.vaif.studio";async function mt(t,e,o="public"){let n=await fetch(`${ft}/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 ge(t){let e=K__default.default(),o=w();(!o||!o.token)&&(console.log(p__default.default.red("Not logged in")),console.log(p__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 A(n);}catch(i){e.fail("Failed to load config"),console.log(p__default.default.red(`
3644
- Error: ${i}`)),process.exit(1);}r||(e.fail("No configuration found"),console.log(p__default.default.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let s=t.projectId||r.projectId||o.projectId;s||(e.fail("No project ID specified"),console.log(p__default.default.yellow(`
3645
- 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 mt(o.token,s,i);e.succeed("Schema fetched successfully");let l=t.output||I__default.default.resolve("vaif.schema.json"),c={$schema:"https://vaif.studio/schemas/schema.json",projectId:s,schema:i,pulledAt:new Date().toISOString(),...a};R__default.default.writeFileSync(l,JSON.stringify(c,null,2),"utf-8"),console.log(""),console.log(p__default.default.green(`Schema saved to: ${l}`)),console.log(""),console.log(p__default.default.gray("Schema summary:")),console.log(p__default.default.gray(` Tables: ${(a.tables||[]).length}`)),console.log(p__default.default.gray(` Enums: ${(a.enums||[]).length}`)),console.log(p__default.default.gray(` Functions: ${(a.functions||[]).length}`)),console.log(""),console.log(p__default.default.gray("Next steps:")),console.log(p__default.default.gray(" - Run `vaif generate` to generate TypeScript types")),console.log(p__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(p__default.default.red(`
3646
- Error: ${i.message}`)),process.exit(1);}}var ye=process.env.VAIF_API_URL||"https://api.vaif.studio";function vt(t){let e=ae__default.default.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(t,n=>{e.close(),o(n);});})}async function bt(t,e,o){let n=await fetch(`${ye}/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 It(t,e,o){let n=await fetch(`${ye}/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 At(t){if(console.log(""),console.log(p__default.default.bold("Schema Changes:")),console.log(""),t.added.length===0&&t.modified.length===0&&t.removed.length===0){console.log(p__default.default.gray(" No changes detected. Schema is up to date."));return}if(t.added.length>0){console.log(p__default.default.green.bold(" + Added:"));for(let e of t.added)console.log(p__default.default.green(` + ${e.type}: ${e.name}`));console.log("");}if(t.modified.length>0){console.log(p__default.default.yellow.bold(" ~ Modified:"));for(let e of t.modified){console.log(p__default.default.yellow(` ~ ${e.type}: ${e.name}`));for(let o of e.changes)console.log(p__default.default.gray(` ${o}`));}console.log("");}if(t.removed.length>0){console.log(p__default.default.red.bold(" - Removed:"));for(let e of t.removed)console.log(p__default.default.red(` - ${e.type}: ${e.name}`));console.log("");}}async function ve(t){let e=K__default.default(),o=w();(!o||!o.token)&&(console.log(p__default.default.red("Not logged in")),console.log(p__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 A(n);}catch(l){e.fail("Failed to load config"),console.log(p__default.default.red(`
3647
- Error: ${l}`)),process.exit(1);}r||(e.fail("No configuration found"),console.log(p__default.default.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let s=t.projectId||r.projectId||o.projectId;s||(e.fail("No project ID specified"),console.log(p__default.default.yellow(`
3648
- Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1));let i=t.schema||I__default.default.resolve("vaif.schema.json");R__default.default.existsSync(i)||(e.fail("No local schema found"),console.log(p__default.default.yellow(`
3649
- Expected schema file at: ${i}`)),console.log(p__default.default.gray("Run `vaif pull` first to fetch the current schema.")),process.exit(1));let a;try{let l=R__default.default.readFileSync(i,"utf-8");a=JSON.parse(l);}catch(l){e.fail("Failed to parse schema file"),l instanceof Error&&console.log(p__default.default.red(`
3650
- Error: ${l.message}`)),process.exit(1);}e.text="Calculating schema changes...";try{let{diff:l,sql:c}=await bt(o.token,s,a);if(e.stop(),At(l),l.added.length===0&&l.modified.length===0&&l.removed.length===0){console.log("");return}if(c.length>0){console.log(p__default.default.bold("SQL Migrations:")),console.log("");for(let f of c)console.log(p__default.default.gray(` ${f}`));console.log("");}if(t.dryRun){console.log(p__default.default.yellow("Dry run mode - no changes applied.")),console.log(p__default.default.gray("Remove --dry-run to apply these changes."));return}if(!t.force){l.removed.length>0&&(console.log(p__default.default.red.bold("\u26A0\uFE0F Warning: This will remove tables/columns from your database.")),console.log(p__default.default.red(" This action cannot be undone!")),console.log(""));let d=await vt(p__default.default.cyan("Apply these changes? [y/N] "));if(d.toLowerCase()!=="y"&&d.toLowerCase()!=="yes"){console.log(p__default.default.yellow(`
3651
- Cancelled. No changes applied.`));return}}e.start("Applying schema changes...");let u=await It(o.token,s,a);if(u.success){if(e.succeed("Schema changes applied successfully"),console.log(""),u.migrations.length>0){console.log(p__default.default.gray("Migrations applied:"));for(let f of u.migrations)console.log(p__default.default.gray(` - ${f}`));console.log("");}console.log(p__default.default.green("Your database schema is now up to date.")),console.log(p__default.default.gray("Run `vaif generate` to update your TypeScript types.")),console.log("");}else e.fail("Failed to apply some changes");}catch(l){e.fail("Failed to push schema changes"),l instanceof Error&&console.log(p__default.default.red(`
3652
- Error: ${l.message}`)),process.exit(1);}}var we=process.env.VAIF_API_URL||"https://api.vaif.studio";async function wt(t,e,o){let n=await fetch(`${we}/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 St(t,e,o){let n=new URL(`${we}/v1/projects/${e}/functions`);o&&n.searchParams.set("envId",o);let r=await fetch(n.toString(),{headers:{Authorization:`Bearer ${t}`}});if(!r.ok){let s=await r.text();throw new Error(`Failed to list functions: ${s}`)}return r.json()}function be(t){switch(I__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 Ie(t){let e=[],o=[".ts",".js",".mjs",".py",".go",".rs"];function n(r){if(!R__default.default.existsSync(r))return;let s=R__default.default.readdirSync(r,{withFileTypes:true});for(let i of s){let a=I__default.default.join(r,i.name);if(i.isDirectory())i.name!=="node_modules"&&!i.name.startsWith(".")&&n(a);else if(i.isFile()){let l=I__default.default.extname(i.name).toLowerCase();o.includes(l)&&(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 Se(t){let e=K__default.default(),o=w();(!o||!o.token)&&(console.log(p__default.default.red("Not logged in")),console.log(p__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await A(n);}catch{}let s=t.projectId||r?.projectId||o.projectId;s||(console.log(p__default.default.red("No project ID specified")),console.log(p__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(p__default.default.bold("VAIF Functions Deploy")),console.log(""),e.start("Scanning for function files...");let i=I__default.default.resolve("functions"),a=I__default.default.resolve("src/functions"),l=[];if(t.entrypoint){let d=I__default.default.resolve(t.entrypoint);R__default.default.existsSync(d)||(e.fail(`File not found: ${t.entrypoint}`),process.exit(1)),l=[d];}else l=[...Ie(i),...Ie(a)];l.length===0&&(e.fail("No function files found"),console.log(p__default.default.yellow(`
3653
- Place your functions in:`)),console.log(p__default.default.gray(" - ./functions/")),console.log(p__default.default.gray(" - ./src/functions/")),console.log(p__default.default.gray(`
3654
- Or specify an entrypoint with --entrypoint`)),process.exit(1)),e.succeed(`Found ${l.length} function(s)`),t.name&&(l=l.filter(d=>I__default.default.basename(d,I__default.default.extname(d)).includes(t.name)),l.length===0&&(console.log(p__default.default.yellow(`
3655
- No functions matching "${t.name}" found`)),process.exit(1))),console.log(""),console.log(p__default.default.gray("Functions to deploy:"));for(let d of l){let m=I__default.default.basename(I__default.default.dirname(d))||I__default.default.basename(d,I__default.default.extname(d)),b=t.runtime||be(d);console.log(p__default.default.gray(` - ${m} (${b})`));}if(console.log(""),t.dryRun){console.log(p__default.default.yellow("Dry run mode - no functions deployed."));return}let c=[];for(let d of l){let m=I__default.default.basename(I__default.default.dirname(d))||I__default.default.basename(d,I__default.default.extname(d)),b=t.runtime||be(d);e.start(`Deploying ${m}...`);try{let C=R__default.default.readFileSync(d,"utf-8"),U=await wt(o.token,s,{name:m,runtime:b,entrypoint:I__default.default.basename(d),code:C,envId:t.envId});e.succeed(`Deployed ${m} (v${U.version})`),c.push({name:m,success:!0,version:U.version});}catch(C){let U=C instanceof Error?C.message:"Unknown error";e.fail(`Failed to deploy ${m}`),c.push({name:m,success:false,error:U});}}console.log("");let u=c.filter(d=>d.success).length;if(c.filter(d=>!d.success).length===0)console.log(p__default.default.green(`\u2713 Successfully deployed ${u} function(s)`));else {console.log(p__default.default.yellow(`Deployed ${u}/${c.length} function(s)`)),console.log(""),console.log(p__default.default.red("Failed deployments:"));for(let d of c.filter(m=>!m.success))console.log(p__default.default.red(` - ${d.name}: ${d.error}`));}console.log("");}async function Ee(t){let e=K__default.default(),o=w();(!o||!o.token)&&(console.log(p__default.default.red("Not logged in")),console.log(p__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await A(n);}catch{}let s=t.projectId||r?.projectId||o.projectId;s||(console.log(p__default.default.red("No project ID specified")),process.exit(1)),e.start("Fetching functions...");try{let i=await St(o.token,s,t.envId);if(e.stop(),i.length===0){console.log(p__default.default.yellow(`
3656
- No functions found`)),console.log(p__default.default.gray("Deploy your first function with: vaif functions deploy"));return}console.log(""),console.log(p__default.default.bold(`Functions (${i.length}):`)),console.log(""),console.log(p__default.default.gray(" "+"NAME".padEnd(25)+"RUNTIME".padEnd(15)+"VERSION".padEnd(10)+"STATUS".padEnd(12)+"LAST DEPLOYED")),console.log(p__default.default.gray(" "+"-".repeat(80)));for(let a of i){let l=a.status==="active"?p__default.default.green:a.status==="deploying"?p__default.default.yellow:p__default.default.red;console.log(" "+a.name.padEnd(25)+a.runtime.padEnd(15)+`v${a.version}`.padEnd(10)+l(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(p__default.default.red(`
3657
- Error: ${i.message}`)),process.exit(1);}}var B=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Et(t,e,o,n,r){let s=await fetch(`${B}/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(!s.ok){let i=await s.text();throw new Error(`Failed to seed ${o}: ${i}`)}return s.json()}async function xt(t,e){let o=await fetch(`${B}/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 Z(t){let e=[];if(!R__default.default.existsSync(t))return e;let o=R__default.default.readdirSync(t,{withFileTypes:true});for(let n of o)if(n.isFile()){let r=I__default.default.extname(n.name).toLowerCase();(r===".json"||r===".ts"||r===".js")&&e.push(I__default.default.join(t,n.name));}return e.sort()}async function xe(t){let e=I__default.default.extname(t).toLowerCase();if(e===".json"){let o=R__default.default.readFileSync(t,"utf-8"),n=JSON.parse(o);return Array.isArray(n)?[{table:I__default.default.basename(t,e),data:n}]:n.table&&n.data?[n]:Object.entries(n).map(([r,s])=>({table:r,data:s}))}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 _e(t){let e=K__default.default(),o=w();(!o||!o.token)&&(console.log(p__default.default.red("Not logged in")),console.log(p__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await A(n);}catch{}let s=t.projectId||r?.projectId||o.projectId;s||(console.log(p__default.default.red("No project ID specified")),console.log(p__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(p__default.default.bold("VAIF Database Seed")),console.log("");let i=[];if(t.file){let u=I__default.default.resolve(t.file);R__default.default.existsSync(u)||(console.log(p__default.default.red(`File not found: ${t.file}`)),process.exit(1)),i=[u];}else {let u=I__default.default.resolve("seeds"),f=I__default.default.resolve("prisma/seed"),d=I__default.default.resolve("db/seeds");i=[...Z(u),...Z(f),...Z(d)];}i.length===0&&(console.log(p__default.default.yellow("No seed files found")),console.log(p__default.default.gray(`
3658
- Place your seed files in one of these directories:`)),console.log(p__default.default.gray(" - ./seeds/")),console.log(p__default.default.gray(" - ./prisma/seed/")),console.log(p__default.default.gray(" - ./db/seeds/")),console.log(p__default.default.gray(`
3659
- Or specify a file with --file`)),console.log(p__default.default.gray(`
3660
- Example seed file (seeds/users.json):`)),console.log(p__default.default.gray(" [")),console.log(p__default.default.gray(' { "name": "John Doe", "email": "john@example.com" },')),console.log(p__default.default.gray(' { "name": "Jane Doe", "email": "jane@example.com" }')),console.log(p__default.default.gray(" ]")),process.exit(1)),console.log(p__default.default.gray("Seed files found:"));for(let u of i)console.log(p__default.default.gray(` - ${I__default.default.relative(process.cwd(),u)}`));if(console.log(""),t.truncate&&(console.log(p__default.default.yellow("\u26A0\uFE0F Tables will be truncated before seeding")),console.log("")),t.dryRun){console.log(p__default.default.yellow("Dry run mode - no data will be inserted.")),console.log("");for(let u of i){e.start(`Loading ${I__default.default.basename(u)}...`);try{let f=await xe(u);e.stop();for(let d of f)t.table&&d.table!==t.table||(console.log(p__default.default.cyan(`Table: ${d.table}`)),console.log(p__default.default.gray(` Records: ${d.data.length}`)),d.data.length>0&&console.log(p__default.default.gray(` Sample: ${JSON.stringify(d.data[0],null,2).slice(0,100)}...`)),console.log(""));}catch(f){e.fail(`Failed to load ${I__default.default.basename(u)}`),f instanceof Error&&console.log(p__default.default.red(` Error: ${f.message}`));}}return}let a=[];for(let u of i){e.start(`Processing ${I__default.default.basename(u)}...`);try{let f=await xe(u);e.stop();for(let d of f)if(!(t.table&&d.table!==t.table)){if(d.data.length===0){console.log(p__default.default.gray(` Skipping ${d.table} (no records)`));continue}e.start(`Seeding ${d.table} (${d.data.length} records)...`);try{let m=await Et(o.token,s,d.table,d.data,{truncate:t.truncate});e.succeed(`Seeded ${d.table}: ${m.inserted} records`),a.push({table:d.table,inserted:m.inserted});}catch(m){let b=m instanceof Error?m.message:"Unknown error";e.fail(`Failed to seed ${d.table}`),a.push({table:d.table,inserted:0,error:b});}}}catch(f){e.fail(`Failed to load ${I__default.default.basename(u)}`),f instanceof Error&&console.log(p__default.default.red(` Error: ${f.message}`));}}console.log("");let l=a.reduce((u,f)=>u+f.inserted,0),c=a.filter(u=>u.error).length;if(c===0)console.log(p__default.default.green(`\u2713 Successfully seeded ${l} records across ${a.length} table(s)`));else {console.log(p__default.default.yellow(`Seeded ${l} records with ${c} error(s)`)),console.log(""),console.log(p__default.default.red("Errors:"));for(let u of a.filter(f=>f.error))console.log(p__default.default.red(` - ${u.table}: ${u.error}`));}console.log("");}async function Te(t){let e=K__default.default(),o=w();(!o||!o.token)&&(console.log(p__default.default.red("Not logged in")),console.log(p__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await A(n);}catch{}let s=t.projectId||r?.projectId||o.projectId;s||(console.log(p__default.default.red("No project ID specified")),console.log(p__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=I__default.default.resolve(t.dir||"./drizzle");if(console.log(""),console.log(p__default.default.bold("VAIF Database Push")),console.log(""),!R__default.default.existsSync(i)){let f=I__default.default.resolve("./migrations");R__default.default.existsSync(f)?console.log(p__default.default.gray(`Using migrations from: ${f}`)):(console.log(p__default.default.red(`Migrations directory not found: ${i}`)),console.log(p__default.default.gray(`
3661
- Expected one of:`)),console.log(p__default.default.gray(" - ./drizzle/")),console.log(p__default.default.gray(" - ./migrations/")),console.log(p__default.default.gray(`
3662
- Or specify with: vaif db push --dir <path>`)),process.exit(1));}let a=[],l=R__default.default.readdirSync(i,{withFileTypes:true});for(let f of l)if(f.isFile()&&f.name.endsWith(".sql"))a.push(I__default.default.join(i,f.name));else if(f.isDirectory()){let d=R__default.default.readdirSync(I__default.default.join(i,f.name),{withFileTypes:true});for(let m of d)m.isFile()&&m.name.endsWith(".sql")&&a.push(I__default.default.join(i,f.name,m.name));}a.sort(),a.length===0&&(console.log(p__default.default.yellow("No SQL migration files found")),process.exit(1)),console.log(p__default.default.gray(`Found ${a.length} migration(s):`));for(let f of a)console.log(p__default.default.gray(` - ${I__default.default.relative(process.cwd(),f)}`));if(console.log(""),t.dryRun){console.log(p__default.default.yellow("Dry run mode - no migrations will be applied.")),console.log("");for(let f of a){let d=R__default.default.readFileSync(f,"utf-8");console.log(p__default.default.cyan(`--- ${I__default.default.basename(f)} ---`)),console.log(p__default.default.gray(d.slice(0,500))),d.length>500&&console.log(p__default.default.gray("...")),console.log("");}return}let c=0,u=0;for(let f of a){let d=R__default.default.readFileSync(f,"utf-8"),m=I__default.default.relative(process.cwd(),f);e.start(`Applying ${m}...`);try{let b=await fetch(`${B}/v1/projects/${s}/schema/execute`,{method:"POST",headers:{Authorization:`Bearer ${o.token}`,"Content-Type":"application/json"},body:JSON.stringify({sql:d})});if(!b.ok){let C=await b.text();throw new Error(C)}e.succeed(`Applied ${m}`),c++;}catch(b){let C=b instanceof Error?b.message:"Unknown error";e.fail(`Failed ${m}: ${C}`),u++;}}console.log(""),console.log(u===0?p__default.default.green(`Successfully applied ${c} migration(s)`):p__default.default.yellow(`Applied ${c}, failed ${u} migration(s)`)),console.log("");}async function Fe(t){let e=K__default.default(),o=w();(!o||!o.token)&&(console.log(p__default.default.red("Not logged in")),console.log(p__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await A(n);}catch{}let s=t.projectId||r?.projectId||o.projectId;s||(console.log(p__default.default.red("No project ID specified")),console.log(p__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=I__default.default.resolve(t.output||"vaif.schema.json");console.log(""),console.log(p__default.default.bold("VAIF Database Pull")),console.log(""),e.start("Pulling schema from remote...");try{let a=await fetch(`${B}/v1/projects/${s}/schema`,{headers:{Authorization:`Bearer ${o.token}`}});if(!a.ok){let u=await a.text();throw new Error(`Failed to pull schema: ${u}`)}let l=await a.json();R__default.default.writeFileSync(i,JSON.stringify(l,null,2),"utf-8"),e.succeed(`Schema written to ${I__default.default.relative(process.cwd(),i)}`);let c=l.tables?.length??Object.keys(l).length;console.log(p__default.default.gray(` ${c} table(s) pulled`)),console.log("");}catch(a){e.fail("Failed to pull schema"),a instanceof Error&&console.log(p__default.default.red(`
3663
- Error: ${a.message}`)),process.exit(1);}}async function Pe(t){let e=K__default.default(),o=w();(!o||!o.token)&&(console.log(p__default.default.red("Not logged in")),console.log(p__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await A(n);}catch{}let s=t.projectId||r?.projectId||o.projectId;s||(console.log(p__default.default.red("No project ID specified")),process.exit(1)),console.log(""),console.log(p__default.default.red.bold("\u26A0\uFE0F DATABASE RESET")),console.log(""),console.log(p__default.default.red("This will:")),console.log(p__default.default.red(" - Drop all tables")),console.log(p__default.default.red(" - Delete all data")),console.log(p__default.default.red(" - Reset migrations")),console.log(""),console.log(p__default.default.red.bold("This action cannot be undone!")),console.log(""),t.force||(console.log(p__default.default.yellow("Use --force to confirm this action.")),process.exit(1)),e.start("Resetting database...");try{await xt(o.token,s),e.succeed("Database reset complete"),console.log(""),console.log(p__default.default.gray("Your database is now empty.")),console.log(p__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(p__default.default.red(`
3664
- Error: ${i.message}`)),process.exit(1);}}var je=process.env.VAIF_API_URL||"https://api.vaif.studio";function Re(t,e,o){return t.projectId||e?.projectId||o.projectId||null}async function Ne(t){let e=K__default.default(),o=w();(!o||!o.token)&&(console.log(p__default.default.red("Not logged in")),console.log(p__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await A(n);}catch{}let s=Re(t,r,o);s||(console.log(p__default.default.red("No project ID specified")),console.log(p__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(p__default.default.bold("VAIF Generate API Key")),console.log(""),e.start("Generating API key...");try{let a=await fetch(`${je}/v1/projects/${s}/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 l=await a.json();e.succeed("API key generated"),console.log(""),console.log(p__default.default.green(` Name: ${l.name}`)),console.log(p__default.default.green(` Key: ${l.key}`)),console.log(""),console.log(p__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(p__default.default.red(`
3665
- Error: ${a.message}`)),process.exit(1);}}async function Le(t){let e=K__default.default(),o=w();(!o||!o.token)&&(console.log(p__default.default.red("Not logged in")),console.log(p__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await A(n);}catch{}let s=Re(t,r,o);s||(console.log(p__default.default.red("No project ID specified")),console.log(p__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(p__default.default.bold("VAIF API Keys")),console.log(""),e.start("Fetching API keys...");try{let i=await fetch(`${je}/v1/projects/${s}/api-keys`,{headers:{Authorization:`Bearer ${o.token}`}});if(!i.ok){let f=await i.text();throw new Error(`Failed to list keys: ${f}`)}let a=await i.json(),l=a.keys||a;if(e.stop(),!Array.isArray(l)||l.length===0){console.log(p__default.default.yellow("No API keys found")),console.log(p__default.default.gray(`
3666
- Generate one with: vaif keys generate`));return}let c=Math.max(8,...l.map(f=>(f.name||"").length)),u=` ${"Name".padEnd(c)} ${"Key".padEnd(24)} Created`;console.log(p__default.default.gray(u)),console.log(p__default.default.gray(" "+"-".repeat(u.length-2)));for(let f of l){let d=(f.name||"unnamed").padEnd(c),m=f.maskedKey||f.prefix||`${(f.key||"").slice(0,12)}...`,b=f.createdAt?new Date(f.createdAt).toLocaleDateString():"N/A";console.log(` ${d} ${m.padEnd(24)} ${b}`);}console.log(""),console.log(p__default.default.gray(` ${l.length} key(s) total`)),console.log("");}catch(i){e.fail("Failed to list API keys"),i instanceof Error&&console.log(p__default.default.red(`
3667
- Error: ${i.message}`)),process.exit(1);}}var De=process.env.VAIF_API_URL||"https://api.vaif.studio";function Tt(t){try{let e=new URL(t);return e.password&&(e.password="****"),e.toString()}catch{return t.replace(/:[^@/]+@/,":****@")}}async function Ve(t){let e=K__default.default(),o=w();(!o||!o.token)&&(console.log(p__default.default.red("Not logged in")),console.log(p__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await A(n);}catch{}let s=t.projectId||r?.projectId||o.projectId;s||(console.log(p__default.default.red("No project ID specified")),console.log(p__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(`${De}/v1/projects/${s}`,{headers:{Authorization:`Bearer ${o.token}`}});if(!i.ok){let u=await i.text();throw new Error(`Failed to fetch project: ${u}`)}let a=await i.json();e.stop(),console.log(""),console.log(p__default.default.bold("VAIF Project Info")),console.log("");let l=16,c=(u,f)=>{console.log(` ${p__default.default.gray(u.padEnd(l))} ${f}`);};c("Name:",p__default.default.white(a.name||"N/A")),c("Project ID:",p__default.default.white(s)),c("Region:",p__default.default.white(a.region||"us-east-1")),c("Plan:",p__default.default.white(a.plan||a.tier||"free")),c("Created:",p__default.default.white(a.createdAt?new Date(a.createdAt).toLocaleDateString():"N/A")),console.log(""),c("API URL:",p__default.default.cyan(a.apiUrl||`${De}/v1`)),c("WS URL:",p__default.default.cyan(a.wsUrl||a.realtimeUrl||"N/A")),c("DB URL:",p__default.default.cyan(a.databaseUrl?Tt(a.databaseUrl):"N/A")),c("Storage URL:",p__default.default.cyan(a.storageUrl||"N/A")),console.log("");}catch(i){e.fail("Failed to fetch project info"),i instanceof Error&&console.log(p__default.default.red(`
3668
- Error: ${i.message}`)),process.exit(1);}}var Pt=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Ue(t){let e=K__default.default(),o=w();(!o||!o.token)&&(console.log(p__default.default.red("Not logged in")),console.log(p__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await A(n);}catch{}let s=t.projectId||r?.projectId||o.projectId;s||(console.log(p__default.default.red("No project ID specified")),console.log(p__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(`${Pt}/v1/projects/${s}?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(p__default.default.bold("VAIF Project Status")),console.log("");let l=22,c=(b,C)=>{console.log(` ${p__default.default.gray(b.padEnd(l))} ${C}`);};c("Project:",p__default.default.white(a.name||s)),c("Plan:",p__default.default.white(a.plan||a.tier||"free")),console.log(""),console.log(p__default.default.gray(" --- Resources ---")),console.log("");let u=a.tableCount??a.tables?.length??"N/A",f=a.functionCount??a.functions?.length??"N/A",d=a.bucketCount??a.storage?.buckets?.length??"N/A",m=a.activeConnections??a.connections??"N/A";c("Tables:",p__default.default.white(String(u))),c("Functions:",p__default.default.white(String(f))),c("Storage Buckets:",p__default.default.white(String(d))),c("Active Connections:",p__default.default.white(String(m))),a.usage&&(console.log(""),console.log(p__default.default.gray(" --- Usage ---")),console.log(""),a.usage.dbSize&&c("Database Size:",p__default.default.white(a.usage.dbSize)),a.usage.storageSize&&c("Storage Size:",p__default.default.white(a.usage.storageSize)),a.usage.bandwidth&&c("Bandwidth:",p__default.default.white(a.usage.bandwidth)),a.usage.functionInvocations!=null&&c("Function Invocations:",p__default.default.white(String(a.usage.functionInvocations)))),console.log("");}catch(i){e.fail("Failed to fetch project status"),i instanceof Error&&console.log(p__default.default.red(`
3669
- Error: ${i.message}`)),process.exit(1);}}commander.program.name("vaif").description("VAIF CLI - Type generation and development tools").version("1.5.1");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(pe);commander.program.command("logout").description("Log out and remove stored credentials").action(fe);commander.program.command("whoami").description("Show current authenticated user").action(me);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(le);commander.program.command("templates").alias("tpl").description("List available project templates").action(re);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(Ve);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(Ue);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(ge);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(ve);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(ne);var ke=commander.program.command("functions").alias("fn").description("Manage serverless functions");ke.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(Se);ke.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(Ee);var q=commander.program.command("db").description("Database management commands");q.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(Te);q.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(Fe);q.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(_e);q.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(Pe);var Oe=commander.program.command("keys").description("Manage API keys");Oe.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(Ne);Oe.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(Le);commander.program.parse(process.argv);process.argv.slice(2).length||commander.program.outputHelp();
3678
+ `,"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(`
3680
+ 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(`
3683
+ 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
+ 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(`
3693
+ 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
+ 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
+ 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
+ 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(`
3698
+ 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
+ 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(`
3701
+ 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(`
3703
+ 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
+ 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(`
3706
+ 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(`
3711
+ 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(`
3714
+ 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();