@vaiftech/cli 1.6.0 → 1.6.2

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