@vaiftech/cli 1.6.3 → 1.6.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -1
- package/dist/{chunk-M7YUCF3X.js → chunk-OB2QEQ2L.js} +26 -24
- package/dist/cli.cjs +58 -56
- package/dist/cli.js +36 -36
- package/dist/index.cjs +18 -16
- package/dist/index.d.cts +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,42 +1,42 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {d,c,b,a}from'./chunk-
|
|
3
|
-
Could not connect to VAIF API. Please try again later.`)),process.exit(1));let c=await n.json();t=c.code,
|
|
4
|
-
Could not connect to VAIF API.`)),console.log(l.gray("Check your internet connection or try: vaif login --email")),process.exit(1);}o.stop(),console.log(l.cyan(" Opening browser for authentication...")),console.log(""),console.log(l.gray(" If the browser doesn't open, visit this URL:")),console.log(l.white(` ${
|
|
5
|
-
The authentication session expired. Please try again.`)),process.exit(1));continue}let c=await n.json();if(c.ok&&c.accessToken){let f={token:c.accessToken,email:c.user?.email,projectId:e,expiresAt:new Date(Date.now()+c.expiresIn*1e3).toISOString()};
|
|
6
|
-
Timed out waiting for browser authentication.`)),console.log(l.gray("Try again or use: vaif login --email")),process.exit(1);}async function
|
|
7
|
-
No email provided. Login cancelled.`)),process.exit(1));let t=await
|
|
8
|
-
No password provided. Login cancelled.`)),process.exit(1));let
|
|
9
|
-
${
|
|
10
|
-
Could not connect to VAIF API. Please try again later.`)),process.exit(1);}}async function
|
|
11
|
-
Your session has expired. Please login again.`)),process.exit(1)),o.succeed("Authenticated"),console.log(""),console.log(l.green(` Email: ${
|
|
12
|
-
Error: ${
|
|
13
|
-
Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1)),o.text="Fetching remote schema...";try{let
|
|
14
|
-
Error: ${
|
|
15
|
-
Error: ${c}`)),process.exit(1);}
|
|
16
|
-
Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1));let
|
|
17
|
-
Expected schema file at: ${
|
|
18
|
-
Error: ${c.message}`)),process.exit(1);}o.text="Calculating schema changes...";try{let{diff:c,sql:f}=await
|
|
19
|
-
Cancelled. No changes applied.`));return}}o.start("Applying schema changes...");let p=await
|
|
20
|
-
Error: ${c.message}`)),process.exit(1);}}var
|
|
2
|
+
import {d,c,b,a}from'./chunk-OB2QEQ2L.js';import'dotenv/config';import {program}from'commander';import k from'fs';import w from'path';import Ve from'os';import {exec}from'child_process';import U from'ora';import l from'chalk';import oe from'readline';var G=w.join(Ve.homedir(),".vaif"),O=w.join(G,"auth.json"),_=process.env.VAIF_API_URL||"https://api.vaif.studio";function Le(){k.existsSync(G)||k.mkdirSync(G,{recursive:true});}function te(e){Le(),k.writeFileSync(O,JSON.stringify(e,null,2),"utf-8"),k.chmodSync(O,384);}function v(){if(!k.existsSync(O))return null;try{let e=k.readFileSync(O,"utf-8");return JSON.parse(e)}catch{return null}}function Te(e){let o=oe.createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{o.question(e,s=>{o.close(),t(s);});})}function _e(e){return new Promise(o=>{let t=oe.createInterface({input:process.stdin,output:process.stdout});process.stdin;let a=process.stdout.write.bind(process.stdout),r=false;process.stdout.write=((...i)=>r?true:a(...i)),t.question(e,i=>{r=false,process.stdout.write=a,console.log(""),t.close(),o(i);}),r=true;})}function Ue(e){let o=process.platform,t;o==="darwin"?t=`open "${e}"`:o==="win32"?t=`start "" "${e}"`:t=`xdg-open "${e}"`,exec(t,s=>{});}function ze(e){return new Promise(o=>setTimeout(o,e))}async function Je(e){try{let o=await fetch(`${_}/auth/me`,{headers:{Authorization:`Bearer ${e}`}});if(o.ok){let t=await o.json();return {valid:!0,email:t.user?.email||t.email}}return {valid:!1}}catch{return {valid:false}}}async function Be(e){let o=U();o.start("Setting up authentication...");let t,s;try{let n=await fetch(`${_}/auth/cli/authorize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})});n.ok||(o.fail("Failed to initiate authentication"),console.log(l.red(`
|
|
3
|
+
Could not connect to VAIF API. Please try again later.`)),process.exit(1));let c=await n.json();t=c.code,s=c.url;}catch{o.fail("Failed to connect to VAIF API"),console.log(l.red(`
|
|
4
|
+
Could not connect to VAIF API.`)),console.log(l.gray("Check your internet connection or try: vaif login --email")),process.exit(1);}o.stop(),console.log(l.cyan(" Opening browser for authentication...")),console.log(""),console.log(l.gray(" If the browser doesn't open, visit this URL:")),console.log(l.white(` ${s}`)),console.log(""),Ue(s),o.start("Waiting for browser authentication...");let a=12e4,r=2e3,i=Date.now();for(;Date.now()-i<a;){await ze(r);try{let n=await fetch(`${_}/auth/cli/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!n.ok){let f=await n.json();(f.error==="ExpiredCode"||f.error==="InvalidCode")&&(o.fail("Authentication expired"),console.log(l.red(`
|
|
5
|
+
The authentication session expired. Please try again.`)),process.exit(1));continue}let c=await n.json();if(c.ok&&c.accessToken){let f={token:c.accessToken,email:c.user?.email,projectId:e,expiresAt:new Date(Date.now()+c.expiresIn*1e3).toISOString()};te(f),o.succeed("Logged in successfully"),console.log(""),c.user?.email&&console.log(l.green(` Authenticated as: ${c.user.email}`)),console.log(l.gray(` Config saved to: ${O}`)),console.log("");return}}catch{}}o.fail("Authentication timed out"),console.log(l.red(`
|
|
6
|
+
Timed out waiting for browser authentication.`)),console.log(l.gray("Try again or use: vaif login --email")),process.exit(1);}async function Ke(e){console.log(""),console.log(l.bold("VAIF CLI Login")),console.log(l.gray("Enter your VAIF account credentials")),console.log("");let o=await Te(l.cyan(" Email: "));(!o||o.trim()==="")&&(console.log(l.red(`
|
|
7
|
+
No email provided. Login cancelled.`)),process.exit(1));let t=await _e(l.cyan(" Password: "));(!t||t.trim()==="")&&(console.log(l.red(`
|
|
8
|
+
No password provided. Login cancelled.`)),process.exit(1));let s=U("Authenticating...").start();try{let a=await fetch(`${_}/auth/cli/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:o.trim(),password:t})}),r=await a.json();(!a.ok||!r.ok)&&(s.fail("Login failed"),console.log(l.red(`
|
|
9
|
+
${r.message||"Invalid email or password."}`)),process.exit(1));let i={token:r.accessToken,email:r.user?.email,projectId:e,expiresAt:new Date(Date.now()+r.expiresIn*1e3).toISOString()};te(i),s.succeed("Logged in successfully"),console.log(""),r.user?.email&&console.log(l.green(` Authenticated as: ${r.user.email}`)),console.log(l.gray(` Config saved to: ${O}`)),console.log("");}catch{s.fail("Failed to connect to VAIF API"),console.log(l.red(`
|
|
10
|
+
Could not connect to VAIF API. Please try again later.`)),process.exit(1);}}async function ne(e){console.log(""),console.log(l.bold("Welcome to VAIF CLI")),console.log(l.gray("Authenticate to access your VAIF projects")),console.log(""),e.email?await Ke(e.projectId):await Be(e.projectId),console.log(l.gray("You can now use VAIF CLI commands like:")),console.log(l.gray(" vaif pull - Pull remote schema")),console.log(l.gray(" vaif push - Push schema changes")),console.log(l.gray(" vaif generate - Generate TypeScript types")),console.log("");}async function se(){k.existsSync(O)?(k.unlinkSync(O),console.log(l.green("Logged out successfully"))):console.log(l.yellow("Not currently logged in"));}async function ie(){let e=v();(!e||!e.token)&&(console.log(l.yellow("Not logged in")),console.log(l.gray("Run `vaif login` to authenticate")),process.exit(1));let o=U("Checking authentication...").start(),{valid:t,email:s}=await Je(e.token);t||(o.fail("Session expired"),console.log(l.yellow(`
|
|
11
|
+
Your session has expired. Please login again.`)),process.exit(1)),o.succeed("Authenticated"),console.log(""),console.log(l.green(` Email: ${s||e.email||"Unknown"}`)),e.projectId&&console.log(l.green(` Project: ${e.projectId}`)),console.log("");}var Ge=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Ye(e,o,t="public"){let s=await fetch(`${Ge}/v1/projects/${o}/schema?schema=${t}`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});if(!s.ok){let a=await s.text();throw new Error(`Failed to fetch schema: ${a}`)}return s.json()}async function re(e){let o=U(),t=v();(!t||!t.token)&&(console.log(l.red("Not logged in")),console.log(l.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",a$1=null;o.start("Loading configuration...");try{a$1=await a(s);}catch(i){o.fail("Failed to load config"),console.log(l.red(`
|
|
12
|
+
Error: ${i}`)),process.exit(1);}a$1||(o.fail("No configuration found"),console.log(l.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let r=e.projectId||a$1.projectId||process.env.VAIF_PROJECT_ID||t.projectId;r||(o.fail("No project ID specified"),console.log(l.yellow(`
|
|
13
|
+
Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1)),o.text="Fetching remote schema...";try{let i=e.schema||a$1.database?.schema||"public",n=await Ye(t.token,r,i);o.succeed("Schema fetched successfully");let c=e.output||w.resolve("vaif.schema.json"),f={$schema:"https://vaif.studio/schemas/schema.json",projectId:r,schema:i,pulledAt:new Date().toISOString(),...n};k.writeFileSync(c,JSON.stringify(f,null,2),"utf-8"),console.log(""),console.log(l.green(`Schema saved to: ${c}`)),console.log(""),console.log(l.gray("Schema summary:")),console.log(l.gray(` Tables: ${(n.tables||[]).length}`)),console.log(l.gray(` Enums: ${(n.enums||[]).length}`)),console.log(l.gray(` Functions: ${(n.functions||[]).length}`)),console.log(""),console.log(l.gray("Next steps:")),console.log(l.gray(" - Run `vaif generate` to generate TypeScript types")),console.log(l.gray(" - Edit the schema and run `vaif push` to deploy changes")),console.log("");}catch(i){o.fail("Failed to fetch schema"),i instanceof Error&&console.log(l.red(`
|
|
14
|
+
Error: ${i.message}`)),process.exit(1);}}var ae=process.env.VAIF_API_URL||"https://api.vaif.studio";function Ze(e){let o=oe.createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{o.question(e,s=>{o.close(),t(s);});})}async function eo(e,o,t){let s=await fetch(`${ae}/v1/projects/${o}/schema/preview`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({schema:t})});if(!s.ok){let a=await s.text();throw new Error(`Failed to preview changes: ${a}`)}return s.json()}async function oo(e,o,t){let s=await fetch(`${ae}/v1/projects/${o}/schema/apply`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({schema:t})});if(!s.ok){let a=await s.text();throw new Error(`Failed to apply changes: ${a}`)}return s.json()}function to(e){if(console.log(""),console.log(l.bold("Schema Changes:")),console.log(""),e.added.length===0&&e.modified.length===0&&e.removed.length===0){console.log(l.gray(" No changes detected. Schema is up to date."));return}if(e.added.length>0){console.log(l.green.bold(" + Added:"));for(let o of e.added)console.log(l.green(` + ${o.type}: ${o.name}`));console.log("");}if(e.modified.length>0){console.log(l.yellow.bold(" ~ Modified:"));for(let o of e.modified){console.log(l.yellow(` ~ ${o.type}: ${o.name}`));for(let t of o.changes)console.log(l.gray(` ${t}`));}console.log("");}if(e.removed.length>0){console.log(l.red.bold(" - Removed:"));for(let o of e.removed)console.log(l.red(` - ${o.type}: ${o.name}`));console.log("");}}async function le(e){let o=U(),t=v();(!t||!t.token)&&(console.log(l.red("Not logged in")),console.log(l.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",a$1=null;o.start("Loading configuration...");try{a$1=await a(s);}catch(c){o.fail("Failed to load config"),console.log(l.red(`
|
|
15
|
+
Error: ${c}`)),process.exit(1);}a$1||(o.fail("No configuration found"),console.log(l.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let r=e.projectId||a$1.projectId||process.env.VAIF_PROJECT_ID||t.projectId;r||(o.fail("No project ID specified"),console.log(l.yellow(`
|
|
16
|
+
Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1));let i=e.schema||w.resolve("vaif.schema.json");k.existsSync(i)||(o.fail("No local schema found"),console.log(l.yellow(`
|
|
17
|
+
Expected schema file at: ${i}`)),console.log(l.gray("Run `vaif pull` first to fetch the current schema.")),process.exit(1));let n;try{let c=k.readFileSync(i,"utf-8");n=JSON.parse(c);}catch(c){o.fail("Failed to parse schema file"),c instanceof Error&&console.log(l.red(`
|
|
18
|
+
Error: ${c.message}`)),process.exit(1);}o.text="Calculating schema changes...";try{let{diff:c,sql:f}=await eo(t.token,r,n);if(o.stop(),to(c),c.added.length===0&&c.modified.length===0&&c.removed.length===0){console.log("");return}if(f.length>0){console.log(l.bold("SQL Migrations:")),console.log("");for(let d of f)console.log(l.gray(` ${d}`));console.log("");}if(e.dryRun){console.log(l.yellow("Dry run mode - no changes applied.")),console.log(l.gray("Remove --dry-run to apply these changes."));return}if(!e.force){c.removed.length>0&&(console.log(l.red.bold("\u26A0\uFE0F Warning: This will remove tables/columns from your database.")),console.log(l.red(" This action cannot be undone!")),console.log(""));let g=await Ze(l.cyan("Apply these changes? [y/N] "));if(g.toLowerCase()!=="y"&&g.toLowerCase()!=="yes"){console.log(l.yellow(`
|
|
19
|
+
Cancelled. No changes applied.`));return}}o.start("Applying schema changes...");let p=await oo(t.token,r,n);if(p.success){if(o.succeed("Schema changes applied successfully"),console.log(""),p.migrations.length>0){console.log(l.gray("Migrations applied:"));for(let d of p.migrations)console.log(l.gray(` - ${d}`));console.log("");}console.log(l.green("Your database schema is now up to date.")),console.log(l.gray("Run `vaif generate` to update your TypeScript types.")),console.log("");}else o.fail("Failed to apply some changes");}catch(c){o.fail("Failed to push schema changes"),c instanceof Error&&console.log(l.red(`
|
|
20
|
+
Error: ${c.message}`)),process.exit(1);}}var pe=process.env.VAIF_API_URL||"https://api.vaif.studio";async function no(e,o,t){let s=await fetch(`${pe}/v1/projects/${o}/functions`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({name:t.name,runtime:t.runtime,entrypoint:t.entrypoint,code:t.code,envId:t.envId})});if(!s.ok){let a=await s.text();throw new Error(`Failed to deploy function: ${a}`)}return s.json()}async function so(e,o,t){let s=new URL(`${pe}/v1/projects/${o}/functions`);t&&s.searchParams.set("envId",t);let a=await fetch(s.toString(),{headers:{Authorization:`Bearer ${e}`}});if(!a.ok){let r=await a.text();throw new Error(`Failed to list functions: ${r}`)}return a.json()}function ge(e){switch(w.extname(e).toLowerCase()){case ".ts":return "typescript";case ".js":case ".mjs":return "nodejs";case ".py":return "python";case ".go":return "go";case ".rs":return "rust";default:return "nodejs"}}function fe(e){let o=[],t=[".ts",".js",".mjs",".py",".go",".rs"],s=["drizzle.config.ts","tsconfig.json","package.json"];if(!k.existsSync(e))return o;let a=k.readdirSync(e,{withFileTypes:true});for(let r of a){let i=w.join(e,r.name);if(r.isDirectory()){if(r.name!=="node_modules"&&!r.name.startsWith(".")){let n=k.readdirSync(i,{withFileTypes:true});for(let c of n)if(c.isFile()){let f=w.extname(c.name).toLowerCase();if(t.includes(f)){o.push(w.join(i,c.name));break}}}}else if(r.isFile()){let n=w.extname(r.name).toLowerCase();t.includes(n)&&!s.includes(r.name)&&o.push(i);}}return o}async function ue(e){let o=U(),t=v();(!t||!t.token)&&(console.log(l.red("Not logged in")),console.log(l.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",a$1=null;try{a$1=await a(s);}catch{}let r=e.projectId||a$1?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;r||(console.log(l.red("No project ID specified")),console.log(l.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(l.bold("VAIF Functions Deploy")),console.log(""),o.start("Scanning for function files...");let i=w.resolve("functions"),n=w.resolve("src/functions"),c=[];if(e.entrypoint){let g=w.resolve(e.entrypoint);k.existsSync(g)||(o.fail(`File not found: ${e.entrypoint}`),process.exit(1)),c=[g];}else c=[...fe(i),...fe(n)];c.length===0&&(o.fail("No function files found"),console.log(l.yellow(`
|
|
21
21
|
Place your functions in:`)),console.log(l.gray(" - ./functions/")),console.log(l.gray(" - ./src/functions/")),console.log(l.gray(`
|
|
22
22
|
Or specify an entrypoint with --entrypoint`)),process.exit(1)),o.succeed(`Found ${c.length} function(s)`),e.name&&(c=c.filter(g=>w.basename(g,w.extname(g)).includes(e.name)),c.length===0&&(console.log(l.yellow(`
|
|
23
|
-
No functions matching "${e.name}" found`)),process.exit(1))),console.log(""),console.log(l.gray("Functions to deploy:"));for(let g of c){let y=w.basename(w.dirname(g))||w.basename(g,w.extname(g)),
|
|
24
|
-
No functions found`)),console.log(l.gray("Deploy your first function with: vaif functions deploy"));return}console.log(""),console.log(l.bold(`Functions (${
|
|
25
|
-
Error: ${
|
|
23
|
+
No functions matching "${e.name}" found`)),process.exit(1))),console.log(""),console.log(l.gray("Functions to deploy:"));for(let g of c){let y=w.basename(w.dirname(g)),j=y==="functions"||y==="src"?w.basename(g,w.extname(g)):y,C=e.runtime||ge(g);console.log(l.gray(` - ${j} (${C})`));}if(console.log(""),e.dryRun){console.log(l.yellow("Dry run mode - no functions deployed."));return}let f=[];for(let g of c){let y=w.basename(w.dirname(g)),j=y==="functions"||y==="src"?w.basename(g,w.extname(g)):y,C=e.runtime||ge(g);o.start(`Deploying ${j}...`);try{let L=k.readFileSync(g,"utf-8"),T=await no(t.token,r,{name:j,runtime:C,entrypoint:w.basename(g),code:L,envId:e.envId});o.succeed(`Deployed ${j} (v${T.version})`),f.push({name:j,success:!0,version:T.version});}catch(L){let T=L instanceof Error?L.message:"Unknown error";o.fail(`Failed to deploy ${j}`),f.push({name:j,success:false,error:T});}}console.log("");let p=f.filter(g=>g.success).length;if(f.filter(g=>!g.success).length===0)console.log(l.green(`\u2713 Successfully deployed ${p} function(s)`));else {console.log(l.yellow(`Deployed ${p}/${f.length} function(s)`)),console.log(""),console.log(l.red("Failed deployments:"));for(let g of f.filter(y=>!y.success))console.log(l.red(` - ${g.name}: ${g.error}`));}console.log("");}async function me(e){let o=U(),t=v();(!t||!t.token)&&(console.log(l.red("Not logged in")),console.log(l.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",a$1=null;try{a$1=await a(s);}catch{}let r=e.projectId||a$1?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;r||(console.log(l.red("No project ID specified")),process.exit(1)),o.start("Fetching functions...");try{let i=await so(t.token,r,e.envId);if(o.stop(),i.length===0){console.log(l.yellow(`
|
|
24
|
+
No functions found`)),console.log(l.gray("Deploy your first function with: vaif functions deploy"));return}console.log(""),console.log(l.bold(`Functions (${i.length}):`)),console.log(""),console.log(l.gray(" "+"NAME".padEnd(25)+"RUNTIME".padEnd(15)+"VERSION".padEnd(10)+"STATUS".padEnd(12)+"LAST DEPLOYED")),console.log(l.gray(" "+"-".repeat(80)));for(let n of i){let c=n.status==="active"?l.green:n.status==="deploying"?l.yellow:l.red;console.log(" "+n.name.padEnd(25)+n.runtime.padEnd(15)+`v${n.version}`.padEnd(10)+c(n.status.padEnd(12))+(n.lastDeployed?new Date(n.lastDeployed).toLocaleDateString():"-"));}console.log("");}catch(i){o.fail("Failed to fetch functions"),i instanceof Error&&console.log(l.red(`
|
|
25
|
+
Error: ${i.message}`)),process.exit(1);}}var z=process.env.VAIF_API_URL||"https://api.vaif.studio";async function io(e,o,t,s,a){let r=await fetch(`${z}/v1/projects/${o}/db/seed`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({table:t,records:s,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 ro(e,o){let t=await fetch(`${z}/v1/projects/${o}/db/reset`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});if(!t.ok){let s=await t.text();throw new Error(`Failed to reset database: ${s}`)}return t.json()}function H(e){let o=[];if(!k.existsSync(e))return o;let t=k.readdirSync(e,{withFileTypes:true});for(let s of t)if(s.isFile()){let a=w.extname(s.name).toLowerCase();(a===".json"||a===".ts"||a===".js")&&o.push(w.join(e,s.name));}return o.sort()}async function he(e){let o=w.extname(e).toLowerCase();if(o===".json"){let t=k.readFileSync(e,"utf-8"),s=JSON.parse(t);return Array.isArray(s)?[{table:w.basename(e,o),data:s}]:s.table&&s.data?[s]:Object.entries(s).map(([a,r])=>({table:a,data:r}))}else if(o===".ts"||o===".js"){let t=await import(e),s=t.default||t;return typeof s=="function"?s():s}throw new Error(`Unsupported file format: ${o}`)}async function ye(e){let o=U(),t=v();(!t||!t.token)&&(console.log(l.red("Not logged in")),console.log(l.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",a$1=null;try{a$1=await a(s);}catch{}let r=e.projectId||a$1?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;r||(console.log(l.red("No project ID specified")),console.log(l.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(l.bold("VAIF Database Seed")),console.log("");let i=[];if(e.file){let p=w.resolve(e.file);k.existsSync(p)||(console.log(l.red(`File not found: ${e.file}`)),process.exit(1)),i=[p];}else {let p=w.resolve("seeds"),d=w.resolve("prisma/seed"),g=w.resolve("db/seeds");i=[...H(p),...H(d),...H(g)];}i.length===0&&(console.log(l.yellow("No seed files found")),console.log(l.gray(`
|
|
26
26
|
Place your seed files in one of these directories:`)),console.log(l.gray(" - ./seeds/")),console.log(l.gray(" - ./prisma/seed/")),console.log(l.gray(" - ./db/seeds/")),console.log(l.gray(`
|
|
27
27
|
Or specify a file with --file`)),console.log(l.gray(`
|
|
28
|
-
Example seed file (seeds/users.json):`)),console.log(l.gray(" [")),console.log(l.gray(' { "name": "John Doe", "email": "john@example.com" },')),console.log(l.gray(' { "name": "Jane Doe", "email": "jane@example.com" }')),console.log(l.gray(" ]")),process.exit(1)),console.log(l.gray("Seed files found:"));for(let p of
|
|
28
|
+
Example seed file (seeds/users.json):`)),console.log(l.gray(" [")),console.log(l.gray(' { "name": "John Doe", "email": "john@example.com" },')),console.log(l.gray(' { "name": "Jane Doe", "email": "jane@example.com" }')),console.log(l.gray(" ]")),process.exit(1)),console.log(l.gray("Seed files found:"));for(let p of i)console.log(l.gray(` - ${w.relative(process.cwd(),p)}`));if(console.log(""),e.truncate&&(console.log(l.yellow("\u26A0\uFE0F Tables will be truncated before seeding")),console.log("")),e.dryRun){console.log(l.yellow("Dry run mode - no data will be inserted.")),console.log("");for(let p of i){o.start(`Loading ${w.basename(p)}...`);try{let d=await he(p);o.stop();for(let g of d)e.table&&g.table!==e.table||(console.log(l.cyan(`Table: ${g.table}`)),console.log(l.gray(` Records: ${g.data.length}`)),g.data.length>0&&console.log(l.gray(` Sample: ${JSON.stringify(g.data[0],null,2).slice(0,100)}...`)),console.log(""));}catch(d){o.fail(`Failed to load ${w.basename(p)}`),d instanceof Error&&console.log(l.red(` Error: ${d.message}`));}}return}let n=[];for(let p of i){o.start(`Processing ${w.basename(p)}...`);try{let d=await he(p);o.stop();for(let g of d)if(!(e.table&&g.table!==e.table)){if(g.data.length===0){console.log(l.gray(` Skipping ${g.table} (no records)`));continue}o.start(`Seeding ${g.table} (${g.data.length} records)...`);try{let y=await io(t.token,r,g.table,g.data,{truncate:e.truncate});o.succeed(`Seeded ${g.table}: ${y.inserted} records`),n.push({table:g.table,inserted:y.inserted});}catch(y){let j=y instanceof Error?y.message:"Unknown error";o.fail(`Failed to seed ${g.table}`),n.push({table:g.table,inserted:0,error:j});}}}catch(d){o.fail(`Failed to load ${w.basename(p)}`),d instanceof Error&&console.log(l.red(` Error: ${d.message}`));}}console.log("");let c=n.reduce((p,d)=>p+d.inserted,0),f=n.filter(p=>p.error).length;if(f===0)console.log(l.green(`\u2713 Successfully seeded ${c} records across ${n.length} table(s)`));else {console.log(l.yellow(`Seeded ${c} records with ${f} error(s)`)),console.log(""),console.log(l.red("Errors:"));for(let p of n.filter(d=>d.error))console.log(l.red(` - ${p.table}: ${p.error}`));}console.log("");}async function we(e){let o=U(),t=v();(!t||!t.token)&&(console.log(l.red("Not logged in")),console.log(l.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",a$1=null;try{a$1=await a(s);}catch{}let r=e.projectId||a$1?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;r||(console.log(l.red("No project ID specified")),console.log(l.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=w.resolve(e.dir||"./drizzle");if(console.log(""),console.log(l.bold("VAIF Database Push")),console.log(""),!k.existsSync(i)){let d=w.resolve("./migrations");k.existsSync(d)?console.log(l.gray(`Using migrations from: ${d}`)):(console.log(l.red(`Migrations directory not found: ${i}`)),console.log(l.gray(`
|
|
29
29
|
Expected one of:`)),console.log(l.gray(" - ./drizzle/")),console.log(l.gray(" - ./migrations/")),console.log(l.gray(`
|
|
30
|
-
Or specify with: vaif db push --dir <path>`)),process.exit(1));}let n=[],c=k.readdirSync(
|
|
31
|
-
Error: ${n.message}`)),process.exit(1);}}async function ve(e){let o=
|
|
32
|
-
Error: ${
|
|
33
|
-
Error: ${n.message}`)),process.exit(1);}}async function
|
|
34
|
-
Generate one with: vaif keys generate`));return}let f=Math.max(8,...c.map(d=>(d.name||"").length)),p=` ${"Name".padEnd(f)} ${"Key".padEnd(24)} Created`;console.log(l.gray(p)),console.log(l.gray(" "+"-".repeat(p.length-2)));for(let d of c){let g=(d.name||"unnamed").padEnd(f),y=d.maskedKey||d.prefix||`${(d.key||"").slice(0,12)}...`,
|
|
35
|
-
Error: ${
|
|
36
|
-
Error: ${c.message}`)),process.exit(1);}}async function
|
|
37
|
-
Create one with: vaif secrets set <name> <value>`));return}let c=Math.max(8,...n.map(p=>p.key.length)),f=` ${"Name".padEnd(c)} Created`;console.log(l.gray(f)),console.log(l.gray(" "+"-".repeat(f.length-2)));for(let p of n){let d=p.key.padEnd(c),g=p.createdAt?new Date(p.createdAt).toLocaleDateString():"N/A";console.log(` ${d} ${g}`);}console.log(""),console.log(l.gray(` ${n.length} secret(s) total`)),console.log(l.gray(" Values are hidden. Use `vaif secrets get <name>` to reveal.")),console.log("");}catch(
|
|
38
|
-
Error: ${
|
|
39
|
-
Error: ${
|
|
40
|
-
Error: ${
|
|
41
|
-
Error: ${
|
|
42
|
-
Error: ${
|
|
30
|
+
Or specify with: vaif db push --dir <path>`)),process.exit(1));}let n=[],c=k.readdirSync(i,{withFileTypes:true});for(let d of c)if(d.isFile()&&d.name.endsWith(".sql"))n.push(w.join(i,d.name));else if(d.isDirectory()){let g=k.readdirSync(w.join(i,d.name),{withFileTypes:true});for(let y of g)y.isFile()&&y.name.endsWith(".sql")&&n.push(w.join(i,d.name,y.name));}n.sort(),n.length===0&&(console.log(l.yellow("No SQL migration files found")),process.exit(1)),console.log(l.gray(`Found ${n.length} migration(s):`));for(let d of n)console.log(l.gray(` - ${w.relative(process.cwd(),d)}`));if(console.log(""),e.dryRun){console.log(l.yellow("Dry run mode - no migrations will be applied.")),console.log("");for(let d of n){let g=k.readFileSync(d,"utf-8");console.log(l.cyan(`--- ${w.basename(d)} ---`)),console.log(l.gray(g.slice(0,500))),g.length>500&&console.log(l.gray("...")),console.log("");}return}let f=0,p=0;for(let d of n){let g=k.readFileSync(d,"utf-8"),y=w.relative(process.cwd(),d);o.start(`Applying ${y}...`);try{let j=await fetch(`${z}/schema-engine/query/${r}`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({sql:g})});if(!j.ok){let C=await j.text();throw new Error(C)}o.succeed(`Applied ${y}`),f++;}catch(j){let C=j instanceof Error?j.message:"Unknown error";o.fail(`Failed ${y}: ${C}`),p++;}}console.log(""),console.log(p===0?l.green(`Successfully applied ${f} migration(s)`):l.yellow(`Applied ${f}, failed ${p} migration(s)`)),console.log("");}async function je(e){let o=U(),t=v();(!t||!t.token)&&(console.log(l.red("Not logged in")),console.log(l.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",a$1=null;try{a$1=await a(s);}catch{}let r=e.projectId||a$1?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;r||(console.log(l.red("No project ID specified")),console.log(l.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=w.resolve(e.output||"vaif.schema.json");console.log(""),console.log(l.bold("VAIF Database Pull")),console.log(""),o.start("Pulling schema from remote...");try{let n=await fetch(`${z}/schema-engine/introspect/${r}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!n.ok){let p=await n.text();throw new Error(`Failed to pull schema: ${p}`)}let c=await n.json();k.writeFileSync(i,JSON.stringify(c,null,2),"utf-8"),o.succeed(`Schema written to ${w.relative(process.cwd(),i)}`);let f=c.tables?.length??Object.keys(c).length;console.log(l.gray(` ${f} table(s) pulled`)),console.log("");}catch(n){o.fail("Failed to pull schema"),n instanceof Error&&console.log(l.red(`
|
|
31
|
+
Error: ${n.message}`)),process.exit(1);}}async function ve(e){let o=U(),t=v();(!t||!t.token)&&(console.log(l.red("Not logged in")),console.log(l.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",a$1=null;try{a$1=await a(s);}catch{}let r=e.projectId||a$1?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;r||(console.log(l.red("No project ID specified")),process.exit(1)),console.log(""),console.log(l.red.bold("\u26A0\uFE0F DATABASE RESET")),console.log(""),console.log(l.red("This will:")),console.log(l.red(" - Drop all tables")),console.log(l.red(" - Delete all data")),console.log(l.red(" - Reset migrations")),console.log(""),console.log(l.red.bold("This action cannot be undone!")),console.log(""),e.force||(console.log(l.yellow("Use --force to confirm this action.")),process.exit(1)),o.start("Resetting database...");try{await ro(t.token,r),o.succeed("Database reset complete"),console.log(""),console.log(l.gray("Your database is now empty.")),console.log(l.gray("Run `vaif push` to apply your schema, then `vaif db seed` to seed data.")),console.log("");}catch(i){o.fail("Failed to reset database"),i instanceof Error&&console.log(l.red(`
|
|
32
|
+
Error: ${i.message}`)),process.exit(1);}}var $e=process.env.VAIF_API_URL||"https://api.vaif.studio";function be(e,o,t){return e.projectId||o?.projectId||process.env.VAIF_PROJECT_ID||t.projectId||null}async function Ae(e){let o=U(),t=v();(!t||!t.token)&&(console.log(l.red("Not logged in")),console.log(l.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",a$1=null;try{a$1=await a(s);}catch{}let r=be(e,a$1,t);r||(console.log(l.red("No project ID specified")),console.log(l.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=e.name||`cli-key-${Date.now()}`;console.log(""),console.log(l.bold("VAIF Generate API Key")),console.log(""),o.start("Generating API key...");try{let n=await fetch(`${$e}/v1/projects/${r}/api-keys`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:i})});if(!n.ok){let f=await n.text();throw new Error(`Failed to generate key: ${f}`)}let c=await n.json();o.succeed("API key generated"),console.log(""),console.log(l.green(` Name: ${c.name}`)),console.log(l.green(` Key: ${c.key}`)),console.log(""),console.log(l.yellow.bold(" Save this key now - it will not be shown again!")),console.log("");}catch(n){o.fail("Failed to generate API key"),n instanceof Error&&console.log(l.red(`
|
|
33
|
+
Error: ${n.message}`)),process.exit(1);}}async function Se(e){let o=U(),t=v();(!t||!t.token)&&(console.log(l.red("Not logged in")),console.log(l.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",a$1=null;try{a$1=await a(s);}catch{}let r=be(e,a$1,t);r||(console.log(l.red("No project ID specified")),console.log(l.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(l.bold("VAIF API Keys")),console.log(""),o.start("Fetching API keys...");try{let i=await fetch(`${$e}/v1/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 n=await i.json(),c=n.keys||n;if(o.stop(),!Array.isArray(c)||c.length===0){console.log(l.yellow("No API keys found")),console.log(l.gray(`
|
|
34
|
+
Generate one with: vaif keys generate`));return}let f=Math.max(8,...c.map(d=>(d.name||"").length)),p=` ${"Name".padEnd(f)} ${"Key".padEnd(24)} Created`;console.log(l.gray(p)),console.log(l.gray(" "+"-".repeat(p.length-2)));for(let d of c){let g=(d.name||"unnamed").padEnd(f),y=d.maskedKey||d.prefix||`${(d.key||"").slice(0,12)}...`,j=d.createdAt?new Date(d.createdAt).toLocaleDateString():"N/A";console.log(` ${g} ${y.padEnd(24)} ${j}`);}console.log(""),console.log(l.gray(` ${c.length} key(s) total`)),console.log("");}catch(i){o.fail("Failed to list API keys"),i instanceof Error&&console.log(l.red(`
|
|
35
|
+
Error: ${i.message}`)),process.exit(1);}}var V=process.env.VAIF_API_URL||"https://api.vaif.studio";function ao(e,o,t){return e.projectId||o?.projectId||process.env.VAIF_PROJECT_ID||t.projectId||null}function B(){let e=v();return (!e||!e.token)&&(console.log(l.red("Not logged in")),console.log(l.gray("Run `vaif login` first to authenticate")),process.exit(1)),e}async function K(e){try{return await a(e||"vaif.config.json")}catch{return null}}function M(e,o,t){let s=ao(e,o,t);return s||(console.log(l.red("No project ID specified")),console.log(l.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),s}async function Pe(e,o,t){let s=U(),a=B(),r=await K(t.config),i=M(t,r,a),n=o;if(t.fromFile)try{n=k.readFileSync(t.fromFile,"utf-8");}catch(c){console.log(l.red(`Failed to read file: ${t.fromFile}`)),c instanceof Error&&console.log(l.gray(c.message)),process.exit(1);}n||(console.log(l.red("No value provided")),console.log(l.gray("Provide a value as argument or use --from-file <path>")),process.exit(1)),console.log(""),console.log(l.bold("VAIF Set Secret")),console.log(""),s.start("Checking for existing secret...");try{let c=new URL(`${V}/functions/secrets/project/${i}`);t.envId&&c.searchParams.set("envId",t.envId);let f=await fetch(c.toString(),{headers:{Authorization:`Bearer ${a.token}`}});if(!f.ok)throw new Error(`Failed to check existing secrets: ${await f.text()}`);let d=(await f.json()).find(g=>g.key===e);if(d){s.text=`Updating secret "${e}"...`;let g=await fetch(`${V}/functions/secrets/${d.id}`,{method:"PUT",headers:{Authorization:`Bearer ${a.token}`,"Content-Type":"application/json"},body:JSON.stringify({value:n})});if(!g.ok)throw new Error(`Failed to update secret: ${await g.text()}`);s.succeed(`Updated secret "${e}"`);}else {s.text=`Creating secret "${e}"...`;let g=await fetch(`${V}/functions/secrets`,{method:"POST",headers:{Authorization:`Bearer ${a.token}`,"Content-Type":"application/json"},body:JSON.stringify({projectId:i,envId:t.envId,key:e,value:n})});if(!g.ok)throw new Error(`Failed to create secret: ${await g.text()}`);s.succeed(`Created secret "${e}"`);}console.log("");}catch(c){s.fail("Failed to set secret"),c instanceof Error&&console.log(l.red(`
|
|
36
|
+
Error: ${c.message}`)),process.exit(1);}}async function xe(e){let o=U(),t=B(),s=await K(e.config),a=M(e,s,t);console.log(""),console.log(l.bold("VAIF Secrets")),console.log(""),o.start("Fetching secrets...");try{let r=new URL(`${V}/functions/secrets/project/${a}`);e.envId&&r.searchParams.set("envId",e.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 n=await i.json();if(o.stop(),n.length===0){console.log(l.yellow("No secrets found")),console.log(l.gray(`
|
|
37
|
+
Create one with: vaif secrets set <name> <value>`));return}let c=Math.max(8,...n.map(p=>p.key.length)),f=` ${"Name".padEnd(c)} Created`;console.log(l.gray(f)),console.log(l.gray(" "+"-".repeat(f.length-2)));for(let p of n){let d=p.key.padEnd(c),g=p.createdAt?new Date(p.createdAt).toLocaleDateString():"N/A";console.log(` ${d} ${g}`);}console.log(""),console.log(l.gray(` ${n.length} secret(s) total`)),console.log(l.gray(" Values are hidden. Use `vaif secrets get <name>` to reveal.")),console.log("");}catch(r){o.fail("Failed to list secrets"),r instanceof Error&&console.log(l.red(`
|
|
38
|
+
Error: ${r.message}`)),process.exit(1);}}async function Fe(e,o){let t=U(),s=B(),a=await K(o.config),r=M(o,a,s);console.log(""),t.start("Fetching secret...");try{let i=new URL(`${V}/functions/secrets/project/${r}`);o.envId&&i.searchParams.set("envId",o.envId);let n=await fetch(i.toString(),{headers:{Authorization:`Bearer ${s.token}`}});if(!n.ok)throw new Error(`Failed to fetch secrets: ${await n.text()}`);let f=(await n.json()).find(g=>g.key===e);f||(t.fail(`Secret "${e}" not found`),process.exit(1));let p=await fetch(`${V}/functions/secrets/${f.id}/value`,{headers:{Authorization:`Bearer ${s.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(l.red(`
|
|
39
|
+
Error: ${i.message}`)),process.exit(1);}}async function ke(e,o){let t=U(),s=B(),a=await K(o.config),r=M(o,a,s);console.log(""),console.log(l.bold("VAIF Delete Secret")),console.log(""),t.start("Finding secret...");try{let i=new URL(`${V}/functions/secrets/project/${r}`);o.envId&&i.searchParams.set("envId",o.envId);let n=await fetch(i.toString(),{headers:{Authorization:`Bearer ${s.token}`}});if(!n.ok)throw new Error(`Failed to fetch secrets: ${await n.text()}`);let f=(await n.json()).find(d=>d.key===e);f||(t.fail(`Secret "${e}" not found`),process.exit(1)),t.text=`Deleting secret "${e}"...`;let p=await fetch(`${V}/functions/secrets/${f.id}`,{method:"DELETE",headers:{Authorization:`Bearer ${s.token}`}});if(!p.ok)throw new Error(`Failed to delete secret: ${await p.text()}`);t.succeed(`Deleted secret "${e}"`),console.log("");}catch(i){t.fail("Failed to delete secret"),i instanceof Error&&console.log(l.red(`
|
|
40
|
+
Error: ${i.message}`)),process.exit(1);}}var Ce=process.env.VAIF_API_URL||"https://api.vaif.studio";function go(e){try{let o=new URL(e);return o.password&&(o.password="****"),o.toString()}catch{return e.replace(/:[^@/]+@/,":****@")}}async function De(e){let o=U(),t=v();(!t||!t.token)&&(console.log(l.red("Not logged in")),console.log(l.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",a$1=null;try{a$1=await a(s);}catch{}let r=e.projectId||a$1?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;r||(console.log(l.red("No project ID specified")),console.log(l.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),o.start("Fetching project info...");try{let i=await fetch(`${Ce}/v1/projects/${r}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!i.ok){let p=await i.text();throw new Error(`Failed to fetch project: ${p}`)}let n=await i.json();o.stop(),console.log(""),console.log(l.bold("VAIF Project Info")),console.log("");let c=16,f=(p,d)=>{console.log(` ${l.gray(p.padEnd(c))} ${d}`);};f("Name:",l.white(n.name||"N/A")),f("Project ID:",l.white(r)),f("Region:",l.white(n.region||"us-east-1")),f("Plan:",l.white(n.plan||n.tier||"free")),f("Created:",l.white(n.createdAt?new Date(n.createdAt).toLocaleDateString():"N/A")),console.log(""),f("API URL:",l.cyan(n.apiUrl||`${Ce}/v1`)),f("WS URL:",l.cyan(n.wsUrl||n.realtimeUrl||"N/A")),f("DB URL:",l.cyan(n.databaseUrl?go(n.databaseUrl):"N/A")),f("Storage URL:",l.cyan(n.storageUrl||"N/A")),console.log("");}catch(i){o.fail("Failed to fetch project info"),i instanceof Error&&console.log(l.red(`
|
|
41
|
+
Error: ${i.message}`)),process.exit(1);}}var po=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Ee(e){let o=U(),t=v();(!t||!t.token)&&(console.log(l.red("Not logged in")),console.log(l.gray("Run `vaif login` first to authenticate")),process.exit(1));let s=e.config||"vaif.config.json",a$1=null;try{a$1=await a(s);}catch{}let r=e.projectId||a$1?.projectId||process.env.VAIF_PROJECT_ID||t.projectId;r||(console.log(l.red("No project ID specified")),console.log(l.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),o.start("Fetching project status...");try{let i=await fetch(`${po}/v1/projects/${r}?include=tables,functions,storage,connections`,{headers:{Authorization:`Bearer ${t.token}`}});if(!i.ok){let j=await i.text();throw new Error(`Failed to fetch project status: ${j}`)}let n=await i.json();o.stop(),console.log(""),console.log(l.bold("VAIF Project Status")),console.log("");let c=22,f=(j,C)=>{console.log(` ${l.gray(j.padEnd(c))} ${C}`);};f("Project:",l.white(n.name||r)),f("Plan:",l.white(n.plan||n.tier||"free")),console.log(""),console.log(l.gray(" --- Resources ---")),console.log("");let p=n.tableCount??n.tables?.length??"N/A",d=n.functionCount??n.functions?.length??"N/A",g=n.bucketCount??n.storage?.buckets?.length??"N/A",y=n.activeConnections??n.connections??"N/A";f("Tables:",l.white(String(p))),f("Functions:",l.white(String(d))),f("Storage Buckets:",l.white(String(g))),f("Active Connections:",l.white(String(y))),n.usage&&(console.log(""),console.log(l.gray(" --- Usage ---")),console.log(""),n.usage.dbSize&&f("Database Size:",l.white(n.usage.dbSize)),n.usage.storageSize&&f("Storage Size:",l.white(n.usage.storageSize)),n.usage.bandwidth&&f("Bandwidth:",l.white(n.usage.bandwidth)),n.usage.functionInvocations!=null&&f("Function Invocations:",l.white(String(n.usage.functionInvocations)))),console.log("");}catch(i){o.fail("Failed to fetch project status"),i instanceof Error&&console.log(l.red(`
|
|
42
|
+
Error: ${i.message}`)),process.exit(1);}}program.name("vaif").description("VAIF CLI - Type generation and development tools").version("1.6.5");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(ne);program.command("logout").description("Log out and remove stored credentials").action(se);program.command("whoami").description("Show current authenticated user").action(ie);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(d);program.command("templates").alias("tpl").description("List available project templates").action(c);program.command("info").description("Show project information (name, region, URLs)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").action(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(Ee);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(re);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(le);program.command("generate").alias("gen").description("Generate TypeScript types from your database schema").option("-c, --connection <url>","Database connection string").option("-o, --output <path>","Output file path","./src/types/database.ts").option("--schema <name>","Schema name","public").option("--config <path>","Config file path","vaif.config.json").option("--dry-run","Preview generated types without writing").action(b);var Re=program.command("functions").alias("fn").description("Manage serverless functions");Re.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(ue);Re.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 q=program.command("db").description("Database management commands");q.command("push").description("Push local Drizzle migrations to VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-d, --dir <path>","Migrations directory","./drizzle").option("--dry-run","Preview without applying").action(we);q.command("pull").description("Pull schema from VAIF project").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-o, --output <path>","Output file","vaif.schema.json").action(je);q.command("seed").description("Seed your database with test data").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-f, --file <path>","Specific seed file").option("-t, --table <name>","Seed specific table only").option("--truncate","Truncate tables before seeding").option("--dry-run","Preview seeding without inserting data").action(ye);q.command("reset").description("Reset database (drop all tables and data)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-f, --force","Confirm reset (required)").action(ve);var Oe=program.command("keys").description("Manage API keys");Oe.command("generate").description("Generate a new API key").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-n, --name <name>","Key name").action(Ae);Oe.command("list").alias("ls").description("List API keys").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").action(Se);var W=program.command("secrets").alias("sec").description("Manage function secrets");W.command("set <name> [value]").description("Create or update a secret").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").option("--from-file <path>","Read secret value from a file").action(Pe);W.command("list").alias("ls").description("List all secrets (names only)").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").action(xe);W.command("get <name>").description("Reveal a secret value").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").action(Fe);W.command("delete <name>").description("Delete a secret").option("-c, --config <path>","Config file path","vaif.config.json").option("-p, --project-id <id>","Project ID (overrides config)").option("-e, --env-id <id>","Environment ID or name").action(ke);program.parse(process.argv);process.argv.slice(2).length||program.outputHelp();
|
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var v=require('fs'),w=require('path'),M=require('dotenv'),K=require('pg'),z=require('ora'),d=require('chalk'),q=require('prettier'),j=require('readline');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var v__default=/*#__PURE__*/_interopDefault(v);var w__default=/*#__PURE__*/_interopDefault(w);var M__default=/*#__PURE__*/_interopDefault(M);var K__default=/*#__PURE__*/_interopDefault(K);var z__default=/*#__PURE__*/_interopDefault(z);var d__default=/*#__PURE__*/_interopDefault(d);var q__default=/*#__PURE__*/_interopDefault(q);var j__default=/*#__PURE__*/_interopDefault(j);M__default.default.config();async function E(n){let a=w__default.default.resolve(n);if(!v__default.default.existsSync(a))return null;try{let t=v__default.default.readFileSync(a,"utf-8"),e=JSON.parse(t);return e.database?.url&&(e.database.url=U(e.database.url)),e.api?.apiKey&&(e.api.apiKey=U(e.api.apiKey)),e}catch{throw new Error(`Failed to parse config file: ${n}`)}}function U(n){return n.replace(/\$\{([^}]+)\}/g,(a,t)=>process.env[t]||a)}async function B(n,a){let t=await n.query(`
|
|
2
2
|
SELECT table_name, table_type
|
|
3
3
|
FROM information_schema.tables
|
|
4
4
|
WHERE table_schema = $1
|
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
ORDER BY t.typname, e.enumsortorder
|
|
47
47
|
`,[a]),c=new Map;for(let l of t.rows)c.set(l.table_name,[]);for(let l of e.rows){let s=c.get(l.table_name);s&&s.push(l);}let u=new Map;for(let l of r.rows){let s=u.get(l.enum_name)||[];s.push(l.enum_value),u.set(l.enum_name,s);}return {tables:c,enums:u,foreignKeys:i.rows}}var S={smallint:"number",integer:"number",bigint:"string",int2:"number",int4:"number",int8:"string",decimal:"string",numeric:"string",real:"number",float4:"number",float8:"number","double precision":"number",money:"string",boolean:"boolean",bool:"boolean",text:"string",varchar:"string",char:"string",character:"string","character varying":"string",name:"string",citext:"string",date:"string",time:"string",timetz:"string","time without time zone":"string","time with time zone":"string",timestamp:"string",timestamptz:"string","timestamp without time zone":"string","timestamp with time zone":"string",interval:"string",bytea:"Buffer",uuid:"string",json:"unknown",jsonb:"unknown",inet:"string",cidr:"string",macaddr:"string",macaddr8:"string",point:"{ x: number; y: number }",line:"string",lseg:"string",box:"string",path:"string",polygon:"string",circle:"string",ARRAY:"unknown[]"};function $(n,a){let{data_type:t,udt_name:e,is_nullable:i}=n;if(a.has(e)){let u=a.get(e).map(l=>`"${l}"`).join(" | ");return i==="YES"?`(${u}) | null`:u}if(t==="ARRAY"){let c=e.replace(/^_/,"");if(a.has(c)){let s=a.get(c).map(o=>`"${o}"`).join(" | ");return i==="YES"?`(${s})[] | null`:`(${s})[]`}let u=S[c]||"unknown";return i==="YES"?`${u}[] | null`:`${u}[]`}let r=S[t]||S[e]||"unknown";return i==="YES"&&(r=`${r} | null`),r}function x(n){return n.split(/[_\-\s]+/).map(a=>a.charAt(0).toUpperCase()+a.slice(1).toLowerCase()).join("")}function Y(n,a){let t=x(n),e=a.map(i=>` | "${i}"`).join(`
|
|
48
48
|
`);return `export type ${t} =
|
|
49
|
-
${e};`}function G(n,a,t){let e=x(n),i=[],r=[],c=[];for(let o of a){let
|
|
49
|
+
${e};`}function G(n,a,t){let e=x(n),i=[],r=[],c=[];for(let o of a){let p=$(o,t),m=o.column_name,g=o.column_default!==null||o.is_identity==="YES",y=o.is_nullable==="YES";i.push(` ${m}: ${p};`),g||o.column_name==="id"?r.push(` ${m}?: ${p.replace(" | null","")} | null;`):y?r.push(` ${m}?: ${p};`):r.push(` ${m}: ${p.replace(" | null","")};`),c.push(` ${m}?: ${p.replace(" | null","")} | null;`);}let u=`export interface ${e} {
|
|
50
50
|
${i.join(`
|
|
51
51
|
`)}
|
|
52
52
|
}`,l=`export interface ${e}Insert {
|
|
@@ -56,9 +56,9 @@ ${r.join(`
|
|
|
56
56
|
${c.join(`
|
|
57
57
|
`)}
|
|
58
58
|
}`;return {base:u,insert:l,update:s}}function H(n,a,t){let e=["/**"," * Auto-generated TypeScript types from database schema"," * Generated by @vaiftech/cli",` * Generated at: ${new Date().toISOString()}`," * "," * DO NOT EDIT MANUALLY - changes will be overwritten"," */",""];if(a.size>0){e.push("// ============ ENUMS ============"),e.push("");for(let[r,c]of a)e.push(Y(r,c)),e.push("");}e.push("// ============ TABLES ============"),e.push("");let i=[];for(let[r,c]of n){let{base:u,insert:l,update:s}=G(r,c,a);i.push(r),e.push(u),e.push(""),e.push(l),e.push(""),e.push(s),e.push("");}e.push("// ============ DATABASE SCHEMA ============"),e.push(""),e.push("export interface Database {");for(let r of i){let c=x(r);e.push(` ${r}: {`),e.push(` Row: ${c};`),e.push(` Insert: ${c}Insert;`),e.push(` Update: ${c}Update;`),e.push(" };");}return e.push("}"),e.push(""),e.push("export type TableName = keyof Database;"),e.push(""),e.push("// ============ HELPER TYPES ============"),e.push(""),e.push('export type Row<T extends TableName> = Database[T]["Row"];'),e.push('export type Insert<T extends TableName> = Database[T]["Insert"];'),e.push('export type Update<T extends TableName> = Database[T]["Update"];'),e.push(""),e.join(`
|
|
59
|
-
`)}async function J(n){let a=z__default.default("Loading configuration...").start();try{let t=await E(n.config),e=n.connection||t?.database?.url||process.env.DATABASE_URL;e||(a.fail("No database connection string provided"),console.log(
|
|
60
|
-
Provide a connection string via:`)),console.log(
|
|
61
|
-
Error: ${t.message}`)),t.message.includes("ECONNREFUSED")&&console.log(
|
|
59
|
+
`)}async function J(n){let a=z__default.default("Loading configuration...").start();try{let t=await E(n.config),e=n.connection||t?.database?.url||process.env.DATABASE_URL;e||(a.fail("No database connection string provided"),console.log(d__default.default.yellow(`
|
|
60
|
+
Provide a connection string via:`)),console.log(d__default.default.gray(" --connection <url>")),console.log(d__default.default.gray(" DATABASE_URL environment variable")),console.log(d__default.default.gray(" vaif.config.json database.url")),process.exit(1)),a.text="Connecting to database...";let i=new K__default.default.Client({connectionString:e});await i.connect(),a.text="Introspecting schema...";let{tables:r,enums:c,foreignKeys:u}=await B(i,n.schema);if(await i.end(),r.size===0){a.warn(`No tables found in schema "${n.schema}"`);return}a.text=`Generating types for ${r.size} tables...`;let l=H(r,c,u),s=await q__default.default.format(l,{parser:"typescript",semi:!0,singleQuote:!1,trailingComma:"es5",printWidth:100});if(n.dryRun){a.succeed("Generated types (dry run):"),console.log(""),console.log(d__default.default.gray("\u2500".repeat(60))),console.log(s),console.log(d__default.default.gray("\u2500".repeat(60)));return}let o=w__default.default.resolve(n.output),p=w__default.default.dirname(o);v__default.default.existsSync(p)||v__default.default.mkdirSync(p,{recursive:!0}),v__default.default.writeFileSync(o,s,"utf-8"),a.succeed(`Generated types for ${r.size} tables \u2192 ${d__default.default.cyan(n.output)}`),console.log(""),console.log(d__default.default.green("Generated:")),console.log(d__default.default.gray(` Tables: ${r.size}`)),console.log(d__default.default.gray(` Enums: ${c.size}`)),console.log(""),console.log(d__default.default.gray("Import in your code:")),console.log(d__default.default.cyan(` import type { Database, Row, Insert, Update } from "${n.output.replace(/\.ts$/,"")}";`));}catch(t){a.fail("Failed to generate types"),t instanceof Error&&(console.error(d__default.default.red(`
|
|
61
|
+
Error: ${t.message}`)),t.message.includes("ECONNREFUSED")&&console.log(d__default.default.yellow(`
|
|
62
62
|
Make sure your database is running and accessible.`))),process.exit(1);}}var b=[{name:"database",label:"Database",description:"CRUD queries, type-safe operations"},{name:"auth",label:"Authentication",description:"login, signup, OAuth, sessions"},{name:"realtime",label:"Realtime",description:"live subscriptions, presence"},{name:"storage",label:"Storage",description:"file uploads, signed URLs"},{name:"functions",label:"Functions",description:"serverless function calls"}],W={"nextjs-fullstack":{name:"Next.js Full-Stack",description:"Next.js app with server/client VAIF client, auth middleware, and React hooks",tag:"Next.js",defaultFeatures:["database","auth"],files:[{path:"package.json",content:`{
|
|
63
63
|
"name": "my-vaif-app",
|
|
64
64
|
"private": true,
|
|
@@ -3688,16 +3688,18 @@ export const posts = pgTable("posts", {
|
|
|
3688
3688
|
|
|
3689
3689
|
return Response.json({ message: \`Hello, \${name}!\` });
|
|
3690
3690
|
}
|
|
3691
|
-
`}]},dependencies:["@vaiftech/client","@vaiftech/auth"],postInstructions:["Copy .env.example to .env.local and fill in your project credentials","Create a 'product-images' storage bucket in your VAIF dashboard","Import storage helpers from '@/lib/storage' in your API routes","Use uploadProductImage() in your product creation flow","Run: npx vaif generate to generate TypeScript types"]}};async function X(n){if(!process.stdin.isTTY||!process.stdout.isTTY)return n;let a=new Set(n.map(e=>b.findIndex(i=>i.name===e)).filter(e=>e>=0)),t=0;return new Promise(e=>{let i=
|
|
3692
|
-
? Which VAIF features do you want to include?`)),b.forEach((u,l)=>{let s=a.has(l)?
|
|
3693
|
-
Unknown template: ${n}`)),console.log(
|
|
3694
|
-
`)),process.exit(1));let e;a.features&&a.features.length>0?e=a.features.filter(s=>b.some(o=>o.name===s)):
|
|
3695
|
-
|
|
3696
|
-
`,"utf-8")
|
|
3697
|
-
|
|
3691
|
+
`}]},dependencies:["@vaiftech/client","@vaiftech/auth"],postInstructions:["Copy .env.example to .env.local and fill in your project credentials","Create a 'product-images' storage bucket in your VAIF dashboard","Import storage helpers from '@/lib/storage' in your API routes","Use uploadProductImage() in your product creation flow","Run: npx vaif generate to generate TypeScript types"]}};async function X(n){if(!process.stdin.isTTY||!process.stdout.isTTY)return n;let a=new Set(n.map(e=>b.findIndex(i=>i.name===e)).filter(e=>e>=0)),t=0;return new Promise(e=>{let i=j__default.default.createInterface({input:process.stdin,output:process.stdout});j__default.default.emitKeypressEvents(process.stdin,i),process.stdin.setRawMode&&process.stdin.setRawMode(true);function r(){let u=b.length+2;process.stdout.write(`\x1B[${u}A`),c();}function c(){console.log(d__default.default.bold(`
|
|
3692
|
+
? Which VAIF features do you want to include?`)),b.forEach((u,l)=>{let s=a.has(l)?d__default.default.green("[x]"):"[ ]",o=l===t?d__default.default.cyan("> "):" ";console.log(`${o}${s} ${u.label} ${d__default.default.gray(`(${u.description})`)}`);}),console.log(d__default.default.gray(" (up/down to move, space to toggle, enter to confirm)"));}c(),process.stdin.on("keypress",(u,l)=>{if(l.name==="up"&&t>0)t--,r();else if(l.name==="down"&&t<b.length-1)t++,r();else if(l.name==="space")a.has(t)?a.delete(t):a.add(t),r();else if(l.name==="return"){process.stdin.setRawMode&&process.stdin.setRawMode(false),i.close();let s=[...a].sort().map(o=>b[o].name);e(s.length>0?s:n);}else l.name==="c"&&l.ctrl&&(process.stdin.setRawMode&&process.stdin.setRawMode(false),i.close(),process.exit(0));});})}async function F(n,a={}){let t=W[n];t||(console.log(d__default.default.red(`
|
|
3693
|
+
Unknown template: ${n}`)),console.log(d__default.default.yellow(`Run 'vaif templates' to see available templates.
|
|
3694
|
+
`)),process.exit(1));let e;a.features&&a.features.length>0?e=a.features.filter(s=>b.some(o=>o.name===s)):a.addOnly?(console.log(d__default.default.red(`
|
|
3695
|
+
No features specified.`)),console.log(d__default.default.yellow("Usage: vaif init --template <name> --add-features <features>")),console.log(d__default.default.gray("Available features: auth, database, realtime, storage, functions")),process.exit(1)):t.featureFiles&&Object.keys(t.featureFiles).length>0?e=await X(t.defaultFeatures??["database","auth"]):e=t.defaultFeatures??[],a.addOnly?(console.log(""),console.log(d__default.default.bold(`Adding features to ${d__default.default.cyan(t.name)} project...`)),console.log(d__default.default.gray(` Features: ${e.join(", ")}`)),console.log("")):(console.log(""),console.log(d__default.default.bold(`Scaffolding ${d__default.default.cyan(t.name)} template...`)),e.length>0&&console.log(d__default.default.gray(` Features: ${e.join(", ")}`)),console.log(""));let i=a.addOnly?[]:[...t.files];if(t.featureFiles)for(let s of e){let o=t.featureFiles[s];o&&i.push(...o);}let r=0,c=0;for(let s of i){let o=w__default.default.resolve(s.path),p=w__default.default.dirname(o);if(v__default.default.existsSync(p)||v__default.default.mkdirSync(p,{recursive:true}),s.path==="package.json"&&v__default.default.existsSync(o)&&!a.force)try{let m=JSON.parse(v__default.default.readFileSync(o,"utf-8")),g=JSON.parse(s.content),y=N=>{if(!N)return {};let L={};for(let[k,_]of Object.entries(N))!_.startsWith("workspace:")&&!_.startsWith("link:")&&!_.startsWith("file:")&&(L[k]=_);return L};m.dependencies={...y(m.dependencies),...g.dependencies||{}},m.devDependencies={...y(m.devDependencies),...g.devDependencies||{}},g.scripts&&(m.scripts={...m.scripts||{},...g.scripts}),v__default.default.writeFileSync(o,JSON.stringify(m,null,2)+`
|
|
3696
|
+
`,"utf-8"),console.log(d__default.default.green(` merge ${s.path} (added dependencies)`)),r++;continue}catch{}if(v__default.default.existsSync(o)&&!a.force){console.log(d__default.default.yellow(` skip ${s.path} (already exists)`)),c++;continue}v__default.default.writeFileSync(o,s.content,"utf-8"),console.log(d__default.default.green(` create ${s.path}`)),r++;}console.log(""),r>0&&console.log(d__default.default.green(`Created ${r} file${r!==1?"s":""}.`)),c>0&&console.log(d__default.default.yellow(`Skipped ${c} file${c!==1?"s":""} (use --force to overwrite).`));let u={auth:{"@vaiftech/auth":"^1.0.0"},database:{},realtime:{},storage:{},functions:{}},l=w__default.default.resolve("package.json");if(v__default.default.existsSync(l)&&e.length>0)try{let s=JSON.parse(v__default.default.readFileSync(l,"utf-8")),o=!1;for(let p of e){let m=u[p];if(m)for(let[g,y]of Object.entries(m))s.dependencies?.[g]||(s.dependencies=s.dependencies||{},s.dependencies[g]=y,o=!0);}o&&v__default.default.writeFileSync(l,JSON.stringify(s,null,2)+`
|
|
3697
|
+
`,"utf-8");}catch{}(t.dependencies?.length||t.devDependencies?.length)&&(console.log(""),console.log(d__default.default.bold("Install dependencies:")),t.dependencies?.length&&console.log(d__default.default.cyan(` npm install ${t.dependencies.join(" ")}`)),t.devDependencies?.length&&console.log(d__default.default.cyan(` npm install -D ${t.devDependencies.join(" ")}`))),console.log(""),console.log(d__default.default.bold.green("Project scaffolded successfully!")),console.log(""),console.log(d__default.default.bold(" Next steps:")),t.postInstructions.forEach(s=>{console.log(d__default.default.gray(` ${s}`));}),console.log(""),console.log(d__default.default.gray(" Get your project credentials at https://vaif.studio/app/security/api-keys")),console.log("");}var Z={$schema:"https://vaif.studio/schemas/config.json",projectId:"",database:{url:"${DATABASE_URL}",schema:"public"},types:{output:"./src/types/database.ts"},api:{baseUrl:"https://api.vaif.studio"}};async function ee(n){if(n.addFeatures){n.template||(console.log(d__default.default.red(`
|
|
3698
|
+
--add-features requires --template to know which template to use.`)),console.log(d__default.default.gray("Example: vaif init --template react-spa --add-features functions,storage")),process.exit(1));let e=n.addFeatures.split(",").map(i=>i.trim());await F(n.template,{force:n.force,features:e,addOnly:true});return}let a=z__default.default("Initializing VAIF configuration...").start(),t=w__default.default.resolve("vaif.config.json");v__default.default.existsSync(t)&&!n.force&&(a.fail("vaif.config.json already exists"),console.log(d__default.default.yellow(`
|
|
3699
|
+
Use --force to overwrite existing configuration.`)),process.exit(1));try{if(v__default.default.writeFileSync(t,JSON.stringify(Z,null,2),"utf-8"),a.succeed("Created vaif.config.json"),n.template){let e=n.features?n.features.split(",").map(i=>i.trim()):void 0;await F(n.template,{force:n.force,features:e});}else {let e=w__default.default.resolve(".env.example");if(v__default.default.existsSync(e)||(v__default.default.writeFileSync(e,`# VAIF Configuration
|
|
3698
3700
|
DATABASE_URL=postgresql://user:password@localhost:5432/database
|
|
3699
3701
|
VAIF_API_KEY=your-api-key
|
|
3700
|
-
`,"utf-8"),console.log(
|
|
3702
|
+
`,"utf-8"),console.log(d__default.default.gray("Created .env.example"))),n.typescript){let i=w__default.default.resolve("src/types");v__default.default.existsSync(i)||(v__default.default.mkdirSync(i,{recursive:!0}),console.log(d__default.default.gray("Created src/types directory")));}console.log(""),console.log(d__default.default.green("VAIF initialized successfully!")),console.log(""),console.log(d__default.default.gray("Next steps:")),console.log(d__default.default.gray(" 1. Update vaif.config.json with your project ID")),console.log(d__default.default.gray(" 2. Set DATABASE_URL in your environment")),console.log(d__default.default.gray(" 3. Run: npx vaif generate")),console.log("");}}catch(e){a.fail("Failed to initialize"),e instanceof Error&&console.error(d__default.default.red(`
|
|
3701
3703
|
Error: ${e.message}`)),process.exit(1);}}async function Ve(n){let{connectionString:a,schema:t="public"}=n,e=new K__default.default.Client({connectionString:a});await e.connect();try{let i=await e.query(`
|
|
3702
3704
|
SELECT table_name, table_type
|
|
3703
3705
|
FROM information_schema.tables
|
|
@@ -3728,9 +3730,9 @@ Error: ${e.message}`)),process.exit(1);}}async function Ve(n){let{connectionStri
|
|
|
3728
3730
|
JOIN pg_namespace n ON n.oid = t.typnamespace
|
|
3729
3731
|
WHERE n.nspname = $1
|
|
3730
3732
|
ORDER BY t.typname, e.enumsortorder
|
|
3731
|
-
`,[t]),u=new Map;for(let o of i.rows)u.set(o.table_name,[]);for(let o of r.rows){let
|
|
3733
|
+
`,[t]),u=new Map;for(let o of i.rows)u.set(o.table_name,[]);for(let o of r.rows){let p=u.get(o.table_name);p&&p.push(o);}let l=new Map;for(let o of c.rows){let p=l.get(o.enum_name)||[];p.push(o.enum_value),l.set(o.enum_name,p);}let s=ie(u,l);return q__default.default.format(s,{parser:"typescript",semi:!0,singleQuote:!1,trailingComma:"es5",printWidth:100})}finally{await e.end();}}var P={smallint:"number",integer:"number",bigint:"string",int2:"number",int4:"number",int8:"string",decimal:"string",numeric:"string",real:"number",float4:"number",float8:"number","double precision":"number",money:"string",boolean:"boolean",bool:"boolean",text:"string",varchar:"string",char:"string",character:"string","character varying":"string",name:"string",citext:"string",date:"string",time:"string",timetz:"string",timestamp:"string",timestamptz:"string","timestamp without time zone":"string","timestamp with time zone":"string",interval:"string",bytea:"Buffer",uuid:"string",json:"unknown",jsonb:"unknown",inet:"string",cidr:"string",macaddr:"string",point:"{ x: number; y: number }",ARRAY:"unknown[]"};function ne(n,a){let{data_type:t,udt_name:e,is_nullable:i}=n;if(a.has(e)){let u=a.get(e).map(l=>`"${l}"`).join(" | ");return i==="YES"?`(${u}) | null`:u}if(t==="ARRAY"){let c=e.replace(/^_/,"");if(a.has(c)){let s=a.get(c).map(o=>`"${o}"`).join(" | ");return i==="YES"?`(${s})[] | null`:`(${s})[]`}let u=P[c]||"unknown";return i==="YES"?`${u}[] | null`:`${u}[]`}let r=P[t]||P[e]||"unknown";return i==="YES"&&(r=`${r} | null`),r}function C(n){return n.split(/[_\-\s]+/).map(a=>a.charAt(0).toUpperCase()+a.slice(1).toLowerCase()).join("")}function ie(n,a){let t=["/**"," * Auto-generated TypeScript types from database schema"," * Generated by @vaiftech/cli",` * Generated at: ${new Date().toISOString()}`," * "," * DO NOT EDIT MANUALLY - changes will be overwritten"," */",""];if(a.size>0){t.push("// ============ ENUMS ============"),t.push("");for(let[i,r]of a){let c=C(i),u=r.map(l=>` | "${l}"`).join(`
|
|
3732
3734
|
`);t.push(`export type ${c} =
|
|
3733
|
-
${u};`),t.push("");}}t.push("// ============ TABLES ============"),t.push("");let e=[];for(let[i,r]of n){e.push(i);let c=
|
|
3735
|
+
${u};`),t.push("");}}t.push("// ============ TABLES ============"),t.push("");let e=[];for(let[i,r]of n){e.push(i);let c=C(i),u=[],l=[],s=[];for(let o of r){let p=ne(o,a),m=o.column_name,g=o.column_default!==null||o.is_identity==="YES",y=o.is_nullable==="YES";u.push(` ${m}: ${p};`),g||o.column_name==="id"?l.push(` ${m}?: ${p.replace(" | null","")} | null;`):y?l.push(` ${m}?: ${p};`):l.push(` ${m}: ${p.replace(" | null","")};`),s.push(` ${m}?: ${p.replace(" | null","")} | null;`);}t.push(`export interface ${c} {
|
|
3734
3736
|
${u.join(`
|
|
3735
3737
|
`)}
|
|
3736
3738
|
}`),t.push(""),t.push(`export interface ${c}Insert {
|
|
@@ -3739,5 +3741,5 @@ ${l.join(`
|
|
|
3739
3741
|
}`),t.push(""),t.push(`export interface ${c}Update {
|
|
3740
3742
|
${s.join(`
|
|
3741
3743
|
`)}
|
|
3742
|
-
}`),t.push("");}t.push("// ============ DATABASE SCHEMA ============"),t.push(""),t.push("export interface Database {");for(let i of e){let r=
|
|
3744
|
+
}`),t.push("");}t.push("// ============ DATABASE SCHEMA ============"),t.push(""),t.push("export interface Database {");for(let i of e){let r=C(i);t.push(` ${i}: {`),t.push(` Row: ${r};`),t.push(` Insert: ${r}Insert;`),t.push(` Update: ${r}Update;`),t.push(" };");}return t.push("}"),t.push(""),t.push("export type TableName = keyof Database;"),t.push(""),t.push("// ============ HELPER TYPES ============"),t.push(""),t.push('export type Row<T extends TableName> = Database[T]["Row"];'),t.push('export type Insert<T extends TableName> = Database[T]["Insert"];'),t.push('export type Update<T extends TableName> = Database[T]["Update"];'),t.push(""),t.join(`
|
|
3743
3745
|
`)}exports.generateTypes=J;exports.generateTypesFromConnection=Ve;exports.initConfig=ee;exports.loadConfig=E;
|
package/dist/index.d.cts
CHANGED
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export{b as generateTypes,d as initConfig,a as loadConfig}from'./chunk-
|
|
1
|
+
export{b as generateTypes,d as initConfig,a as loadConfig}from'./chunk-OB2QEQ2L.js';import T from'pg';import $ from'prettier';async function S(p){let{connectionString:a,schema:e="public"}=p,r=new T.Client({connectionString:a});await r.connect();try{let t=await r.query(`
|
|
2
2
|
SELECT table_name, table_type
|
|
3
3
|
FROM information_schema.tables
|
|
4
4
|
WHERE table_schema = $1
|