@vaiftech/cli 1.9.6 → 1.9.8

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.
Files changed (4) hide show
  1. package/README.md +5 -3
  2. package/dist/cli.cjs +256 -76
  3. package/dist/cli.js +235 -55
  4. package/package.json +10 -10
package/dist/cli.js CHANGED
@@ -1,67 +1,80 @@
1
1
  #!/usr/bin/env node
2
- import {c,d,e,h,g,f as f$1,b,a}from'./chunk-T7GOLIY4.js';import'dotenv/config';import {program}from'commander';import f from'chalk';import F from'fs';import $ from'path';import B from'ora';import We from'readline';var Je=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Ke(o,e,t="public"){let n=await fetch(`${Je}/projects/${e}/schema?schema=${t}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}});if(!n.ok){let a=await n.text();throw new Error(`Failed to fetch schema: ${a}`)}return n.json()}async function ce(o){let e=B(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",a$1=null;e.start("Loading configuration...");try{a$1=await a(n);}catch(i){e.fail("Failed to load config"),console.log(f.red(`
3
- Error: ${i}`)),process.exit(1);}a$1||(e.fail("No configuration found"),console.log(f.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let r=o.projectId||a$1.projectId||process.env.VAIF_PROJECT_ID||t.projectId;r||(e.fail("No project ID specified"),console.log(f.yellow(`
4
- Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1)),e.text="Fetching remote schema...";try{let i=o.schema||a$1.database?.schema||"public",s=await Ke(t.token,r,i);e.succeed("Schema fetched successfully");let c=o.output||$.resolve("vaif.schema.json"),g={$schema:"https://vaif.studio/schemas/schema.json",projectId:r,schema:i,pulledAt:new Date().toISOString(),...s};F.writeFileSync(c,JSON.stringify(g,null,2),"utf-8"),console.log(""),console.log(f.green(`Schema saved to: ${c}`)),console.log(""),console.log(f.gray("Schema summary:")),console.log(f.gray(` Tables: ${(s.tables||[]).length}`)),console.log(f.gray(` Enums: ${(s.enums||[]).length}`)),console.log(f.gray(` Functions: ${(s.functions||[]).length}`)),console.log(""),console.log(f.gray("Next steps:")),console.log(f.gray(" - Run `vaif generate` to generate TypeScript types")),console.log(f.gray(" - Edit the schema and run `vaif push` to deploy changes")),console.log("");}catch(i){e.fail("Failed to fetch schema"),i instanceof Error&&console.log(f.red(`
5
- Error: ${i.message}`)),process.exit(1);}}var de=process.env.VAIF_API_URL||"https://api.vaif.studio";function Ge(o){let e=We.createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(o,n=>{e.close(),t(n);});})}async function Ye(o,e,t){let n=await fetch(`${de}/projects/${e}/schema/preview`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({schema:t})});if(!n.ok){let a=await n.text();throw new Error(`Failed to preview changes: ${a}`)}return n.json()}async function He(o,e,t){let n=await fetch(`${de}/projects/${e}/schema/apply`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({schema:t})});if(!n.ok){let a=await n.text();throw new Error(`Failed to apply changes: ${a}`)}return n.json()}function Qe(o){if(console.log(""),console.log(f.bold("Schema Changes:")),console.log(""),o.added.length===0&&o.modified.length===0&&o.removed.length===0){console.log(f.gray(" No changes detected. Schema is up to date."));return}if(o.added.length>0){console.log(f.green.bold(" + Added:"));for(let e of o.added)console.log(f.green(` + ${e.type}: ${e.name}`));console.log("");}if(o.modified.length>0){console.log(f.yellow.bold(" ~ Modified:"));for(let e of o.modified){console.log(f.yellow(` ~ ${e.type}: ${e.name}`));for(let t of e.changes)console.log(f.gray(` ${t}`));}console.log("");}if(o.removed.length>0){console.log(f.red.bold(" - Removed:"));for(let e of o.removed)console.log(f.red(` - ${e.type}: ${e.name}`));console.log("");}}async function fe(o){let e=B(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",a$1=null;e.start("Loading configuration...");try{a$1=await a(n);}catch(c){e.fail("Failed to load config"),console.log(f.red(`
6
- Error: ${c}`)),process.exit(1);}a$1||(e.fail("No configuration found"),console.log(f.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let r=o.projectId||a$1.projectId||process.env.VAIF_PROJECT_ID||t.projectId;r||(e.fail("No project ID specified"),console.log(f.yellow(`
7
- Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1));let i=o.schema||$.resolve("vaif.schema.json");F.existsSync(i)||(e.fail("No local schema found"),console.log(f.yellow(`
8
- Expected schema file at: ${i}`)),console.log(f.gray("Run `vaif pull` first to fetch the current schema.")),process.exit(1));let s;try{let c=F.readFileSync(i,"utf-8");s=JSON.parse(c);}catch(c){e.fail("Failed to parse schema file"),c instanceof Error&&console.log(f.red(`
9
- Error: ${c.message}`)),process.exit(1);}e.text="Calculating schema changes...";try{let{diff:c,sql:g}=await Ye(t.token,r,s);if(e.stop(),Qe(c),c.added.length===0&&c.modified.length===0&&c.removed.length===0){console.log("");return}if(g.length>0){console.log(f.bold("SQL Migrations:")),console.log("");for(let d of g)console.log(f.gray(` ${d}`));console.log("");}if(o.dryRun){console.log(f.yellow("Dry run mode - no changes applied.")),console.log(f.gray("Remove --dry-run to apply these changes."));return}if(!o.force){c.removed.length>0&&(console.log(f.red.bold("\u26A0\uFE0F Warning: This will remove tables/columns from your database.")),console.log(f.red(" This action cannot be undone!")),console.log(""));let l=await Ge(f.cyan("Apply these changes? [y/N] "));if(l.toLowerCase()!=="y"&&l.toLowerCase()!=="yes"){console.log(f.yellow(`
10
- Cancelled. No changes applied.`));return}}e.start("Applying schema changes...");let p=await He(t.token,r,s);if(p.success){if(e.succeed("Schema changes applied successfully"),console.log(""),p.migrations.length>0){console.log(f.gray("Migrations applied:"));for(let d of p.migrations)console.log(f.gray(` - ${d}`));console.log("");}console.log(f.green("Your database schema is now up to date.")),console.log(f.gray("Run `vaif generate` to update your TypeScript types.")),console.log("");}else e.fail("Failed to apply some changes");}catch(c){e.fail("Failed to push schema changes"),c instanceof Error&&console.log(f.red(`
11
- Error: ${c.message}`)),process.exit(1);}}var z=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Xe(o,e,t,n){let a=new URL(`${z}/functions/project/${e}`);n&&a.searchParams.set("envId",n);let r=await fetch(a.toString(),{headers:{Authorization:`Bearer ${o}`}});if(!r.ok)return null;let i=await r.json(),s=i.functions||i;return Array.isArray(s)&&s.find(c=>c.name===t)||null}async function Ze(o,e,t){let n=await fetch(`${z}/functions/`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({projectId:e,name:t.name,runtime:t.runtime,entrypoint:t.entrypoint,envId:t.envId})});if(!n.ok){let a=await n.text();throw new Error(`Failed to create function: ${a}`)}return n.json()}async function eo(o,e,t){let n=await fetch(`${z}/functions/${e}/source`,{method:"PUT",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({sourceCode:t})});if(!n.ok){let a=await n.text();throw new Error(`Failed to deploy source: ${a}`)}}async function oo(o,e,t){let n=new URL(`${z}/functions/project/${e}`);t&&n.searchParams.set("envId",t);let a=await fetch(n.toString(),{headers:{Authorization:`Bearer ${o}`}});if(!a.ok){let i=await a.text();throw new Error(`Failed to list functions: ${i}`)}let r=await a.json();return r.functions||r}function ge(o){switch($.extname(o).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 pe(o){let e=[],t=[".ts",".js",".mjs",".py",".go",".rs"],n=["drizzle.config.ts","tsconfig.json","package.json"];if(!F.existsSync(o))return e;let a=F.readdirSync(o,{withFileTypes:true});for(let r of a){let i=$.join(o,r.name);if(r.isDirectory()){if(r.name!=="node_modules"&&!r.name.startsWith(".")){let s=F.readdirSync(i,{withFileTypes:true});for(let c of s)if(c.isFile()){let g=$.extname(c.name).toLowerCase();if(t.includes(g)){e.push($.join(i,c.name));break}}}}else if(r.isFile()){let s=$.extname(r.name).toLowerCase();t.includes(s)&&!n.includes(r.name)&&e.push(i);}}return e}async function he(o){let e=B(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",a$1=null;try{a$1=await a(n);}catch{}let r=o.projectId||a$1?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;r||(console.log(f.red("No project ID specified")),console.log(f.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(f.bold("VAIF Functions Deploy")),console.log(""),e.start("Scanning for function files...");let i=$.resolve("functions"),s=$.resolve("src/functions"),c=[];if(o.entrypoint){let l=$.resolve(o.entrypoint);F.existsSync(l)||(e.fail(`File not found: ${o.entrypoint}`),process.exit(1)),c=[l];}else c=[...pe(i),...pe(s)];c.length===0&&(e.fail("No function files found"),console.log(f.yellow(`
2
+ import {c,d,e,h,g,f as f$1,b,a}from'./chunk-T7GOLIY4.js';import'dotenv/config';import {createRequire}from'module';import {program}from'commander';import f from'chalk';import F from'fs';import b$1 from'path';import J from'ora';import We from'readline';var Be=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Ke(o,e,t="public"){let n=await fetch(`${Be}/projects/${e}/schema?schema=${t}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}});if(!n.ok){let i=await n.text();throw new Error(`Failed to fetch schema: ${i}`)}return n.json()}async function ce(o){let e=J(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",i=null;e.start("Loading configuration...");try{i=await a(n);}catch(r){e.fail("Failed to load config"),console.log(f.red(`
3
+ Error: ${r}`)),process.exit(1);}i||(e.fail("No configuration found"),console.log(f.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let a$1=o.projectId||i.projectId||process.env.VAIF_PROJECT_ID||t.projectId;a$1||(e.fail("No project ID specified"),console.log(f.yellow(`
4
+ Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1)),e.text="Fetching remote schema...";try{let r=o.schema||i.database?.schema||"public",s=await Ke(t.token,a$1,r);e.succeed("Schema fetched successfully");let c=o.output||b$1.resolve("vaif.schema.json"),g={$schema:"https://vaif.studio/schemas/schema.json",projectId:a$1,schema:r,pulledAt:new Date().toISOString(),...s};F.writeFileSync(c,JSON.stringify(g,null,2),"utf-8"),console.log(""),console.log(f.green(`Schema saved to: ${c}`)),console.log(""),console.log(f.gray("Schema summary:")),console.log(f.gray(` Tables: ${(s.tables||[]).length}`)),console.log(f.gray(` Enums: ${(s.enums||[]).length}`)),console.log(f.gray(` Functions: ${(s.functions||[]).length}`)),console.log(""),console.log(f.gray("Next steps:")),console.log(f.gray(" - Run `vaif generate` to generate TypeScript types")),console.log(f.gray(" - Edit the schema and run `vaif push` to deploy changes")),console.log("");}catch(r){e.fail("Failed to fetch schema"),r instanceof Error&&console.log(f.red(`
5
+ Error: ${r.message}`)),process.exit(1);}}var de=process.env.VAIF_API_URL||"https://api.vaif.studio";function Ge(o){let e=We.createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(o,n=>{e.close(),t(n);});})}async function He(o,e,t){let n=await fetch(`${de}/projects/${e}/schema/preview`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({schema:t})});if(!n.ok){let i=await n.text();throw new Error(`Failed to preview changes: ${i}`)}return n.json()}async function Ye(o,e,t){let n=await fetch(`${de}/projects/${e}/schema/apply`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({schema:t})});if(!n.ok){let i=await n.text();throw new Error(`Failed to apply changes: ${i}`)}return n.json()}function Qe(o){if(console.log(""),console.log(f.bold("Schema Changes:")),console.log(""),o.added.length===0&&o.modified.length===0&&o.removed.length===0){console.log(f.gray(" No changes detected. Schema is up to date."));return}if(o.added.length>0){console.log(f.green.bold(" + Added:"));for(let e of o.added)console.log(f.green(` + ${e.type}: ${e.name}`));console.log("");}if(o.modified.length>0){console.log(f.yellow.bold(" ~ Modified:"));for(let e of o.modified){console.log(f.yellow(` ~ ${e.type}: ${e.name}`));for(let t of e.changes)console.log(f.gray(` ${t}`));}console.log("");}if(o.removed.length>0){console.log(f.red.bold(" - Removed:"));for(let e of o.removed)console.log(f.red(` - ${e.type}: ${e.name}`));console.log("");}}async function fe(o){let e=J(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",i=null;e.start("Loading configuration...");try{i=await a(n);}catch(c){e.fail("Failed to load config"),console.log(f.red(`
6
+ Error: ${c}`)),process.exit(1);}i||(e.fail("No configuration found"),console.log(f.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let a$1=o.projectId||i.projectId||process.env.VAIF_PROJECT_ID||t.projectId;a$1||(e.fail("No project ID specified"),console.log(f.yellow(`
7
+ Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1));let r=o.schema||b$1.resolve("vaif.schema.json");F.existsSync(r)||(e.fail("No local schema found"),console.log(f.yellow(`
8
+ Expected schema file at: ${r}`)),console.log(f.gray("Run `vaif pull` first to fetch the current schema.")),process.exit(1));let s;try{let c=F.readFileSync(r,"utf-8");s=JSON.parse(c);}catch(c){e.fail("Failed to parse schema file"),c instanceof Error&&console.log(f.red(`
9
+ Error: ${c.message}`)),process.exit(1);}e.text="Calculating schema changes...";try{let{diff:c,sql:g}=await He(t.token,a$1,s);if(e.stop(),Qe(c),c.added.length===0&&c.modified.length===0&&c.removed.length===0){console.log("");return}if(g.length>0){console.log(f.bold("SQL Migrations:")),console.log("");for(let d of g)console.log(f.gray(` ${d}`));console.log("");}if(o.dryRun){console.log(f.yellow("Dry run mode - no changes applied.")),console.log(f.gray("Remove --dry-run to apply these changes."));return}if(!o.force){c.removed.length>0&&(console.log(f.red.bold("\u26A0\uFE0F Warning: This will remove tables/columns from your database.")),console.log(f.red(" This action cannot be undone!")),console.log(""));let l=await Ge(f.cyan("Apply these changes? [y/N] "));if(l.toLowerCase()!=="y"&&l.toLowerCase()!=="yes"){console.log(f.yellow(`
10
+ Cancelled. No changes applied.`));return}}e.start("Applying schema changes...");let p=await Ye(t.token,a$1,s);if(p.success){if(e.succeed("Schema changes applied successfully"),console.log(""),p.migrations.length>0){console.log(f.gray("Migrations applied:"));for(let d of p.migrations)console.log(f.gray(` - ${d}`));console.log("");}console.log(f.green("Your database schema is now up to date.")),console.log(f.gray("Run `vaif generate` to update your TypeScript types.")),console.log("");}else e.fail("Failed to apply some changes");}catch(c){e.fail("Failed to push schema changes"),c instanceof Error&&console.log(f.red(`
11
+ Error: ${c.message}`)),process.exit(1);}}var z=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Xe(o,e,t,n){let i=new URL(`${z}/functions/project/${e}`);n&&i.searchParams.set("envId",n);let a=await fetch(i.toString(),{headers:{Authorization:`Bearer ${o}`}});if(!a.ok)return null;let r=await a.json(),s=r.functions||r;return Array.isArray(s)&&s.find(c=>c.name===t)||null}async function Ze(o,e,t){let n=await fetch(`${z}/functions/`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({projectId:e,name:t.name,runtime:t.runtime,entrypoint:t.entrypoint,envId:t.envId})});if(!n.ok){let i=await n.text();throw new Error(`Failed to create function: ${i}`)}return n.json()}async function eo(o,e,t){let n=await fetch(`${z}/functions/${e}/source`,{method:"PUT",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({sourceCode:t})});if(!n.ok){let i=await n.text();throw new Error(`Failed to deploy source: ${i}`)}}async function oo(o,e,t){let n=new URL(`${z}/functions/project/${e}`);t&&n.searchParams.set("envId",t);let i=await fetch(n.toString(),{headers:{Authorization:`Bearer ${o}`}});if(!i.ok){let r=await i.text();throw new Error(`Failed to list functions: ${r}`)}let a=await i.json();return a.functions||a}function ge(o){switch(b$1.extname(o).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 pe(o){let e=[],t=[".ts",".js",".mjs",".py",".go",".rs"],n=["drizzle.config.ts","tsconfig.json","package.json"];if(!F.existsSync(o))return e;let i=F.readdirSync(o,{withFileTypes:true});for(let a of i){let r=b$1.join(o,a.name);if(a.isDirectory()){if(a.name!=="node_modules"&&!a.name.startsWith(".")){let s=F.readdirSync(r,{withFileTypes:true});for(let c of s)if(c.isFile()){let g=b$1.extname(c.name).toLowerCase();if(t.includes(g)){e.push(b$1.join(r,c.name));break}}}}else if(a.isFile()){let s=b$1.extname(a.name).toLowerCase();t.includes(s)&&!n.includes(a.name)&&e.push(r);}}return e}async function he(o){let e=J(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",i=null;try{i=await a(n);}catch{}let a$1=o.projectId||i?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;a$1||(console.log(f.red("No project ID specified")),console.log(f.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(f.bold("VAIF Functions Deploy")),console.log(""),e.start("Scanning for function files...");let r=b$1.resolve("functions"),s=b$1.resolve("src/functions"),c=[];if(o.entrypoint){let l=b$1.resolve(o.entrypoint);F.existsSync(l)||(e.fail(`File not found: ${o.entrypoint}`),process.exit(1)),c=[l];}else c=[...pe(r),...pe(s)];c.length===0&&(e.fail("No function files found"),console.log(f.yellow(`
12
12
  Place your functions in:`)),console.log(f.gray(" - ./functions/")),console.log(f.gray(" - ./src/functions/")),console.log(f.gray(`
13
- Or specify an entrypoint with --entrypoint`)),process.exit(1)),e.succeed(`Found ${c.length} function(s)`),o.name&&(c=c.filter(l=>$.basename(l,$.extname(l)).includes(o.name)),c.length===0&&(console.log(f.yellow(`
14
- No functions matching "${o.name}" found`)),process.exit(1))),console.log(""),console.log(f.gray("Functions to deploy:"));for(let l of c){let u=$.basename($.dirname(l)),y=u==="functions"||u==="src"?$.basename(l,$.extname(l)):u,D=o.runtime||ge(l);console.log(f.gray(` - ${y} (${D})`));}if(console.log(""),o.dryRun){console.log(f.yellow("Dry run mode - no functions deployed."));return}let g=[];for(let l of c){let u=$.basename($.dirname(l)),y=u==="functions"||u==="src"?$.basename(l,$.extname(l)):u,D=o.runtime||ge(l);e.start(`Deploying ${y}...`);try{let U=F.readFileSync(l,"utf-8"),L=await Xe(t.token,r,y,o.envId);L||(e.text=`Creating ${y}...`,L=await Ze(t.token,r,{name:y,runtime:D,entrypoint:$.basename(l),envId:o.envId})),e.text=`Deploying ${y}...`,await eo(t.token,L.id,U),e.succeed(`Deployed ${y}`),g.push({name:y,success:!0});}catch(U){let L=U instanceof Error?U.message:"Unknown error";e.fail(`Failed to deploy ${y}`),g.push({name:y,success:false,error:L});}}console.log("");let p=g.filter(l=>l.success).length;if(g.filter(l=>!l.success).length===0)console.log(f.green(`\u2713 Successfully deployed ${p} function(s)`));else {console.log(f.yellow(`Deployed ${p}/${g.length} function(s)`)),console.log(""),console.log(f.red("Failed deployments:"));for(let l of g.filter(u=>!u.success))console.log(f.red(` - ${l.name}: ${l.error}`));}console.log("");}async function me(o){let e=B(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",a$1=null;try{a$1=await a(n);}catch{}let r=o.projectId||a$1?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;r||(console.log(f.red("No project ID specified")),process.exit(1)),e.start("Fetching functions...");try{let i=await oo(t.token,r,o.envId);if(e.stop(),i.length===0){console.log(f.yellow(`
15
- No functions found`)),console.log(f.gray("Deploy your first function with: vaif functions deploy"));return}console.log(""),console.log(f.bold(`Functions (${i.length}):`)),console.log(""),console.log(f.gray(" "+"NAME".padEnd(25)+"RUNTIME".padEnd(15)+"STATUS".padEnd(12)+"INVOCATIONS".padEnd(14)+"LAST DEPLOYED")),console.log(f.gray(" "+"-".repeat(80)));for(let s of i){let c=s.deployStatus==="deployed"?f.green:s.deployStatus==="deploying"?f.yellow:s.deployStatus==="failed"?f.red:f.gray;console.log(" "+s.name.padEnd(25)+s.runtime.padEnd(15)+c(s.deployStatus.padEnd(12))+String(s.invocationCount??0).padEnd(14)+(s.deployedAt?new Date(s.deployedAt).toLocaleDateString():"-"));}console.log("");}catch(i){e.fail("Failed to fetch functions"),i instanceof Error&&console.log(f.red(`
16
- Error: ${i.message}`)),process.exit(1);}}var J=process.env.VAIF_API_URL||"https://api.vaif.studio";async function to(o,e,t,n,a){let r=await fetch(`${J}/projects/${e}/db/seed`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({table:t,records:n,truncate:a?.truncate??false})});if(!r.ok){let i=await r.text();throw new Error(`Failed to seed ${t}: ${i}`)}return r.json()}async function no(o,e){let t=await fetch(`${J}/projects/${e}/db/reset`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}});if(!t.ok){let n=await t.text();throw new Error(`Failed to reset database: ${n}`)}return t.json()}function H(o){let e=[];if(!F.existsSync(o))return e;let t=F.readdirSync(o,{withFileTypes:true});for(let n of t)if(n.isFile()){let a=$.extname(n.name).toLowerCase();(a===".json"||a===".ts"||a===".js")&&e.push($.join(o,n.name));}return e.sort()}async function ye(o){let e=$.extname(o).toLowerCase();if(e===".json"){let t=F.readFileSync(o,"utf-8"),n=JSON.parse(t);return Array.isArray(n)?[{table:$.basename(o,e),data:n}]:n.table&&n.data?[n]:Object.entries(n).map(([a,r])=>({table:a,data:r}))}else if(e===".ts"||e===".js"){let t=await import(o),n=t.default||t;return typeof n=="function"?n():n}throw new Error(`Unsupported file format: ${e}`)}async function we(o){let e=B(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",a$1=null;try{a$1=await a(n);}catch{}let r=o.projectId||a$1?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;r||(console.log(f.red("No project ID specified")),console.log(f.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(f.bold("VAIF Database Seed")),console.log("");let i=[];if(o.file){let p=$.resolve(o.file);F.existsSync(p)||(console.log(f.red(`File not found: ${o.file}`)),process.exit(1)),i=[p];}else {let p=$.resolve("seeds"),d=$.resolve("prisma/seed"),l=$.resolve("db/seeds");i=[...H(p),...H(d),...H(l)];}i.length===0&&(console.log(f.yellow("No seed files found")),console.log(f.gray(`
13
+ Or specify an entrypoint with --entrypoint`)),process.exit(1)),e.succeed(`Found ${c.length} function(s)`),o.name&&(c=c.filter(l=>b$1.basename(l,b$1.extname(l)).includes(o.name)),c.length===0&&(console.log(f.yellow(`
14
+ No functions matching "${o.name}" found`)),process.exit(1))),console.log(""),console.log(f.gray("Functions to deploy:"));for(let l of c){let u=b$1.basename(b$1.dirname(l)),y=u==="functions"||u==="src"?b$1.basename(l,b$1.extname(l)):u,T=o.runtime||ge(l);console.log(f.gray(` - ${y} (${T})`));}if(console.log(""),o.dryRun){console.log(f.yellow("Dry run mode - no functions deployed."));return}let g=[];for(let l of c){let u=b$1.basename(b$1.dirname(l)),y=u==="functions"||u==="src"?b$1.basename(l,b$1.extname(l)):u,T=o.runtime||ge(l);e.start(`Deploying ${y}...`);try{let V=F.readFileSync(l,"utf-8"),L=await Xe(t.token,a$1,y,o.envId);L||(e.text=`Creating ${y}...`,L=await Ze(t.token,a$1,{name:y,runtime:T,entrypoint:b$1.basename(l),envId:o.envId})),e.text=`Deploying ${y}...`,await eo(t.token,L.id,V),e.succeed(`Deployed ${y}`),g.push({name:y,success:!0});}catch(V){let L=V instanceof Error?V.message:"Unknown error";e.fail(`Failed to deploy ${y}`),g.push({name:y,success:false,error:L});}}console.log("");let p=g.filter(l=>l.success).length;if(g.filter(l=>!l.success).length===0)console.log(f.green(`\u2713 Successfully deployed ${p} function(s)`));else {console.log(f.yellow(`Deployed ${p}/${g.length} function(s)`)),console.log(""),console.log(f.red("Failed deployments:"));for(let l of g.filter(u=>!u.success))console.log(f.red(` - ${l.name}: ${l.error}`));}console.log("");}async function me(o){let e=J(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",i=null;try{i=await a(n);}catch{}let a$1=o.projectId||i?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;a$1||(console.log(f.red("No project ID specified")),process.exit(1)),e.start("Fetching functions...");try{let r=await oo(t.token,a$1,o.envId);if(e.stop(),r.length===0){console.log(f.yellow(`
15
+ No functions found`)),console.log(f.gray("Deploy your first function with: vaif functions deploy"));return}console.log(""),console.log(f.bold(`Functions (${r.length}):`)),console.log(""),console.log(f.gray(" "+"NAME".padEnd(25)+"RUNTIME".padEnd(15)+"STATUS".padEnd(12)+"INVOCATIONS".padEnd(14)+"LAST DEPLOYED")),console.log(f.gray(" "+"-".repeat(80)));for(let s of r){let c=s.deployStatus==="deployed"?f.green:s.deployStatus==="deploying"?f.yellow:s.deployStatus==="failed"?f.red:f.gray;console.log(" "+s.name.padEnd(25)+s.runtime.padEnd(15)+c(s.deployStatus.padEnd(12))+String(s.invocationCount??0).padEnd(14)+(s.deployedAt?new Date(s.deployedAt).toLocaleDateString():"-"));}console.log("");}catch(r){e.fail("Failed to fetch functions"),r instanceof Error&&console.log(f.red(`
16
+ Error: ${r.message}`)),process.exit(1);}}var B=process.env.VAIF_API_URL||"https://api.vaif.studio";async function to(o,e,t,n,i){let a=await fetch(`${B}/projects/${e}/db/seed`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({table:t,records:n,truncate:i?.truncate??false})});if(!a.ok){let r=await a.text();throw new Error(`Failed to seed ${t}: ${r}`)}return a.json()}async function no(o,e){let t=await fetch(`${B}/projects/${e}/db/reset`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}});if(!t.ok){let n=await t.text();throw new Error(`Failed to reset database: ${n}`)}return t.json()}function Y(o){let e=[];if(!F.existsSync(o))return e;let t=F.readdirSync(o,{withFileTypes:true});for(let n of t)if(n.isFile()){let i=b$1.extname(n.name).toLowerCase();(i===".json"||i===".ts"||i===".js")&&e.push(b$1.join(o,n.name));}return e.sort()}async function ye(o){let e=b$1.extname(o).toLowerCase();if(e===".json"){let t=F.readFileSync(o,"utf-8"),n=JSON.parse(t);return Array.isArray(n)?[{table:b$1.basename(o,e),data:n}]:n.table&&n.data?[n]:Object.entries(n).map(([i,a])=>({table:i,data:a}))}else if(e===".ts"||e===".js"){let t=await import(o),n=t.default||t;return typeof n=="function"?n():n}throw new Error(`Unsupported file format: ${e}`)}async function we(o){let e=J(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",i=null;try{i=await a(n);}catch{}let a$1=o.projectId||i?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;a$1||(console.log(f.red("No project ID specified")),console.log(f.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(f.bold("VAIF Database Seed")),console.log("");let r=[];if(o.file){let p=b$1.resolve(o.file);F.existsSync(p)||(console.log(f.red(`File not found: ${o.file}`)),process.exit(1)),r=[p];}else {let p=b$1.resolve("seeds"),d=b$1.resolve("prisma/seed"),l=b$1.resolve("db/seeds");r=[...Y(p),...Y(d),...Y(l)];}r.length===0&&(console.log(f.yellow("No seed files found")),console.log(f.gray(`
17
17
  Place your seed files in one of these directories:`)),console.log(f.gray(" - ./seeds/")),console.log(f.gray(" - ./prisma/seed/")),console.log(f.gray(" - ./db/seeds/")),console.log(f.gray(`
18
18
  Or specify a file with --file`)),console.log(f.gray(`
19
- Example seed file (seeds/users.json):`)),console.log(f.gray(" [")),console.log(f.gray(' { "name": "John Doe", "email": "john@example.com" },')),console.log(f.gray(' { "name": "Jane Doe", "email": "jane@example.com" }')),console.log(f.gray(" ]")),process.exit(1)),console.log(f.gray("Seed files found:"));for(let p of i)console.log(f.gray(` - ${$.relative(process.cwd(),p)}`));if(console.log(""),o.truncate&&(console.log(f.yellow("\u26A0\uFE0F Tables will be truncated before seeding")),console.log("")),o.dryRun){console.log(f.yellow("Dry run mode - no data will be inserted.")),console.log("");for(let p of i){e.start(`Loading ${$.basename(p)}...`);try{let d=await ye(p);e.stop();for(let l of d)o.table&&l.table!==o.table||(console.log(f.cyan(`Table: ${l.table}`)),console.log(f.gray(` Records: ${l.data.length}`)),l.data.length>0&&console.log(f.gray(` Sample: ${JSON.stringify(l.data[0],null,2).slice(0,100)}...`)),console.log(""));}catch(d){e.fail(`Failed to load ${$.basename(p)}`),d instanceof Error&&console.log(f.red(` Error: ${d.message}`));}}return}let s=[];for(let p of i){e.start(`Processing ${$.basename(p)}...`);try{let d=await ye(p);e.stop();for(let l of d)if(!(o.table&&l.table!==o.table)){if(l.data.length===0){console.log(f.gray(` Skipping ${l.table} (no records)`));continue}e.start(`Seeding ${l.table} (${l.data.length} records)...`);try{let u=await to(t.token,r,l.table,l.data,{truncate:o.truncate});e.succeed(`Seeded ${l.table}: ${u.inserted} records`),s.push({table:l.table,inserted:u.inserted});}catch(u){let y=u instanceof Error?u.message:"Unknown error";e.fail(`Failed to seed ${l.table}`),s.push({table:l.table,inserted:0,error:y});}}}catch(d){e.fail(`Failed to load ${$.basename(p)}`),d instanceof Error&&console.log(f.red(` Error: ${d.message}`));}}console.log("");let c=s.reduce((p,d)=>p+d.inserted,0),g=s.filter(p=>p.error).length;if(g===0)console.log(f.green(`\u2713 Successfully seeded ${c} records across ${s.length} table(s)`));else {console.log(f.yellow(`Seeded ${c} records with ${g} error(s)`)),console.log(""),console.log(f.red("Errors:"));for(let p of s.filter(d=>d.error))console.log(f.red(` - ${p.table}: ${p.error}`));}console.log("");}async function je(o){let e=B(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",a$1=null;try{a$1=await a(n);}catch{}let r=o.projectId||a$1?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;r||(console.log(f.red("No project ID specified")),console.log(f.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=$.resolve(o.dir||"./drizzle");if(console.log(""),console.log(f.bold("VAIF Database Push")),console.log(""),!F.existsSync(i)){let d=$.resolve("./migrations");F.existsSync(d)?console.log(f.gray(`Using migrations from: ${d}`)):(console.log(f.red(`Migrations directory not found: ${i}`)),console.log(f.gray(`
19
+ Example seed file (seeds/users.json):`)),console.log(f.gray(" [")),console.log(f.gray(' { "name": "John Doe", "email": "john@example.com" },')),console.log(f.gray(' { "name": "Jane Doe", "email": "jane@example.com" }')),console.log(f.gray(" ]")),process.exit(1)),console.log(f.gray("Seed files found:"));for(let p of r)console.log(f.gray(` - ${b$1.relative(process.cwd(),p)}`));if(console.log(""),o.truncate&&(console.log(f.yellow("\u26A0\uFE0F Tables will be truncated before seeding")),console.log("")),o.dryRun){console.log(f.yellow("Dry run mode - no data will be inserted.")),console.log("");for(let p of r){e.start(`Loading ${b$1.basename(p)}...`);try{let d=await ye(p);e.stop();for(let l of d)o.table&&l.table!==o.table||(console.log(f.cyan(`Table: ${l.table}`)),console.log(f.gray(` Records: ${l.data.length}`)),l.data.length>0&&console.log(f.gray(` Sample: ${JSON.stringify(l.data[0],null,2).slice(0,100)}...`)),console.log(""));}catch(d){e.fail(`Failed to load ${b$1.basename(p)}`),d instanceof Error&&console.log(f.red(` Error: ${d.message}`));}}return}let s=[];for(let p of r){e.start(`Processing ${b$1.basename(p)}...`);try{let d=await ye(p);e.stop();for(let l of d)if(!(o.table&&l.table!==o.table)){if(l.data.length===0){console.log(f.gray(` Skipping ${l.table} (no records)`));continue}e.start(`Seeding ${l.table} (${l.data.length} records)...`);try{let u=await to(t.token,a$1,l.table,l.data,{truncate:o.truncate});e.succeed(`Seeded ${l.table}: ${u.inserted} records`),s.push({table:l.table,inserted:u.inserted});}catch(u){let y=u instanceof Error?u.message:"Unknown error";e.fail(`Failed to seed ${l.table}`),s.push({table:l.table,inserted:0,error:y});}}}catch(d){e.fail(`Failed to load ${b$1.basename(p)}`),d instanceof Error&&console.log(f.red(` Error: ${d.message}`));}}console.log("");let c=s.reduce((p,d)=>p+d.inserted,0),g=s.filter(p=>p.error).length;if(g===0)console.log(f.green(`\u2713 Successfully seeded ${c} records across ${s.length} table(s)`));else {console.log(f.yellow(`Seeded ${c} records with ${g} error(s)`)),console.log(""),console.log(f.red("Errors:"));for(let p of s.filter(d=>d.error))console.log(f.red(` - ${p.table}: ${p.error}`));}console.log("");}async function je(o){let e=J(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",i=null;try{i=await a(n);}catch{}let a$1=o.projectId||i?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;a$1||(console.log(f.red("No project ID specified")),console.log(f.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let r=b$1.resolve(o.dir||"./drizzle");if(console.log(""),console.log(f.bold("VAIF Database Push")),console.log(""),!F.existsSync(r)){let d=b$1.resolve("./migrations");F.existsSync(d)?console.log(f.gray(`Using migrations from: ${d}`)):(console.log(f.red(`Migrations directory not found: ${r}`)),console.log(f.gray(`
20
20
  Expected one of:`)),console.log(f.gray(" - ./drizzle/")),console.log(f.gray(" - ./migrations/")),console.log(f.gray(`
21
- Or specify with: vaif db push --dir <path>`)),process.exit(1));}let s=[],c=F.readdirSync(i,{withFileTypes:true});for(let d of c)if(d.isFile()&&d.name.endsWith(".sql"))s.push($.join(i,d.name));else if(d.isDirectory()){let l=F.readdirSync($.join(i,d.name),{withFileTypes:true});for(let u of l)u.isFile()&&u.name.endsWith(".sql")&&s.push($.join(i,d.name,u.name));}s.sort(),s.length===0&&(console.log(f.yellow("No SQL migration files found")),process.exit(1)),console.log(f.gray(`Found ${s.length} migration(s):`));for(let d of s)console.log(f.gray(` - ${$.relative(process.cwd(),d)}`));if(console.log(""),o.dryRun){console.log(f.yellow("Dry run mode - no migrations will be applied.")),console.log("");for(let d of s){let l=F.readFileSync(d,"utf-8");console.log(f.cyan(`--- ${$.basename(d)} ---`)),console.log(f.gray(l.slice(0,500))),l.length>500&&console.log(f.gray("...")),console.log("");}return}let g=0,p=0;for(let d of s){let l=F.readFileSync(d,"utf-8"),u=$.relative(process.cwd(),d);e.start(`Applying ${u}...`);try{let y=await fetch(`${J}/schema-engine/query/${r}`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({sql:l})});if(!y.ok){let D=await y.text();throw new Error(D)}e.succeed(`Applied ${u}`),g++;}catch(y){let D=y instanceof Error?y.message:"Unknown error";e.fail(`Failed ${u}: ${D}`),p++;}}console.log(""),console.log(p===0?f.green(`Successfully applied ${g} migration(s)`):f.yellow(`Applied ${g}, failed ${p} migration(s)`)),console.log("");}async function ve(o){let e=B(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",a$1=null;try{a$1=await a(n);}catch{}let r=o.projectId||a$1?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;r||(console.log(f.red("No project ID specified")),console.log(f.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=$.resolve(o.output||"vaif.schema.json");console.log(""),console.log(f.bold("VAIF Database Pull")),console.log(""),e.start("Pulling schema from remote...");try{let s=await fetch(`${J}/schema-engine/introspect/${r}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!s.ok){let p=await s.text();throw new Error(`Failed to pull schema: ${p}`)}let c=await s.json();F.writeFileSync(i,JSON.stringify(c,null,2),"utf-8"),e.succeed(`Schema written to ${$.relative(process.cwd(),i)}`);let g=c.tables?.length??Object.keys(c).length;console.log(f.gray(` ${g} table(s) pulled`)),console.log("");}catch(s){e.fail("Failed to pull schema"),s instanceof Error&&console.log(f.red(`
22
- Error: ${s.message}`)),process.exit(1);}}async function Ie(o){let e=B(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",a$1=null;try{a$1=await a(n);}catch{}let r=o.projectId||a$1?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;r||(console.log(f.red("No project ID specified")),process.exit(1)),console.log(""),console.log(f.red.bold("\u26A0\uFE0F DATABASE RESET")),console.log(""),console.log(f.red("This will:")),console.log(f.red(" - Drop all tables")),console.log(f.red(" - Delete all data")),console.log(f.red(" - Reset migrations")),console.log(""),console.log(f.red.bold("This action cannot be undone!")),console.log(""),o.force||(console.log(f.yellow("Use --force to confirm this action.")),process.exit(1)),e.start("Resetting database...");try{await no(t.token,r),e.succeed("Database reset complete"),console.log(""),console.log(f.gray("Your database is now empty.")),console.log(f.gray("Run `vaif push` to apply your schema, then `vaif db seed` to seed data.")),console.log("");}catch(i){e.fail("Failed to reset database"),i instanceof Error&&console.log(f.red(`
23
- Error: ${i.message}`)),process.exit(1);}}var be=process.env.VAIF_API_URL||"https://api.vaif.studio";function Se(o,e,t){return o.projectId||e?.projectId||process.env.VAIF_PROJECT_ID||t.projectId||null}async function ke(o){let e=B(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",a$1=null;try{a$1=await a(n);}catch{}let r=Se(o,a$1,t);r||(console.log(f.red("No project ID specified")),console.log(f.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=o.name||`cli-key-${Date.now()}`;console.log(""),console.log(f.bold("VAIF Generate API Key")),console.log(""),e.start("Generating API key...");try{let s=await fetch(`${be}/projects/${r}/api-keys`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:i})});if(!s.ok){let g=await s.text();throw new Error(`Failed to generate key: ${g}`)}let c=await s.json();e.succeed("API key generated"),console.log(""),console.log(f.green(` Name: ${c.name}`)),console.log(f.green(` Key: ${c.key}`)),console.log(""),console.log(f.yellow.bold(" Save this key now - it will not be shown again!")),console.log("");}catch(s){e.fail("Failed to generate API key"),s instanceof Error&&console.log(f.red(`
24
- Error: ${s.message}`)),process.exit(1);}}async function Ae(o){let e=B(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",a$1=null;try{a$1=await a(n);}catch{}let r=Se(o,a$1,t);r||(console.log(f.red("No project ID specified")),console.log(f.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(f.bold("VAIF API Keys")),console.log(""),e.start("Fetching API keys...");try{let i=await fetch(`${be}/projects/${r}/api-keys`,{headers:{Authorization:`Bearer ${t.token}`}});if(!i.ok){let d=await i.text();throw new Error(`Failed to list keys: ${d}`)}let s=await i.json(),c=s.keys||s;if(e.stop(),!Array.isArray(c)||c.length===0){console.log(f.yellow("No API keys found")),console.log(f.gray(`
25
- Generate one with: vaif keys generate`));return}let g=Math.max(8,...c.map(d=>(d.name||"").length)),p=` ${"Name".padEnd(g)} ${"Key".padEnd(24)} Created`;console.log(f.gray(p)),console.log(f.gray(" "+"-".repeat(p.length-2)));for(let d of c){let l=(d.name||"unnamed").padEnd(g),u=d.maskedKey||d.prefix||`${(d.key||"").slice(0,12)}...`,y=d.createdAt?new Date(d.createdAt).toLocaleDateString():"N/A";console.log(` ${l} ${u.padEnd(24)} ${y}`);}console.log(""),console.log(f.gray(` ${c.length} key(s) total`)),console.log("");}catch(i){e.fail("Failed to list API keys"),i instanceof Error&&console.log(f.red(`
26
- Error: ${i.message}`)),process.exit(1);}}var _=process.env.VAIF_API_URL||"https://api.vaif.studio";function io(o,e,t){return o.projectId||e?.projectId||process.env.VAIF_PROJECT_ID||t.projectId||null}function M(){let o=b();return (!o||!o.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1)),o}async function q(o){try{return await a(o||"vaif.config.json")}catch{return null}}function W(o,e,t){let n=io(o,e,t);return n||(console.log(f.red("No project ID specified")),console.log(f.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),n}async function Pe(o,e,t){let n=B(),a=M(),r=await q(t.config),i=W(t,r,a),s=e;if(t.fromFile)try{s=F.readFileSync(t.fromFile,"utf-8");}catch(c){console.log(f.red(`Failed to read file: ${t.fromFile}`)),c instanceof Error&&console.log(f.gray(c.message)),process.exit(1);}s||(console.log(f.red("No value provided")),console.log(f.gray("Provide a value as argument or use --from-file <path>")),process.exit(1)),console.log(""),console.log(f.bold("VAIF Set Secret")),console.log(""),n.start("Checking for existing secret...");try{let c=new URL(`${_}/functions/secrets/project/${i}`);t.envId&&c.searchParams.set("envId",t.envId);let g=await fetch(c.toString(),{headers:{Authorization:`Bearer ${a.token}`}});if(!g.ok)throw new Error(`Failed to check existing secrets: ${await g.text()}`);let d=(await g.json()).find(l=>l.key===o);if(d){n.text=`Updating secret "${o}"...`;let l=await fetch(`${_}/functions/secrets/${d.id}`,{method:"PUT",headers:{Authorization:`Bearer ${a.token}`,"Content-Type":"application/json"},body:JSON.stringify({value:s})});if(!l.ok)throw new Error(`Failed to update secret: ${await l.text()}`);n.succeed(`Updated secret "${o}"`);}else {n.text=`Creating secret "${o}"...`;let l=await fetch(`${_}/functions/secrets`,{method:"POST",headers:{Authorization:`Bearer ${a.token}`,"Content-Type":"application/json"},body:JSON.stringify({projectId:i,envId:t.envId,key:o,value:s})});if(!l.ok)throw new Error(`Failed to create secret: ${await l.text()}`);n.succeed(`Created secret "${o}"`);}console.log("");}catch(c){n.fail("Failed to set secret"),c instanceof Error&&console.log(f.red(`
27
- Error: ${c.message}`)),process.exit(1);}}async function Ce(o){let e=B(),t=M(),n=await q(o.config),a=W(o,n,t);console.log(""),console.log(f.bold("VAIF Secrets")),console.log(""),e.start("Fetching secrets...");try{let r=new URL(`${_}/functions/secrets/project/${a}`);o.envId&&r.searchParams.set("envId",o.envId);let i=await fetch(r.toString(),{headers:{Authorization:`Bearer ${t.token}`}});if(!i.ok)throw new Error(`Failed to list secrets: ${await i.text()}`);let s=await i.json();if(e.stop(),s.length===0){console.log(f.yellow("No secrets found")),console.log(f.gray(`
28
- Create one with: vaif secrets set <name> <value>`));return}let c=Math.max(8,...s.map(p=>p.key.length)),g=` ${"Name".padEnd(c)} Created`;console.log(f.gray(g)),console.log(f.gray(" "+"-".repeat(g.length-2)));for(let p of s){let d=p.key.padEnd(c),l=p.createdAt?new Date(p.createdAt).toLocaleDateString():"N/A";console.log(` ${d} ${l}`);}console.log(""),console.log(f.gray(` ${s.length} secret(s) total`)),console.log(f.gray(" Values are hidden. Use `vaif secrets get <name>` to reveal.")),console.log("");}catch(r){e.fail("Failed to list secrets"),r instanceof Error&&console.log(f.red(`
29
- Error: ${r.message}`)),process.exit(1);}}async function Ee(o,e){let t=B(),n=M(),a=await q(e.config),r=W(e,a,n);console.log(""),t.start("Fetching secret...");try{let i=new URL(`${_}/functions/secrets/project/${r}`);e.envId&&i.searchParams.set("envId",e.envId);let s=await fetch(i.toString(),{headers:{Authorization:`Bearer ${n.token}`}});if(!s.ok)throw new Error(`Failed to fetch secrets: ${await s.text()}`);let g=(await s.json()).find(l=>l.key===o);g||(t.fail(`Secret "${o}" not found`),process.exit(1));let p=await fetch(`${_}/functions/secrets/${g.id}/value`,{headers:{Authorization:`Bearer ${n.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(i){t.fail("Failed to get secret"),i instanceof Error&&console.log(f.red(`
30
- Error: ${i.message}`)),process.exit(1);}}async function xe(o,e){let t=B(),n=M(),a=await q(e.config),r=W(e,a,n);console.log(""),console.log(f.bold("VAIF Delete Secret")),console.log(""),t.start("Finding secret...");try{let i=new URL(`${_}/functions/secrets/project/${r}`);e.envId&&i.searchParams.set("envId",e.envId);let s=await fetch(i.toString(),{headers:{Authorization:`Bearer ${n.token}`}});if(!s.ok)throw new Error(`Failed to fetch secrets: ${await s.text()}`);let g=(await s.json()).find(d=>d.key===o);g||(t.fail(`Secret "${o}" not found`),process.exit(1)),t.text=`Deleting secret "${o}"...`;let p=await fetch(`${_}/functions/secrets/${g.id}`,{method:"DELETE",headers:{Authorization:`Bearer ${n.token}`}});if(!p.ok)throw new Error(`Failed to delete secret: ${await p.text()}`);t.succeed(`Deleted secret "${o}"`),console.log("");}catch(i){t.fail("Failed to delete secret"),i instanceof Error&&console.log(f.red(`
31
- Error: ${i.message}`)),process.exit(1);}}var Fe=process.env.VAIF_API_URL||"https://api.vaif.studio";function ao(o){try{let e=new URL(o);return e.password&&(e.password="****"),e.toString()}catch{return o.replace(/:[^@/]+@/,":****@")}}async function De(o){let e=B(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",a$1=null;try{a$1=await a(n);}catch{}let r=o.projectId||a$1?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;r||(console.log(f.red("No project ID specified")),console.log(f.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),e.start("Fetching project info...");try{let i=await fetch(`${Fe}/projects/${r}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!i.ok){let p=await i.text();throw new Error(`Failed to fetch project: ${p}`)}let s=await i.json();e.stop(),console.log(""),console.log(f.bold("VAIF Project Info")),console.log("");let c=16,g=(p,d)=>{console.log(` ${f.gray(p.padEnd(c))} ${d}`);};g("Name:",f.white(s.name||"N/A")),g("Project ID:",f.white(r)),g("Region:",f.white(s.region||"us-east-1")),g("Plan:",f.white(s.plan||s.tier||"free")),g("Created:",f.white(s.createdAt?new Date(s.createdAt).toLocaleDateString():"N/A")),console.log(""),g("API URL:",f.cyan(s.apiUrl||`${Fe}/v1`)),g("WS URL:",f.cyan(s.wsUrl||s.realtimeUrl||"N/A")),g("DB URL:",f.cyan(s.databaseUrl?ao(s.databaseUrl):"N/A")),g("Storage URL:",f.cyan(s.storageUrl||"N/A")),console.log("");}catch(i){e.fail("Failed to fetch project info"),i instanceof Error&&console.log(f.red(`
32
- Error: ${i.message}`)),process.exit(1);}}var lo=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Te(o){let e=B(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",a$1=null;try{a$1=await a(n);}catch{}let r=o.projectId||a$1?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;r||(console.log(f.red("No project ID specified")),console.log(f.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),e.start("Fetching project status...");try{let i=await fetch(`${lo}/projects/${r}?include=tables,functions,storage,connections`,{headers:{Authorization:`Bearer ${t.token}`}});if(!i.ok){let y=await i.text();throw new Error(`Failed to fetch project status: ${y}`)}let s=await i.json();e.stop(),console.log(""),console.log(f.bold("VAIF Project Status")),console.log("");let c=22,g=(y,D)=>{console.log(` ${f.gray(y.padEnd(c))} ${D}`);};g("Project:",f.white(s.name||r)),g("Plan:",f.white(s.plan||s.tier||"free")),console.log(""),console.log(f.gray(" --- Resources ---")),console.log("");let p=s.tableCount??s.tables?.length??"N/A",d=s.functionCount??s.functions?.length??"N/A",l=s.bucketCount??s.storage?.buckets?.length??"N/A",u=s.activeConnections??s.connections??"N/A";g("Tables:",f.white(String(p))),g("Functions:",f.white(String(d))),g("Storage Buckets:",f.white(String(l))),g("Active Connections:",f.white(String(u))),s.usage&&(console.log(""),console.log(f.gray(" --- Usage ---")),console.log(""),s.usage.dbSize&&g("Database Size:",f.white(s.usage.dbSize)),s.usage.storageSize&&g("Storage Size:",f.white(s.usage.storageSize)),s.usage.bandwidth&&g("Bandwidth:",f.white(s.usage.bandwidth)),s.usage.functionInvocations!=null&&g("Function Invocations:",f.white(String(s.usage.functionInvocations)))),console.log("");}catch(i){e.fail("Failed to fetch project status"),i instanceof Error&&console.log(f.red(`
33
- Error: ${i.message}`)),process.exit(1);}}var N=process.env.VAIF_API_URL||"https://api.vaif.studio";function go(o){let e=We.createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(o,n=>{e.close(),t(n.trim());});})}function po(o,e,t){return o.projectId||e?.projectId||process.env.VAIF_PROJECT_ID||t.projectId||null}async function uo(o){let e=B("Fetching your projects...").start();try{let t=await fetch(`${N}/projects`,{headers:{Authorization:`Bearer ${o}`}});if(!t.ok)return e.fail("Could not fetch projects"),null;let n=await t.json();if(!n||n.length===0)return e.fail("No projects found. Create a project at https://vaif.studio first."),null;if(n.length===1)return e.succeed(`Found project: ${f.cyan(n[0].name)} (${n[0].id})`),n[0].id;e.succeed(`Found ${n.length} projects
34
- `);for(let i=0;i<n.length;i++)console.log(f.gray(` ${i+1}.`)+` ${f.white(n[i].name)} ${f.gray(`(${n[i].id})`)}`);console.log("");let a=await go(f.cyan(` Select a project [1-${n.length}]: `)),r=parseInt(a,10)-1;return isNaN(r)||r<0||r>=n.length?(console.log(f.red(`
35
- Invalid selection.`)),null):n[r].id}catch{return e.fail("Could not fetch projects"),null}}function ho(o){if(!o||o.length===0)return "*No tables found. Create tables in the VAIF Studio dashboard.*";let e="";for(let t of o){e+=`### \`${t.name}\`
21
+ Or specify with: vaif db push --dir <path>`)),process.exit(1));}let s=[],c=F.readdirSync(r,{withFileTypes:true});for(let d of c)if(d.isFile()&&d.name.endsWith(".sql"))s.push(b$1.join(r,d.name));else if(d.isDirectory()){let l=F.readdirSync(b$1.join(r,d.name),{withFileTypes:true});for(let u of l)u.isFile()&&u.name.endsWith(".sql")&&s.push(b$1.join(r,d.name,u.name));}s.sort(),s.length===0&&(console.log(f.yellow("No SQL migration files found")),process.exit(1)),console.log(f.gray(`Found ${s.length} migration(s):`));for(let d of s)console.log(f.gray(` - ${b$1.relative(process.cwd(),d)}`));if(console.log(""),o.dryRun){console.log(f.yellow("Dry run mode - no migrations will be applied.")),console.log("");for(let d of s){let l=F.readFileSync(d,"utf-8");console.log(f.cyan(`--- ${b$1.basename(d)} ---`)),console.log(f.gray(l.slice(0,500))),l.length>500&&console.log(f.gray("...")),console.log("");}return}let g=0,p=0;for(let d of s){let l=F.readFileSync(d,"utf-8"),u=b$1.relative(process.cwd(),d);e.start(`Applying ${u}...`);try{let y=await fetch(`${B}/schema-engine/query/${a$1}`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({sql:l})});if(!y.ok){let T=await y.text();throw new Error(T)}e.succeed(`Applied ${u}`),g++;}catch(y){let T=y instanceof Error?y.message:"Unknown error";e.fail(`Failed ${u}: ${T}`),p++;}}console.log(""),console.log(p===0?f.green(`Successfully applied ${g} migration(s)`):f.yellow(`Applied ${g}, failed ${p} migration(s)`)),console.log("");}async function ve(o){let e=J(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",i=null;try{i=await a(n);}catch{}let a$1=o.projectId||i?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;a$1||(console.log(f.red("No project ID specified")),console.log(f.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let r=b$1.resolve(o.output||"vaif.schema.json");console.log(""),console.log(f.bold("VAIF Database Pull")),console.log(""),e.start("Pulling schema from remote...");try{let s=await fetch(`${B}/schema-engine/introspect/${a$1}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!s.ok){let p=await s.text();throw new Error(`Failed to pull schema: ${p}`)}let c=await s.json();F.writeFileSync(r,JSON.stringify(c,null,2),"utf-8"),e.succeed(`Schema written to ${b$1.relative(process.cwd(),r)}`);let g=c.tables?.length??Object.keys(c).length;console.log(f.gray(` ${g} table(s) pulled`)),console.log("");}catch(s){e.fail("Failed to pull schema"),s instanceof Error&&console.log(f.red(`
22
+ Error: ${s.message}`)),process.exit(1);}}async function Ie(o){let e=J(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",i=null;try{i=await a(n);}catch{}let a$1=o.projectId||i?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;a$1||(console.log(f.red("No project ID specified")),process.exit(1)),console.log(""),console.log(f.red.bold("\u26A0\uFE0F DATABASE RESET")),console.log(""),console.log(f.red("This will:")),console.log(f.red(" - Drop all tables")),console.log(f.red(" - Delete all data")),console.log(f.red(" - Reset migrations")),console.log(""),console.log(f.red.bold("This action cannot be undone!")),console.log(""),o.force||(console.log(f.yellow("Use --force to confirm this action.")),process.exit(1)),e.start("Resetting database...");try{await no(t.token,a$1),e.succeed("Database reset complete"),console.log(""),console.log(f.gray("Your database is now empty.")),console.log(f.gray("Run `vaif push` to apply your schema, then `vaif db seed` to seed data.")),console.log("");}catch(r){e.fail("Failed to reset database"),r instanceof Error&&console.log(f.red(`
23
+ Error: ${r.message}`)),process.exit(1);}}var $e=process.env.VAIF_API_URL||"https://api.vaif.studio";function Se(o,e,t){return o.projectId||e?.projectId||process.env.VAIF_PROJECT_ID||t.projectId||null}async function ke(o){let e=J(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",i=null;try{i=await a(n);}catch{}let a$1=Se(o,i,t);a$1||(console.log(f.red("No project ID specified")),console.log(f.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let r=o.name||`cli-key-${Date.now()}`;console.log(""),console.log(f.bold("VAIF Generate API Key")),console.log(""),e.start("Generating API key...");try{let s=await fetch(`${$e}/projects/${a$1}/api-keys`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:r})});if(!s.ok){let g=await s.text();throw new Error(`Failed to generate key: ${g}`)}let c=await s.json();e.succeed("API key generated"),console.log(""),console.log(f.green(` Name: ${c.name}`)),console.log(f.green(` Key: ${c.key}`)),console.log(""),console.log(f.yellow.bold(" Save this key now - it will not be shown again!")),console.log("");}catch(s){e.fail("Failed to generate API key"),s instanceof Error&&console.log(f.red(`
24
+ Error: ${s.message}`)),process.exit(1);}}async function Ae(o){let e=J(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",i=null;try{i=await a(n);}catch{}let a$1=Se(o,i,t);a$1||(console.log(f.red("No project ID specified")),console.log(f.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(f.bold("VAIF API Keys")),console.log(""),e.start("Fetching API keys...");try{let r=await fetch(`${$e}/projects/${a$1}/api-keys`,{headers:{Authorization:`Bearer ${t.token}`}});if(!r.ok){let d=await r.text();throw new Error(`Failed to list keys: ${d}`)}let s=await r.json(),c=s.keys||s;if(e.stop(),!Array.isArray(c)||c.length===0){console.log(f.yellow("No API keys found")),console.log(f.gray(`
25
+ Generate one with: vaif keys generate`));return}let g=Math.max(8,...c.map(d=>(d.name||"").length)),p=` ${"Name".padEnd(g)} ${"Key".padEnd(24)} Created`;console.log(f.gray(p)),console.log(f.gray(" "+"-".repeat(p.length-2)));for(let d of c){let l=(d.name||"unnamed").padEnd(g),u=d.maskedKey||d.prefix||`${(d.key||"").slice(0,12)}...`,y=d.createdAt?new Date(d.createdAt).toLocaleDateString():"N/A";console.log(` ${l} ${u.padEnd(24)} ${y}`);}console.log(""),console.log(f.gray(` ${c.length} key(s) total`)),console.log("");}catch(r){e.fail("Failed to list API keys"),r instanceof Error&&console.log(f.red(`
26
+ Error: ${r.message}`)),process.exit(1);}}var _=process.env.VAIF_API_URL||"https://api.vaif.studio";function io(o,e,t){return o.projectId||e?.projectId||process.env.VAIF_PROJECT_ID||t.projectId||null}function q(){let o=b();return (!o||!o.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1)),o}async function M(o){try{return await a(o||"vaif.config.json")}catch{return null}}function W(o,e,t){let n=io(o,e,t);return n||(console.log(f.red("No project ID specified")),console.log(f.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),n}async function Pe(o,e,t){let n=J(),i=q(),a=await M(t.config),r=W(t,a,i),s=e;if(t.fromFile)try{s=F.readFileSync(t.fromFile,"utf-8");}catch(c){console.log(f.red(`Failed to read file: ${t.fromFile}`)),c instanceof Error&&console.log(f.gray(c.message)),process.exit(1);}s||(console.log(f.red("No value provided")),console.log(f.gray("Provide a value as argument or use --from-file <path>")),process.exit(1)),console.log(""),console.log(f.bold("VAIF Set Secret")),console.log(""),n.start("Checking for existing secret...");try{let c=new URL(`${_}/functions/secrets/project/${r}`);t.envId&&c.searchParams.set("envId",t.envId);let g=await fetch(c.toString(),{headers:{Authorization:`Bearer ${i.token}`}});if(!g.ok)throw new Error(`Failed to check existing secrets: ${await g.text()}`);let d=(await g.json()).find(l=>l.key===o);if(d){n.text=`Updating secret "${o}"...`;let l=await fetch(`${_}/functions/secrets/${d.id}`,{method:"PUT",headers:{Authorization:`Bearer ${i.token}`,"Content-Type":"application/json"},body:JSON.stringify({value:s})});if(!l.ok)throw new Error(`Failed to update secret: ${await l.text()}`);n.succeed(`Updated secret "${o}"`);}else {n.text=`Creating secret "${o}"...`;let l=await fetch(`${_}/functions/secrets`,{method:"POST",headers:{Authorization:`Bearer ${i.token}`,"Content-Type":"application/json"},body:JSON.stringify({projectId:r,envId:t.envId,key:o,value:s})});if(!l.ok)throw new Error(`Failed to create secret: ${await l.text()}`);n.succeed(`Created secret "${o}"`);}console.log("");}catch(c){n.fail("Failed to set secret"),c instanceof Error&&console.log(f.red(`
27
+ Error: ${c.message}`)),process.exit(1);}}async function Ce(o){let e=J(),t=q(),n=await M(o.config),i=W(o,n,t);console.log(""),console.log(f.bold("VAIF Secrets")),console.log(""),e.start("Fetching secrets...");try{let a=new URL(`${_}/functions/secrets/project/${i}`);o.envId&&a.searchParams.set("envId",o.envId);let r=await fetch(a.toString(),{headers:{Authorization:`Bearer ${t.token}`}});if(!r.ok)throw new Error(`Failed to list secrets: ${await r.text()}`);let s=await r.json();if(e.stop(),s.length===0){console.log(f.yellow("No secrets found")),console.log(f.gray(`
28
+ Create one with: vaif secrets set <name> <value>`));return}let c=Math.max(8,...s.map(p=>p.key.length)),g=` ${"Name".padEnd(c)} Created`;console.log(f.gray(g)),console.log(f.gray(" "+"-".repeat(g.length-2)));for(let p of s){let d=p.key.padEnd(c),l=p.createdAt?new Date(p.createdAt).toLocaleDateString():"N/A";console.log(` ${d} ${l}`);}console.log(""),console.log(f.gray(` ${s.length} secret(s) total`)),console.log(f.gray(" Values are hidden. Use `vaif secrets get <name>` to reveal.")),console.log("");}catch(a){e.fail("Failed to list secrets"),a instanceof Error&&console.log(f.red(`
29
+ Error: ${a.message}`)),process.exit(1);}}async function Ee(o,e){let t=J(),n=q(),i=await M(e.config),a=W(e,i,n);console.log(""),t.start("Fetching secret...");try{let r=new URL(`${_}/functions/secrets/project/${a}`);e.envId&&r.searchParams.set("envId",e.envId);let s=await fetch(r.toString(),{headers:{Authorization:`Bearer ${n.token}`}});if(!s.ok)throw new Error(`Failed to fetch secrets: ${await s.text()}`);let g=(await s.json()).find(l=>l.key===o);g||(t.fail(`Secret "${o}" not found`),process.exit(1));let p=await fetch(`${_}/functions/secrets/${g.id}/value`,{headers:{Authorization:`Bearer ${n.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(r){t.fail("Failed to get secret"),r instanceof Error&&console.log(f.red(`
30
+ Error: ${r.message}`)),process.exit(1);}}async function xe(o,e){let t=J(),n=q(),i=await M(e.config),a=W(e,i,n);console.log(""),console.log(f.bold("VAIF Delete Secret")),console.log(""),t.start("Finding secret...");try{let r=new URL(`${_}/functions/secrets/project/${a}`);e.envId&&r.searchParams.set("envId",e.envId);let s=await fetch(r.toString(),{headers:{Authorization:`Bearer ${n.token}`}});if(!s.ok)throw new Error(`Failed to fetch secrets: ${await s.text()}`);let g=(await s.json()).find(d=>d.key===o);g||(t.fail(`Secret "${o}" not found`),process.exit(1)),t.text=`Deleting secret "${o}"...`;let p=await fetch(`${_}/functions/secrets/${g.id}`,{method:"DELETE",headers:{Authorization:`Bearer ${n.token}`}});if(!p.ok)throw new Error(`Failed to delete secret: ${await p.text()}`);t.succeed(`Deleted secret "${o}"`),console.log("");}catch(r){t.fail("Failed to delete secret"),r instanceof Error&&console.log(f.red(`
31
+ Error: ${r.message}`)),process.exit(1);}}var Fe=process.env.VAIF_API_URL||"https://api.vaif.studio";function ao(o){try{let e=new URL(o);return e.password&&(e.password="****"),e.toString()}catch{return o.replace(/:[^@/]+@/,":****@")}}async function Te(o){let e=J(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",i=null;try{i=await a(n);}catch{}let a$1=o.projectId||i?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;a$1||(console.log(f.red("No project ID specified")),console.log(f.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),e.start("Fetching project info...");try{let r=await fetch(`${Fe}/projects/${a$1}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!r.ok){let p=await r.text();throw new Error(`Failed to fetch project: ${p}`)}let s=await r.json();e.stop(),console.log(""),console.log(f.bold("VAIF Project Info")),console.log("");let c=16,g=(p,d)=>{console.log(` ${f.gray(p.padEnd(c))} ${d}`);};g("Name:",f.white(s.name||"N/A")),g("Project ID:",f.white(a$1)),g("Region:",f.white(s.region||"us-east-1")),g("Plan:",f.white(s.plan||s.tier||"free")),g("Created:",f.white(s.createdAt?new Date(s.createdAt).toLocaleDateString():"N/A")),console.log(""),g("API URL:",f.cyan(s.apiUrl||`${Fe}/v1`)),g("WS URL:",f.cyan(s.wsUrl||s.realtimeUrl||"N/A")),g("DB URL:",f.cyan(s.databaseUrl?ao(s.databaseUrl):"N/A")),g("Storage URL:",f.cyan(s.storageUrl||"N/A")),console.log("");}catch(r){e.fail("Failed to fetch project info"),r instanceof Error&&console.log(f.red(`
32
+ Error: ${r.message}`)),process.exit(1);}}var lo=process.env.VAIF_API_URL||"https://api.vaif.studio";async function De(o){let e=J(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",i=null;try{i=await a(n);}catch{}let a$1=o.projectId||i?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;a$1||(console.log(f.red("No project ID specified")),console.log(f.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),e.start("Fetching project status...");try{let r=await fetch(`${lo}/projects/${a$1}?include=tables,functions,storage,connections`,{headers:{Authorization:`Bearer ${t.token}`}});if(!r.ok){let y=await r.text();throw new Error(`Failed to fetch project status: ${y}`)}let s=await r.json();e.stop(),console.log(""),console.log(f.bold("VAIF Project Status")),console.log("");let c=22,g=(y,T)=>{console.log(` ${f.gray(y.padEnd(c))} ${T}`);};g("Project:",f.white(s.name||a$1)),g("Plan:",f.white(s.plan||s.tier||"free")),console.log(""),console.log(f.gray(" --- Resources ---")),console.log("");let p=s.tableCount??s.tables?.length??"N/A",d=s.functionCount??s.functions?.length??"N/A",l=s.bucketCount??s.storage?.buckets?.length??"N/A",u=s.activeConnections??s.connections??"N/A";g("Tables:",f.white(String(p))),g("Functions:",f.white(String(d))),g("Storage Buckets:",f.white(String(l))),g("Active Connections:",f.white(String(u))),s.usage&&(console.log(""),console.log(f.gray(" --- Usage ---")),console.log(""),s.usage.dbSize&&g("Database Size:",f.white(s.usage.dbSize)),s.usage.storageSize&&g("Storage Size:",f.white(s.usage.storageSize)),s.usage.bandwidth&&g("Bandwidth:",f.white(s.usage.bandwidth)),s.usage.functionInvocations!=null&&g("Function Invocations:",f.white(String(s.usage.functionInvocations)))),console.log("");}catch(r){e.fail("Failed to fetch project status"),r instanceof Error&&console.log(f.red(`
33
+ Error: ${r.message}`)),process.exit(1);}}var N=process.env.VAIF_API_URL||"https://api.vaif.studio";function go(o){let e=We.createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(o,n=>{e.close(),t(n.trim());});})}function po(o,e,t){return o.projectId||e?.projectId||process.env.VAIF_PROJECT_ID||t.projectId||null}async function uo(o){let e=J("Fetching your projects...").start();try{let t=await fetch(`${N}/projects`,{headers:{Authorization:`Bearer ${o}`}});if(!t.ok)return e.fail("Could not fetch projects"),null;let n=await t.json();if(!n||n.length===0)return e.fail("No projects found. Create a project at https://vaif.studio first."),null;if(n.length===1)return e.succeed(`Found project: ${f.cyan(n[0].name)} (${n[0].id})`),n[0].id;e.succeed(`Found ${n.length} projects
34
+ `);for(let r=0;r<n.length;r++)console.log(f.gray(` ${r+1}.`)+` ${f.white(n[r].name)} ${f.gray(`(${n[r].id})`)}`);console.log("");let i=await go(f.cyan(` Select a project [1-${n.length}]: `)),a=parseInt(i,10)-1;return isNaN(a)||a<0||a>=n.length?(console.log(f.red(`
35
+ Invalid selection.`)),null):n[a].id}catch{return e.fail("Could not fetch projects"),null}}function ho(o){if(!o||o.length===0)return "*No tables found. Create tables in the VAIF Studio dashboard.*";let e="";for(let t of o){e+=`### \`${t.name}\`
36
36
 
37
37
  `,e+=`| Column | Type | Nullable | Default | Constraints |
38
38
  `,e+=`|--------|------|----------|---------|-------------|
39
- `;for(let n of t.columns){let a=[];n.isPrimaryKey&&a.push("PK"),n.nullable||a.push("NOT NULL");let r=t.foreignKeys?.find(i=>i.column===n.name);r&&a.push(`FK \u2192 ${r.foreignTable}.${r.foreignColumn}`),e+=`| ${n.name} | ${n.type} | ${n.nullable?"yes":"no"} | ${n.defaultValue||"-"} | ${a.join(", ")||"-"} |
39
+ `;for(let n of t.columns){let i=[];n.isPrimaryKey&&i.push("PK"),n.nullable||i.push("NOT NULL");let a=t.foreignKeys?.find(r=>r.column===n.name);a&&i.push(`FK \u2192 ${a.foreignTable}.${a.foreignColumn}`),e+=`| ${n.name} | ${n.type} | ${n.nullable?"yes":"no"} | ${n.defaultValue||"-"} | ${i.join(", ")||"-"} |
40
40
  `;}e+=`
41
- `;}return e}function mo(o,e,t){let n=o.slice(0,3);if(n.length===0)return "";let a="";for(let r of n){let i=r.columns.filter(c=>!c.isPrimaryKey&&c.name!=="created_at"&&c.name!=="updated_at"),s=i.slice(0,3).map(c=>` ${c.name}: ${yo(c)}`).join(`,
42
- `);a+=`### \`${r.name}\`
41
+ `;}return e}function mo(o,e,t){let n=o.slice(0,3);if(n.length===0)return "";let i="";for(let a of n){let r=a.columns.filter(c=>!c.isPrimaryKey&&c.name!=="created_at"&&c.name!=="updated_at"),s=r.slice(0,3).map(c=>` ${c.name}: ${yo(c)}`).join(`,
42
+ `);i+=`### \`${a.name}\`
43
43
 
44
- `,a+="```typescript\n",a+=`// Select all
45
- const ${r.name} = await vaif.from("${r.name}").select();
44
+ `,i+="```typescript\n",i+=`// Select all
45
+ const ${a.name} = await vaif.from("${a.name}").select();
46
46
 
47
- `,a+=`// Select with filter
48
- const filtered = await vaif.from("${r.name}").select().eq("${i[0]?.name||"id"}", value);
47
+ `,i+=`// Select with filter
48
+ const filtered = await vaif.from("${a.name}").select().eq("${r[0]?.name||"id"}", value);
49
49
 
50
- `,a+=`// Insert
51
- const created = await vaif.from("${r.name}").insert({
50
+ `,i+=`// Insert
51
+ const created = await vaif.from("${a.name}").insert({
52
52
  ${s}
53
53
  });
54
54
 
55
- `,a+=`// Update
56
- await vaif.from("${r.name}").update(recordId, {
57
- ${i[0]?.name||"name"}: newValue
55
+ `,i+=`// Update
56
+ await vaif.from("${a.name}").update(recordId, {
57
+ ${r[0]?.name||"name"}: newValue
58
58
  });
59
59
 
60
- `,a+=`// Delete
61
- await vaif.from("${r.name}").delete(recordId);
62
- `,a+="```\n\n";}return a}function yo(o){let e=o.type.toLowerCase();return e.includes("uuid")?'"crypto.randomUUID()"':e.includes("int")||e.includes("serial")?"42":e.includes("bool")?"true":e.includes("timestamp")||e.includes("date")?'"new Date().toISOString()"':e.includes("json")?"{}":e.includes("float")||e.includes("numeric")||e.includes("decimal")||e.includes("double")?"3.14":`"example_${o.name}"`}function wo(o){let{projectId:e,apiKey:t,apiUrl:n,projectName:a,schema:r}=o,i=ho(r.tables),s=mo(r.tables);return `# VAIF Studio Backend
60
+ `,i+=`// Delete
61
+ await vaif.from("${a.name}").delete(recordId);
62
+ `,i+="```\n\n",a===n[0]&&(i+=`#### Direct REST API (fetch)
63
63
 
64
- This project uses **VAIF Studio** as its backend. Project: **${a}** (\`${e}\`).
64
+ `,i+="```typescript\n",i+=`// GET all rows (returns { data: [...], count: N })
65
+ `,i+=`const res = await fetch("${e}/generated/${a.name}", {
66
+ `,i+=` headers: { "x-vaif-key": "${t}" },
67
+ `,i+=`});
68
+ `,i+=`const { data } = await res.json();
69
+
70
+ `,i+=`// GET single row (returns { data: {...} })
71
+ `,i+=`const res2 = await fetch("${e}/generated/${a.name}/\${id}", {
72
+ `,i+=` headers: { "x-vaif-key": "${t}" },
73
+ `,i+=`});
74
+ `,i+=`const { data: record } = await res2.json();
75
+ `,i+="```\n\n");}return i}function yo(o){let e=o.type.toLowerCase();return e.includes("uuid")?'"crypto.randomUUID()"':e.includes("int")||e.includes("serial")?"42":e.includes("bool")?"true":e.includes("timestamp")||e.includes("date")?'"new Date().toISOString()"':e.includes("json")?"{}":e.includes("float")||e.includes("numeric")||e.includes("decimal")||e.includes("double")?"3.14":`"example_${o.name}"`}function wo(o){let{projectId:e,apiKey:t,apiUrl:n,projectName:i,schema:a}=o,r=ho(a.tables),s=mo(a.tables,n,t);return `# VAIF Studio Backend
76
+
77
+ This project uses **VAIF Studio** as its backend. Project: **${i}** (\`${e}\`).
65
78
 
66
79
  ## SDK Setup
67
80
 
@@ -81,7 +94,7 @@ const vaif = createVaifClient({
81
94
 
82
95
  ## Database Schema
83
96
 
84
- ${i}
97
+ ${r}
85
98
 
86
99
  ## CRUD Examples
87
100
 
@@ -377,6 +390,50 @@ const result = await vaif.functions.invoke("send_welcome_email", {
377
390
  });
378
391
  \`\`\`
379
392
 
393
+ ### Authenticated Context in Functions
394
+
395
+ Access the caller's verified identity via \\\`vaif.auth\\\`:
396
+
397
+ \`\`\`typescript
398
+ export default async function handler(req) {
399
+ const auth = vaif.auth;
400
+ // auth.type = 'user' | 'api_key' | 'function'
401
+ // auth.userId \u2014 User ID (for user/function types)
402
+ // auth.email \u2014 User email (for user type)
403
+ // auth.projectId \u2014 Always present
404
+ // auth.scopes \u2014 API key scopes (for api_key type)
405
+
406
+ if (!auth || auth.type !== 'user') {
407
+ return { statusCode: 401, body: { error: 'Unauthorized' } };
408
+ }
409
+
410
+ return { body: { message: "Hello " + auth.email } };
411
+ }
412
+ \`\`\`
413
+
414
+ ### Function-to-Function Invocation
415
+
416
+ Call other functions from within a handler:
417
+
418
+ \`\`\`typescript
419
+ export default async function handler(req) {
420
+ const result = await vaif.invoke("send_email", {
421
+ to: "user@example.com",
422
+ subject: "Hello",
423
+ });
424
+ return { statusCode: 200, body: result };
425
+ }
426
+ \`\`\`
427
+
428
+ ### Database Triggers
429
+
430
+ Fire functions automatically on insert/update/delete events. Configure triggers via the API:
431
+
432
+ \`\`\`
433
+ POST /functions/\\\${functionId}/triggers
434
+ { "event": "db.insert", "tableName": "orders", "enabled": true }
435
+ \`\`\`
436
+
380
437
  ## API Key Management
381
438
 
382
439
  API keys are project-scoped and used for data-plane authentication (CRUD, storage, functions).
@@ -463,6 +520,87 @@ The SDK supports these filter operators:
463
520
  | \`ilike\` | Pattern match (case-insensitive) | \`.ilike("name", "%john%")\` |
464
521
  | \`is\` | IS comparison (null, true, false) | \`.is("deleted_at", null)\` |
465
522
 
523
+ ### JSONB Subkey Filters
524
+
525
+ Filter on nested JSONB fields using arrow notation:
526
+
527
+ | Filter | SQL Generated |
528
+ |--------|--------------|
529
+ | \\\`filter[metadata->status]=active\\\` | \\\`metadata->>'status' = 'active'\\\` |
530
+ | \\\`filter[config->theme.ilike]=%dark%\\\` | \\\`config->>'theme' ILIKE '%dark%'\\\` |
531
+ | \\\`filter[data->user->role]=admin\\\` | \\\`data->'user'->>'role' = 'admin'\\\` |
532
+
533
+ All standard operators work with JSONB paths. The last segment uses \\\`->>\\\` (text extraction).
534
+
535
+ ### Compound Filters (AND + OR)
536
+
537
+ Combine AND and OR conditions:
538
+
539
+ \`\`\`
540
+ ?filter[status]=active&or_filter[role]=admin&or_filter[role]=moderator
541
+ \`\`\`
542
+
543
+ This generates: \\\`WHERE status = 'active' AND (role = 'admin' OR role = 'moderator')\\\`
544
+
545
+ ### Full-Text Search
546
+
547
+ \`\`\`typescript
548
+ const results = await fetch("${n}/generated/posts/search", {
549
+ method: "POST",
550
+ headers: { "x-vaif-key": "${t}", "Content-Type": "application/json" },
551
+ body: JSON.stringify({
552
+ query: "search term",
553
+ columns: ["title", "body"],
554
+ limit: 20,
555
+ }),
556
+ });
557
+ // Results ranked by ts_rank score
558
+ \`\`\`
559
+
560
+ ### Aggregation
561
+
562
+ \`\`\`typescript
563
+ const stats = await fetch("${n}/generated/orders/aggregate", {
564
+ method: "POST",
565
+ headers: { "x-vaif-key": "${t}", "Content-Type": "application/json" },
566
+ body: JSON.stringify({
567
+ aggregates: [
568
+ { fn: "count", column: "*" },
569
+ { fn: "sum", column: "total" },
570
+ { fn: "avg", column: "total" },
571
+ ],
572
+ groupBy: ["status"],
573
+ }),
574
+ });
575
+ \`\`\`
576
+
577
+ ### Joins (Foreign Key Includes)
578
+
579
+ Include related rows by specifying foreign key columns:
580
+
581
+ \`\`\`
582
+ GET /generated/posts?include=author_id&include=category_id
583
+ \`\`\`
584
+
585
+ Returns posts with \\\`author_id_included\\\` and \\\`category_id_included\\\` objects containing the related rows.
586
+
587
+ ### Upsert
588
+
589
+ Insert or update on conflict:
590
+
591
+ \`\`\`typescript
592
+ const result = await fetch("${n}/generated/users", {
593
+ method: "POST",
594
+ headers: { "x-vaif-key": "${t}", "Content-Type": "application/json" },
595
+ body: JSON.stringify({
596
+ email: "alice@example.com",
597
+ name: "Alice",
598
+ _upsert: true,
599
+ _conflictColumns: ["email"],
600
+ }),
601
+ });
602
+ \`\`\`
603
+
466
604
  ### Pagination
467
605
 
468
606
  \`\`\`typescript
@@ -471,6 +609,44 @@ const page1 = await vaif.from("posts").select().limit(20).offset(0);
471
609
  const page2 = await vaif.from("posts").select().limit(20).offset(20);
472
610
  \`\`\`
473
611
 
612
+ ### REST API Response Format
613
+
614
+ When calling the REST API directly (without the SDK), all data-plane responses are wrapped:
615
+
616
+ \`\`\`typescript
617
+ // GET /generated/{table} \u2192 list
618
+ { data: [...], count: 5 }
619
+
620
+ // GET /generated/{table}/{id} \u2192 single record
621
+ { data: { id: "...", ... } }
622
+
623
+ // POST /generated/{table} \u2192 created record
624
+ { data: { id: "...", ... } }
625
+
626
+ // PATCH /generated/{table}/{id} \u2192 updated record
627
+ { data: { id: "...", ... } }
628
+
629
+ // DELETE /generated/{table}/{id}
630
+ { ok: true }
631
+
632
+ // Error responses
633
+ { error: "NotFound", message: "...", requestId: "..." }
634
+ \`\`\`
635
+
636
+ The SDK unwraps these automatically, but if you use \`fetch()\` directly, access the data via \`response.data\`.
637
+
638
+ ### Numeric/Decimal Column Serialization
639
+
640
+ PostgreSQL \`numeric\` and \`decimal\` columns serialize to **JSON strings** (to preserve arbitrary precision). This is standard behavior. Any column typed as \`numeric\` or \`decimal\` will arrive as \`"3.14"\` not \`3.14\`.
641
+
642
+ \`\`\`typescript
643
+ // Wrong \u2014 value is a string, comparison may fail
644
+ if (item.price > 10.0) { ... }
645
+
646
+ // Correct \u2014 parse before arithmetic
647
+ if (parseFloat(item.price) > 10.0) { ... }
648
+ \`\`\`
649
+
474
650
  ### Auth Headers
475
651
 
476
652
  VAIF uses **two auth modes** \u2014 choose the right one for each operation:
@@ -489,14 +665,18 @@ The \`.mcp.json\` file configures an MCP server that gives Claude Code direct ac
489
665
  | Tool | What it does |
490
666
  |------|-------------|
491
667
  | \`list_tables\`, \`describe_table\` | Inspect database schema |
492
- | \`query_rows\`, \`insert_row\`, \`update_row\`, \`delete_row\` | CRUD operations on any table |
493
- | \`create_function\`, \`deploy_function\`, \`invoke_function\` | Create, deploy, and call serverless functions |
494
- | \`create_bucket\`, \`list_buckets\`, \`list_files\`, \`get_signed_url\` | Storage management |
495
- | \`enable_realtime\`, \`realtime_status\` | Enable/check realtime subscriptions |
496
668
  | \`get_schema\` | Full schema as JSON |
669
+ | \`create_tables\` | Create or update tables declaratively |
670
+ | \`query_rows\` | Query with filters, JSONB paths, pagination |
671
+ | \`insert_row\`, \`update_row\`, \`delete_row\` | CRUD operations on any table |
672
+ | \`list_functions\`, \`deploy_function\`, \`invoke_function\` | Function management |
673
+ | \`get_function_logs\` | Execution history with status filters |
674
+ | \`set_secret\`, \`list_secrets\`, \`delete_secret\` | Function secrets |
675
+ | \`list_buckets\`, \`list_files\`, \`get_signed_url\` | Storage operations |
676
+ | \`enable_realtime\`, \`realtime_status\` | Realtime subscriptions |
497
677
 
498
678
  > **Note**: MCP tools are only available to the main Claude Code session, not to spawned sub-agents (Task tool). The main session should handle all VAIF backend operations directly.
499
- `}async function Oe(o){let e=B(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",a$1=null;try{a$1=await a(n);}catch{}let r=po(o,a$1,t);r||(console.log(f.yellow(`No project ID specified \u2014 fetching your projects...
500
- `)),r=await uo(t.token),r||(console.log(f.gray(`
501
- Tip: pass --project-id <id> or set projectId in vaif.config.json`)),process.exit(1)));let i=$.resolve(o.outputDir||".");console.log(""),console.log(f.bold("VAIF Claude Code Setup")),console.log(f.gray(` Project: ${r}`)),console.log(""),e.start("Fetching database schema...");let s={tables:[]};try{let d=await fetch(`${N}/schema-engine/introspect/${r}`,{headers:{Authorization:`Bearer ${t.token}`}});d.ok?(s=await d.json(),e.succeed(`Fetched schema (${s.tables?.length||0} tables)`)):e.warn("Could not fetch schema \u2014 continuing without it");}catch{e.warn("Could not fetch schema \u2014 continuing without it");}e.start("Fetching project info...");let c=r,g=N;try{let d=await fetch(`${N}/projects/${r}`,{headers:{Authorization:`Bearer ${t.token}`}});if(d.ok){let l=await d.json(),u=l.project||l;c=u.name||r,g=u.apiUrl||N,e.succeed(`Project: ${c}`);}else e.warn("Could not fetch project info \u2014 using defaults");}catch{e.warn("Could not fetch project info \u2014 using defaults");}let p=o.apiKey||a$1?.api?.apiKey||"";if(!p){e.start("Generating API key for Claude Code...");try{let d=`claude-code-${Date.now()}`,l=await fetch(`${N}/projects/${r}/api-keys`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:d,scopes:["crud","realtime","functions","storage"]})});if(l.ok){let u=await l.json();p=u.apiKey||u.key,e.succeed(`Generated API key: ${d}`);}else e.fail("Could not auto-generate API key"),console.log(f.yellow(" Pass one with --api-key or generate via `vaif keys generate`")),process.exit(1);}catch{e.fail("Could not auto-generate API key"),console.log(f.yellow(" Pass one with --api-key or generate via `vaif keys generate`")),process.exit(1);}}if(!o.skipMcp){e.start("Writing .mcp.json...");let d={mcpServers:{"vaif-studio":{command:"npx",args:["@vaiftech/mcp"],env:{VAIF_API_KEY:p,VAIF_PROJECT_ID:r,VAIF_API_URL:g,VAIF_AUTH_TOKEN:t.token}}}},l=$.join(i,".mcp.json");F.writeFileSync(l,JSON.stringify(d,null,2)+`
502
- `,"utf-8"),e.succeed(`Written ${f.cyan(".mcp.json")}`);}if(!o.skipClaudeMd){e.start("Writing CLAUDE.md...");let d=wo({projectId:r,apiKey:p,apiUrl:g,projectName:c,schema:s}),l=$.join(i,"CLAUDE.md");F.writeFileSync(l,d,"utf-8"),e.succeed(`Written ${f.cyan("CLAUDE.md")}`);}console.log(""),console.log(f.green.bold(" Claude Code integration configured!")),console.log(""),o.skipMcp||console.log(f.gray(" MCP Server: ")+f.white(".mcp.json")),o.skipClaudeMd||console.log(f.gray(" Context: ")+f.white("CLAUDE.md")),console.log(""),console.log(f.bold(" Next steps:")),console.log(f.gray(" 1. Open this project in Claude Code")),console.log(f.gray(" 2. The MCP server auto-connects to your VAIF project")),console.log(f.gray(" 3. Ask Claude to query, modify, or build against your schema")),console.log("");}var Ne="1.9.6",X=f.hex("#00f0ff"),Z=f.hex("#7b61ff"),ee=f.hex("#ff3dff"),oe=f.hex("#00ff9d"),j=f.hex("#555570"),O=f.hex("#00f0ff");function jo(){console.log(""),console.log(X(" \u2566 \u2566")+Z("\u2554\u2550\u2557\u2566")+ee("\u2554\u2550\u2557 ")+oe("\u2554\u2550\u2557\u2566 \u2566")),console.log(X(" \u255A\u2557\u2554\u255D")+Z("\u2560\u2550\u2563\u2551")+ee("\u2560\u2563 ")+oe("\u2551 \u2551 \u2551")),console.log(X(" \u255A\u255D ")+Z("\u2569 \u2569\u2569")+ee("\u255A ")+oe("\u255A\u2550\u255D\u2569\u2550\u255D\u2569")),console.log(""),console.log(j(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(O(" VAIF Studio CLI")+j(` v${Ne}`)),console.log(j(" Build full-stack apps at lightning speed")),console.log(j(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(""),console.log(f.bold(" Quick Start")),console.log(j(" $ ")+O("vaif login")+j(" Authenticate")),console.log(j(" $ ")+O("vaif init -t react-spa")+j(" Scaffold project")),console.log(j(" $ ")+O("vaif db push")+j(" Push migrations")),console.log(j(" $ ")+O("vaif generate")+j(" Generate types")),console.log(j(" $ ")+O("vaif functions deploy")+j(" Deploy functions")),console.log(""),console.log(f.bold(" Categories")),console.log(j(" auth ")+f.white("login, logout, whoami")),console.log(j(" project ")+f.white("init, templates, info, status")),console.log(j(" schema ")+f.white("pull, push, generate")),console.log(j(" database ")+f.white("db push, db pull, db seed, db reset")),console.log(j(" deploy ")+f.white("functions deploy, functions list")),console.log(j(" security ")+f.white("keys, secrets")),console.log(j(" ai ")+f.white("claude-setup")),console.log(""),console.log(j(" Run ")+O("vaif <command> --help")+j(" for details")),console.log(j(" Docs: ")+f.underline("https://docs.vaif.studio")),console.log("");}program.name("vaif").description("VAIF CLI - Type generation and development tools").version(Ne);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(c);program.command("logout").description("Log out and remove stored credentials").action(d);program.command("whoami").description("Show current authenticated user").action(e);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").option("--add-features <features>","Add features to an existing project (requires --template)").action(h);program.command("templates").alias("tpl").description("List available project templates").action(g);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(De);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(Te);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(ce);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(fe);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(f$1);var Le=program.command("functions").alias("fn").description("Manage serverless functions");Le.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(he);Le.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(me);var G=program.command("db").description("Database management commands");G.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(je);G.command("pull").description("Pull schema from VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-o, --output <path>","Output file","vaif.schema.json").action(ve);G.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(we);G.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(Ie);var Ve=program.command("keys").description("Manage API keys");Ve.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(ke);Ve.command("list").alias("ls").description("List API keys").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").action(Ae);var Y=program.command("secrets").alias("sec").description("Manage function secrets");Y.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(Pe);Y.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(Ce);Y.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(Ee);Y.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(xe);program.command("claude-setup").description("Configure Claude Code integration (MCP server + CLAUDE.md)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID").option("-k, --api-key <key>","API key for MCP server").option("--skip-mcp","Skip generating .mcp.json").option("--skip-claude-md","Skip generating CLAUDE.md").option("-o, --output-dir <dir>","Output directory",".").action(Oe);process.argv.slice(2).length||(jo(),process.exit(0));program.parse(process.argv);
679
+ `}async function Oe(o){let e=J(),t=b();(!t||!t.token)&&(console.log(f.red("Not logged in")),console.log(f.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=o.config||"vaif.config.json",i=null;try{i=await a(n);}catch{}let a$1=po(o,i,t);a$1||(console.log(f.yellow(`No project ID specified \u2014 fetching your projects...
680
+ `)),a$1=await uo(t.token),a$1||(console.log(f.gray(`
681
+ Tip: pass --project-id <id> or set projectId in vaif.config.json`)),process.exit(1)));let r=b$1.resolve(o.outputDir||".");console.log(""),console.log(f.bold("VAIF Claude Code Setup")),console.log(f.gray(` Project: ${a$1}`)),console.log(""),e.start("Fetching database schema...");let s={tables:[]};try{let d=await fetch(`${N}/schema-engine/introspect/${a$1}`,{headers:{Authorization:`Bearer ${t.token}`}});d.ok?(s=await d.json(),e.succeed(`Fetched schema (${s.tables?.length||0} tables)`)):e.warn("Could not fetch schema \u2014 continuing without it");}catch{e.warn("Could not fetch schema \u2014 continuing without it");}e.start("Fetching project info...");let c=a$1,g=N;try{let d=await fetch(`${N}/projects/${a$1}`,{headers:{Authorization:`Bearer ${t.token}`}});if(d.ok){let l=await d.json(),u=l.project||l;c=u.name||a$1,g=u.apiUrl||N,e.succeed(`Project: ${c}`);}else e.warn("Could not fetch project info \u2014 using defaults");}catch{e.warn("Could not fetch project info \u2014 using defaults");}let p=o.apiKey||i?.api?.apiKey||"";if(!p){e.start("Generating API key for Claude Code...");try{let d=`claude-code-${Date.now()}`,l=await fetch(`${N}/projects/${a$1}/api-keys`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:d,scopes:["crud","realtime","functions","storage"]})});if(l.ok){let u=await l.json();p=u.apiKey||u.key,e.succeed(`Generated API key: ${d}`);}else e.fail("Could not auto-generate API key"),console.log(f.yellow(" Pass one with --api-key or generate via `vaif keys generate`")),process.exit(1);}catch{e.fail("Could not auto-generate API key"),console.log(f.yellow(" Pass one with --api-key or generate via `vaif keys generate`")),process.exit(1);}}if(!o.skipMcp){e.start("Writing .mcp.json...");let d={mcpServers:{"vaif-studio":{command:"npx",args:["@vaiftech/mcp"],env:{VAIF_API_KEY:p,VAIF_PROJECT_ID:a$1,VAIF_API_URL:g,VAIF_AUTH_TOKEN:t.token}}}},l=b$1.join(r,".mcp.json");F.writeFileSync(l,JSON.stringify(d,null,2)+`
682
+ `,"utf-8"),e.succeed(`Written ${f.cyan(".mcp.json")}`);}if(!o.skipClaudeMd){e.start("Writing CLAUDE.md...");let d=wo({projectId:a$1,apiKey:p,apiUrl:g,projectName:c,schema:s}),l=b$1.join(r,"CLAUDE.md");F.writeFileSync(l,d,"utf-8"),e.succeed(`Written ${f.cyan("CLAUDE.md")}`);}console.log(""),console.log(f.green.bold(" Claude Code integration configured!")),console.log(""),o.skipMcp||console.log(f.gray(" MCP Server: ")+f.white(".mcp.json")),o.skipClaudeMd||console.log(f.gray(" Context: ")+f.white("CLAUDE.md")),console.log(""),console.log(f.bold(" Next steps:")),console.log(f.gray(" 1. Open this project in Claude Code")),console.log(f.gray(" 2. The MCP server auto-connects to your VAIF project")),console.log(f.gray(" 3. Ask Claude to query, modify, or build against your schema")),console.log("");}var vo=createRequire(import.meta.url),{version:Ne}=vo("../package.json"),X=f.hex("#00f0ff"),Z=f.hex("#7b61ff"),ee=f.hex("#ff3dff"),oe=f.hex("#00ff9d"),j=f.hex("#555570"),O=f.hex("#00f0ff");function Io(){console.log(""),console.log(X(" \u2566 \u2566")+Z("\u2554\u2550\u2557\u2566")+ee("\u2554\u2550\u2557 ")+oe("\u2554\u2550\u2557\u2566 \u2566")),console.log(X(" \u255A\u2557\u2554\u255D")+Z("\u2560\u2550\u2563\u2551")+ee("\u2560\u2563 ")+oe("\u2551 \u2551 \u2551")),console.log(X(" \u255A\u255D ")+Z("\u2569 \u2569\u2569")+ee("\u255A ")+oe("\u255A\u2550\u255D\u2569\u2550\u255D\u2569")),console.log(""),console.log(j(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(O(" VAIF Studio CLI")+j(` v${Ne}`)),console.log(j(" Build full-stack apps at lightning speed")),console.log(j(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(""),console.log(f.bold(" Quick Start")),console.log(j(" $ ")+O("vaif login")+j(" Authenticate")),console.log(j(" $ ")+O("vaif init -t react-spa")+j(" Scaffold project")),console.log(j(" $ ")+O("vaif db push")+j(" Push migrations")),console.log(j(" $ ")+O("vaif generate")+j(" Generate types")),console.log(j(" $ ")+O("vaif functions deploy")+j(" Deploy functions")),console.log(""),console.log(f.bold(" Categories")),console.log(j(" auth ")+f.white("login, logout, whoami")),console.log(j(" project ")+f.white("init, templates, info, status")),console.log(j(" schema ")+f.white("pull, push, generate")),console.log(j(" database ")+f.white("db push, db pull, db seed, db reset")),console.log(j(" deploy ")+f.white("functions deploy, functions list")),console.log(j(" security ")+f.white("keys, secrets")),console.log(j(" ai ")+f.white("claude-setup")),console.log(""),console.log(j(" Run ")+O("vaif <command> --help")+j(" for details")),console.log(j(" Docs: ")+f.underline("https://docs.vaif.studio")),console.log("");}program.name("vaif").description("VAIF CLI - Type generation and development tools").version(Ne);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(c);program.command("logout").description("Log out and remove stored credentials").action(d);program.command("whoami").description("Show current authenticated user").action(e);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").option("--add-features <features>","Add features to an existing project (requires --template)").action(h);program.command("templates").alias("tpl").description("List available project templates").action(g);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(Te);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(ce);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(fe);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(f$1);var Le=program.command("functions").alias("fn").description("Manage serverless functions");Le.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(he);Le.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(me);var G=program.command("db").description("Database management commands");G.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(je);G.command("pull").description("Pull schema from VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-o, --output <path>","Output file","vaif.schema.json").action(ve);G.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(we);G.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(Ie);var Ue=program.command("keys").description("Manage API keys");Ue.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(ke);Ue.command("list").alias("ls").description("List API keys").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").action(Ae);var H=program.command("secrets").alias("sec").description("Manage function secrets");H.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(Pe);H.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(Ce);H.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(Ee);H.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(xe);program.command("claude-setup").description("Configure Claude Code integration (MCP server + CLAUDE.md)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID").option("-k, --api-key <key>","API key for MCP server").option("--skip-mcp","Skip generating .mcp.json").option("--skip-claude-md","Skip generating CLAUDE.md").option("-o, --output-dir <dir>","Output directory",".").action(Oe);process.argv.slice(2).length||(Io(),process.exit(0));program.parse(process.argv);