@vaiftech/cli 1.2.0 → 1.3.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.js CHANGED
@@ -1,31 +1,37 @@
1
1
  #!/usr/bin/env node
2
- import {d,c,b,a}from'./chunk-VD3KS4ZK.js';import {program}from'commander';import k from'fs';import y from'path';import bo from'os';import V from'ora';import r from'chalk';import $o from'readline';var U=y.join(bo.homedir(),".vaif"),N=y.join(U,"auth.json"),So=process.env.VAIF_API_URL||"https://api.vaif.studio";function Ao(){k.existsSync(U)||k.mkdirSync(U,{recursive:true});}function Po(e){Ao(),k.writeFileSync(N,JSON.stringify(e,null,2),"utf-8"),k.chmodSync(N,384);}function w(){if(!k.existsSync(N))return null;try{let e=k.readFileSync(N,"utf-8");return JSON.parse(e)}catch{return null}}function xo(e){let o=$o.createInterface({input:process.stdin,output:process.stdout});return new Promise(n=>{o.question(e,s=>{o.close(),n(s);});})}async function G(e){try{let o=await fetch(`${So}/v1/auth/me`,{headers:{Authorization:`Bearer ${e}`}});return o.ok?{valid:!0,email:(await o.json()).email}:{valid:!1}}catch{return {valid:false}}}async function M(e){let o=V();console.log(""),console.log(r.bold("Welcome to VAIF CLI")),console.log(r.gray("Authenticate to access your VAIF projects")),console.log("");let n=e.token;n||(console.log(r.gray("To get your API token:")),console.log(r.gray(" 1. Go to https://vaif.studio/settings/api-keys")),console.log(r.gray(" 2. Create a new API key or copy an existing one")),console.log(""),n=await xo(r.cyan("Enter your API token: ")),(!n||n.trim()==="")&&(console.log(r.red(`
3
- No token provided. Login cancelled.`)),process.exit(1))),o.start("Validating token...");let{valid:s,email:c}=await G(n.trim());s||(o.fail("Invalid token"),console.log(r.red(`
4
- The provided token is invalid or expired.`)),console.log(r.gray("Please check your token and try again.")),process.exit(1));let f={token:n.trim(),email:c,projectId:e.projectId,expiresAt:new Date(Date.now()+720*60*60*1e3).toISOString()};Po(f),o.succeed("Logged in successfully"),console.log(""),c&&console.log(r.green(` Authenticated as: ${c}`)),console.log(r.gray(` Config saved to: ${N}`)),console.log(""),console.log(r.gray("You can now use VAIF CLI commands like:")),console.log(r.gray(" vaif pull - Pull remote schema")),console.log(r.gray(" vaif push - Push schema changes")),console.log(r.gray(" vaif generate - Generate TypeScript types")),console.log("");}async function W(){k.existsSync(N)?(k.unlinkSync(N),console.log(r.green("Logged out successfully"))):console.log(r.yellow("Not currently logged in"));}async function Y(){let e=w();(!e||!e.token)&&(console.log(r.yellow("Not logged in")),console.log(r.gray("Run `vaif login` to authenticate")),process.exit(1));let o=V("Checking authentication...").start(),{valid:n,email:s}=await G(e.token);n||(o.fail("Session expired"),console.log(r.yellow(`
5
- Your session has expired. Please login again.`)),process.exit(1)),o.succeed("Authenticated"),console.log(""),console.log(r.green(` Email: ${s||e.email||"Unknown"}`)),e.projectId&&console.log(r.green(` Project: ${e.projectId}`)),console.log("");}var Do=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Eo(e,o,n="public"){let s=await fetch(`${Do}/v1/projects/${o}/schema?schema=${n}`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});if(!s.ok){let c=await s.text();throw new Error(`Failed to fetch schema: ${c}`)}return s.json()}async function H(e){let o=V(),n=w();(!n||!n.token)&&(console.log(r.red("Not logged in")),console.log(r.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",c=null;o.start("Loading configuration...");try{c=await a(s);}catch(i){o.fail("Failed to load config"),console.log(r.red(`
6
- Error: ${i}`)),process.exit(1);}c||(o.fail("No configuration found"),console.log(r.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let f=e.projectId||c.projectId||n.projectId;f||(o.fail("No project ID specified"),console.log(r.yellow(`
7
- Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1)),o.text="Fetching remote schema...";try{let i=e.schema||c.database?.schema||"public",t=await Eo(n.token,f,i);o.succeed("Schema fetched successfully");let l=e.output||y.resolve("vaif.schema.json"),d={$schema:"https://vaif.studio/schemas/schema.json",projectId:f,schema:i,pulledAt:new Date().toISOString(),...t};k.writeFileSync(l,JSON.stringify(d,null,2),"utf-8"),console.log(""),console.log(r.green(`Schema saved to: ${l}`)),console.log(""),console.log(r.gray("Schema summary:")),console.log(r.gray(` Tables: ${(t.tables||[]).length}`)),console.log(r.gray(` Enums: ${(t.enums||[]).length}`)),console.log(r.gray(` Functions: ${(t.functions||[]).length}`)),console.log(""),console.log(r.gray("Next steps:")),console.log(r.gray(" - Run `vaif generate` to generate TypeScript types")),console.log(r.gray(" - Edit the schema and run `vaif push` to deploy changes")),console.log("");}catch(i){o.fail("Failed to fetch schema"),i instanceof Error&&console.log(r.red(`
8
- Error: ${i.message}`)),process.exit(1);}}var X=process.env.VAIF_API_URL||"https://api.vaif.studio";function Vo(e){let o=$o.createInterface({input:process.stdin,output:process.stdout});return new Promise(n=>{o.question(e,s=>{o.close(),n(s);});})}async function Lo(e,o,n){let s=await fetch(`${X}/v1/projects/${o}/schema/preview`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({schema:n})});if(!s.ok){let c=await s.text();throw new Error(`Failed to preview changes: ${c}`)}return s.json()}async function To(e,o,n){let s=await fetch(`${X}/v1/projects/${o}/schema/apply`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({schema:n})});if(!s.ok){let c=await s.text();throw new Error(`Failed to apply changes: ${c}`)}return s.json()}function Uo(e){if(console.log(""),console.log(r.bold("Schema Changes:")),console.log(""),e.added.length===0&&e.modified.length===0&&e.removed.length===0){console.log(r.gray(" No changes detected. Schema is up to date."));return}if(e.added.length>0){console.log(r.green.bold(" + Added:"));for(let o of e.added)console.log(r.green(` + ${o.type}: ${o.name}`));console.log("");}if(e.modified.length>0){console.log(r.yellow.bold(" ~ Modified:"));for(let o of e.modified){console.log(r.yellow(` ~ ${o.type}: ${o.name}`));for(let n of o.changes)console.log(r.gray(` ${n}`));}console.log("");}if(e.removed.length>0){console.log(r.red.bold(" - Removed:"));for(let o of e.removed)console.log(r.red(` - ${o.type}: ${o.name}`));console.log("");}}async function Z(e){let o=V(),n=w();(!n||!n.token)&&(console.log(r.red("Not logged in")),console.log(r.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",c=null;o.start("Loading configuration...");try{c=await a(s);}catch(l){o.fail("Failed to load config"),console.log(r.red(`
9
- Error: ${l}`)),process.exit(1);}c||(o.fail("No configuration found"),console.log(r.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let f=e.projectId||c.projectId||n.projectId;f||(o.fail("No project ID specified"),console.log(r.yellow(`
10
- Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1));let i=e.schema||y.resolve("vaif.schema.json");k.existsSync(i)||(o.fail("No local schema found"),console.log(r.yellow(`
11
- Expected schema file at: ${i}`)),console.log(r.gray("Run `vaif pull` first to fetch the current schema.")),process.exit(1));let t;try{let l=k.readFileSync(i,"utf-8");t=JSON.parse(l);}catch(l){o.fail("Failed to parse schema file"),l instanceof Error&&console.log(r.red(`
12
- Error: ${l.message}`)),process.exit(1);}o.text="Calculating schema changes...";try{let{diff:l,sql:d}=await Lo(n.token,f,t);if(o.stop(),Uo(l),l.added.length===0&&l.modified.length===0&&l.removed.length===0){console.log("");return}if(d.length>0){console.log(r.bold("SQL Migrations:")),console.log("");for(let g of d)console.log(r.gray(` ${g}`));console.log("");}if(e.dryRun){console.log(r.yellow("Dry run mode - no changes applied.")),console.log(r.gray("Remove --dry-run to apply these changes."));return}if(!e.force){l.removed.length>0&&(console.log(r.red.bold("\u26A0\uFE0F Warning: This will remove tables/columns from your database.")),console.log(r.red(" This action cannot be undone!")),console.log(""));let a=await Vo(r.cyan("Apply these changes? [y/N] "));if(a.toLowerCase()!=="y"&&a.toLowerCase()!=="yes"){console.log(r.yellow(`
13
- Cancelled. No changes applied.`));return}}o.start("Applying schema changes...");let p=await To(n.token,f,t);if(p.success){if(o.succeed("Schema changes applied successfully"),console.log(""),p.migrations.length>0){console.log(r.gray("Migrations applied:"));for(let g of p.migrations)console.log(r.gray(` - ${g}`));console.log("");}console.log(r.green("Your database schema is now up to date.")),console.log(r.gray("Run `vaif generate` to update your TypeScript types.")),console.log("");}else o.fail("Failed to apply some changes");}catch(l){o.fail("Failed to push schema changes"),l instanceof Error&&console.log(r.red(`
14
- Error: ${l.message}`)),process.exit(1);}}var to=process.env.VAIF_API_URL||"https://api.vaif.studio";async function _o(e,o,n){let s=await fetch(`${to}/v1/projects/${o}/functions`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({name:n.name,runtime:n.runtime,entrypoint:n.entrypoint,code:n.code,envId:n.envId})});if(!s.ok){let c=await s.text();throw new Error(`Failed to deploy function: ${c}`)}return s.json()}async function zo(e,o,n){let s=new URL(`${to}/v1/projects/${o}/functions`);n&&s.searchParams.set("envId",n);let c=await fetch(s.toString(),{headers:{Authorization:`Bearer ${e}`}});if(!c.ok){let f=await c.text();throw new Error(`Failed to list functions: ${f}`)}return c.json()}function oo(e){switch(y.extname(e).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 eo(e){let o=[],n=[".ts",".js",".mjs",".py",".go",".rs"];function s(c){if(!k.existsSync(c))return;let f=k.readdirSync(c,{withFileTypes:true});for(let i of f){let t=y.join(c,i.name);if(i.isDirectory())i.name!=="node_modules"&&!i.name.startsWith(".")&&s(t);else if(i.isFile()){let l=y.extname(i.name).toLowerCase();n.includes(l)&&(i.name==="index.ts"||i.name==="index.js"||i.name.includes("function")||i.name.includes("handler"))&&o.push(t);}}}return s(e),o}async function io(e){let o=V(),n=w();(!n||!n.token)&&(console.log(r.red("Not logged in")),console.log(r.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",c=null;try{c=await a(s);}catch{}let f=e.projectId||c?.projectId||n.projectId;f||(console.log(r.red("No project ID specified")),console.log(r.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(r.bold("VAIF Functions Deploy")),console.log(""),o.start("Scanning for function files...");let i=y.resolve("functions"),t=y.resolve("src/functions"),l=[];if(e.entrypoint){let a=y.resolve(e.entrypoint);k.existsSync(a)||(o.fail(`File not found: ${e.entrypoint}`),process.exit(1)),l=[a];}else l=[...eo(i),...eo(t)];l.length===0&&(o.fail("No function files found"),console.log(r.yellow(`
15
- Place your functions in:`)),console.log(r.gray(" - ./functions/")),console.log(r.gray(" - ./src/functions/")),console.log(r.gray(`
16
- Or specify an entrypoint with --entrypoint`)),process.exit(1)),o.succeed(`Found ${l.length} function(s)`),e.name&&(l=l.filter(a=>y.basename(a,y.extname(a)).includes(e.name)),l.length===0&&(console.log(r.yellow(`
17
- No functions matching "${e.name}" found`)),process.exit(1))),console.log(""),console.log(r.gray("Functions to deploy:"));for(let a of l){let h=y.basename(y.dirname(a))||y.basename(a,y.extname(a)),$=e.runtime||oo(a);console.log(r.gray(` - ${h} (${$})`));}if(console.log(""),e.dryRun){console.log(r.yellow("Dry run mode - no functions deployed."));return}let d=[];for(let a of l){let h=y.basename(y.dirname(a))||y.basename(a,y.extname(a)),$=e.runtime||oo(a);o.start(`Deploying ${h}...`);try{let F=k.readFileSync(a,"utf-8"),R=await _o(n.token,f,{name:h,runtime:$,entrypoint:y.basename(a),code:F,envId:e.envId});o.succeed(`Deployed ${h} (v${R.version})`),d.push({name:h,success:!0,version:R.version});}catch(F){let R=F instanceof Error?F.message:"Unknown error";o.fail(`Failed to deploy ${h}`),d.push({name:h,success:false,error:R});}}console.log("");let p=d.filter(a=>a.success).length;if(d.filter(a=>!a.success).length===0)console.log(r.green(`\u2713 Successfully deployed ${p} function(s)`));else {console.log(r.yellow(`Deployed ${p}/${d.length} function(s)`)),console.log(""),console.log(r.red("Failed deployments:"));for(let a of d.filter(h=>!h.success))console.log(r.red(` - ${a.name}: ${a.error}`));}console.log("");}async function so(e){let o=V(),n=w();(!n||!n.token)&&(console.log(r.red("Not logged in")),console.log(r.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",c=null;try{c=await a(s);}catch{}let f=e.projectId||c?.projectId||n.projectId;f||(console.log(r.red("No project ID specified")),process.exit(1)),o.start("Fetching functions...");try{let i=await zo(n.token,f,e.envId);if(o.stop(),i.length===0){console.log(r.yellow(`
18
- No functions found`)),console.log(r.gray("Deploy your first function with: vaif functions deploy"));return}console.log(""),console.log(r.bold(`Functions (${i.length}):`)),console.log(""),console.log(r.gray(" "+"NAME".padEnd(25)+"RUNTIME".padEnd(15)+"VERSION".padEnd(10)+"STATUS".padEnd(12)+"LAST DEPLOYED")),console.log(r.gray(" "+"-".repeat(80)));for(let t of i){let l=t.status==="active"?r.green:t.status==="deploying"?r.yellow:r.red;console.log(" "+t.name.padEnd(25)+t.runtime.padEnd(15)+`v${t.version}`.padEnd(10)+l(t.status.padEnd(12))+(t.lastDeployed?new Date(t.lastDeployed).toLocaleDateString():"-"));}console.log("");}catch(i){o.fail("Failed to fetch functions"),i instanceof Error&&console.log(r.red(`
19
- Error: ${i.message}`)),process.exit(1);}}var L=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Bo(e,o,n,s,c){let f=await fetch(`${L}/v1/projects/${o}/db/seed`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({table:n,records:s,truncate:c?.truncate??false})});if(!f.ok){let i=await f.text();throw new Error(`Failed to seed ${n}: ${i}`)}return f.json()}async function Jo(e,o){let n=await fetch(`${L}/v1/projects/${o}/db/reset`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});if(!n.ok){let s=await n.text();throw new Error(`Failed to reset database: ${s}`)}return n.json()}function _(e){let o=[];if(!k.existsSync(e))return o;let n=k.readdirSync(e,{withFileTypes:true});for(let s of n)if(s.isFile()){let c=y.extname(s.name).toLowerCase();(c===".json"||c===".ts"||c===".js")&&o.push(y.join(e,s.name));}return o.sort()}async function ro(e){let o=y.extname(e).toLowerCase();if(o===".json"){let n=k.readFileSync(e,"utf-8"),s=JSON.parse(n);return Array.isArray(s)?[{table:y.basename(e,o),data:s}]:s.table&&s.data?[s]:Object.entries(s).map(([c,f])=>({table:c,data:f}))}else if(o===".ts"||o===".js"){let n=await import(e),s=n.default||n;return typeof s=="function"?s():s}throw new Error(`Unsupported file format: ${o}`)}async function co(e){let o=V(),n=w();(!n||!n.token)&&(console.log(r.red("Not logged in")),console.log(r.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",c=null;try{c=await a(s);}catch{}let f=e.projectId||c?.projectId||n.projectId;f||(console.log(r.red("No project ID specified")),console.log(r.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(r.bold("VAIF Database Seed")),console.log("");let i=[];if(e.file){let p=y.resolve(e.file);k.existsSync(p)||(console.log(r.red(`File not found: ${e.file}`)),process.exit(1)),i=[p];}else {let p=y.resolve("seeds"),g=y.resolve("prisma/seed"),a=y.resolve("db/seeds");i=[..._(p),..._(g),..._(a)];}i.length===0&&(console.log(r.yellow("No seed files found")),console.log(r.gray(`
20
- Place your seed files in one of these directories:`)),console.log(r.gray(" - ./seeds/")),console.log(r.gray(" - ./prisma/seed/")),console.log(r.gray(" - ./db/seeds/")),console.log(r.gray(`
21
- Or specify a file with --file`)),console.log(r.gray(`
22
- Example seed file (seeds/users.json):`)),console.log(r.gray(" [")),console.log(r.gray(' { "name": "John Doe", "email": "john@example.com" },')),console.log(r.gray(' { "name": "Jane Doe", "email": "jane@example.com" }')),console.log(r.gray(" ]")),process.exit(1)),console.log(r.gray("Seed files found:"));for(let p of i)console.log(r.gray(` - ${y.relative(process.cwd(),p)}`));if(console.log(""),e.truncate&&(console.log(r.yellow("\u26A0\uFE0F Tables will be truncated before seeding")),console.log("")),e.dryRun){console.log(r.yellow("Dry run mode - no data will be inserted.")),console.log("");for(let p of i){o.start(`Loading ${y.basename(p)}...`);try{let g=await ro(p);o.stop();for(let a of g)e.table&&a.table!==e.table||(console.log(r.cyan(`Table: ${a.table}`)),console.log(r.gray(` Records: ${a.data.length}`)),a.data.length>0&&console.log(r.gray(` Sample: ${JSON.stringify(a.data[0],null,2).slice(0,100)}...`)),console.log(""));}catch(g){o.fail(`Failed to load ${y.basename(p)}`),g instanceof Error&&console.log(r.red(` Error: ${g.message}`));}}return}let t=[];for(let p of i){o.start(`Processing ${y.basename(p)}...`);try{let g=await ro(p);o.stop();for(let a of g)if(!(e.table&&a.table!==e.table)){if(a.data.length===0){console.log(r.gray(` Skipping ${a.table} (no records)`));continue}o.start(`Seeding ${a.table} (${a.data.length} records)...`);try{let h=await Bo(n.token,f,a.table,a.data,{truncate:e.truncate});o.succeed(`Seeded ${a.table}: ${h.inserted} records`),t.push({table:a.table,inserted:h.inserted});}catch(h){let $=h instanceof Error?h.message:"Unknown error";o.fail(`Failed to seed ${a.table}`),t.push({table:a.table,inserted:0,error:$});}}}catch(g){o.fail(`Failed to load ${y.basename(p)}`),g instanceof Error&&console.log(r.red(` Error: ${g.message}`));}}console.log("");let l=t.reduce((p,g)=>p+g.inserted,0),d=t.filter(p=>p.error).length;if(d===0)console.log(r.green(`\u2713 Successfully seeded ${l} records across ${t.length} table(s)`));else {console.log(r.yellow(`Seeded ${l} records with ${d} error(s)`)),console.log(""),console.log(r.red("Errors:"));for(let p of t.filter(g=>g.error))console.log(r.red(` - ${p.table}: ${p.error}`));}console.log("");}async function ao(e){let o=V(),n=w();(!n||!n.token)&&(console.log(r.red("Not logged in")),console.log(r.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",c=null;try{c=await a(s);}catch{}let f=e.projectId||c?.projectId||n.projectId;f||(console.log(r.red("No project ID specified")),console.log(r.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=y.resolve(e.dir||"./drizzle");if(console.log(""),console.log(r.bold("VAIF Database Push")),console.log(""),!k.existsSync(i)){let g=y.resolve("./migrations");k.existsSync(g)?console.log(r.gray(`Using migrations from: ${g}`)):(console.log(r.red(`Migrations directory not found: ${i}`)),console.log(r.gray(`
23
- Expected one of:`)),console.log(r.gray(" - ./drizzle/")),console.log(r.gray(" - ./migrations/")),console.log(r.gray(`
24
- Or specify with: vaif db push --dir <path>`)),process.exit(1));}let t=[],l=k.readdirSync(i,{withFileTypes:true});for(let g of l)if(g.isFile()&&g.name.endsWith(".sql"))t.push(y.join(i,g.name));else if(g.isDirectory()){let a=k.readdirSync(y.join(i,g.name),{withFileTypes:true});for(let h of a)h.isFile()&&h.name.endsWith(".sql")&&t.push(y.join(i,g.name,h.name));}t.sort(),t.length===0&&(console.log(r.yellow("No SQL migration files found")),process.exit(1)),console.log(r.gray(`Found ${t.length} migration(s):`));for(let g of t)console.log(r.gray(` - ${y.relative(process.cwd(),g)}`));if(console.log(""),e.dryRun){console.log(r.yellow("Dry run mode - no migrations will be applied.")),console.log("");for(let g of t){let a=k.readFileSync(g,"utf-8");console.log(r.cyan(`--- ${y.basename(g)} ---`)),console.log(r.gray(a.slice(0,500))),a.length>500&&console.log(r.gray("...")),console.log("");}return}let d=0,p=0;for(let g of t){let a=k.readFileSync(g,"utf-8"),h=y.relative(process.cwd(),g);o.start(`Applying ${h}...`);try{let $=await fetch(`${L}/v1/projects/${f}/schema/execute`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify({sql:a})});if(!$.ok){let F=await $.text();throw new Error(F)}o.succeed(`Applied ${h}`),d++;}catch($){let F=$ instanceof Error?$.message:"Unknown error";o.fail(`Failed ${h}: ${F}`),p++;}}console.log(""),console.log(p===0?r.green(`Successfully applied ${d} migration(s)`):r.yellow(`Applied ${d}, failed ${p} migration(s)`)),console.log("");}async function lo(e){let o=V(),n=w();(!n||!n.token)&&(console.log(r.red("Not logged in")),console.log(r.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",c=null;try{c=await a(s);}catch{}let f=e.projectId||c?.projectId||n.projectId;f||(console.log(r.red("No project ID specified")),console.log(r.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=y.resolve(e.output||"vaif.schema.json");console.log(""),console.log(r.bold("VAIF Database Pull")),console.log(""),o.start("Pulling schema from remote...");try{let t=await fetch(`${L}/v1/projects/${f}/schema`,{headers:{Authorization:`Bearer ${n.token}`}});if(!t.ok){let p=await t.text();throw new Error(`Failed to pull schema: ${p}`)}let l=await t.json();k.writeFileSync(i,JSON.stringify(l,null,2),"utf-8"),o.succeed(`Schema written to ${y.relative(process.cwd(),i)}`);let d=l.tables?.length??Object.keys(l).length;console.log(r.gray(` ${d} table(s) pulled`)),console.log("");}catch(t){o.fail("Failed to pull schema"),t instanceof Error&&console.log(r.red(`
25
- Error: ${t.message}`)),process.exit(1);}}async function go(e){let o=V(),n=w();(!n||!n.token)&&(console.log(r.red("Not logged in")),console.log(r.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",c=null;try{c=await a(s);}catch{}let f=e.projectId||c?.projectId||n.projectId;f||(console.log(r.red("No project ID specified")),process.exit(1)),console.log(""),console.log(r.red.bold("\u26A0\uFE0F DATABASE RESET")),console.log(""),console.log(r.red("This will:")),console.log(r.red(" - Drop all tables")),console.log(r.red(" - Delete all data")),console.log(r.red(" - Reset migrations")),console.log(""),console.log(r.red.bold("This action cannot be undone!")),console.log(""),e.force||(console.log(r.yellow("Use --force to confirm this action.")),process.exit(1)),o.start("Resetting database...");try{await Jo(n.token,f),o.succeed("Database reset complete"),console.log(""),console.log(r.gray("Your database is now empty.")),console.log(r.gray("Run `vaif push` to apply your schema, then `vaif db seed` to seed data.")),console.log("");}catch(i){o.fail("Failed to reset database"),i instanceof Error&&console.log(r.red(`
26
- Error: ${i.message}`)),process.exit(1);}}var po=process.env.VAIF_API_URL||"https://api.vaif.studio";function uo(e,o,n){return e.projectId||o?.projectId||n.projectId||null}async function mo(e){let o=V(),n=w();(!n||!n.token)&&(console.log(r.red("Not logged in")),console.log(r.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",c=null;try{c=await a(s);}catch{}let f=uo(e,c,n);f||(console.log(r.red("No project ID specified")),console.log(r.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=e.name||`cli-key-${Date.now()}`;console.log(""),console.log(r.bold("VAIF Generate API Key")),console.log(""),o.start("Generating API key...");try{let t=await fetch(`${po}/v1/projects/${f}/api-keys`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:i})});if(!t.ok){let d=await t.text();throw new Error(`Failed to generate key: ${d}`)}let l=await t.json();o.succeed("API key generated"),console.log(""),console.log(r.green(` Name: ${l.name}`)),console.log(r.green(` Key: ${l.key}`)),console.log(""),console.log(r.yellow.bold(" Save this key now - it will not be shown again!")),console.log("");}catch(t){o.fail("Failed to generate API key"),t instanceof Error&&console.log(r.red(`
27
- Error: ${t.message}`)),process.exit(1);}}async function ho(e){let o=V(),n=w();(!n||!n.token)&&(console.log(r.red("Not logged in")),console.log(r.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",c=null;try{c=await a(s);}catch{}let f=uo(e,c,n);f||(console.log(r.red("No project ID specified")),console.log(r.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(r.bold("VAIF API Keys")),console.log(""),o.start("Fetching API keys...");try{let i=await fetch(`${po}/v1/projects/${f}/api-keys`,{headers:{Authorization:`Bearer ${n.token}`}});if(!i.ok){let g=await i.text();throw new Error(`Failed to list keys: ${g}`)}let t=await i.json(),l=t.keys||t;if(o.stop(),!Array.isArray(l)||l.length===0){console.log(r.yellow("No API keys found")),console.log(r.gray(`
28
- Generate one with: vaif keys generate`));return}let d=Math.max(8,...l.map(g=>(g.name||"").length)),p=` ${"Name".padEnd(d)} ${"Key".padEnd(24)} Created`;console.log(r.gray(p)),console.log(r.gray(" "+"-".repeat(p.length-2)));for(let g of l){let a=(g.name||"unnamed").padEnd(d),h=g.maskedKey||g.prefix||`${(g.key||"").slice(0,12)}...`,$=g.createdAt?new Date(g.createdAt).toLocaleDateString():"N/A";console.log(` ${a} ${h.padEnd(24)} ${$}`);}console.log(""),console.log(r.gray(` ${l.length} key(s) total`)),console.log("");}catch(i){o.fail("Failed to list API keys"),i instanceof Error&&console.log(r.red(`
29
- Error: ${i.message}`)),process.exit(1);}}var yo=process.env.VAIF_API_URL||"https://api.vaif.studio";function qo(e){try{let o=new URL(e);return o.password&&(o.password="****"),o.toString()}catch{return e.replace(/:[^@/]+@/,":****@")}}async function jo(e){let o=V(),n=w();(!n||!n.token)&&(console.log(r.red("Not logged in")),console.log(r.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",c=null;try{c=await a(s);}catch{}let f=e.projectId||c?.projectId||n.projectId;f||(console.log(r.red("No project ID specified")),console.log(r.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),o.start("Fetching project info...");try{let i=await fetch(`${yo}/v1/projects/${f}`,{headers:{Authorization:`Bearer ${n.token}`}});if(!i.ok){let p=await i.text();throw new Error(`Failed to fetch project: ${p}`)}let t=await i.json();o.stop(),console.log(""),console.log(r.bold("VAIF Project Info")),console.log("");let l=16,d=(p,g)=>{console.log(` ${r.gray(p.padEnd(l))} ${g}`);};d("Name:",r.white(t.name||"N/A")),d("Project ID:",r.white(f)),d("Region:",r.white(t.region||"us-east-1")),d("Plan:",r.white(t.plan||t.tier||"free")),d("Created:",r.white(t.createdAt?new Date(t.createdAt).toLocaleDateString():"N/A")),console.log(""),d("API URL:",r.cyan(t.apiUrl||`${yo}/v1`)),d("WS URL:",r.cyan(t.wsUrl||t.realtimeUrl||"N/A")),d("DB URL:",r.cyan(t.databaseUrl?qo(t.databaseUrl):"N/A")),d("Storage URL:",r.cyan(t.storageUrl||"N/A")),console.log("");}catch(i){o.fail("Failed to fetch project info"),i instanceof Error&&console.log(r.red(`
30
- Error: ${i.message}`)),process.exit(1);}}var Mo=process.env.VAIF_API_URL||"https://api.vaif.studio";async function wo(e){let o=V(),n=w();(!n||!n.token)&&(console.log(r.red("Not logged in")),console.log(r.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",c=null;try{c=await a(s);}catch{}let f=e.projectId||c?.projectId||n.projectId;f||(console.log(r.red("No project ID specified")),console.log(r.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),o.start("Fetching project status...");try{let i=await fetch(`${Mo}/v1/projects/${f}?include=tables,functions,storage,connections`,{headers:{Authorization:`Bearer ${n.token}`}});if(!i.ok){let $=await i.text();throw new Error(`Failed to fetch project status: ${$}`)}let t=await i.json();o.stop(),console.log(""),console.log(r.bold("VAIF Project Status")),console.log("");let l=22,d=($,F)=>{console.log(` ${r.gray($.padEnd(l))} ${F}`);};d("Project:",r.white(t.name||f)),d("Plan:",r.white(t.plan||t.tier||"free")),console.log(""),console.log(r.gray(" --- Resources ---")),console.log("");let p=t.tableCount??t.tables?.length??"N/A",g=t.functionCount??t.functions?.length??"N/A",a=t.bucketCount??t.storage?.buckets?.length??"N/A",h=t.activeConnections??t.connections??"N/A";d("Tables:",r.white(String(p))),d("Functions:",r.white(String(g))),d("Storage Buckets:",r.white(String(a))),d("Active Connections:",r.white(String(h))),t.usage&&(console.log(""),console.log(r.gray(" --- Usage ---")),console.log(""),t.usage.dbSize&&d("Database Size:",r.white(t.usage.dbSize)),t.usage.storageSize&&d("Storage Size:",r.white(t.usage.storageSize)),t.usage.bandwidth&&d("Bandwidth:",r.white(t.usage.bandwidth)),t.usage.functionInvocations!=null&&d("Function Invocations:",r.white(String(t.usage.functionInvocations)))),console.log("");}catch(i){o.fail("Failed to fetch project status"),i instanceof Error&&console.log(r.red(`
31
- Error: ${i.message}`)),process.exit(1);}}program.name("vaif").description("VAIF CLI - Type generation and development tools").version("1.2.0");program.command("login").description("Authenticate with VAIF").option("-t, --token <token>","API token (will prompt if not provided)").option("-p, --project-id <id>","Default project ID").action(M);program.command("logout").description("Log out and remove stored credentials").action(W);program.command("whoami").description("Show current authenticated user").action(Y);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)").action(d);program.command("templates").alias("tpl").description("List available project templates").action(c);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(jo);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(wo);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(H);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(Z);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(b);var vo=program.command("functions").alias("fn").description("Manage serverless functions");vo.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(io);vo.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(so);var T=program.command("db").description("Database management commands");T.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(ao);T.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(lo);T.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(co);T.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(go);var Io=program.command("keys").description("Manage API keys");Io.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(mo);Io.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(ho);program.parse(process.argv);process.argv.slice(2).length||program.outputHelp();
2
+ import {d,c,b,a}from'./chunk-7XA2HKEQ.js';import {program}from'commander';import F from'fs';import w from'path';import So from'os';import {exec}from'child_process';import V from'ora';import c$1 from'chalk';import q from'readline';var _=w.join(So.homedir(),".vaif"),D=w.join(_,"auth.json"),O=process.env.VAIF_API_URL||"https://api.vaif.studio";function Po(){F.existsSync(_)||F.mkdirSync(_,{recursive:true});}function G(e){Po(),F.writeFileSync(D,JSON.stringify(e,null,2),"utf-8"),F.chmodSync(D,384);}function j(){if(!F.existsSync(D))return null;try{let e=F.readFileSync(D,"utf-8");return JSON.parse(e)}catch{return null}}function xo(e){let o=q.createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{o.question(e,i=>{o.close(),t(i);});})}function Fo(e){return new Promise(o=>{let t=q.createInterface({input:process.stdin,output:process.stdout});process.stdin;let r=process.stdout.write.bind(process.stdout),l=false;process.stdout.write=((...s)=>l?true:r(...s)),t.question(e,s=>{l=false,process.stdout.write=r,console.log(""),t.close(),o(s);}),l=true;})}function ko(e){let o=process.platform,t;o==="darwin"?t=`open "${e}"`:o==="win32"?t=`start "" "${e}"`:t=`xdg-open "${e}"`,exec(t,i=>{});}function Co(e){return new Promise(o=>setTimeout(o,e))}async function Do(e){try{let o=await fetch(`${O}/auth/me`,{headers:{Authorization:`Bearer ${e}`}});if(o.ok){let t=await o.json();return {valid:!0,email:t.user?.email||t.email}}return {valid:!1}}catch{return {valid:false}}}async function Eo(e){let o=V();o.start("Setting up authentication...");let t,i;try{let n=await fetch(`${O}/auth/cli/authorize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})});n.ok||(o.fail("Failed to initiate authentication"),console.log(c$1.red(`
3
+ Could not connect to VAIF API. Please try again later.`)),process.exit(1));let a=await n.json();t=a.code,i=a.url;}catch{o.fail("Failed to connect to VAIF API"),console.log(c$1.red(`
4
+ Could not connect to VAIF API.`)),console.log(c$1.gray("Check your internet connection or try: vaif login --email")),process.exit(1);}o.stop(),console.log(c$1.cyan(" Opening browser for authentication...")),console.log(""),console.log(c$1.gray(" If the browser doesn't open, visit this URL:")),console.log(c$1.white(` ${i}`)),console.log(""),ko(i),o.start("Waiting for browser authentication...");let r=12e4,l=2e3,s=Date.now();for(;Date.now()-s<r;){await Co(l);try{let n=await fetch(`${O}/auth/cli/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!n.ok){let d=await n.json();(d.error==="ExpiredCode"||d.error==="InvalidCode")&&(o.fail("Authentication expired"),console.log(c$1.red(`
5
+ The authentication session expired. Please try again.`)),process.exit(1));continue}let a=await n.json();if(a.ok&&a.accessToken){let d={token:a.accessToken,email:a.user?.email,projectId:e,expiresAt:new Date(Date.now()+a.expiresIn*1e3).toISOString()};G(d),o.succeed("Logged in successfully"),console.log(""),a.user?.email&&console.log(c$1.green(` Authenticated as: ${a.user.email}`)),console.log(c$1.gray(` Config saved to: ${D}`)),console.log("");return}}catch{}}o.fail("Authentication timed out"),console.log(c$1.red(`
6
+ Timed out waiting for browser authentication.`)),console.log(c$1.gray("Try again or use: vaif login --email")),process.exit(1);}async function No(e){console.log(""),console.log(c$1.bold("VAIF CLI Login")),console.log(c$1.gray("Enter your VAIF account credentials")),console.log("");let o=await xo(c$1.cyan(" Email: "));(!o||o.trim()==="")&&(console.log(c$1.red(`
7
+ No email provided. Login cancelled.`)),process.exit(1));let t=await Fo(c$1.cyan(" Password: "));(!t||t.trim()==="")&&(console.log(c$1.red(`
8
+ No password provided. Login cancelled.`)),process.exit(1));let i=V("Authenticating...").start();try{let r=await fetch(`${O}/auth/cli/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:o.trim(),password:t})}),l=await r.json();(!r.ok||!l.ok)&&(i.fail("Login failed"),console.log(c$1.red(`
9
+ ${l.message||"Invalid email or password."}`)),process.exit(1));let s={token:l.accessToken,email:l.user?.email,projectId:e,expiresAt:new Date(Date.now()+l.expiresIn*1e3).toISOString()};G(s),i.succeed("Logged in successfully"),console.log(""),l.user?.email&&console.log(c$1.green(` Authenticated as: ${l.user.email}`)),console.log(c$1.gray(` Config saved to: ${D}`)),console.log("");}catch{i.fail("Failed to connect to VAIF API"),console.log(c$1.red(`
10
+ Could not connect to VAIF API. Please try again later.`)),process.exit(1);}}async function Y(e){console.log(""),console.log(c$1.bold("Welcome to VAIF CLI")),console.log(c$1.gray("Authenticate to access your VAIF projects")),console.log(""),e.email?await No(e.projectId):await Eo(e.projectId),console.log(c$1.gray("You can now use VAIF CLI commands like:")),console.log(c$1.gray(" vaif pull - Pull remote schema")),console.log(c$1.gray(" vaif push - Push schema changes")),console.log(c$1.gray(" vaif generate - Generate TypeScript types")),console.log("");}async function H(){F.existsSync(D)?(F.unlinkSync(D),console.log(c$1.green("Logged out successfully"))):console.log(c$1.yellow("Not currently logged in"));}async function Q(){let e=j();(!e||!e.token)&&(console.log(c$1.yellow("Not logged in")),console.log(c$1.gray("Run `vaif login` to authenticate")),process.exit(1));let o=V("Checking authentication...").start(),{valid:t,email:i}=await Do(e.token);t||(o.fail("Session expired"),console.log(c$1.yellow(`
11
+ Your session has expired. Please login again.`)),process.exit(1)),o.succeed("Authenticated"),console.log(""),console.log(c$1.green(` Email: ${i||e.email||"Unknown"}`)),e.projectId&&console.log(c$1.green(` Project: ${e.projectId}`)),console.log("");}var Vo=process.env.VAIF_API_URL||"https://api.vaif.studio";async function To(e,o,t="public"){let i=await fetch(`${Vo}/v1/projects/${o}/schema?schema=${t}`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});if(!i.ok){let r=await i.text();throw new Error(`Failed to fetch schema: ${r}`)}return i.json()}async function X(e){let o=V(),t=j();(!t||!t.token)&&(console.log(c$1.red("Not logged in")),console.log(c$1.gray("Run `vaif login` first to authenticate")),process.exit(1));let i=e.config||"vaif.config.json",r=null;o.start("Loading configuration...");try{r=await a(i);}catch(s){o.fail("Failed to load config"),console.log(c$1.red(`
12
+ Error: ${s}`)),process.exit(1);}r||(o.fail("No configuration found"),console.log(c$1.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let l=e.projectId||r.projectId||t.projectId;l||(o.fail("No project ID specified"),console.log(c$1.yellow(`
13
+ Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1)),o.text="Fetching remote schema...";try{let s=e.schema||r.database?.schema||"public",n=await To(t.token,l,s);o.succeed("Schema fetched successfully");let a=e.output||w.resolve("vaif.schema.json"),d={$schema:"https://vaif.studio/schemas/schema.json",projectId:l,schema:s,pulledAt:new Date().toISOString(),...n};F.writeFileSync(a,JSON.stringify(d,null,2),"utf-8"),console.log(""),console.log(c$1.green(`Schema saved to: ${a}`)),console.log(""),console.log(c$1.gray("Schema summary:")),console.log(c$1.gray(` Tables: ${(n.tables||[]).length}`)),console.log(c$1.gray(` Enums: ${(n.enums||[]).length}`)),console.log(c$1.gray(` Functions: ${(n.functions||[]).length}`)),console.log(""),console.log(c$1.gray("Next steps:")),console.log(c$1.gray(" - Run `vaif generate` to generate TypeScript types")),console.log(c$1.gray(" - Edit the schema and run `vaif push` to deploy changes")),console.log("");}catch(s){o.fail("Failed to fetch schema"),s instanceof Error&&console.log(c$1.red(`
14
+ Error: ${s.message}`)),process.exit(1);}}var oo=process.env.VAIF_API_URL||"https://api.vaif.studio";function Bo(e){let o=q.createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{o.question(e,i=>{o.close(),t(i);});})}async function Jo(e,o,t){let i=await fetch(`${oo}/v1/projects/${o}/schema/preview`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({schema:t})});if(!i.ok){let r=await i.text();throw new Error(`Failed to preview changes: ${r}`)}return i.json()}async function Ko(e,o,t){let i=await fetch(`${oo}/v1/projects/${o}/schema/apply`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({schema:t})});if(!i.ok){let r=await i.text();throw new Error(`Failed to apply changes: ${r}`)}return i.json()}function Mo(e){if(console.log(""),console.log(c$1.bold("Schema Changes:")),console.log(""),e.added.length===0&&e.modified.length===0&&e.removed.length===0){console.log(c$1.gray(" No changes detected. Schema is up to date."));return}if(e.added.length>0){console.log(c$1.green.bold(" + Added:"));for(let o of e.added)console.log(c$1.green(` + ${o.type}: ${o.name}`));console.log("");}if(e.modified.length>0){console.log(c$1.yellow.bold(" ~ Modified:"));for(let o of e.modified){console.log(c$1.yellow(` ~ ${o.type}: ${o.name}`));for(let t of o.changes)console.log(c$1.gray(` ${t}`));}console.log("");}if(e.removed.length>0){console.log(c$1.red.bold(" - Removed:"));for(let o of e.removed)console.log(c$1.red(` - ${o.type}: ${o.name}`));console.log("");}}async function eo(e){let o=V(),t=j();(!t||!t.token)&&(console.log(c$1.red("Not logged in")),console.log(c$1.gray("Run `vaif login` first to authenticate")),process.exit(1));let i=e.config||"vaif.config.json",r=null;o.start("Loading configuration...");try{r=await a(i);}catch(a){o.fail("Failed to load config"),console.log(c$1.red(`
15
+ Error: ${a}`)),process.exit(1);}r||(o.fail("No configuration found"),console.log(c$1.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let l=e.projectId||r.projectId||t.projectId;l||(o.fail("No project ID specified"),console.log(c$1.yellow(`
16
+ Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1));let s=e.schema||w.resolve("vaif.schema.json");F.existsSync(s)||(o.fail("No local schema found"),console.log(c$1.yellow(`
17
+ Expected schema file at: ${s}`)),console.log(c$1.gray("Run `vaif pull` first to fetch the current schema.")),process.exit(1));let n;try{let a=F.readFileSync(s,"utf-8");n=JSON.parse(a);}catch(a){o.fail("Failed to parse schema file"),a instanceof Error&&console.log(c$1.red(`
18
+ Error: ${a.message}`)),process.exit(1);}o.text="Calculating schema changes...";try{let{diff:a,sql:d}=await Jo(t.token,l,n);if(o.stop(),Mo(a),a.added.length===0&&a.modified.length===0&&a.removed.length===0){console.log("");return}if(d.length>0){console.log(c$1.bold("SQL Migrations:")),console.log("");for(let f of d)console.log(c$1.gray(` ${f}`));console.log("");}if(e.dryRun){console.log(c$1.yellow("Dry run mode - no changes applied.")),console.log(c$1.gray("Remove --dry-run to apply these changes."));return}if(!e.force){a.removed.length>0&&(console.log(c$1.red.bold("\u26A0\uFE0F Warning: This will remove tables/columns from your database.")),console.log(c$1.red(" This action cannot be undone!")),console.log(""));let g=await Bo(c$1.cyan("Apply these changes? [y/N] "));if(g.toLowerCase()!=="y"&&g.toLowerCase()!=="yes"){console.log(c$1.yellow(`
19
+ Cancelled. No changes applied.`));return}}o.start("Applying schema changes...");let p=await Ko(t.token,l,n);if(p.success){if(o.succeed("Schema changes applied successfully"),console.log(""),p.migrations.length>0){console.log(c$1.gray("Migrations applied:"));for(let f of p.migrations)console.log(c$1.gray(` - ${f}`));console.log("");}console.log(c$1.green("Your database schema is now up to date.")),console.log(c$1.gray("Run `vaif generate` to update your TypeScript types.")),console.log("");}else o.fail("Failed to apply some changes");}catch(a){o.fail("Failed to push schema changes"),a instanceof Error&&console.log(c$1.red(`
20
+ Error: ${a.message}`)),process.exit(1);}}var io=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Wo(e,o,t){let i=await fetch(`${io}/v1/projects/${o}/functions`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({name:t.name,runtime:t.runtime,entrypoint:t.entrypoint,code:t.code,envId:t.envId})});if(!i.ok){let r=await i.text();throw new Error(`Failed to deploy function: ${r}`)}return i.json()}async function qo(e,o,t){let i=new URL(`${io}/v1/projects/${o}/functions`);t&&i.searchParams.set("envId",t);let r=await fetch(i.toString(),{headers:{Authorization:`Bearer ${e}`}});if(!r.ok){let l=await r.text();throw new Error(`Failed to list functions: ${l}`)}return r.json()}function to(e){switch(w.extname(e).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 no(e){let o=[],t=[".ts",".js",".mjs",".py",".go",".rs"];function i(r){if(!F.existsSync(r))return;let l=F.readdirSync(r,{withFileTypes:true});for(let s of l){let n=w.join(r,s.name);if(s.isDirectory())s.name!=="node_modules"&&!s.name.startsWith(".")&&i(n);else if(s.isFile()){let a=w.extname(s.name).toLowerCase();t.includes(a)&&(s.name==="index.ts"||s.name==="index.js"||s.name.includes("function")||s.name.includes("handler"))&&o.push(n);}}}return i(e),o}async function ro(e){let o=V(),t=j();(!t||!t.token)&&(console.log(c$1.red("Not logged in")),console.log(c$1.gray("Run `vaif login` first to authenticate")),process.exit(1));let i=e.config||"vaif.config.json",r=null;try{r=await a(i);}catch{}let l=e.projectId||r?.projectId||t.projectId;l||(console.log(c$1.red("No project ID specified")),console.log(c$1.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(c$1.bold("VAIF Functions Deploy")),console.log(""),o.start("Scanning for function files...");let s=w.resolve("functions"),n=w.resolve("src/functions"),a$1=[];if(e.entrypoint){let g=w.resolve(e.entrypoint);F.existsSync(g)||(o.fail(`File not found: ${e.entrypoint}`),process.exit(1)),a$1=[g];}else a$1=[...no(s),...no(n)];a$1.length===0&&(o.fail("No function files found"),console.log(c$1.yellow(`
21
+ Place your functions in:`)),console.log(c$1.gray(" - ./functions/")),console.log(c$1.gray(" - ./src/functions/")),console.log(c$1.gray(`
22
+ Or specify an entrypoint with --entrypoint`)),process.exit(1)),o.succeed(`Found ${a$1.length} function(s)`),e.name&&(a$1=a$1.filter(g=>w.basename(g,w.extname(g)).includes(e.name)),a$1.length===0&&(console.log(c$1.yellow(`
23
+ No functions matching "${e.name}" found`)),process.exit(1))),console.log(""),console.log(c$1.gray("Functions to deploy:"));for(let g of a$1){let y=w.basename(w.dirname(g))||w.basename(g,w.extname(g)),$=e.runtime||to(g);console.log(c$1.gray(` - ${y} (${$})`));}if(console.log(""),e.dryRun){console.log(c$1.yellow("Dry run mode - no functions deployed."));return}let d=[];for(let g of a$1){let y=w.basename(w.dirname(g))||w.basename(g,w.extname(g)),$=e.runtime||to(g);o.start(`Deploying ${y}...`);try{let k=F.readFileSync(g,"utf-8"),R=await Wo(t.token,l,{name:y,runtime:$,entrypoint:w.basename(g),code:k,envId:e.envId});o.succeed(`Deployed ${y} (v${R.version})`),d.push({name:y,success:!0,version:R.version});}catch(k){let R=k instanceof Error?k.message:"Unknown error";o.fail(`Failed to deploy ${y}`),d.push({name:y,success:false,error:R});}}console.log("");let p=d.filter(g=>g.success).length;if(d.filter(g=>!g.success).length===0)console.log(c$1.green(`\u2713 Successfully deployed ${p} function(s)`));else {console.log(c$1.yellow(`Deployed ${p}/${d.length} function(s)`)),console.log(""),console.log(c$1.red("Failed deployments:"));for(let g of d.filter(y=>!y.success))console.log(c$1.red(` - ${g.name}: ${g.error}`));}console.log("");}async function co(e){let o=V(),t=j();(!t||!t.token)&&(console.log(c$1.red("Not logged in")),console.log(c$1.gray("Run `vaif login` first to authenticate")),process.exit(1));let i=e.config||"vaif.config.json",r=null;try{r=await a(i);}catch{}let l=e.projectId||r?.projectId||t.projectId;l||(console.log(c$1.red("No project ID specified")),process.exit(1)),o.start("Fetching functions...");try{let s=await qo(t.token,l,e.envId);if(o.stop(),s.length===0){console.log(c$1.yellow(`
24
+ No functions found`)),console.log(c$1.gray("Deploy your first function with: vaif functions deploy"));return}console.log(""),console.log(c$1.bold(`Functions (${s.length}):`)),console.log(""),console.log(c$1.gray(" "+"NAME".padEnd(25)+"RUNTIME".padEnd(15)+"VERSION".padEnd(10)+"STATUS".padEnd(12)+"LAST DEPLOYED")),console.log(c$1.gray(" "+"-".repeat(80)));for(let n of s){let a=n.status==="active"?c$1.green:n.status==="deploying"?c$1.yellow:c$1.red;console.log(" "+n.name.padEnd(25)+n.runtime.padEnd(15)+`v${n.version}`.padEnd(10)+a(n.status.padEnd(12))+(n.lastDeployed?new Date(n.lastDeployed).toLocaleDateString():"-"));}console.log("");}catch(s){o.fail("Failed to fetch functions"),s instanceof Error&&console.log(c$1.red(`
25
+ Error: ${s.message}`)),process.exit(1);}}var T=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Go(e,o,t,i,r){let l=await fetch(`${T}/v1/projects/${o}/db/seed`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({table:t,records:i,truncate:r?.truncate??false})});if(!l.ok){let s=await l.text();throw new Error(`Failed to seed ${t}: ${s}`)}return l.json()}async function Yo(e,o){let t=await fetch(`${T}/v1/projects/${o}/db/reset`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});if(!t.ok){let i=await t.text();throw new Error(`Failed to reset database: ${i}`)}return t.json()}function B(e){let o=[];if(!F.existsSync(e))return o;let t=F.readdirSync(e,{withFileTypes:true});for(let i of t)if(i.isFile()){let r=w.extname(i.name).toLowerCase();(r===".json"||r===".ts"||r===".js")&&o.push(w.join(e,i.name));}return o.sort()}async function ao(e){let o=w.extname(e).toLowerCase();if(o===".json"){let t=F.readFileSync(e,"utf-8"),i=JSON.parse(t);return Array.isArray(i)?[{table:w.basename(e,o),data:i}]:i.table&&i.data?[i]:Object.entries(i).map(([r,l])=>({table:r,data:l}))}else if(o===".ts"||o===".js"){let t=await import(e),i=t.default||t;return typeof i=="function"?i():i}throw new Error(`Unsupported file format: ${o}`)}async function lo(e){let o=V(),t=j();(!t||!t.token)&&(console.log(c$1.red("Not logged in")),console.log(c$1.gray("Run `vaif login` first to authenticate")),process.exit(1));let i=e.config||"vaif.config.json",r=null;try{r=await a(i);}catch{}let l=e.projectId||r?.projectId||t.projectId;l||(console.log(c$1.red("No project ID specified")),console.log(c$1.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(c$1.bold("VAIF Database Seed")),console.log("");let s=[];if(e.file){let p=w.resolve(e.file);F.existsSync(p)||(console.log(c$1.red(`File not found: ${e.file}`)),process.exit(1)),s=[p];}else {let p=w.resolve("seeds"),f=w.resolve("prisma/seed"),g=w.resolve("db/seeds");s=[...B(p),...B(f),...B(g)];}s.length===0&&(console.log(c$1.yellow("No seed files found")),console.log(c$1.gray(`
26
+ Place your seed files in one of these directories:`)),console.log(c$1.gray(" - ./seeds/")),console.log(c$1.gray(" - ./prisma/seed/")),console.log(c$1.gray(" - ./db/seeds/")),console.log(c$1.gray(`
27
+ Or specify a file with --file`)),console.log(c$1.gray(`
28
+ Example seed file (seeds/users.json):`)),console.log(c$1.gray(" [")),console.log(c$1.gray(' { "name": "John Doe", "email": "john@example.com" },')),console.log(c$1.gray(' { "name": "Jane Doe", "email": "jane@example.com" }')),console.log(c$1.gray(" ]")),process.exit(1)),console.log(c$1.gray("Seed files found:"));for(let p of s)console.log(c$1.gray(` - ${w.relative(process.cwd(),p)}`));if(console.log(""),e.truncate&&(console.log(c$1.yellow("\u26A0\uFE0F Tables will be truncated before seeding")),console.log("")),e.dryRun){console.log(c$1.yellow("Dry run mode - no data will be inserted.")),console.log("");for(let p of s){o.start(`Loading ${w.basename(p)}...`);try{let f=await ao(p);o.stop();for(let g of f)e.table&&g.table!==e.table||(console.log(c$1.cyan(`Table: ${g.table}`)),console.log(c$1.gray(` Records: ${g.data.length}`)),g.data.length>0&&console.log(c$1.gray(` Sample: ${JSON.stringify(g.data[0],null,2).slice(0,100)}...`)),console.log(""));}catch(f){o.fail(`Failed to load ${w.basename(p)}`),f instanceof Error&&console.log(c$1.red(` Error: ${f.message}`));}}return}let n=[];for(let p of s){o.start(`Processing ${w.basename(p)}...`);try{let f=await ao(p);o.stop();for(let g of f)if(!(e.table&&g.table!==e.table)){if(g.data.length===0){console.log(c$1.gray(` Skipping ${g.table} (no records)`));continue}o.start(`Seeding ${g.table} (${g.data.length} records)...`);try{let y=await Go(t.token,l,g.table,g.data,{truncate:e.truncate});o.succeed(`Seeded ${g.table}: ${y.inserted} records`),n.push({table:g.table,inserted:y.inserted});}catch(y){let $=y instanceof Error?y.message:"Unknown error";o.fail(`Failed to seed ${g.table}`),n.push({table:g.table,inserted:0,error:$});}}}catch(f){o.fail(`Failed to load ${w.basename(p)}`),f instanceof Error&&console.log(c$1.red(` Error: ${f.message}`));}}console.log("");let a$1=n.reduce((p,f)=>p+f.inserted,0),d=n.filter(p=>p.error).length;if(d===0)console.log(c$1.green(`\u2713 Successfully seeded ${a$1} records across ${n.length} table(s)`));else {console.log(c$1.yellow(`Seeded ${a$1} records with ${d} error(s)`)),console.log(""),console.log(c$1.red("Errors:"));for(let p of n.filter(f=>f.error))console.log(c$1.red(` - ${p.table}: ${p.error}`));}console.log("");}async function go(e){let o=V(),t=j();(!t||!t.token)&&(console.log(c$1.red("Not logged in")),console.log(c$1.gray("Run `vaif login` first to authenticate")),process.exit(1));let i=e.config||"vaif.config.json",r=null;try{r=await a(i);}catch{}let l=e.projectId||r?.projectId||t.projectId;l||(console.log(c$1.red("No project ID specified")),console.log(c$1.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let s=w.resolve(e.dir||"./drizzle");if(console.log(""),console.log(c$1.bold("VAIF Database Push")),console.log(""),!F.existsSync(s)){let f=w.resolve("./migrations");F.existsSync(f)?console.log(c$1.gray(`Using migrations from: ${f}`)):(console.log(c$1.red(`Migrations directory not found: ${s}`)),console.log(c$1.gray(`
29
+ Expected one of:`)),console.log(c$1.gray(" - ./drizzle/")),console.log(c$1.gray(" - ./migrations/")),console.log(c$1.gray(`
30
+ Or specify with: vaif db push --dir <path>`)),process.exit(1));}let n=[],a$1=F.readdirSync(s,{withFileTypes:true});for(let f of a$1)if(f.isFile()&&f.name.endsWith(".sql"))n.push(w.join(s,f.name));else if(f.isDirectory()){let g=F.readdirSync(w.join(s,f.name),{withFileTypes:true});for(let y of g)y.isFile()&&y.name.endsWith(".sql")&&n.push(w.join(s,f.name,y.name));}n.sort(),n.length===0&&(console.log(c$1.yellow("No SQL migration files found")),process.exit(1)),console.log(c$1.gray(`Found ${n.length} migration(s):`));for(let f of n)console.log(c$1.gray(` - ${w.relative(process.cwd(),f)}`));if(console.log(""),e.dryRun){console.log(c$1.yellow("Dry run mode - no migrations will be applied.")),console.log("");for(let f of n){let g=F.readFileSync(f,"utf-8");console.log(c$1.cyan(`--- ${w.basename(f)} ---`)),console.log(c$1.gray(g.slice(0,500))),g.length>500&&console.log(c$1.gray("...")),console.log("");}return}let d=0,p=0;for(let f of n){let g=F.readFileSync(f,"utf-8"),y=w.relative(process.cwd(),f);o.start(`Applying ${y}...`);try{let $=await fetch(`${T}/v1/projects/${l}/schema/execute`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({sql:g})});if(!$.ok){let k=await $.text();throw new Error(k)}o.succeed(`Applied ${y}`),d++;}catch($){let k=$ instanceof Error?$.message:"Unknown error";o.fail(`Failed ${y}: ${k}`),p++;}}console.log(""),console.log(p===0?c$1.green(`Successfully applied ${d} migration(s)`):c$1.yellow(`Applied ${d}, failed ${p} migration(s)`)),console.log("");}async function fo(e){let o=V(),t=j();(!t||!t.token)&&(console.log(c$1.red("Not logged in")),console.log(c$1.gray("Run `vaif login` first to authenticate")),process.exit(1));let i=e.config||"vaif.config.json",r=null;try{r=await a(i);}catch{}let l=e.projectId||r?.projectId||t.projectId;l||(console.log(c$1.red("No project ID specified")),console.log(c$1.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let s=w.resolve(e.output||"vaif.schema.json");console.log(""),console.log(c$1.bold("VAIF Database Pull")),console.log(""),o.start("Pulling schema from remote...");try{let n=await fetch(`${T}/v1/projects/${l}/schema`,{headers:{Authorization:`Bearer ${t.token}`}});if(!n.ok){let p=await n.text();throw new Error(`Failed to pull schema: ${p}`)}let a=await n.json();F.writeFileSync(s,JSON.stringify(a,null,2),"utf-8"),o.succeed(`Schema written to ${w.relative(process.cwd(),s)}`);let d=a.tables?.length??Object.keys(a).length;console.log(c$1.gray(` ${d} table(s) pulled`)),console.log("");}catch(n){o.fail("Failed to pull schema"),n instanceof Error&&console.log(c$1.red(`
31
+ Error: ${n.message}`)),process.exit(1);}}async function po(e){let o=V(),t=j();(!t||!t.token)&&(console.log(c$1.red("Not logged in")),console.log(c$1.gray("Run `vaif login` first to authenticate")),process.exit(1));let i=e.config||"vaif.config.json",r=null;try{r=await a(i);}catch{}let l=e.projectId||r?.projectId||t.projectId;l||(console.log(c$1.red("No project ID specified")),process.exit(1)),console.log(""),console.log(c$1.red.bold("\u26A0\uFE0F DATABASE RESET")),console.log(""),console.log(c$1.red("This will:")),console.log(c$1.red(" - Drop all tables")),console.log(c$1.red(" - Delete all data")),console.log(c$1.red(" - Reset migrations")),console.log(""),console.log(c$1.red.bold("This action cannot be undone!")),console.log(""),e.force||(console.log(c$1.yellow("Use --force to confirm this action.")),process.exit(1)),o.start("Resetting database...");try{await Yo(t.token,l),o.succeed("Database reset complete"),console.log(""),console.log(c$1.gray("Your database is now empty.")),console.log(c$1.gray("Run `vaif push` to apply your schema, then `vaif db seed` to seed data.")),console.log("");}catch(s){o.fail("Failed to reset database"),s instanceof Error&&console.log(c$1.red(`
32
+ Error: ${s.message}`)),process.exit(1);}}var mo=process.env.VAIF_API_URL||"https://api.vaif.studio";function ho(e,o,t){return e.projectId||o?.projectId||t.projectId||null}async function yo(e){let o=V(),t=j();(!t||!t.token)&&(console.log(c$1.red("Not logged in")),console.log(c$1.gray("Run `vaif login` first to authenticate")),process.exit(1));let i=e.config||"vaif.config.json",r=null;try{r=await a(i);}catch{}let l=ho(e,r,t);l||(console.log(c$1.red("No project ID specified")),console.log(c$1.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let s=e.name||`cli-key-${Date.now()}`;console.log(""),console.log(c$1.bold("VAIF Generate API Key")),console.log(""),o.start("Generating API key...");try{let n=await fetch(`${mo}/v1/projects/${l}/api-keys`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:s})});if(!n.ok){let d=await n.text();throw new Error(`Failed to generate key: ${d}`)}let a=await n.json();o.succeed("API key generated"),console.log(""),console.log(c$1.green(` Name: ${a.name}`)),console.log(c$1.green(` Key: ${a.key}`)),console.log(""),console.log(c$1.yellow.bold(" Save this key now - it will not be shown again!")),console.log("");}catch(n){o.fail("Failed to generate API key"),n instanceof Error&&console.log(c$1.red(`
33
+ Error: ${n.message}`)),process.exit(1);}}async function wo(e){let o=V(),t=j();(!t||!t.token)&&(console.log(c$1.red("Not logged in")),console.log(c$1.gray("Run `vaif login` first to authenticate")),process.exit(1));let i=e.config||"vaif.config.json",r=null;try{r=await a(i);}catch{}let l=ho(e,r,t);l||(console.log(c$1.red("No project ID specified")),console.log(c$1.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(c$1.bold("VAIF API Keys")),console.log(""),o.start("Fetching API keys...");try{let s=await fetch(`${mo}/v1/projects/${l}/api-keys`,{headers:{Authorization:`Bearer ${t.token}`}});if(!s.ok){let f=await s.text();throw new Error(`Failed to list keys: ${f}`)}let n=await s.json(),a=n.keys||n;if(o.stop(),!Array.isArray(a)||a.length===0){console.log(c$1.yellow("No API keys found")),console.log(c$1.gray(`
34
+ Generate one with: vaif keys generate`));return}let d=Math.max(8,...a.map(f=>(f.name||"").length)),p=` ${"Name".padEnd(d)} ${"Key".padEnd(24)} Created`;console.log(c$1.gray(p)),console.log(c$1.gray(" "+"-".repeat(p.length-2)));for(let f of a){let g=(f.name||"unnamed").padEnd(d),y=f.maskedKey||f.prefix||`${(f.key||"").slice(0,12)}...`,$=f.createdAt?new Date(f.createdAt).toLocaleDateString():"N/A";console.log(` ${g} ${y.padEnd(24)} ${$}`);}console.log(""),console.log(c$1.gray(` ${a.length} key(s) total`)),console.log("");}catch(s){o.fail("Failed to list API keys"),s instanceof Error&&console.log(c$1.red(`
35
+ Error: ${s.message}`)),process.exit(1);}}var jo=process.env.VAIF_API_URL||"https://api.vaif.studio";function Qo(e){try{let o=new URL(e);return o.password&&(o.password="****"),o.toString()}catch{return e.replace(/:[^@/]+@/,":****@")}}async function vo(e){let o=V(),t=j();(!t||!t.token)&&(console.log(c$1.red("Not logged in")),console.log(c$1.gray("Run `vaif login` first to authenticate")),process.exit(1));let i=e.config||"vaif.config.json",r=null;try{r=await a(i);}catch{}let l=e.projectId||r?.projectId||t.projectId;l||(console.log(c$1.red("No project ID specified")),console.log(c$1.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),o.start("Fetching project info...");try{let s=await fetch(`${jo}/v1/projects/${l}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!s.ok){let p=await s.text();throw new Error(`Failed to fetch project: ${p}`)}let n=await s.json();o.stop(),console.log(""),console.log(c$1.bold("VAIF Project Info")),console.log("");let a=16,d=(p,f)=>{console.log(` ${c$1.gray(p.padEnd(a))} ${f}`);};d("Name:",c$1.white(n.name||"N/A")),d("Project ID:",c$1.white(l)),d("Region:",c$1.white(n.region||"us-east-1")),d("Plan:",c$1.white(n.plan||n.tier||"free")),d("Created:",c$1.white(n.createdAt?new Date(n.createdAt).toLocaleDateString():"N/A")),console.log(""),d("API URL:",c$1.cyan(n.apiUrl||`${jo}/v1`)),d("WS URL:",c$1.cyan(n.wsUrl||n.realtimeUrl||"N/A")),d("DB URL:",c$1.cyan(n.databaseUrl?Qo(n.databaseUrl):"N/A")),d("Storage URL:",c$1.cyan(n.storageUrl||"N/A")),console.log("");}catch(s){o.fail("Failed to fetch project info"),s instanceof Error&&console.log(c$1.red(`
36
+ Error: ${s.message}`)),process.exit(1);}}var Zo=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Io(e){let o=V(),t=j();(!t||!t.token)&&(console.log(c$1.red("Not logged in")),console.log(c$1.gray("Run `vaif login` first to authenticate")),process.exit(1));let i=e.config||"vaif.config.json",r=null;try{r=await a(i);}catch{}let l=e.projectId||r?.projectId||t.projectId;l||(console.log(c$1.red("No project ID specified")),console.log(c$1.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),o.start("Fetching project status...");try{let s=await fetch(`${Zo}/v1/projects/${l}?include=tables,functions,storage,connections`,{headers:{Authorization:`Bearer ${t.token}`}});if(!s.ok){let $=await s.text();throw new Error(`Failed to fetch project status: ${$}`)}let n=await s.json();o.stop(),console.log(""),console.log(c$1.bold("VAIF Project Status")),console.log("");let a=22,d=($,k)=>{console.log(` ${c$1.gray($.padEnd(a))} ${k}`);};d("Project:",c$1.white(n.name||l)),d("Plan:",c$1.white(n.plan||n.tier||"free")),console.log(""),console.log(c$1.gray(" --- Resources ---")),console.log("");let p=n.tableCount??n.tables?.length??"N/A",f=n.functionCount??n.functions?.length??"N/A",g=n.bucketCount??n.storage?.buckets?.length??"N/A",y=n.activeConnections??n.connections??"N/A";d("Tables:",c$1.white(String(p))),d("Functions:",c$1.white(String(f))),d("Storage Buckets:",c$1.white(String(g))),d("Active Connections:",c$1.white(String(y))),n.usage&&(console.log(""),console.log(c$1.gray(" --- Usage ---")),console.log(""),n.usage.dbSize&&d("Database Size:",c$1.white(n.usage.dbSize)),n.usage.storageSize&&d("Storage Size:",c$1.white(n.usage.storageSize)),n.usage.bandwidth&&d("Bandwidth:",c$1.white(n.usage.bandwidth)),n.usage.functionInvocations!=null&&d("Function Invocations:",c$1.white(String(n.usage.functionInvocations)))),console.log("");}catch(s){o.fail("Failed to fetch project status"),s instanceof Error&&console.log(c$1.red(`
37
+ Error: ${s.message}`)),process.exit(1);}}program.name("vaif").description("VAIF CLI - Type generation and development tools").version("1.3.0");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(Y);program.command("logout").description("Log out and remove stored credentials").action(H);program.command("whoami").description("Show current authenticated user").action(Q);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(d);program.command("templates").alias("tpl").description("List available project templates").action(c);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(vo);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(Io);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(X);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(eo);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(b);var bo=program.command("functions").alias("fn").description("Manage serverless functions");bo.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(ro);bo.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(co);var U=program.command("db").description("Database management commands");U.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(go);U.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(fo);U.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(lo);U.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(po);var $o=program.command("keys").description("Manage API keys");$o.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(yo);$o.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(wo);program.parse(process.argv);process.argv.slice(2).length||program.outputHelp();