@vaiftech/cli 1.5.1 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,37 +1,42 @@
1
1
  #!/usr/bin/env node
2
- import {d,c,b,a}from'./chunk-F5OP4YDB.js';import {program}from'commander';import F from'fs';import w from'path';import So from'os';import {exec}from'child_process';import V from'ora';import c$1 from'chalk';import q from'readline';var _=w.join(So.homedir(),".vaif"),D=w.join(_,"auth.json"),O=process.env.VAIF_API_URL||"https://api.vaif.studio";function Po(){F.existsSync(_)||F.mkdirSync(_,{recursive:true});}function G(e){Po(),F.writeFileSync(D,JSON.stringify(e,null,2),"utf-8"),F.chmodSync(D,384);}function j(){if(!F.existsSync(D))return null;try{let e=F.readFileSync(D,"utf-8");return JSON.parse(e)}catch{return null}}function xo(e){let o=q.createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{o.question(e,i=>{o.close(),t(i);});})}function Fo(e){return new Promise(o=>{let t=q.createInterface({input:process.stdin,output:process.stdout});process.stdin;let r=process.stdout.write.bind(process.stdout),l=false;process.stdout.write=((...s)=>l?true:r(...s)),t.question(e,s=>{l=false,process.stdout.write=r,console.log(""),t.close(),o(s);}),l=true;})}function ko(e){let o=process.platform,t;o==="darwin"?t=`open "${e}"`:o==="win32"?t=`start "" "${e}"`:t=`xdg-open "${e}"`,exec(t,i=>{});}function Co(e){return new Promise(o=>setTimeout(o,e))}async function Do(e){try{let o=await fetch(`${O}/auth/me`,{headers:{Authorization:`Bearer ${e}`}});if(o.ok){let t=await o.json();return {valid:!0,email:t.user?.email||t.email}}return {valid:!1}}catch{return {valid:false}}}async function Eo(e){let o=V();o.start("Setting up authentication...");let t,i;try{let n=await fetch(`${O}/auth/cli/authorize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})});n.ok||(o.fail("Failed to initiate authentication"),console.log(c$1.red(`
3
- Could not connect to VAIF API. Please try again later.`)),process.exit(1));let a=await n.json();t=a.code,i=a.url;}catch{o.fail("Failed to connect to VAIF API"),console.log(c$1.red(`
4
- Could not connect to VAIF API.`)),console.log(c$1.gray("Check your internet connection or try: vaif login --email")),process.exit(1);}o.stop(),console.log(c$1.cyan(" Opening browser for authentication...")),console.log(""),console.log(c$1.gray(" If the browser doesn't open, visit this URL:")),console.log(c$1.white(` ${i}`)),console.log(""),ko(i),o.start("Waiting for browser authentication...");let r=12e4,l=2e3,s=Date.now();for(;Date.now()-s<r;){await Co(l);try{let n=await fetch(`${O}/auth/cli/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!n.ok){let d=await n.json();(d.error==="ExpiredCode"||d.error==="InvalidCode")&&(o.fail("Authentication expired"),console.log(c$1.red(`
5
- The authentication session expired. Please try again.`)),process.exit(1));continue}let a=await n.json();if(a.ok&&a.accessToken){let d={token:a.accessToken,email:a.user?.email,projectId:e,expiresAt:new Date(Date.now()+a.expiresIn*1e3).toISOString()};G(d),o.succeed("Logged in successfully"),console.log(""),a.user?.email&&console.log(c$1.green(` Authenticated as: ${a.user.email}`)),console.log(c$1.gray(` Config saved to: ${D}`)),console.log("");return}}catch{}}o.fail("Authentication timed out"),console.log(c$1.red(`
6
- Timed out waiting for browser authentication.`)),console.log(c$1.gray("Try again or use: vaif login --email")),process.exit(1);}async function No(e){console.log(""),console.log(c$1.bold("VAIF CLI Login")),console.log(c$1.gray("Enter your VAIF account credentials")),console.log("");let o=await xo(c$1.cyan(" Email: "));(!o||o.trim()==="")&&(console.log(c$1.red(`
7
- No email provided. Login cancelled.`)),process.exit(1));let t=await Fo(c$1.cyan(" Password: "));(!t||t.trim()==="")&&(console.log(c$1.red(`
8
- No password provided. Login cancelled.`)),process.exit(1));let i=V("Authenticating...").start();try{let r=await fetch(`${O}/auth/cli/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:o.trim(),password:t})}),l=await r.json();(!r.ok||!l.ok)&&(i.fail("Login failed"),console.log(c$1.red(`
9
- ${l.message||"Invalid email or password."}`)),process.exit(1));let s={token:l.accessToken,email:l.user?.email,projectId:e,expiresAt:new Date(Date.now()+l.expiresIn*1e3).toISOString()};G(s),i.succeed("Logged in successfully"),console.log(""),l.user?.email&&console.log(c$1.green(` Authenticated as: ${l.user.email}`)),console.log(c$1.gray(` Config saved to: ${D}`)),console.log("");}catch{i.fail("Failed to connect to VAIF API"),console.log(c$1.red(`
10
- Could not connect to VAIF API. Please try again later.`)),process.exit(1);}}async function Y(e){console.log(""),console.log(c$1.bold("Welcome to VAIF CLI")),console.log(c$1.gray("Authenticate to access your VAIF projects")),console.log(""),e.email?await No(e.projectId):await Eo(e.projectId),console.log(c$1.gray("You can now use VAIF CLI commands like:")),console.log(c$1.gray(" vaif pull - Pull remote schema")),console.log(c$1.gray(" vaif push - Push schema changes")),console.log(c$1.gray(" vaif generate - Generate TypeScript types")),console.log("");}async function H(){F.existsSync(D)?(F.unlinkSync(D),console.log(c$1.green("Logged out successfully"))):console.log(c$1.yellow("Not currently logged in"));}async function Q(){let e=j();(!e||!e.token)&&(console.log(c$1.yellow("Not logged in")),console.log(c$1.gray("Run `vaif login` to authenticate")),process.exit(1));let o=V("Checking authentication...").start(),{valid:t,email:i}=await Do(e.token);t||(o.fail("Session expired"),console.log(c$1.yellow(`
11
- Your session has expired. Please login again.`)),process.exit(1)),o.succeed("Authenticated"),console.log(""),console.log(c$1.green(` Email: ${i||e.email||"Unknown"}`)),e.projectId&&console.log(c$1.green(` Project: ${e.projectId}`)),console.log("");}var Vo=process.env.VAIF_API_URL||"https://api.vaif.studio";async function To(e,o,t="public"){let i=await fetch(`${Vo}/v1/projects/${o}/schema?schema=${t}`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});if(!i.ok){let r=await i.text();throw new Error(`Failed to fetch schema: ${r}`)}return i.json()}async function X(e){let o=V(),t=j();(!t||!t.token)&&(console.log(c$1.red("Not logged in")),console.log(c$1.gray("Run `vaif login` first to authenticate")),process.exit(1));let i=e.config||"vaif.config.json",r=null;o.start("Loading configuration...");try{r=await a(i);}catch(s){o.fail("Failed to load config"),console.log(c$1.red(`
12
- Error: ${s}`)),process.exit(1);}r||(o.fail("No configuration found"),console.log(c$1.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let l=e.projectId||r.projectId||t.projectId;l||(o.fail("No project ID specified"),console.log(c$1.yellow(`
13
- Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1)),o.text="Fetching remote schema...";try{let s=e.schema||r.database?.schema||"public",n=await To(t.token,l,s);o.succeed("Schema fetched successfully");let a=e.output||w.resolve("vaif.schema.json"),d={$schema:"https://vaif.studio/schemas/schema.json",projectId:l,schema:s,pulledAt:new Date().toISOString(),...n};F.writeFileSync(a,JSON.stringify(d,null,2),"utf-8"),console.log(""),console.log(c$1.green(`Schema saved to: ${a}`)),console.log(""),console.log(c$1.gray("Schema summary:")),console.log(c$1.gray(` Tables: ${(n.tables||[]).length}`)),console.log(c$1.gray(` Enums: ${(n.enums||[]).length}`)),console.log(c$1.gray(` Functions: ${(n.functions||[]).length}`)),console.log(""),console.log(c$1.gray("Next steps:")),console.log(c$1.gray(" - Run `vaif generate` to generate TypeScript types")),console.log(c$1.gray(" - Edit the schema and run `vaif push` to deploy changes")),console.log("");}catch(s){o.fail("Failed to fetch schema"),s instanceof Error&&console.log(c$1.red(`
14
- Error: ${s.message}`)),process.exit(1);}}var oo=process.env.VAIF_API_URL||"https://api.vaif.studio";function Bo(e){let o=q.createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{o.question(e,i=>{o.close(),t(i);});})}async function Jo(e,o,t){let i=await fetch(`${oo}/v1/projects/${o}/schema/preview`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({schema:t})});if(!i.ok){let r=await i.text();throw new Error(`Failed to preview changes: ${r}`)}return i.json()}async function Ko(e,o,t){let i=await fetch(`${oo}/v1/projects/${o}/schema/apply`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({schema:t})});if(!i.ok){let r=await i.text();throw new Error(`Failed to apply changes: ${r}`)}return i.json()}function Mo(e){if(console.log(""),console.log(c$1.bold("Schema Changes:")),console.log(""),e.added.length===0&&e.modified.length===0&&e.removed.length===0){console.log(c$1.gray(" No changes detected. Schema is up to date."));return}if(e.added.length>0){console.log(c$1.green.bold(" + Added:"));for(let o of e.added)console.log(c$1.green(` + ${o.type}: ${o.name}`));console.log("");}if(e.modified.length>0){console.log(c$1.yellow.bold(" ~ Modified:"));for(let o of e.modified){console.log(c$1.yellow(` ~ ${o.type}: ${o.name}`));for(let t of o.changes)console.log(c$1.gray(` ${t}`));}console.log("");}if(e.removed.length>0){console.log(c$1.red.bold(" - Removed:"));for(let o of e.removed)console.log(c$1.red(` - ${o.type}: ${o.name}`));console.log("");}}async function eo(e){let o=V(),t=j();(!t||!t.token)&&(console.log(c$1.red("Not logged in")),console.log(c$1.gray("Run `vaif login` first to authenticate")),process.exit(1));let i=e.config||"vaif.config.json",r=null;o.start("Loading configuration...");try{r=await a(i);}catch(a){o.fail("Failed to load config"),console.log(c$1.red(`
15
- Error: ${a}`)),process.exit(1);}r||(o.fail("No configuration found"),console.log(c$1.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let l=e.projectId||r.projectId||t.projectId;l||(o.fail("No project ID specified"),console.log(c$1.yellow(`
16
- Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1));let s=e.schema||w.resolve("vaif.schema.json");F.existsSync(s)||(o.fail("No local schema found"),console.log(c$1.yellow(`
17
- Expected schema file at: ${s}`)),console.log(c$1.gray("Run `vaif pull` first to fetch the current schema.")),process.exit(1));let n;try{let a=F.readFileSync(s,"utf-8");n=JSON.parse(a);}catch(a){o.fail("Failed to parse schema file"),a instanceof Error&&console.log(c$1.red(`
18
- Error: ${a.message}`)),process.exit(1);}o.text="Calculating schema changes...";try{let{diff:a,sql:d}=await Jo(t.token,l,n);if(o.stop(),Mo(a),a.added.length===0&&a.modified.length===0&&a.removed.length===0){console.log("");return}if(d.length>0){console.log(c$1.bold("SQL Migrations:")),console.log("");for(let f of d)console.log(c$1.gray(` ${f}`));console.log("");}if(e.dryRun){console.log(c$1.yellow("Dry run mode - no changes applied.")),console.log(c$1.gray("Remove --dry-run to apply these changes."));return}if(!e.force){a.removed.length>0&&(console.log(c$1.red.bold("\u26A0\uFE0F Warning: This will remove tables/columns from your database.")),console.log(c$1.red(" This action cannot be undone!")),console.log(""));let g=await Bo(c$1.cyan("Apply these changes? [y/N] "));if(g.toLowerCase()!=="y"&&g.toLowerCase()!=="yes"){console.log(c$1.yellow(`
19
- Cancelled. No changes applied.`));return}}o.start("Applying schema changes...");let p=await Ko(t.token,l,n);if(p.success){if(o.succeed("Schema changes applied successfully"),console.log(""),p.migrations.length>0){console.log(c$1.gray("Migrations applied:"));for(let f of p.migrations)console.log(c$1.gray(` - ${f}`));console.log("");}console.log(c$1.green("Your database schema is now up to date.")),console.log(c$1.gray("Run `vaif generate` to update your TypeScript types.")),console.log("");}else o.fail("Failed to apply some changes");}catch(a){o.fail("Failed to push schema changes"),a instanceof Error&&console.log(c$1.red(`
20
- Error: ${a.message}`)),process.exit(1);}}var io=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Wo(e,o,t){let i=await fetch(`${io}/v1/projects/${o}/functions`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({name:t.name,runtime:t.runtime,entrypoint:t.entrypoint,code:t.code,envId:t.envId})});if(!i.ok){let r=await i.text();throw new Error(`Failed to deploy function: ${r}`)}return i.json()}async function qo(e,o,t){let i=new URL(`${io}/v1/projects/${o}/functions`);t&&i.searchParams.set("envId",t);let r=await fetch(i.toString(),{headers:{Authorization:`Bearer ${e}`}});if(!r.ok){let l=await r.text();throw new Error(`Failed to list functions: ${l}`)}return r.json()}function to(e){switch(w.extname(e).toLowerCase()){case ".ts":return "typescript";case ".js":case ".mjs":return "nodejs";case ".py":return "python";case ".go":return "go";case ".rs":return "rust";default:return "nodejs"}}function no(e){let o=[],t=[".ts",".js",".mjs",".py",".go",".rs"];function i(r){if(!F.existsSync(r))return;let l=F.readdirSync(r,{withFileTypes:true});for(let s of l){let n=w.join(r,s.name);if(s.isDirectory())s.name!=="node_modules"&&!s.name.startsWith(".")&&i(n);else if(s.isFile()){let a=w.extname(s.name).toLowerCase();t.includes(a)&&(s.name==="index.ts"||s.name==="index.js"||s.name.includes("function")||s.name.includes("handler"))&&o.push(n);}}}return i(e),o}async function ro(e){let o=V(),t=j();(!t||!t.token)&&(console.log(c$1.red("Not logged in")),console.log(c$1.gray("Run `vaif login` first to authenticate")),process.exit(1));let i=e.config||"vaif.config.json",r=null;try{r=await a(i);}catch{}let l=e.projectId||r?.projectId||t.projectId;l||(console.log(c$1.red("No project ID specified")),console.log(c$1.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(c$1.bold("VAIF Functions Deploy")),console.log(""),o.start("Scanning for function files...");let s=w.resolve("functions"),n=w.resolve("src/functions"),a$1=[];if(e.entrypoint){let g=w.resolve(e.entrypoint);F.existsSync(g)||(o.fail(`File not found: ${e.entrypoint}`),process.exit(1)),a$1=[g];}else a$1=[...no(s),...no(n)];a$1.length===0&&(o.fail("No function files found"),console.log(c$1.yellow(`
21
- Place your functions in:`)),console.log(c$1.gray(" - ./functions/")),console.log(c$1.gray(" - ./src/functions/")),console.log(c$1.gray(`
22
- Or specify an entrypoint with --entrypoint`)),process.exit(1)),o.succeed(`Found ${a$1.length} function(s)`),e.name&&(a$1=a$1.filter(g=>w.basename(g,w.extname(g)).includes(e.name)),a$1.length===0&&(console.log(c$1.yellow(`
23
- No functions matching "${e.name}" found`)),process.exit(1))),console.log(""),console.log(c$1.gray("Functions to deploy:"));for(let g of a$1){let y=w.basename(w.dirname(g))||w.basename(g,w.extname(g)),$=e.runtime||to(g);console.log(c$1.gray(` - ${y} (${$})`));}if(console.log(""),e.dryRun){console.log(c$1.yellow("Dry run mode - no functions deployed."));return}let d=[];for(let g of a$1){let y=w.basename(w.dirname(g))||w.basename(g,w.extname(g)),$=e.runtime||to(g);o.start(`Deploying ${y}...`);try{let k=F.readFileSync(g,"utf-8"),R=await Wo(t.token,l,{name:y,runtime:$,entrypoint:w.basename(g),code:k,envId:e.envId});o.succeed(`Deployed ${y} (v${R.version})`),d.push({name:y,success:!0,version:R.version});}catch(k){let R=k instanceof Error?k.message:"Unknown error";o.fail(`Failed to deploy ${y}`),d.push({name:y,success:false,error:R});}}console.log("");let p=d.filter(g=>g.success).length;if(d.filter(g=>!g.success).length===0)console.log(c$1.green(`\u2713 Successfully deployed ${p} function(s)`));else {console.log(c$1.yellow(`Deployed ${p}/${d.length} function(s)`)),console.log(""),console.log(c$1.red("Failed deployments:"));for(let g of d.filter(y=>!y.success))console.log(c$1.red(` - ${g.name}: ${g.error}`));}console.log("");}async function co(e){let o=V(),t=j();(!t||!t.token)&&(console.log(c$1.red("Not logged in")),console.log(c$1.gray("Run `vaif login` first to authenticate")),process.exit(1));let i=e.config||"vaif.config.json",r=null;try{r=await a(i);}catch{}let l=e.projectId||r?.projectId||t.projectId;l||(console.log(c$1.red("No project ID specified")),process.exit(1)),o.start("Fetching functions...");try{let s=await qo(t.token,l,e.envId);if(o.stop(),s.length===0){console.log(c$1.yellow(`
24
- No functions found`)),console.log(c$1.gray("Deploy your first function with: vaif functions deploy"));return}console.log(""),console.log(c$1.bold(`Functions (${s.length}):`)),console.log(""),console.log(c$1.gray(" "+"NAME".padEnd(25)+"RUNTIME".padEnd(15)+"VERSION".padEnd(10)+"STATUS".padEnd(12)+"LAST DEPLOYED")),console.log(c$1.gray(" "+"-".repeat(80)));for(let n of s){let a=n.status==="active"?c$1.green:n.status==="deploying"?c$1.yellow:c$1.red;console.log(" "+n.name.padEnd(25)+n.runtime.padEnd(15)+`v${n.version}`.padEnd(10)+a(n.status.padEnd(12))+(n.lastDeployed?new Date(n.lastDeployed).toLocaleDateString():"-"));}console.log("");}catch(s){o.fail("Failed to fetch functions"),s instanceof Error&&console.log(c$1.red(`
25
- Error: ${s.message}`)),process.exit(1);}}var T=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Go(e,o,t,i,r){let l=await fetch(`${T}/v1/projects/${o}/db/seed`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({table:t,records:i,truncate:r?.truncate??false})});if(!l.ok){let s=await l.text();throw new Error(`Failed to seed ${t}: ${s}`)}return l.json()}async function Yo(e,o){let t=await fetch(`${T}/v1/projects/${o}/db/reset`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});if(!t.ok){let i=await t.text();throw new Error(`Failed to reset database: ${i}`)}return t.json()}function B(e){let o=[];if(!F.existsSync(e))return o;let t=F.readdirSync(e,{withFileTypes:true});for(let i of t)if(i.isFile()){let r=w.extname(i.name).toLowerCase();(r===".json"||r===".ts"||r===".js")&&o.push(w.join(e,i.name));}return o.sort()}async function ao(e){let o=w.extname(e).toLowerCase();if(o===".json"){let t=F.readFileSync(e,"utf-8"),i=JSON.parse(t);return Array.isArray(i)?[{table:w.basename(e,o),data:i}]:i.table&&i.data?[i]:Object.entries(i).map(([r,l])=>({table:r,data:l}))}else if(o===".ts"||o===".js"){let t=await import(e),i=t.default||t;return typeof i=="function"?i():i}throw new Error(`Unsupported file format: ${o}`)}async function lo(e){let o=V(),t=j();(!t||!t.token)&&(console.log(c$1.red("Not logged in")),console.log(c$1.gray("Run `vaif login` first to authenticate")),process.exit(1));let i=e.config||"vaif.config.json",r=null;try{r=await a(i);}catch{}let l=e.projectId||r?.projectId||t.projectId;l||(console.log(c$1.red("No project ID specified")),console.log(c$1.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(c$1.bold("VAIF Database Seed")),console.log("");let s=[];if(e.file){let p=w.resolve(e.file);F.existsSync(p)||(console.log(c$1.red(`File not found: ${e.file}`)),process.exit(1)),s=[p];}else {let p=w.resolve("seeds"),f=w.resolve("prisma/seed"),g=w.resolve("db/seeds");s=[...B(p),...B(f),...B(g)];}s.length===0&&(console.log(c$1.yellow("No seed files found")),console.log(c$1.gray(`
26
- Place your seed files in one of these directories:`)),console.log(c$1.gray(" - ./seeds/")),console.log(c$1.gray(" - ./prisma/seed/")),console.log(c$1.gray(" - ./db/seeds/")),console.log(c$1.gray(`
27
- Or specify a file with --file`)),console.log(c$1.gray(`
28
- Example seed file (seeds/users.json):`)),console.log(c$1.gray(" [")),console.log(c$1.gray(' { "name": "John Doe", "email": "john@example.com" },')),console.log(c$1.gray(' { "name": "Jane Doe", "email": "jane@example.com" }')),console.log(c$1.gray(" ]")),process.exit(1)),console.log(c$1.gray("Seed files found:"));for(let p of s)console.log(c$1.gray(` - ${w.relative(process.cwd(),p)}`));if(console.log(""),e.truncate&&(console.log(c$1.yellow("\u26A0\uFE0F Tables will be truncated before seeding")),console.log("")),e.dryRun){console.log(c$1.yellow("Dry run mode - no data will be inserted.")),console.log("");for(let p of s){o.start(`Loading ${w.basename(p)}...`);try{let f=await ao(p);o.stop();for(let g of f)e.table&&g.table!==e.table||(console.log(c$1.cyan(`Table: ${g.table}`)),console.log(c$1.gray(` Records: ${g.data.length}`)),g.data.length>0&&console.log(c$1.gray(` Sample: ${JSON.stringify(g.data[0],null,2).slice(0,100)}...`)),console.log(""));}catch(f){o.fail(`Failed to load ${w.basename(p)}`),f instanceof Error&&console.log(c$1.red(` Error: ${f.message}`));}}return}let n=[];for(let p of s){o.start(`Processing ${w.basename(p)}...`);try{let f=await ao(p);o.stop();for(let g of f)if(!(e.table&&g.table!==e.table)){if(g.data.length===0){console.log(c$1.gray(` Skipping ${g.table} (no records)`));continue}o.start(`Seeding ${g.table} (${g.data.length} records)...`);try{let y=await Go(t.token,l,g.table,g.data,{truncate:e.truncate});o.succeed(`Seeded ${g.table}: ${y.inserted} records`),n.push({table:g.table,inserted:y.inserted});}catch(y){let $=y instanceof Error?y.message:"Unknown error";o.fail(`Failed to seed ${g.table}`),n.push({table:g.table,inserted:0,error:$});}}}catch(f){o.fail(`Failed to load ${w.basename(p)}`),f instanceof Error&&console.log(c$1.red(` Error: ${f.message}`));}}console.log("");let a$1=n.reduce((p,f)=>p+f.inserted,0),d=n.filter(p=>p.error).length;if(d===0)console.log(c$1.green(`\u2713 Successfully seeded ${a$1} records across ${n.length} table(s)`));else {console.log(c$1.yellow(`Seeded ${a$1} records with ${d} error(s)`)),console.log(""),console.log(c$1.red("Errors:"));for(let p of n.filter(f=>f.error))console.log(c$1.red(` - ${p.table}: ${p.error}`));}console.log("");}async function go(e){let o=V(),t=j();(!t||!t.token)&&(console.log(c$1.red("Not logged in")),console.log(c$1.gray("Run `vaif login` first to authenticate")),process.exit(1));let i=e.config||"vaif.config.json",r=null;try{r=await a(i);}catch{}let l=e.projectId||r?.projectId||t.projectId;l||(console.log(c$1.red("No project ID specified")),console.log(c$1.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let s=w.resolve(e.dir||"./drizzle");if(console.log(""),console.log(c$1.bold("VAIF Database Push")),console.log(""),!F.existsSync(s)){let f=w.resolve("./migrations");F.existsSync(f)?console.log(c$1.gray(`Using migrations from: ${f}`)):(console.log(c$1.red(`Migrations directory not found: ${s}`)),console.log(c$1.gray(`
29
- Expected one of:`)),console.log(c$1.gray(" - ./drizzle/")),console.log(c$1.gray(" - ./migrations/")),console.log(c$1.gray(`
30
- Or specify with: vaif db push --dir <path>`)),process.exit(1));}let n=[],a$1=F.readdirSync(s,{withFileTypes:true});for(let f of a$1)if(f.isFile()&&f.name.endsWith(".sql"))n.push(w.join(s,f.name));else if(f.isDirectory()){let g=F.readdirSync(w.join(s,f.name),{withFileTypes:true});for(let y of g)y.isFile()&&y.name.endsWith(".sql")&&n.push(w.join(s,f.name,y.name));}n.sort(),n.length===0&&(console.log(c$1.yellow("No SQL migration files found")),process.exit(1)),console.log(c$1.gray(`Found ${n.length} migration(s):`));for(let f of n)console.log(c$1.gray(` - ${w.relative(process.cwd(),f)}`));if(console.log(""),e.dryRun){console.log(c$1.yellow("Dry run mode - no migrations will be applied.")),console.log("");for(let f of n){let g=F.readFileSync(f,"utf-8");console.log(c$1.cyan(`--- ${w.basename(f)} ---`)),console.log(c$1.gray(g.slice(0,500))),g.length>500&&console.log(c$1.gray("...")),console.log("");}return}let d=0,p=0;for(let f of n){let g=F.readFileSync(f,"utf-8"),y=w.relative(process.cwd(),f);o.start(`Applying ${y}...`);try{let $=await fetch(`${T}/v1/projects/${l}/schema/execute`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({sql:g})});if(!$.ok){let k=await $.text();throw new Error(k)}o.succeed(`Applied ${y}`),d++;}catch($){let k=$ instanceof Error?$.message:"Unknown error";o.fail(`Failed ${y}: ${k}`),p++;}}console.log(""),console.log(p===0?c$1.green(`Successfully applied ${d} migration(s)`):c$1.yellow(`Applied ${d}, failed ${p} migration(s)`)),console.log("");}async function fo(e){let o=V(),t=j();(!t||!t.token)&&(console.log(c$1.red("Not logged in")),console.log(c$1.gray("Run `vaif login` first to authenticate")),process.exit(1));let i=e.config||"vaif.config.json",r=null;try{r=await a(i);}catch{}let l=e.projectId||r?.projectId||t.projectId;l||(console.log(c$1.red("No project ID specified")),console.log(c$1.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let s=w.resolve(e.output||"vaif.schema.json");console.log(""),console.log(c$1.bold("VAIF Database Pull")),console.log(""),o.start("Pulling schema from remote...");try{let n=await fetch(`${T}/v1/projects/${l}/schema`,{headers:{Authorization:`Bearer ${t.token}`}});if(!n.ok){let p=await n.text();throw new Error(`Failed to pull schema: ${p}`)}let a=await n.json();F.writeFileSync(s,JSON.stringify(a,null,2),"utf-8"),o.succeed(`Schema written to ${w.relative(process.cwd(),s)}`);let d=a.tables?.length??Object.keys(a).length;console.log(c$1.gray(` ${d} table(s) pulled`)),console.log("");}catch(n){o.fail("Failed to pull schema"),n instanceof Error&&console.log(c$1.red(`
31
- Error: ${n.message}`)),process.exit(1);}}async function po(e){let o=V(),t=j();(!t||!t.token)&&(console.log(c$1.red("Not logged in")),console.log(c$1.gray("Run `vaif login` first to authenticate")),process.exit(1));let i=e.config||"vaif.config.json",r=null;try{r=await a(i);}catch{}let l=e.projectId||r?.projectId||t.projectId;l||(console.log(c$1.red("No project ID specified")),process.exit(1)),console.log(""),console.log(c$1.red.bold("\u26A0\uFE0F DATABASE RESET")),console.log(""),console.log(c$1.red("This will:")),console.log(c$1.red(" - Drop all tables")),console.log(c$1.red(" - Delete all data")),console.log(c$1.red(" - Reset migrations")),console.log(""),console.log(c$1.red.bold("This action cannot be undone!")),console.log(""),e.force||(console.log(c$1.yellow("Use --force to confirm this action.")),process.exit(1)),o.start("Resetting database...");try{await Yo(t.token,l),o.succeed("Database reset complete"),console.log(""),console.log(c$1.gray("Your database is now empty.")),console.log(c$1.gray("Run `vaif push` to apply your schema, then `vaif db seed` to seed data.")),console.log("");}catch(s){o.fail("Failed to reset database"),s instanceof Error&&console.log(c$1.red(`
32
- Error: ${s.message}`)),process.exit(1);}}var mo=process.env.VAIF_API_URL||"https://api.vaif.studio";function ho(e,o,t){return e.projectId||o?.projectId||t.projectId||null}async function yo(e){let o=V(),t=j();(!t||!t.token)&&(console.log(c$1.red("Not logged in")),console.log(c$1.gray("Run `vaif login` first to authenticate")),process.exit(1));let i=e.config||"vaif.config.json",r=null;try{r=await a(i);}catch{}let l=ho(e,r,t);l||(console.log(c$1.red("No project ID specified")),console.log(c$1.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let s=e.name||`cli-key-${Date.now()}`;console.log(""),console.log(c$1.bold("VAIF Generate API Key")),console.log(""),o.start("Generating API key...");try{let n=await fetch(`${mo}/v1/projects/${l}/api-keys`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:s})});if(!n.ok){let d=await n.text();throw new Error(`Failed to generate key: ${d}`)}let a=await n.json();o.succeed("API key generated"),console.log(""),console.log(c$1.green(` Name: ${a.name}`)),console.log(c$1.green(` Key: ${a.key}`)),console.log(""),console.log(c$1.yellow.bold(" Save this key now - it will not be shown again!")),console.log("");}catch(n){o.fail("Failed to generate API key"),n instanceof Error&&console.log(c$1.red(`
33
- Error: ${n.message}`)),process.exit(1);}}async function wo(e){let o=V(),t=j();(!t||!t.token)&&(console.log(c$1.red("Not logged in")),console.log(c$1.gray("Run `vaif login` first to authenticate")),process.exit(1));let i=e.config||"vaif.config.json",r=null;try{r=await a(i);}catch{}let l=ho(e,r,t);l||(console.log(c$1.red("No project ID specified")),console.log(c$1.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(c$1.bold("VAIF API Keys")),console.log(""),o.start("Fetching API keys...");try{let s=await fetch(`${mo}/v1/projects/${l}/api-keys`,{headers:{Authorization:`Bearer ${t.token}`}});if(!s.ok){let f=await s.text();throw new Error(`Failed to list keys: ${f}`)}let n=await s.json(),a=n.keys||n;if(o.stop(),!Array.isArray(a)||a.length===0){console.log(c$1.yellow("No API keys found")),console.log(c$1.gray(`
34
- Generate one with: vaif keys generate`));return}let d=Math.max(8,...a.map(f=>(f.name||"").length)),p=` ${"Name".padEnd(d)} ${"Key".padEnd(24)} Created`;console.log(c$1.gray(p)),console.log(c$1.gray(" "+"-".repeat(p.length-2)));for(let f of a){let g=(f.name||"unnamed").padEnd(d),y=f.maskedKey||f.prefix||`${(f.key||"").slice(0,12)}...`,$=f.createdAt?new Date(f.createdAt).toLocaleDateString():"N/A";console.log(` ${g} ${y.padEnd(24)} ${$}`);}console.log(""),console.log(c$1.gray(` ${a.length} key(s) total`)),console.log("");}catch(s){o.fail("Failed to list API keys"),s instanceof Error&&console.log(c$1.red(`
35
- Error: ${s.message}`)),process.exit(1);}}var jo=process.env.VAIF_API_URL||"https://api.vaif.studio";function Qo(e){try{let o=new URL(e);return o.password&&(o.password="****"),o.toString()}catch{return e.replace(/:[^@/]+@/,":****@")}}async function vo(e){let o=V(),t=j();(!t||!t.token)&&(console.log(c$1.red("Not logged in")),console.log(c$1.gray("Run `vaif login` first to authenticate")),process.exit(1));let i=e.config||"vaif.config.json",r=null;try{r=await a(i);}catch{}let l=e.projectId||r?.projectId||t.projectId;l||(console.log(c$1.red("No project ID specified")),console.log(c$1.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),o.start("Fetching project info...");try{let s=await fetch(`${jo}/v1/projects/${l}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!s.ok){let p=await s.text();throw new Error(`Failed to fetch project: ${p}`)}let n=await s.json();o.stop(),console.log(""),console.log(c$1.bold("VAIF Project Info")),console.log("");let a=16,d=(p,f)=>{console.log(` ${c$1.gray(p.padEnd(a))} ${f}`);};d("Name:",c$1.white(n.name||"N/A")),d("Project ID:",c$1.white(l)),d("Region:",c$1.white(n.region||"us-east-1")),d("Plan:",c$1.white(n.plan||n.tier||"free")),d("Created:",c$1.white(n.createdAt?new Date(n.createdAt).toLocaleDateString():"N/A")),console.log(""),d("API URL:",c$1.cyan(n.apiUrl||`${jo}/v1`)),d("WS URL:",c$1.cyan(n.wsUrl||n.realtimeUrl||"N/A")),d("DB URL:",c$1.cyan(n.databaseUrl?Qo(n.databaseUrl):"N/A")),d("Storage URL:",c$1.cyan(n.storageUrl||"N/A")),console.log("");}catch(s){o.fail("Failed to fetch project info"),s instanceof Error&&console.log(c$1.red(`
36
- Error: ${s.message}`)),process.exit(1);}}var Zo=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Io(e){let o=V(),t=j();(!t||!t.token)&&(console.log(c$1.red("Not logged in")),console.log(c$1.gray("Run `vaif login` first to authenticate")),process.exit(1));let i=e.config||"vaif.config.json",r=null;try{r=await a(i);}catch{}let l=e.projectId||r?.projectId||t.projectId;l||(console.log(c$1.red("No project ID specified")),console.log(c$1.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),o.start("Fetching project status...");try{let s=await fetch(`${Zo}/v1/projects/${l}?include=tables,functions,storage,connections`,{headers:{Authorization:`Bearer ${t.token}`}});if(!s.ok){let $=await s.text();throw new Error(`Failed to fetch project status: ${$}`)}let n=await s.json();o.stop(),console.log(""),console.log(c$1.bold("VAIF Project Status")),console.log("");let a=22,d=($,k)=>{console.log(` ${c$1.gray($.padEnd(a))} ${k}`);};d("Project:",c$1.white(n.name||l)),d("Plan:",c$1.white(n.plan||n.tier||"free")),console.log(""),console.log(c$1.gray(" --- Resources ---")),console.log("");let p=n.tableCount??n.tables?.length??"N/A",f=n.functionCount??n.functions?.length??"N/A",g=n.bucketCount??n.storage?.buckets?.length??"N/A",y=n.activeConnections??n.connections??"N/A";d("Tables:",c$1.white(String(p))),d("Functions:",c$1.white(String(f))),d("Storage Buckets:",c$1.white(String(g))),d("Active Connections:",c$1.white(String(y))),n.usage&&(console.log(""),console.log(c$1.gray(" --- Usage ---")),console.log(""),n.usage.dbSize&&d("Database Size:",c$1.white(n.usage.dbSize)),n.usage.storageSize&&d("Storage Size:",c$1.white(n.usage.storageSize)),n.usage.bandwidth&&d("Bandwidth:",c$1.white(n.usage.bandwidth)),n.usage.functionInvocations!=null&&d("Function Invocations:",c$1.white(String(n.usage.functionInvocations)))),console.log("");}catch(s){o.fail("Failed to fetch project status"),s instanceof Error&&console.log(c$1.red(`
37
- Error: ${s.message}`)),process.exit(1);}}program.name("vaif").description("VAIF CLI - Type generation and development tools").version("1.5.1");program.command("login").description("Authenticate with VAIF (opens browser)").option("-e, --email","Login with email/password instead of browser").option("-p, --project-id <id>","Default project ID").action(Y);program.command("logout").description("Log out and remove stored credentials").action(H);program.command("whoami").description("Show current authenticated user").action(Q);program.command("init").description("Initialize VAIF configuration in your project").option("--typescript","Setup for TypeScript project").option("-f, --force","Overwrite existing config").option("-t, --template <name>","Scaffold from a template (run vaif templates for list)").option("--features <features>","Comma-separated features to include: auth,database,realtime,storage,functions").action(d);program.command("templates").alias("tpl").description("List available project templates").action(c);program.command("info").description("Show project information (name, region, URLs)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").action(vo);program.command("status").description("Show project status (tables, functions, storage, connections)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").action(Io);program.command("pull").description("Pull database schema from your VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-o, --output <path>","Output file path","vaif.schema.json").option("-s, --schema <name>","Schema name","public").option("-p, --project-id <id>","Project ID (overrides config)").action(X);program.command("push").description("Push local schema changes to your VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-s, --schema <path>","Schema file path","vaif.schema.json").option("-p, --project-id <id>","Project ID (overrides config)").option("--dry-run","Preview changes without applying").option("-f, --force","Apply changes without confirmation").action(eo);program.command("generate").alias("gen").description("Generate TypeScript types from your database schema").option("-c, --connection <url>","Database connection string").option("-o, --output <path>","Output file path","./src/types/database.ts").option("--schema <name>","Schema name","public").option("--config <path>","Config file path","vaif.config.json").option("--dry-run","Preview generated types without writing").action(b);var bo=program.command("functions").alias("fn").description("Manage serverless functions");bo.command("deploy").description("Deploy functions to your VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID").option("-n, --name <name>","Function name filter").option("-r, --runtime <runtime>","Runtime (nodejs, typescript, python)").option("--entrypoint <file>","Specific entrypoint file").option("--dry-run","Preview deployment without deploying").action(ro);bo.command("list").alias("ls").description("List deployed functions").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID").action(co);var U=program.command("db").description("Database management commands");U.command("push").description("Push local Drizzle migrations to VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-d, --dir <path>","Migrations directory","./drizzle").option("--dry-run","Preview without applying").action(go);U.command("pull").description("Pull schema from VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-o, --output <path>","Output file","vaif.schema.json").action(fo);U.command("seed").description("Seed your database with test data").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-f, --file <path>","Specific seed file").option("-t, --table <name>","Seed specific table only").option("--truncate","Truncate tables before seeding").option("--dry-run","Preview seeding without inserting data").action(lo);U.command("reset").description("Reset database (drop all tables and data)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-f, --force","Confirm reset (required)").action(po);var $o=program.command("keys").description("Manage API keys");$o.command("generate").description("Generate a new API key").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-n, --name <name>","Key name").action(yo);$o.command("list").alias("ls").description("List API keys").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").action(wo);program.parse(process.argv);process.argv.slice(2).length||program.outputHelp();
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(`
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(`
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(`
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(`
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
+ 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
+ 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
+ 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(`
21
+ Place your functions in:`)),console.log(l.gray(" - ./functions/")),console.log(l.gray(" - ./src/functions/")),console.log(l.gray(`
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(`
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(`
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
+ 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(`
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(`
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();
package/dist/index.cjs CHANGED
@@ -527,6 +527,11 @@ export const posts = pgTable("posts", {
527
527
  });
528
528
  `}],functions:[{path:"functions/hello.ts",content:`export default async function handler(req: Request): Promise<Response> {
529
529
  const { name } = await req.json().catch(() => ({ name: "World" }));
530
+
531
+ // Secrets set via \\\`vaif secrets set\\\` or the Security > Secrets page
532
+ // are available as environment variables at runtime:
533
+ // const apiKey = process.env.MY_API_KEY;
534
+
530
535
  return Response.json({ message: \`Hello, \${name}!\` });
531
536
  }
532
537
  `}]},dependencies:["@vaiftech/client","@vaiftech/auth","@vaiftech/react","next","react","react-dom"],devDependencies:["@types/node","@types/react","@types/react-dom","typescript"],postInstructions:["cd my-vaif-app","npm install","# Copy .env.local.example to .env.local and add your VAIF credentials","npm run dev"]},"react-spa":{name:"React SPA",description:"Single-page React app with Vite, VAIF client, and provider wrapper",tag:"React + Vite",defaultFeatures:["database","auth"],files:[{path:"package.json",content:`{
@@ -1036,6 +1041,11 @@ export const posts = pgTable("posts", {
1036
1041
  });
1037
1042
  `}],functions:[{path:"functions/hello.ts",content:`export default async function handler(req: Request): Promise<Response> {
1038
1043
  const { name } = await req.json().catch(() => ({ name: "World" }));
1044
+
1045
+ // Secrets set via \\\`vaif secrets set\\\` or the Security > Secrets page
1046
+ // are available as environment variables at runtime:
1047
+ // const apiKey = process.env.MY_API_KEY;
1048
+
1039
1049
  return Response.json({ message: \`Hello, \${name}!\` });
1040
1050
  }
1041
1051
  `}]},dependencies:["@vaiftech/client","@vaiftech/react","react","react-dom","react-router-dom"],devDependencies:["@types/react","@types/react-dom","@vitejs/plugin-react","typescript","vite"],postInstructions:["cd my-vaif-app","npm install","# Copy .env.example to .env and add your VAIF credentials","npm run dev"]},"ios-swift-app":{name:"iOS Swift App",description:"Swift client manager for iOS/macOS apps using Swift Package Manager",tag:"Swift / iOS",defaultFeatures:["database","auth"],files:[{path:"VaifManager.swift",content:`import Foundation
@@ -1625,6 +1635,11 @@ export const posts = pgTable("posts", {
1625
1635
  });
1626
1636
  `}],functions:[{path:"functions/hello.ts",content:`export default async function handler(req: Request): Promise<Response> {
1627
1637
  const { name } = await req.json().catch(() => ({ name: "World" }));
1638
+
1639
+ // Secrets set via \\\`vaif secrets set\\\` or the Security > Secrets page
1640
+ // are available as environment variables at runtime:
1641
+ // const apiKey = process.env.MY_API_KEY;
1642
+
1628
1643
  return Response.json({ message: \`Hello, \${name}!\` });
1629
1644
  }
1630
1645
  `}]},dependencies:["@vaiftech/sdk-expo","@react-native-async-storage/async-storage","expo","expo-router","react","react-native"],postInstructions:["cd my-vaif-app","npm install","# Copy .env.example to .env and add your VAIF credentials","npx expo start"]},"flutter-app":{name:"Flutter App",description:"Dart/Flutter client setup with environment configuration",tag:"Flutter / Dart",defaultFeatures:["database","auth"],files:[{path:"lib/main.dart",content:`import 'package:flutter/material.dart';
@@ -2236,6 +2251,7 @@ async def invoke_function(function_name: str, payload: dict = {}):
2236
2251
  `},{path:"functions/hello.py",content:`"""Example VAIF serverless function."""
2237
2252
 
2238
2253
  import json
2254
+ import os
2239
2255
 
2240
2256
 
2241
2257
  def handler(request):
@@ -2243,6 +2259,10 @@ def handler(request):
2243
2259
 
2244
2260
  Deploy with: vaif functions deploy
2245
2261
  """
2262
+ # Secrets set via \\\`vaif secrets set\\\` or the Security > Secrets page
2263
+ # are available as environment variables at runtime:
2264
+ # api_key = os.environ.get("MY_API_KEY")
2265
+
2246
2266
  try:
2247
2267
  body = json.loads(request.body) if request.body else {}
2248
2268
  name = body.get("name", "World")
@@ -2557,6 +2577,11 @@ type HelloResponse struct {
2557
2577
  }
2558
2578
 
2559
2579
  // HelloHandler is an example VAIF serverless function.
2580
+ //
2581
+ // Secrets set via \\\`vaif secrets set\\\` or the Security > Secrets page
2582
+ // are available as environment variables at runtime:
2583
+ //
2584
+ // apiKey := os.Getenv("MY_API_KEY") // import "os"
2560
2585
  func HelloHandler(w http.ResponseWriter, r *http.Request) {
2561
2586
  var req HelloRequest
2562
2587
  if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Name == "" {
@@ -2752,6 +2777,11 @@ export const posts = pgTable("posts", {
2752
2777
  });
2753
2778
  `}],functions:[{path:"functions/hello.ts",content:`export default async function handler(req: Request): Promise<Response> {
2754
2779
  const { name } = await req.json().catch(() => ({ name: "World" }));
2780
+
2781
+ // Secrets set via \\\`vaif secrets set\\\` or the Security > Secrets page
2782
+ // are available as environment variables at runtime:
2783
+ // const apiKey = process.env.MY_API_KEY;
2784
+
2755
2785
  return Response.json({ message: \`Hello, \${name}!\` });
2756
2786
  }
2757
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";
@@ -3046,6 +3076,11 @@ export const posts = pgTable("posts", {
3046
3076
  });
3047
3077
  `}],functions:[{path:"functions/hello.ts",content:`export default async function handler(req: Request): Promise<Response> {
3048
3078
  const { name } = await req.json().catch(() => ({ name: "World" }));
3079
+
3080
+ // Secrets set via \\\`vaif secrets set\\\` or the Security > Secrets page
3081
+ // are available as environment variables at runtime:
3082
+ // const apiKey = process.env.MY_API_KEY;
3083
+
3049
3084
  return Response.json({ message: \`Hello, \${name}!\` });
3050
3085
  }
3051
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";
@@ -3352,6 +3387,11 @@ export const posts = pgTable("posts", {
3352
3387
  });
3353
3388
  `}],functions:[{path:"functions/hello.ts",content:`export default async function handler(req: Request): Promise<Response> {
3354
3389
  const { name } = await req.json().catch(() => ({ name: "World" }));
3390
+
3391
+ // Secrets set via \\\`vaif secrets set\\\` or the Security > Secrets page
3392
+ // are available as environment variables at runtime:
3393
+ // const apiKey = process.env.MY_API_KEY;
3394
+
3355
3395
  return Response.json({ message: \`Hello, \${name}!\` });
3356
3396
  }
3357
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";
@@ -3618,6 +3658,11 @@ export const posts = pgTable("posts", {
3618
3658
  });
3619
3659
  `}],functions:[{path:"functions/hello.ts",content:`export default async function handler(req: Request): Promise<Response> {
3620
3660
  const { name } = await req.json().catch(() => ({ name: "World" }));
3661
+
3662
+ // Secrets set via \\\`vaif secrets set\\\` or the Security > Secrets page
3663
+ // are available as environment variables at runtime:
3664
+ // const apiKey = process.env.MY_API_KEY;
3665
+
3621
3666
  return Response.json({ message: \`Hello, \${name}!\` });
3622
3667
  }
3623
3668
  `}]},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(`
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export{b as generateTypes,d as initConfig,a as loadConfig}from'./chunk-F5OP4YDB.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-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(`
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.5.1",
3
+ "version": "1.6.0",
4
4
  "description": "VAIF CLI - Type generation and development tools",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",