@vaiftech/cli 1.7.5 → 1.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +29 -1
- package/dist/{chunk-WYTLXCHQ.js → chunk-T7GOLIY4.js} +52 -35
- package/dist/cli.cjs +271 -61
- package/dist/cli.js +225 -32
- package/dist/index.cjs +55 -38
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,33 +1,226 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {c,d,e,h,g,f,b,a}from'./chunk-
|
|
3
|
-
Error: ${
|
|
4
|
-
Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1)),
|
|
5
|
-
Error: ${
|
|
6
|
-
Error: ${
|
|
7
|
-
Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1));let
|
|
8
|
-
Expected schema file at: ${
|
|
9
|
-
Error: ${
|
|
10
|
-
Cancelled. No changes applied.`));return}}
|
|
11
|
-
Error: ${
|
|
12
|
-
Place your functions in:`)),console.log(
|
|
13
|
-
Or specify an entrypoint with --entrypoint`)),process.exit(1)),
|
|
14
|
-
No functions matching "${
|
|
15
|
-
No functions found`)),console.log(
|
|
16
|
-
Error: ${
|
|
17
|
-
Place your seed files in one of these directories:`)),console.log(
|
|
18
|
-
Or specify a file with --file`)),console.log(
|
|
19
|
-
Example seed file (seeds/users.json):`)),console.log(
|
|
20
|
-
Expected one of:`)),console.log(
|
|
21
|
-
Or specify with: vaif db push --dir <path>`)),process.exit(1));}let n=[],
|
|
22
|
-
Error: ${n.message}`)),process.exit(1);}}async function
|
|
23
|
-
Error: ${
|
|
24
|
-
Error: ${n.message}`)),process.exit(1);}}async function
|
|
25
|
-
Generate one with: vaif keys generate`));return}let d=Math.max(8,...
|
|
26
|
-
Error: ${
|
|
27
|
-
Error: ${
|
|
28
|
-
Create one with: vaif secrets set <name> <value>`));return}let
|
|
29
|
-
Error: ${
|
|
30
|
-
Error: ${
|
|
31
|
-
Error: ${
|
|
32
|
-
Error: ${
|
|
33
|
-
Error: ${
|
|
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 D from'fs';import I from'path';import K from'ora';import qe from'readline';var Ke=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Be(o,e,t="public"){let s=await fetch(`${Ke}/v1/projects/${e}/schema?schema=${t}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}});if(!s.ok){let r=await s.text();throw new Error(`Failed to fetch schema: ${r}`)}return s.json()}async function ce(o){let e=K(),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 s=o.config||"vaif.config.json",r=null;e.start("Loading configuration...");try{r=await a(s);}catch(i){e.fail("Failed to load config"),console.log(f.red(`
|
|
3
|
+
Error: ${i}`)),process.exit(1);}r||(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||r.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 i=o.schema||r.database?.schema||"public",n=await Be(t.token,a$1,i);e.succeed("Schema fetched successfully");let c=o.output||I.resolve("vaif.schema.json"),d={$schema:"https://vaif.studio/schemas/schema.json",projectId:a$1,schema:i,pulledAt:new Date().toISOString(),...n};D.writeFileSync(c,JSON.stringify(d,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: ${(n.tables||[]).length}`)),console.log(f.gray(` Enums: ${(n.enums||[]).length}`)),console.log(f.gray(` Functions: ${(n.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 ge=process.env.VAIF_API_URL||"https://api.vaif.studio";function We(o){let e=qe.createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(o,s=>{e.close(),t(s);});})}async function Ge(o,e,t){let s=await fetch(`${ge}/v1/projects/${e}/schema/preview`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({schema:t})});if(!s.ok){let r=await s.text();throw new Error(`Failed to preview changes: ${r}`)}return s.json()}async function Ye(o,e,t){let s=await fetch(`${ge}/v1/projects/${e}/schema/apply`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({schema:t})});if(!s.ok){let r=await s.text();throw new Error(`Failed to apply changes: ${r}`)}return s.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=K(),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 s=o.config||"vaif.config.json",r=null;e.start("Loading configuration...");try{r=await a(s);}catch(c){e.fail("Failed to load config"),console.log(f.red(`
|
|
6
|
+
Error: ${c}`)),process.exit(1);}r||(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||r.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 i=o.schema||I.resolve("vaif.schema.json");D.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 n;try{let c=D.readFileSync(i,"utf-8");n=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:d}=await Ge(t.token,a$1,n);if(e.stop(),Qe(c),c.added.length===0&&c.modified.length===0&&c.removed.length===0){console.log("");return}if(d.length>0){console.log(f.bold("SQL Migrations:")),console.log("");for(let g of d)console.log(f.gray(` ${g}`));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 We(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,n);if(p.success){if(e.succeed("Schema changes applied successfully"),console.log(""),p.migrations.length>0){console.log(f.gray("Migrations applied:"));for(let g of p.migrations)console.log(f.gray(` - ${g}`));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 He(o,e,t,s){let r=new URL(`${z}/functions/project/${e}`);s&&r.searchParams.set("envId",s);let a=await fetch(r.toString(),{headers:{Authorization:`Bearer ${o}`}});if(!a.ok)return null;let i=await a.json(),n=i.functions||i;return Array.isArray(n)&&n.find(c=>c.name===t)||null}async function Xe(o,e,t){let s=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(!s.ok){let r=await s.text();throw new Error(`Failed to create function: ${r}`)}return s.json()}async function Ze(o,e,t){let s=await fetch(`${z}/functions/${e}/source`,{method:"PUT",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({sourceCode:t})});if(!s.ok){let r=await s.text();throw new Error(`Failed to deploy source: ${r}`)}}async function eo(o,e,t){let s=new URL(`${z}/functions/project/${e}`);t&&s.searchParams.set("envId",t);let r=await fetch(s.toString(),{headers:{Authorization:`Bearer ${o}`}});if(!r.ok){let i=await r.text();throw new Error(`Failed to list functions: ${i}`)}let a=await r.json();return a.functions||a}function de(o){switch(I.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"],s=["drizzle.config.ts","tsconfig.json","package.json"];if(!D.existsSync(o))return e;let r=D.readdirSync(o,{withFileTypes:true});for(let a of r){let i=I.join(o,a.name);if(a.isDirectory()){if(a.name!=="node_modules"&&!a.name.startsWith(".")){let n=D.readdirSync(i,{withFileTypes:true});for(let c of n)if(c.isFile()){let d=I.extname(c.name).toLowerCase();if(t.includes(d)){e.push(I.join(i,c.name));break}}}}else if(a.isFile()){let n=I.extname(a.name).toLowerCase();t.includes(n)&&!s.includes(a.name)&&e.push(i);}}return e}async function me(o){let e=K(),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 s=o.config||"vaif.config.json",r=null;try{r=await a(s);}catch{}let a$1=o.projectId||r?.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 i=I.resolve("functions"),n=I.resolve("src/functions"),c=[];if(o.entrypoint){let l=I.resolve(o.entrypoint);D.existsSync(l)||(e.fail(`File not found: ${o.entrypoint}`),process.exit(1)),c=[l];}else c=[...pe(i),...pe(n)];c.length===0&&(e.fail("No function files found"),console.log(f.yellow(`
|
|
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=>I.basename(l,I.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 h=I.basename(I.dirname(l)),y=h==="functions"||h==="src"?I.basename(l,I.extname(l)):h,E=o.runtime||de(l);console.log(f.gray(` - ${y} (${E})`));}if(console.log(""),o.dryRun){console.log(f.yellow("Dry run mode - no functions deployed."));return}let d=[];for(let l of c){let h=I.basename(I.dirname(l)),y=h==="functions"||h==="src"?I.basename(l,I.extname(l)):h,E=o.runtime||de(l);e.start(`Deploying ${y}...`);try{let _=D.readFileSync(l,"utf-8"),T=await He(t.token,a$1,y,o.envId);T||(e.text=`Creating ${y}...`,T=await Xe(t.token,a$1,{name:y,runtime:E,entrypoint:I.basename(l),envId:o.envId})),e.text=`Deploying ${y}...`,await Ze(t.token,T.id,_),e.succeed(`Deployed ${y}`),d.push({name:y,success:!0});}catch(_){let T=_ instanceof Error?_.message:"Unknown error";e.fail(`Failed to deploy ${y}`),d.push({name:y,success:false,error:T});}}console.log("");let p=d.filter(l=>l.success).length;if(d.filter(l=>!l.success).length===0)console.log(f.green(`\u2713 Successfully deployed ${p} function(s)`));else {console.log(f.yellow(`Deployed ${p}/${d.length} function(s)`)),console.log(""),console.log(f.red("Failed deployments:"));for(let l of d.filter(h=>!h.success))console.log(f.red(` - ${l.name}: ${l.error}`));}console.log("");}async function he(o){let e=K(),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 s=o.config||"vaif.config.json",r=null;try{r=await a(s);}catch{}let a$1=o.projectId||r?.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 i=await eo(t.token,a$1,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 n of i){let c=n.deployStatus==="deployed"?f.green:n.deployStatus==="deploying"?f.yellow:n.deployStatus==="failed"?f.red:f.gray;console.log(" "+n.name.padEnd(25)+n.runtime.padEnd(15)+c(n.deployStatus.padEnd(12))+String(n.invocationCount??0).padEnd(14)+(n.deployedAt?new Date(n.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 B=process.env.VAIF_API_URL||"https://api.vaif.studio";async function oo(o,e,t,s,r){let a=await fetch(`${B}/v1/projects/${e}/db/seed`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({table:t,records:s,truncate:r?.truncate??false})});if(!a.ok){let i=await a.text();throw new Error(`Failed to seed ${t}: ${i}`)}return a.json()}async function to(o,e){let t=await fetch(`${B}/v1/projects/${e}/db/reset`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}});if(!t.ok){let s=await t.text();throw new Error(`Failed to reset database: ${s}`)}return t.json()}function Q(o){let e=[];if(!D.existsSync(o))return e;let t=D.readdirSync(o,{withFileTypes:true});for(let s of t)if(s.isFile()){let r=I.extname(s.name).toLowerCase();(r===".json"||r===".ts"||r===".js")&&e.push(I.join(o,s.name));}return e.sort()}async function ye(o){let e=I.extname(o).toLowerCase();if(e===".json"){let t=D.readFileSync(o,"utf-8"),s=JSON.parse(t);return Array.isArray(s)?[{table:I.basename(o,e),data:s}]:s.table&&s.data?[s]:Object.entries(s).map(([r,a])=>({table:r,data:a}))}else if(e===".ts"||e===".js"){let t=await import(o),s=t.default||t;return typeof s=="function"?s():s}throw new Error(`Unsupported file format: ${e}`)}async function we(o){let e=K(),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 s=o.config||"vaif.config.json",r=null;try{r=await a(s);}catch{}let a$1=o.projectId||r?.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 i=[];if(o.file){let p=I.resolve(o.file);D.existsSync(p)||(console.log(f.red(`File not found: ${o.file}`)),process.exit(1)),i=[p];}else {let p=I.resolve("seeds"),g=I.resolve("prisma/seed"),l=I.resolve("db/seeds");i=[...Q(p),...Q(g),...Q(l)];}i.length===0&&(console.log(f.yellow("No seed files found")),console.log(f.gray(`
|
|
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
|
+
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(` - ${I.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 ${I.basename(p)}...`);try{let g=await ye(p);e.stop();for(let l of g)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(g){e.fail(`Failed to load ${I.basename(p)}`),g instanceof Error&&console.log(f.red(` Error: ${g.message}`));}}return}let n=[];for(let p of i){e.start(`Processing ${I.basename(p)}...`);try{let g=await ye(p);e.stop();for(let l of g)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 h=await oo(t.token,a$1,l.table,l.data,{truncate:o.truncate});e.succeed(`Seeded ${l.table}: ${h.inserted} records`),n.push({table:l.table,inserted:h.inserted});}catch(h){let y=h instanceof Error?h.message:"Unknown error";e.fail(`Failed to seed ${l.table}`),n.push({table:l.table,inserted:0,error:y});}}}catch(g){e.fail(`Failed to load ${I.basename(p)}`),g instanceof Error&&console.log(f.red(` Error: ${g.message}`));}}console.log("");let c=n.reduce((p,g)=>p+g.inserted,0),d=n.filter(p=>p.error).length;if(d===0)console.log(f.green(`\u2713 Successfully seeded ${c} records across ${n.length} table(s)`));else {console.log(f.yellow(`Seeded ${c} records with ${d} error(s)`)),console.log(""),console.log(f.red("Errors:"));for(let p of n.filter(g=>g.error))console.log(f.red(` - ${p.table}: ${p.error}`));}console.log("");}async function je(o){let e=K(),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 s=o.config||"vaif.config.json",r=null;try{r=await a(s);}catch{}let a$1=o.projectId||r?.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 i=I.resolve(o.dir||"./drizzle");if(console.log(""),console.log(f.bold("VAIF Database Push")),console.log(""),!D.existsSync(i)){let g=I.resolve("./migrations");D.existsSync(g)?console.log(f.gray(`Using migrations from: ${g}`)):(console.log(f.red(`Migrations directory not found: ${i}`)),console.log(f.gray(`
|
|
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 n=[],c=D.readdirSync(i,{withFileTypes:true});for(let g of c)if(g.isFile()&&g.name.endsWith(".sql"))n.push(I.join(i,g.name));else if(g.isDirectory()){let l=D.readdirSync(I.join(i,g.name),{withFileTypes:true});for(let h of l)h.isFile()&&h.name.endsWith(".sql")&&n.push(I.join(i,g.name,h.name));}n.sort(),n.length===0&&(console.log(f.yellow("No SQL migration files found")),process.exit(1)),console.log(f.gray(`Found ${n.length} migration(s):`));for(let g of n)console.log(f.gray(` - ${I.relative(process.cwd(),g)}`));if(console.log(""),o.dryRun){console.log(f.yellow("Dry run mode - no migrations will be applied.")),console.log("");for(let g of n){let l=D.readFileSync(g,"utf-8");console.log(f.cyan(`--- ${I.basename(g)} ---`)),console.log(f.gray(l.slice(0,500))),l.length>500&&console.log(f.gray("...")),console.log("");}return}let d=0,p=0;for(let g of n){let l=D.readFileSync(g,"utf-8"),h=I.relative(process.cwd(),g);e.start(`Applying ${h}...`);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 E=await y.text();throw new Error(E)}e.succeed(`Applied ${h}`),d++;}catch(y){let E=y instanceof Error?y.message:"Unknown error";e.fail(`Failed ${h}: ${E}`),p++;}}console.log(""),console.log(p===0?f.green(`Successfully applied ${d} migration(s)`):f.yellow(`Applied ${d}, failed ${p} migration(s)`)),console.log("");}async function ve(o){let e=K(),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 s=o.config||"vaif.config.json",r=null;try{r=await a(s);}catch{}let a$1=o.projectId||r?.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 i=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 n=await fetch(`${B}/schema-engine/introspect/${a$1}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!n.ok){let p=await n.text();throw new Error(`Failed to pull schema: ${p}`)}let c=await n.json();D.writeFileSync(i,JSON.stringify(c,null,2),"utf-8"),e.succeed(`Schema written to ${I.relative(process.cwd(),i)}`);let d=c.tables?.length??Object.keys(c).length;console.log(f.gray(` ${d} table(s) pulled`)),console.log("");}catch(n){e.fail("Failed to pull schema"),n instanceof Error&&console.log(f.red(`
|
|
22
|
+
Error: ${n.message}`)),process.exit(1);}}async function Ie(o){let e=K(),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 s=o.config||"vaif.config.json",r=null;try{r=await a(s);}catch{}let a$1=o.projectId||r?.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 to(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(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 Ae(o){let e=K(),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 s=o.config||"vaif.config.json",r=null;try{r=await a(s);}catch{}let a$1=Se(o,r,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 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 n=await fetch(`${be}/v1/projects/${a$1}/api-keys`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:i})});if(!n.ok){let d=await n.text();throw new Error(`Failed to generate key: ${d}`)}let c=await n.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(n){e.fail("Failed to generate API key"),n instanceof Error&&console.log(f.red(`
|
|
24
|
+
Error: ${n.message}`)),process.exit(1);}}async function Pe(o){let e=K(),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 s=o.config||"vaif.config.json",r=null;try{r=await a(s);}catch{}let a$1=Se(o,r,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 i=await fetch(`${be}/v1/projects/${a$1}/api-keys`,{headers:{Authorization:`Bearer ${t.token}`}});if(!i.ok){let g=await i.text();throw new Error(`Failed to list keys: ${g}`)}let n=await i.json(),c=n.keys||n;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 d=Math.max(8,...c.map(g=>(g.name||"").length)),p=` ${"Name".padEnd(d)} ${"Key".padEnd(24)} Created`;console.log(f.gray(p)),console.log(f.gray(" "+"-".repeat(p.length-2)));for(let g of c){let l=(g.name||"unnamed").padEnd(d),h=g.maskedKey||g.prefix||`${(g.key||"").slice(0,12)}...`,y=g.createdAt?new Date(g.createdAt).toLocaleDateString():"N/A";console.log(` ${l} ${h.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 V=process.env.VAIF_API_URL||"https://api.vaif.studio";function so(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 s=so(o,e,t);return s||(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)),s}async function Ce(o,e,t){let s=K(),r=M(),a=await q(t.config),i=W(t,a,r),n=e;if(t.fromFile)try{n=D.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);}n||(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(""),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 d=await fetch(c.toString(),{headers:{Authorization:`Bearer ${r.token}`}});if(!d.ok)throw new Error(`Failed to check existing secrets: ${await d.text()}`);let g=(await d.json()).find(l=>l.key===o);if(g){s.text=`Updating secret "${o}"...`;let l=await fetch(`${V}/functions/secrets/${g.id}`,{method:"PUT",headers:{Authorization:`Bearer ${r.token}`,"Content-Type":"application/json"},body:JSON.stringify({value:n})});if(!l.ok)throw new Error(`Failed to update secret: ${await l.text()}`);s.succeed(`Updated secret "${o}"`);}else {s.text=`Creating secret "${o}"...`;let l=await fetch(`${V}/functions/secrets`,{method:"POST",headers:{Authorization:`Bearer ${r.token}`,"Content-Type":"application/json"},body:JSON.stringify({projectId:i,envId:t.envId,key:o,value:n})});if(!l.ok)throw new Error(`Failed to create secret: ${await l.text()}`);s.succeed(`Created secret "${o}"`);}console.log("");}catch(c){s.fail("Failed to set secret"),c instanceof Error&&console.log(f.red(`
|
|
27
|
+
Error: ${c.message}`)),process.exit(1);}}async function ke(o){let e=K(),t=M(),s=await q(o.config),r=W(o,s,t);console.log(""),console.log(f.bold("VAIF Secrets")),console.log(""),e.start("Fetching secrets...");try{let a=new URL(`${V}/functions/secrets/project/${r}`);o.envId&&a.searchParams.set("envId",o.envId);let i=await fetch(a.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(e.stop(),n.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,...n.map(p=>p.key.length)),d=` ${"Name".padEnd(c)} Created`;console.log(f.gray(d)),console.log(f.gray(" "+"-".repeat(d.length-2)));for(let p of n){let g=p.key.padEnd(c),l=p.createdAt?new Date(p.createdAt).toLocaleDateString():"N/A";console.log(` ${g} ${l}`);}console.log(""),console.log(f.gray(` ${n.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 Fe(o,e){let t=K(),s=M(),r=await q(e.config),a=W(e,r,s);console.log(""),t.start("Fetching secret...");try{let i=new URL(`${V}/functions/secrets/project/${a}`);e.envId&&i.searchParams.set("envId",e.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 d=(await n.json()).find(l=>l.key===o);d||(t.fail(`Secret "${o}" not found`),process.exit(1));let p=await fetch(`${V}/functions/secrets/${d.id}/value`,{headers:{Authorization:`Bearer ${s.token}`}});if(!p.ok)throw new Error(`Failed to get secret value: ${await p.text()}`);let g=await p.json();t.stop(),console.log(g.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=K(),s=M(),r=await q(e.config),a=W(e,r,s);console.log(""),console.log(f.bold("VAIF Delete Secret")),console.log(""),t.start("Finding secret...");try{let i=new URL(`${V}/functions/secrets/project/${a}`);e.envId&&i.searchParams.set("envId",e.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 d=(await n.json()).find(g=>g.key===o);d||(t.fail(`Secret "${o}" not found`),process.exit(1)),t.text=`Deleting secret "${o}"...`;let p=await fetch(`${V}/functions/secrets/${d.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 "${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 De=process.env.VAIF_API_URL||"https://api.vaif.studio";function ro(o){try{let e=new URL(o);return e.password&&(e.password="****"),e.toString()}catch{return o.replace(/:[^@/]+@/,":****@")}}async function Ee(o){let e=K(),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 s=o.config||"vaif.config.json",r=null;try{r=await a(s);}catch{}let a$1=o.projectId||r?.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 i=await fetch(`${De}/v1/projects/${a$1}`,{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();e.stop(),console.log(""),console.log(f.bold("VAIF Project Info")),console.log("");let c=16,d=(p,g)=>{console.log(` ${f.gray(p.padEnd(c))} ${g}`);};d("Name:",f.white(n.name||"N/A")),d("Project ID:",f.white(a$1)),d("Region:",f.white(n.region||"us-east-1")),d("Plan:",f.white(n.plan||n.tier||"free")),d("Created:",f.white(n.createdAt?new Date(n.createdAt).toLocaleDateString():"N/A")),console.log(""),d("API URL:",f.cyan(n.apiUrl||`${De}/v1`)),d("WS URL:",f.cyan(n.wsUrl||n.realtimeUrl||"N/A")),d("DB URL:",f.cyan(n.databaseUrl?ro(n.databaseUrl):"N/A")),d("Storage URL:",f.cyan(n.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 co=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Re(o){let e=K(),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 s=o.config||"vaif.config.json",r=null;try{r=await a(s);}catch{}let a$1=o.projectId||r?.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 i=await fetch(`${co}/v1/projects/${a$1}?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 n=await i.json();e.stop(),console.log(""),console.log(f.bold("VAIF Project Status")),console.log("");let c=22,d=(y,E)=>{console.log(` ${f.gray(y.padEnd(c))} ${E}`);};d("Project:",f.white(n.name||a$1)),d("Plan:",f.white(n.plan||n.tier||"free")),console.log(""),console.log(f.gray(" --- Resources ---")),console.log("");let p=n.tableCount??n.tables?.length??"N/A",g=n.functionCount??n.functions?.length??"N/A",l=n.bucketCount??n.storage?.buckets?.length??"N/A",h=n.activeConnections??n.connections??"N/A";d("Tables:",f.white(String(p))),d("Functions:",f.white(String(g))),d("Storage Buckets:",f.white(String(l))),d("Active Connections:",f.white(String(h))),n.usage&&(console.log(""),console.log(f.gray(" --- Usage ---")),console.log(""),n.usage.dbSize&&d("Database Size:",f.white(n.usage.dbSize)),n.usage.storageSize&&d("Storage Size:",f.white(n.usage.storageSize)),n.usage.bandwidth&&d("Bandwidth:",f.white(n.usage.bandwidth)),n.usage.functionInvocations!=null&&d("Function Invocations:",f.white(String(n.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 L=process.env.VAIF_API_URL||"https://api.vaif.studio";function go(o,e,t){return o.projectId||e?.projectId||process.env.VAIF_PROJECT_ID||t.projectId||null}function fo(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}\`
|
|
34
|
+
|
|
35
|
+
`,e+=`| Column | Type | Nullable | Default | Constraints |
|
|
36
|
+
`,e+=`|--------|------|----------|---------|-------------|
|
|
37
|
+
`;for(let s of t.columns){let r=[];s.isPrimaryKey&&r.push("PK"),s.nullable||r.push("NOT NULL");let a=t.foreignKeys?.find(i=>i.column===s.name);a&&r.push(`FK \u2192 ${a.foreignTable}.${a.foreignColumn}`),e+=`| ${s.name} | ${s.type} | ${s.nullable?"yes":"no"} | ${s.defaultValue||"-"} | ${r.join(", ")||"-"} |
|
|
38
|
+
`;}e+=`
|
|
39
|
+
`;}return e}function po(o,e,t){let s=o.slice(0,3);if(s.length===0)return "";let r="";for(let a of s){let i=a.columns.filter(c=>!c.isPrimaryKey&&c.name!=="created_at"&&c.name!=="updated_at"),n=i.slice(0,3).map(c=>` ${c.name}: ${uo(c)}`).join(`,
|
|
40
|
+
`);r+=`### \`${a.name}\`
|
|
41
|
+
|
|
42
|
+
`,r+="```typescript\n",r+=`// Select all
|
|
43
|
+
const ${a.name} = await vaif.from("${a.name}").select();
|
|
44
|
+
|
|
45
|
+
`,r+=`// Select with filter
|
|
46
|
+
const filtered = await vaif.from("${a.name}").select().eq("${i[0]?.name||"id"}", value);
|
|
47
|
+
|
|
48
|
+
`,r+=`// Insert
|
|
49
|
+
const created = await vaif.from("${a.name}").insert({
|
|
50
|
+
${n}
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
`,r+=`// Update
|
|
54
|
+
await vaif.from("${a.name}").update(recordId, {
|
|
55
|
+
${i[0]?.name||"name"}: newValue
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
`,r+=`// Delete
|
|
59
|
+
await vaif.from("${a.name}").delete(recordId);
|
|
60
|
+
`,r+="```\n\n";}return r}function uo(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 mo(o){let{projectId:e,apiKey:t,apiUrl:s,projectName:r,schema:a}=o,i=fo(a.tables),n=po(a.tables);return `# VAIF Studio Backend
|
|
61
|
+
|
|
62
|
+
This project uses **VAIF Studio** as its backend. Project: **${r}** (\`${e}\`).
|
|
63
|
+
|
|
64
|
+
## SDK Setup
|
|
65
|
+
|
|
66
|
+
\`\`\`bash
|
|
67
|
+
npm install @vaiftech/client
|
|
68
|
+
\`\`\`
|
|
69
|
+
|
|
70
|
+
\`\`\`typescript
|
|
71
|
+
import { createVaifClient } from "@vaiftech/client";
|
|
72
|
+
|
|
73
|
+
const vaif = createVaifClient({
|
|
74
|
+
baseUrl: "${s}",
|
|
75
|
+
projectId: "${e}",
|
|
76
|
+
apiKey: "${t}",
|
|
77
|
+
});
|
|
78
|
+
\`\`\`
|
|
79
|
+
|
|
80
|
+
## Database Schema
|
|
81
|
+
|
|
82
|
+
${i}
|
|
83
|
+
|
|
84
|
+
## CRUD Examples
|
|
85
|
+
|
|
86
|
+
${n}
|
|
87
|
+
|
|
88
|
+
## Authentication
|
|
89
|
+
|
|
90
|
+
\`\`\`typescript
|
|
91
|
+
import { createAuthClient } from "@vaiftech/auth";
|
|
92
|
+
|
|
93
|
+
const auth = createAuthClient({
|
|
94
|
+
url: "${s}",
|
|
95
|
+
apiKey: "${t}",
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
// Sign up
|
|
99
|
+
const { user, session } = await auth.signUp({
|
|
100
|
+
email: "user@example.com",
|
|
101
|
+
password: "securePassword123",
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
// Sign in with password
|
|
105
|
+
const { session } = await auth.signInWithPassword({
|
|
106
|
+
email: "user@example.com",
|
|
107
|
+
password: "securePassword123",
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
// Sign in with OAuth
|
|
111
|
+
await auth.signInWithOAuth({ provider: "google" });
|
|
112
|
+
|
|
113
|
+
// Session management
|
|
114
|
+
const currentSession = await auth.getSession();
|
|
115
|
+
await auth.signOut();
|
|
116
|
+
|
|
117
|
+
// Listen for auth state changes
|
|
118
|
+
auth.onAuthStateChange((event) => {
|
|
119
|
+
console.log("Auth event:", event.event, event.session);
|
|
120
|
+
});
|
|
121
|
+
\`\`\`
|
|
122
|
+
|
|
123
|
+
## Storage
|
|
124
|
+
|
|
125
|
+
\`\`\`typescript
|
|
126
|
+
// Upload a file
|
|
127
|
+
const { url } = await vaif.storage.upload("avatars", file, {
|
|
128
|
+
contentType: "image/png",
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
// Download a file
|
|
132
|
+
const blob = await vaif.storage.download("avatars", "photo.png");
|
|
133
|
+
|
|
134
|
+
// Create a signed URL (expiring)
|
|
135
|
+
const { signedUrl } = await vaif.storage.createSignedUrl("avatars", "photo.png", {
|
|
136
|
+
expiresIn: 3600,
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
// List files in a bucket
|
|
140
|
+
const files = await vaif.storage.list("avatars", { limit: 100 });
|
|
141
|
+
\`\`\`
|
|
142
|
+
|
|
143
|
+
## Functions
|
|
144
|
+
|
|
145
|
+
\`\`\`typescript
|
|
146
|
+
// Invoke a serverless function
|
|
147
|
+
const result = await vaif.functions.invoke("send-welcome-email", {
|
|
148
|
+
body: { userId: "user_123", template: "welcome" },
|
|
149
|
+
});
|
|
150
|
+
\`\`\`
|
|
151
|
+
|
|
152
|
+
## Realtime
|
|
153
|
+
|
|
154
|
+
\`\`\`typescript
|
|
155
|
+
// Subscribe to a channel
|
|
156
|
+
const channel = vaif.realtime.channel("my-channel");
|
|
157
|
+
|
|
158
|
+
// Listen for postgres changes
|
|
159
|
+
channel.on("postgres_changes", {
|
|
160
|
+
event: "INSERT",
|
|
161
|
+
schema: "public",
|
|
162
|
+
table: "messages",
|
|
163
|
+
}, (payload) => {
|
|
164
|
+
console.log("New message:", payload.new);
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
// Listen for UPDATE events
|
|
168
|
+
channel.on("postgres_changes", {
|
|
169
|
+
event: "UPDATE",
|
|
170
|
+
schema: "public",
|
|
171
|
+
table: "messages",
|
|
172
|
+
}, (payload) => {
|
|
173
|
+
console.log("Updated:", payload.new, "was:", payload.old);
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
// Listen for DELETE events
|
|
177
|
+
channel.on("postgres_changes", {
|
|
178
|
+
event: "DELETE",
|
|
179
|
+
schema: "public",
|
|
180
|
+
table: "messages",
|
|
181
|
+
}, (payload) => {
|
|
182
|
+
console.log("Deleted:", payload.old);
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
// Subscribe to start receiving events
|
|
186
|
+
channel.subscribe();
|
|
187
|
+
|
|
188
|
+
// Unsubscribe when done
|
|
189
|
+
channel.unsubscribe();
|
|
190
|
+
\`\`\`
|
|
191
|
+
|
|
192
|
+
## API Reference Notes
|
|
193
|
+
|
|
194
|
+
### Filter Syntax
|
|
195
|
+
|
|
196
|
+
The SDK supports these filter operators:
|
|
197
|
+
|
|
198
|
+
| Operator | Description | Example |
|
|
199
|
+
|----------|-------------|---------|
|
|
200
|
+
| \`eq\` | Equal | \`.eq("status", "active")\` |
|
|
201
|
+
| \`neq\` | Not equal | \`.neq("status", "deleted")\` |
|
|
202
|
+
| \`gt\` | Greater than | \`.gt("age", 18)\` |
|
|
203
|
+
| \`lt\` | Less than | \`.lt("price", 100)\` |
|
|
204
|
+
| \`gte\` | Greater than or equal | \`.gte("score", 90)\` |
|
|
205
|
+
| \`lte\` | Less than or equal | \`.lte("count", 10)\` |
|
|
206
|
+
| \`in\` | In array | \`.in("role", ["admin", "editor"])\` |
|
|
207
|
+
| \`like\` | Pattern match (case-sensitive) | \`.like("name", "%john%")\` |
|
|
208
|
+
| \`ilike\` | Pattern match (case-insensitive) | \`.ilike("name", "%john%")\` |
|
|
209
|
+
| \`is\` | IS comparison (null, true, false) | \`.is("deleted_at", null)\` |
|
|
210
|
+
|
|
211
|
+
### Pagination
|
|
212
|
+
|
|
213
|
+
\`\`\`typescript
|
|
214
|
+
// Default: limit 20, offset 0
|
|
215
|
+
const page1 = await vaif.from("posts").select().limit(20).offset(0);
|
|
216
|
+
const page2 = await vaif.from("posts").select().limit(20).offset(20);
|
|
217
|
+
\`\`\`
|
|
218
|
+
|
|
219
|
+
### Auth Headers
|
|
220
|
+
|
|
221
|
+
All authenticated requests require:
|
|
222
|
+
- \`Authorization: Bearer <jwt_token>\` \u2014 for user-scoped requests
|
|
223
|
+
- \`x-api-key: <api_key>\` \u2014 for server-side / service-role requests
|
|
224
|
+
- \`x-project-id: ${e}\` \u2014 identifies the project
|
|
225
|
+
`}async function Ve(o){let e=K(),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 s=o.config||"vaif.config.json",r=null;try{r=await a(s);}catch{}let a$1=go(o,r,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 i=I.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 n={tables:[]};try{let g=await fetch(`${L}/schema-engine/introspect/${a$1}`,{headers:{Authorization:`Bearer ${t.token}`}});g.ok?(n=await g.json(),e.succeed(`Fetched schema (${n.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,d=L;try{let g=await fetch(`${L}/v1/projects/${a$1}`,{headers:{Authorization:`Bearer ${t.token}`}});if(g.ok){let l=await g.json();c=l.name||a$1,d=l.apiUrl||L,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||r?.api?.apiKey||"";if(!p){e.start("Generating API key for Claude Code...");try{let g=`claude-code-${Date.now()}`,l=await fetch(`${L}/v1/projects/${a$1}/api-keys`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:g})});l.ok?(p=(await l.json()).key,e.succeed(`Generated API key: ${g}`)):(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 g={mcpServers:{"vaif-studio":{command:"npx",args:["@vaiftech/mcp"],env:{VAIF_API_KEY:p,VAIF_PROJECT_ID:a$1,VAIF_API_URL:d,VAIF_AUTH_TOKEN:t.token}}}},l=I.join(i,".mcp.json");D.writeFileSync(l,JSON.stringify(g,null,2)+`
|
|
226
|
+
`,"utf-8"),e.succeed(`Written ${f.cyan(".mcp.json")}`);}if(!o.skipClaudeMd){e.start("Writing CLAUDE.md...");let g=mo({projectId:a$1,apiKey:p,apiUrl:d,projectName:c,schema:n}),l=I.join(i,"CLAUDE.md");D.writeFileSync(l,g,"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 Oe="1.8.0",X=f.hex("#00f0ff"),Z=f.hex("#7b61ff"),ee=f.hex("#ff3dff"),oe=f.hex("#00ff9d"),w=f.hex("#555570"),O=f.hex("#00f0ff");function ho(){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(w(" \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")+w(` v${Oe}`)),console.log(w(" Build full-stack apps at lightning speed")),console.log(w(" \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(w(" $ ")+O("vaif login")+w(" Authenticate")),console.log(w(" $ ")+O("vaif init -t react-spa")+w(" Scaffold project")),console.log(w(" $ ")+O("vaif db push")+w(" Push migrations")),console.log(w(" $ ")+O("vaif generate")+w(" Generate types")),console.log(w(" $ ")+O("vaif functions deploy")+w(" Deploy functions")),console.log(""),console.log(f.bold(" Categories")),console.log(w(" auth ")+f.white("login, logout, whoami")),console.log(w(" project ")+f.white("init, templates, info, status")),console.log(w(" schema ")+f.white("pull, push, generate")),console.log(w(" database ")+f.white("db push, db pull, db seed, db reset")),console.log(w(" deploy ")+f.white("functions deploy, functions list")),console.log(w(" security ")+f.white("keys, secrets")),console.log(w(" ai ")+f.white("claude-setup")),console.log(""),console.log(w(" Run ")+O("vaif <command> --help")+w(" for details")),console.log(w(" Docs: ")+f.underline("https://docs.vaif.studio")),console.log("");}program.name("vaif").description("VAIF CLI - Type generation and development tools").version(Oe);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(Ee);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(Re);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 Te=program.command("functions").alias("fn").description("Manage serverless functions");Te.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(me);Te.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(he);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(Ae);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(Pe);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(Ce);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(ke);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(Fe);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(Ve);process.argv.slice(2).length||(ho(),process.exit(0));program.parse(process.argv);
|