@vaiftech/cli 1.6.5 → 1.6.6
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 +1 -1
- package/dist/cli.cjs +56 -56
- package/dist/cli.js +36 -36
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
[](https://www.npmjs.com/package/@vaiftech/cli)
|
|
4
4
|
[](https://opensource.org/licenses/MIT)
|
|
5
5
|
|
|
6
|
-
Command-line tools for [VAIF Studio](https://vaif.studio) (v1.6.
|
|
6
|
+
Command-line tools for [VAIF Studio](https://vaif.studio) (v1.6.6) — scaffold full projects from templates with feature selection, browser-based authentication, manage schemas, deploy functions, generate TypeScript types, and more.
|
|
7
7
|
|
|
8
8
|
## Installation
|
|
9
9
|
|
package/dist/cli.cjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
'use strict';require('dotenv/config');var commander=require('commander'),D=require('fs'),A=require('path'),et=require('pg'),
|
|
2
|
+
'use strict';require('dotenv/config');var commander=require('commander'),D=require('fs'),A=require('path'),et=require('pg'),J=require('ora'),f=require('chalk'),ot=require('prettier'),Ze=require('dotenv'),ge=require('readline'),ut=require('os'),child_process=require('child_process');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var D__default=/*#__PURE__*/_interopDefault(D);var A__default=/*#__PURE__*/_interopDefault(A);var et__default=/*#__PURE__*/_interopDefault(et);var J__default=/*#__PURE__*/_interopDefault(J);var f__default=/*#__PURE__*/_interopDefault(f);var ot__default=/*#__PURE__*/_interopDefault(ot);var Ze__default=/*#__PURE__*/_interopDefault(Ze);var ge__default=/*#__PURE__*/_interopDefault(ge);var ut__default=/*#__PURE__*/_interopDefault(ut);Ze__default.default.config();async function I(t){let e=A__default.default.resolve(t);if(!D__default.default.existsSync(e))return null;try{let o=D__default.default.readFileSync(e,"utf-8"),n=JSON.parse(o);return n.database?.url&&(n.database.url=ue(n.database.url)),n.api?.apiKey&&(n.api.apiKey=ue(n.api.apiKey)),n}catch{throw new Error(`Failed to parse config file: ${t}`)}}function ue(t){return t.replace(/\$\{([^}]+)\}/g,(e,o)=>process.env[o]||e)}async function nt(t,e){let o=await t.query(`
|
|
3
3
|
SELECT table_name, table_type
|
|
4
4
|
FROM information_schema.tables
|
|
5
5
|
WHERE table_schema = $1
|
|
6
6
|
AND table_type = 'BASE TABLE'
|
|
7
7
|
ORDER BY table_name
|
|
8
|
-
`,[
|
|
8
|
+
`,[e]),n=await t.query(`
|
|
9
9
|
SELECT
|
|
10
10
|
table_name,
|
|
11
11
|
column_name,
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
FROM information_schema.columns
|
|
21
21
|
WHERE table_schema = $1
|
|
22
22
|
ORDER BY table_name, ordinal_position
|
|
23
|
-
`,[
|
|
23
|
+
`,[e]),r=await t.query(`
|
|
24
24
|
SELECT
|
|
25
25
|
tc.constraint_name,
|
|
26
26
|
tc.table_name,
|
|
@@ -36,7 +36,7 @@
|
|
|
36
36
|
AND ccu.table_schema = tc.table_schema
|
|
37
37
|
WHERE tc.constraint_type = 'FOREIGN KEY'
|
|
38
38
|
AND tc.table_schema = $1
|
|
39
|
-
`,[
|
|
39
|
+
`,[e]),s=await t.query(`
|
|
40
40
|
SELECT
|
|
41
41
|
t.typname as enum_name,
|
|
42
42
|
e.enumlabel as enum_value
|
|
@@ -45,9 +45,9 @@
|
|
|
45
45
|
JOIN pg_namespace n ON n.oid = t.typnamespace
|
|
46
46
|
WHERE n.nspname = $1
|
|
47
47
|
ORDER BY t.typname, e.enumsortorder
|
|
48
|
-
`,[
|
|
48
|
+
`,[e]),i=new Map;for(let l of o.rows)i.set(l.table_name,[]);for(let l of n.rows){let c=i.get(l.table_name);c&&c.push(l);}let a=new Map;for(let l of s.rows){let c=a.get(l.enum_name)||[];c.push(l.enum_value),a.set(l.enum_name,c);}return {tables:i,enums:a,foreignKeys:r.rows}}var oe={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 at(t,e){let{data_type:o,udt_name:n,is_nullable:r}=t;if(e.has(n)){let a=e.get(n).map(l=>`"${l}"`).join(" | ");return r==="YES"?`(${a}) | null`:a}if(o==="ARRAY"){let i=n.replace(/^_/,"");if(e.has(i)){let c=e.get(i).map(d=>`"${d}"`).join(" | ");return r==="YES"?`(${c})[] | null`:`(${c})[]`}let a=oe[i]||"unknown";return r==="YES"?`${a}[] | null`:`${a}[]`}let s=oe[o]||oe[n]||"unknown";return r==="YES"&&(s=`${s} | null`),s}function ne(t){return t.split(/[_\-\s]+/).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}function it(t,e){let o=ne(t),n=e.map(r=>` | "${r}"`).join(`
|
|
49
49
|
`);return `export type ${o} =
|
|
50
|
-
${n};`}function rt(e,
|
|
50
|
+
${n};`}function rt(t,e,o){let n=ne(t),r=[],s=[],i=[];for(let d of e){let p=at(d,o),u=d.column_name,m=d.column_default!==null||d.is_identity==="YES",y=d.is_nullable==="YES";r.push(` ${u}: ${p};`),m||d.column_name==="id"?s.push(` ${u}?: ${p.replace(" | null","")} | null;`):y?s.push(` ${u}?: ${p};`):s.push(` ${u}: ${p.replace(" | null","")};`),i.push(` ${u}?: ${p.replace(" | null","")} | null;`);}let a=`export interface ${n} {
|
|
51
51
|
${r.join(`
|
|
52
52
|
`)}
|
|
53
53
|
}`,l=`export interface ${n}Insert {
|
|
@@ -56,11 +56,11 @@ ${s.join(`
|
|
|
56
56
|
}`,c=`export interface ${n}Update {
|
|
57
57
|
${i.join(`
|
|
58
58
|
`)}
|
|
59
|
-
}`;return {base:a,insert:l,update:c}}function st(e,
|
|
60
|
-
`)}async function
|
|
61
|
-
Provide a connection string via:`)),console.log(f__default.default.gray(" --connection <url>")),console.log(f__default.default.gray(" DATABASE_URL environment variable")),console.log(f__default.default.gray(" vaif.config.json database.url")),process.exit(1)),
|
|
59
|
+
}`;return {base:a,insert:l,update:c}}function st(t,e,o){let n=["/**"," * 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(e.size>0){n.push("// ============ ENUMS ============"),n.push("");for(let[s,i]of e)n.push(it(s,i)),n.push("");}n.push("// ============ TABLES ============"),n.push("");let r=[];for(let[s,i]of t){let{base:a,insert:l,update:c}=rt(s,i,e);r.push(s),n.push(a),n.push(""),n.push(l),n.push(""),n.push(c),n.push("");}n.push("// ============ DATABASE SCHEMA ============"),n.push(""),n.push("export interface Database {");for(let s of r){let i=ne(s);n.push(` ${s}: {`),n.push(` Row: ${i};`),n.push(` Insert: ${i}Insert;`),n.push(` Update: ${i}Update;`),n.push(" };");}return n.push("}"),n.push(""),n.push("export type TableName = keyof Database;"),n.push(""),n.push("// ============ HELPER TYPES ============"),n.push(""),n.push('export type Row<T extends TableName> = Database[T]["Row"];'),n.push('export type Insert<T extends TableName> = Database[T]["Insert"];'),n.push('export type Update<T extends TableName> = Database[T]["Update"];'),n.push(""),n.join(`
|
|
60
|
+
`)}async function fe(t){let e=J__default.default("Loading configuration...").start();try{let o=await I(t.config),n=t.connection||o?.database?.url||process.env.DATABASE_URL;n||(e.fail("No database connection string provided"),console.log(f__default.default.yellow(`
|
|
61
|
+
Provide a connection string via:`)),console.log(f__default.default.gray(" --connection <url>")),console.log(f__default.default.gray(" DATABASE_URL environment variable")),console.log(f__default.default.gray(" vaif.config.json database.url")),process.exit(1)),e.text="Connecting to database...";let r=new et__default.default.Client({connectionString:n});await r.connect(),e.text="Introspecting schema...";let{tables:s,enums:i,foreignKeys:a}=await nt(r,t.schema);if(await r.end(),s.size===0){e.warn(`No tables found in schema "${t.schema}"`);return}e.text=`Generating types for ${s.size} tables...`;let l=st(s,i,a),c=await ot__default.default.format(l,{parser:"typescript",semi:!0,singleQuote:!1,trailingComma:"es5",printWidth:100});if(t.dryRun){e.succeed("Generated types (dry run):"),console.log(""),console.log(f__default.default.gray("\u2500".repeat(60))),console.log(c),console.log(f__default.default.gray("\u2500".repeat(60)));return}let d=A__default.default.resolve(t.output),p=A__default.default.dirname(d);D__default.default.existsSync(p)||D__default.default.mkdirSync(p,{recursive:!0}),D__default.default.writeFileSync(d,c,"utf-8"),e.succeed(`Generated types for ${s.size} tables \u2192 ${f__default.default.cyan(t.output)}`),console.log(""),console.log(f__default.default.green("Generated:")),console.log(f__default.default.gray(` Tables: ${s.size}`)),console.log(f__default.default.gray(` Enums: ${i.size}`)),console.log(""),console.log(f__default.default.gray("Import in your code:")),console.log(f__default.default.cyan(` import type { Database, Row, Insert, Update } from "${t.output.replace(/\.ts$/,"")}";`));}catch(o){e.fail("Failed to generate types"),o instanceof Error&&(console.error(f__default.default.red(`
|
|
62
62
|
Error: ${o.message}`)),o.message.includes("ECONNREFUSED")&&console.log(f__default.default.yellow(`
|
|
63
|
-
Make sure your database is running and accessible.`))),process.exit(1);}}var M=[{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"}],
|
|
63
|
+
Make sure your database is running and accessible.`))),process.exit(1);}}var M=[{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"}],me={"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:`{
|
|
64
64
|
"name": "my-vaif-app",
|
|
65
65
|
"private": true,
|
|
66
66
|
"version": "0.1.0",
|
|
@@ -3689,56 +3689,56 @@ export const posts = pgTable("posts", {
|
|
|
3689
3689
|
|
|
3690
3690
|
return Response.json({ message: \`Hello, \${name}!\` });
|
|
3691
3691
|
}
|
|
3692
|
-
`}]},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"]}};function
|
|
3693
|
-
? Which VAIF features do you want to include?`)),M.forEach((a,l)=>{let c=
|
|
3694
|
-
Unknown template: ${
|
|
3695
|
-
`)),process.exit(1));let n;
|
|
3696
|
-
No features specified.`)),console.log(f__default.default.yellow("Usage: vaif init --template <name> --add-features <features>")),console.log(f__default.default.gray("Available features: auth, database, realtime, storage, functions")),process.exit(1)):o.featureFiles&&Object.keys(o.featureFiles).length>0?n=await lt(o.defaultFeatures??["database","auth"]):n=o.defaultFeatures??[],
|
|
3697
|
-
`,"utf-8"),console.log(f__default.default.green(` merge ${c.path} (added dependencies)`)),s++;continue}catch{}if(D__default.default.existsSync(d)&&!
|
|
3698
|
-
`,"utf-8");}catch{}(o.dependencies?.length||o.devDependencies?.length)&&(console.log(""),console.log(f__default.default.bold("Install dependencies:")),o.dependencies?.length&&console.log(f__default.default.cyan(` npm install ${o.dependencies.join(" ")}`)),o.devDependencies?.length&&console.log(f__default.default.cyan(` npm install -D ${o.devDependencies.join(" ")}`))),console.log(""),console.log(f__default.default.bold.green("Project scaffolded successfully!")),console.log(""),console.log(f__default.default.bold(" Next steps:")),o.postInstructions.forEach(c=>{console.log(f__default.default.gray(` ${c}`));}),console.log(""),console.log(f__default.default.gray(" Get your project credentials at https://vaif.studio/app/security/api-keys")),console.log("");}var dt={$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
|
|
3699
|
-
--add-features requires --template to know which template to use.`)),console.log(f__default.default.gray("Example: vaif init --template react-spa --add-features functions,storage")),process.exit(1));let n=
|
|
3700
|
-
Use --force to overwrite existing configuration.`)),process.exit(1));try{if(D__default.default.writeFileSync(o,JSON.stringify(dt,null,2),"utf-8"),
|
|
3692
|
+
`}]},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"]}};function he(){console.log(""),console.log(f__default.default.bold("Available project templates")),console.log("");let t=26,e=22;console.log(` ${f__default.default.gray("Template".padEnd(t))}${f__default.default.gray("Stack".padEnd(e))}${f__default.default.gray("Description")}`),console.log(f__default.default.gray(" "+"-".repeat(t+e+40)));for(let[o,n]of Object.entries(me))console.log(` ${f__default.default.cyan(o.padEnd(t))}${f__default.default.yellow(n.tag.padEnd(e))}${f__default.default.white(n.description)}`);console.log(""),console.log(f__default.default.gray("Usage:")),console.log(f__default.default.gray(" npx @vaiftech/cli init --template <name>")),console.log(f__default.default.gray(" npx @vaiftech/cli init -t nextjs-fullstack")),console.log(f__default.default.gray(" npx @vaiftech/cli init -t react-spa --features auth,database,realtime")),console.log(""),console.log(f__default.default.gray("Available features: auth, database, realtime, storage, functions")),console.log("");}async function lt(t){if(!process.stdin.isTTY||!process.stdout.isTTY)return t;let e=new Set(t.map(n=>M.findIndex(r=>r.name===n)).filter(n=>n>=0)),o=0;return new Promise(n=>{let r=ge__default.default.createInterface({input:process.stdin,output:process.stdout});ge__default.default.emitKeypressEvents(process.stdin,r),process.stdin.setRawMode&&process.stdin.setRawMode(true);function s(){let a=M.length+2;process.stdout.write(`\x1B[${a}A`),i();}function i(){console.log(f__default.default.bold(`
|
|
3693
|
+
? Which VAIF features do you want to include?`)),M.forEach((a,l)=>{let c=e.has(l)?f__default.default.green("[x]"):"[ ]",d=l===o?f__default.default.cyan("> "):" ";console.log(`${d}${c} ${a.label} ${f__default.default.gray(`(${a.description})`)}`);}),console.log(f__default.default.gray(" (up/down to move, space to toggle, enter to confirm)"));}i(),process.stdin.on("keypress",(a,l)=>{if(l.name==="up"&&o>0)o--,s();else if(l.name==="down"&&o<M.length-1)o++,s();else if(l.name==="space")e.has(o)?e.delete(o):e.add(o),s();else if(l.name==="return"){process.stdin.setRawMode&&process.stdin.setRawMode(false),r.close();let c=[...e].sort().map(d=>M[d].name);n(c.length>0?c:t);}else l.name==="c"&&l.ctrl&&(process.stdin.setRawMode&&process.stdin.setRawMode(false),r.close(),process.exit(0));});})}async function ie(t,e={}){let o=me[t];o||(console.log(f__default.default.red(`
|
|
3694
|
+
Unknown template: ${t}`)),console.log(f__default.default.yellow(`Run 'vaif templates' to see available templates.
|
|
3695
|
+
`)),process.exit(1));let n;e.features&&e.features.length>0?n=e.features.filter(c=>M.some(d=>d.name===c)):e.addOnly?(console.log(f__default.default.red(`
|
|
3696
|
+
No features specified.`)),console.log(f__default.default.yellow("Usage: vaif init --template <name> --add-features <features>")),console.log(f__default.default.gray("Available features: auth, database, realtime, storage, functions")),process.exit(1)):o.featureFiles&&Object.keys(o.featureFiles).length>0?n=await lt(o.defaultFeatures??["database","auth"]):n=o.defaultFeatures??[],e.addOnly?(console.log(""),console.log(f__default.default.bold(`Adding features to ${f__default.default.cyan(o.name)} project...`)),console.log(f__default.default.gray(` Features: ${n.join(", ")}`)),console.log("")):(console.log(""),console.log(f__default.default.bold(`Scaffolding ${f__default.default.cyan(o.name)} template...`)),n.length>0&&console.log(f__default.default.gray(` Features: ${n.join(", ")}`)),console.log(""));let r=e.addOnly?[]:[...o.files];if(o.featureFiles)for(let c of n){let d=o.featureFiles[c];d&&r.push(...d);}let s=0,i=0;for(let c of r){let d=A__default.default.resolve(c.path),p=A__default.default.dirname(d);if(D__default.default.existsSync(p)||D__default.default.mkdirSync(p,{recursive:true}),c.path==="package.json"&&D__default.default.existsSync(d)&&!e.force)try{let u=JSON.parse(D__default.default.readFileSync(d,"utf-8")),m=JSON.parse(c.content),y=R=>{if(!R)return {};let O={};for(let[$,B]of Object.entries(R))!B.startsWith("workspace:")&&!B.startsWith("link:")&&!B.startsWith("file:")&&(O[$]=B);return O};u.dependencies={...y(u.dependencies),...m.dependencies||{}},u.devDependencies={...y(u.devDependencies),...m.devDependencies||{}},m.scripts&&(u.scripts={...u.scripts||{},...m.scripts}),D__default.default.writeFileSync(d,JSON.stringify(u,null,2)+`
|
|
3697
|
+
`,"utf-8"),console.log(f__default.default.green(` merge ${c.path} (added dependencies)`)),s++;continue}catch{}if(D__default.default.existsSync(d)&&!e.force){console.log(f__default.default.yellow(` skip ${c.path} (already exists)`)),i++;continue}D__default.default.writeFileSync(d,c.content,"utf-8"),console.log(f__default.default.green(` create ${c.path}`)),s++;}console.log(""),s>0&&console.log(f__default.default.green(`Created ${s} file${s!==1?"s":""}.`)),i>0&&console.log(f__default.default.yellow(`Skipped ${i} file${i!==1?"s":""} (use --force to overwrite).`));let a={auth:{"@vaiftech/auth":"^1.0.0"},database:{},realtime:{},storage:{},functions:{}},l=A__default.default.resolve("package.json");if(D__default.default.existsSync(l)&&n.length>0)try{let c=JSON.parse(D__default.default.readFileSync(l,"utf-8")),d=!1;for(let p of n){let u=a[p];if(u)for(let[m,y]of Object.entries(u))c.dependencies?.[m]||(c.dependencies=c.dependencies||{},c.dependencies[m]=y,d=!0);}d&&D__default.default.writeFileSync(l,JSON.stringify(c,null,2)+`
|
|
3698
|
+
`,"utf-8");}catch{}(o.dependencies?.length||o.devDependencies?.length)&&(console.log(""),console.log(f__default.default.bold("Install dependencies:")),o.dependencies?.length&&console.log(f__default.default.cyan(` npm install ${o.dependencies.join(" ")}`)),o.devDependencies?.length&&console.log(f__default.default.cyan(` npm install -D ${o.devDependencies.join(" ")}`))),console.log(""),console.log(f__default.default.bold.green("Project scaffolded successfully!")),console.log(""),console.log(f__default.default.bold(" Next steps:")),o.postInstructions.forEach(c=>{console.log(f__default.default.gray(` ${c}`));}),console.log(""),console.log(f__default.default.gray(" Get your project credentials at https://vaif.studio/app/security/api-keys")),console.log("");}var dt={$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 ye(t){if(t.addFeatures){t.template||(console.log(f__default.default.red(`
|
|
3699
|
+
--add-features requires --template to know which template to use.`)),console.log(f__default.default.gray("Example: vaif init --template react-spa --add-features functions,storage")),process.exit(1));let n=t.addFeatures.split(",").map(r=>r.trim());await ie(t.template,{force:t.force,features:n,addOnly:true});return}let e=J__default.default("Initializing VAIF configuration...").start(),o=A__default.default.resolve("vaif.config.json");D__default.default.existsSync(o)&&!t.force&&(e.fail("vaif.config.json already exists"),console.log(f__default.default.yellow(`
|
|
3700
|
+
Use --force to overwrite existing configuration.`)),process.exit(1));try{if(D__default.default.writeFileSync(o,JSON.stringify(dt,null,2),"utf-8"),e.succeed("Created vaif.config.json"),t.template){let n=t.features?t.features.split(",").map(r=>r.trim()):void 0;await ie(t.template,{force:t.force,features:n});}else {let n=A__default.default.resolve(".env.example");if(D__default.default.existsSync(n)||(D__default.default.writeFileSync(n,`# VAIF Configuration
|
|
3701
3701
|
DATABASE_URL=postgresql://user:password@localhost:5432/database
|
|
3702
3702
|
VAIF_API_KEY=your-api-key
|
|
3703
|
-
`,"utf-8"),console.log(f__default.default.gray("Created .env.example"))),
|
|
3704
|
-
Error: ${n.message}`)),process.exit(1);}}var
|
|
3705
|
-
Could not connect to VAIF API. Please try again later.`)),process.exit(1));let l=await a.json();o=l.code,n=l.url;}catch{
|
|
3706
|
-
Could not connect to VAIF API.`)),console.log(f__default.default.gray("Check your internet connection or try: vaif login --email")),process.exit(1);}
|
|
3707
|
-
The authentication session expired. Please try again.`)),process.exit(1));continue}let l=await a.json();if(l.ok&&l.accessToken){let c={token:l.accessToken,email:l.user?.email,projectId:
|
|
3708
|
-
Timed out waiting for browser authentication.`)),console.log(f__default.default.gray("Try again or use: vaif login --email")),process.exit(1);}async function It(
|
|
3703
|
+
`,"utf-8"),console.log(f__default.default.gray("Created .env.example"))),t.typescript){let r=A__default.default.resolve("src/types");D__default.default.existsSync(r)||(D__default.default.mkdirSync(r,{recursive:!0}),console.log(f__default.default.gray("Created src/types directory")));}console.log(""),console.log(f__default.default.green("VAIF initialized successfully!")),console.log(""),console.log(f__default.default.gray("Next steps:")),console.log(f__default.default.gray(" 1. Update vaif.config.json with your project ID")),console.log(f__default.default.gray(" 2. Set DATABASE_URL in your environment")),console.log(f__default.default.gray(" 3. Run: npx vaif generate")),console.log("");}}catch(n){e.fail("Failed to initialize"),n instanceof Error&&console.error(f__default.default.red(`
|
|
3704
|
+
Error: ${n.message}`)),process.exit(1);}}var se=A__default.default.join(ut__default.default.homedir(),".vaif"),k=A__default.default.join(se,"auth.json"),q=process.env.VAIF_API_URL||"https://api.vaif.studio";function ft(){D__default.default.existsSync(se)||D__default.default.mkdirSync(se,{recursive:true});}function Ie(t){ft(),D__default.default.writeFileSync(k,JSON.stringify(t,null,2),"utf-8"),D__default.default.chmodSync(k,384);}function w(){if(!D__default.default.existsSync(k))return null;try{let t=D__default.default.readFileSync(k,"utf-8");return JSON.parse(t)}catch{return null}}function gt(t){let e=ge__default.default.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(t,n=>{e.close(),o(n);});})}function mt(t){return new Promise(e=>{let o=ge__default.default.createInterface({input:process.stdin,output:process.stdout});process.stdin;let r=process.stdout.write.bind(process.stdout),s=false;process.stdout.write=((...i)=>s?true:r(...i)),o.question(t,i=>{s=false,process.stdout.write=r,console.log(""),o.close(),e(i);}),s=true;})}function ht(t){let e=process.platform,o;e==="darwin"?o=`open "${t}"`:e==="win32"?o=`start "" "${t}"`:o=`xdg-open "${t}"`,child_process.exec(o,n=>{});}function yt(t){return new Promise(e=>setTimeout(e,t))}async function vt(t){try{let e=await fetch(`${q}/auth/me`,{headers:{Authorization:`Bearer ${t}`}});if(e.ok){let o=await e.json();return {valid:!0,email:o.user?.email||o.email}}return {valid:!1}}catch{return {valid:false}}}async function bt(t){let e=J__default.default();e.start("Setting up authentication...");let o,n;try{let a=await fetch(`${q}/auth/cli/authorize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})});a.ok||(e.fail("Failed to initiate authentication"),console.log(f__default.default.red(`
|
|
3705
|
+
Could not connect to VAIF API. Please try again later.`)),process.exit(1));let l=await a.json();o=l.code,n=l.url;}catch{e.fail("Failed to connect to VAIF API"),console.log(f__default.default.red(`
|
|
3706
|
+
Could not connect to VAIF API.`)),console.log(f__default.default.gray("Check your internet connection or try: vaif login --email")),process.exit(1);}e.stop(),console.log(f__default.default.cyan(" Opening browser for authentication...")),console.log(""),console.log(f__default.default.gray(" If the browser doesn't open, visit this URL:")),console.log(f__default.default.white(` ${n}`)),console.log(""),ht(n),e.start("Waiting for browser authentication...");let r=12e4,s=2e3,i=Date.now();for(;Date.now()-i<r;){await yt(s);try{let a=await fetch(`${q}/auth/cli/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:o})});if(!a.ok){let c=await a.json();(c.error==="ExpiredCode"||c.error==="InvalidCode")&&(e.fail("Authentication expired"),console.log(f__default.default.red(`
|
|
3707
|
+
The authentication session expired. Please try again.`)),process.exit(1));continue}let l=await a.json();if(l.ok&&l.accessToken){let c={token:l.accessToken,email:l.user?.email,projectId:t,expiresAt:new Date(Date.now()+l.expiresIn*1e3).toISOString()};Ie(c),e.succeed("Logged in successfully"),console.log(""),l.user?.email&&console.log(f__default.default.green(` Authenticated as: ${l.user.email}`)),console.log(f__default.default.gray(` Config saved to: ${k}`)),console.log("");return}}catch{}}e.fail("Authentication timed out"),console.log(f__default.default.red(`
|
|
3708
|
+
Timed out waiting for browser authentication.`)),console.log(f__default.default.gray("Try again or use: vaif login --email")),process.exit(1);}async function It(t){console.log(""),console.log(f__default.default.bold("VAIF CLI Login")),console.log(f__default.default.gray("Enter your VAIF account credentials")),console.log("");let e=await gt(f__default.default.cyan(" Email: "));(!e||e.trim()==="")&&(console.log(f__default.default.red(`
|
|
3709
3709
|
No email provided. Login cancelled.`)),process.exit(1));let o=await mt(f__default.default.cyan(" Password: "));(!o||o.trim()==="")&&(console.log(f__default.default.red(`
|
|
3710
|
-
No password provided. Login cancelled.`)),process.exit(1));let n=
|
|
3711
|
-
${s.message||"Invalid email or password."}`)),process.exit(1));let i={token:s.accessToken,email:s.user?.email,projectId:
|
|
3712
|
-
Could not connect to VAIF API. Please try again later.`)),process.exit(1);}}async function
|
|
3713
|
-
Your session has expired. Please login again.`)),process.exit(1)),
|
|
3714
|
-
Error: ${i}`)),process.exit(1);}r||(
|
|
3715
|
-
Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1)),
|
|
3716
|
-
Error: ${i.message}`)),process.exit(1);}}var
|
|
3717
|
-
Error: ${l}`)),process.exit(1);}r||(
|
|
3718
|
-
Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1));let i=
|
|
3719
|
-
Expected schema file at: ${i}`)),console.log(f__default.default.gray("Run `vaif pull` first to fetch the current schema.")),process.exit(1));let a;try{let l=D__default.default.readFileSync(i,"utf-8");a=JSON.parse(l);}catch(l){
|
|
3720
|
-
Error: ${l.message}`)),process.exit(1);}
|
|
3721
|
-
Cancelled. No changes applied.`));return}}
|
|
3722
|
-
Error: ${l.message}`)),process.exit(1);}}var
|
|
3710
|
+
No password provided. Login cancelled.`)),process.exit(1));let n=J__default.default("Authenticating...").start();try{let r=await fetch(`${q}/auth/cli/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e.trim(),password:o})}),s=await r.json();(!r.ok||!s.ok)&&(n.fail("Login failed"),console.log(f__default.default.red(`
|
|
3711
|
+
${s.message||"Invalid email or password."}`)),process.exit(1));let i={token:s.accessToken,email:s.user?.email,projectId:t,expiresAt:new Date(Date.now()+s.expiresIn*1e3).toISOString()};Ie(i),n.succeed("Logged in successfully"),console.log(""),s.user?.email&&console.log(f__default.default.green(` Authenticated as: ${s.user.email}`)),console.log(f__default.default.gray(` Config saved to: ${k}`)),console.log("");}catch{n.fail("Failed to connect to VAIF API"),console.log(f__default.default.red(`
|
|
3712
|
+
Could not connect to VAIF API. Please try again later.`)),process.exit(1);}}async function Ae(t){console.log(""),console.log(f__default.default.bold("Welcome to VAIF CLI")),console.log(f__default.default.gray("Authenticate to access your VAIF projects")),console.log(""),t.email?await It(t.projectId):await bt(t.projectId),console.log(f__default.default.gray("You can now use VAIF CLI commands like:")),console.log(f__default.default.gray(" vaif pull - Pull remote schema")),console.log(f__default.default.gray(" vaif push - Push schema changes")),console.log(f__default.default.gray(" vaif generate - Generate TypeScript types")),console.log("");}async function we(){D__default.default.existsSync(k)?(D__default.default.unlinkSync(k),console.log(f__default.default.green("Logged out successfully"))):console.log(f__default.default.yellow("Not currently logged in"));}async function Se(){let t=w();(!t||!t.token)&&(console.log(f__default.default.yellow("Not logged in")),console.log(f__default.default.gray("Run `vaif login` to authenticate")),process.exit(1));let e=J__default.default("Checking authentication...").start(),{valid:o,email:n}=await vt(t.token);o||(e.fail("Session expired"),console.log(f__default.default.yellow(`
|
|
3713
|
+
Your session has expired. Please login again.`)),process.exit(1)),e.succeed("Authenticated"),console.log(""),console.log(f__default.default.green(` Email: ${n||t.email||"Unknown"}`)),t.projectId&&console.log(f__default.default.green(` Project: ${t.projectId}`)),console.log("");}var Et=process.env.VAIF_API_URL||"https://api.vaif.studio";async function _t(t,e,o="public"){let n=await fetch(`${Et}/v1/projects/${e}/schema?schema=${o}`,{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}});if(!n.ok){let r=await n.text();throw new Error(`Failed to fetch schema: ${r}`)}return n.json()}async function Ee(t){let e=J__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;e.start("Loading configuration...");try{r=await I(n);}catch(i){e.fail("Failed to load config"),console.log(f__default.default.red(`
|
|
3714
|
+
Error: ${i}`)),process.exit(1);}r||(e.fail("No configuration found"),console.log(f__default.default.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let s=t.projectId||r.projectId||process.env.VAIF_PROJECT_ID||o.projectId;s||(e.fail("No project ID specified"),console.log(f__default.default.yellow(`
|
|
3715
|
+
Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1)),e.text="Fetching remote schema...";try{let i=t.schema||r.database?.schema||"public",a=await _t(o.token,s,i);e.succeed("Schema fetched successfully");let l=t.output||A__default.default.resolve("vaif.schema.json"),c={$schema:"https://vaif.studio/schemas/schema.json",projectId:s,schema:i,pulledAt:new Date().toISOString(),...a};D__default.default.writeFileSync(l,JSON.stringify(c,null,2),"utf-8"),console.log(""),console.log(f__default.default.green(`Schema saved to: ${l}`)),console.log(""),console.log(f__default.default.gray("Schema summary:")),console.log(f__default.default.gray(` Tables: ${(a.tables||[]).length}`)),console.log(f__default.default.gray(` Enums: ${(a.enums||[]).length}`)),console.log(f__default.default.gray(` Functions: ${(a.functions||[]).length}`)),console.log(""),console.log(f__default.default.gray("Next steps:")),console.log(f__default.default.gray(" - Run `vaif generate` to generate TypeScript types")),console.log(f__default.default.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__default.default.red(`
|
|
3716
|
+
Error: ${i.message}`)),process.exit(1);}}var xe=process.env.VAIF_API_URL||"https://api.vaif.studio";function Pt(t){let e=ge__default.default.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(t,n=>{e.close(),o(n);});})}async function jt(t,e,o){let n=await fetch(`${xe}/v1/projects/${e}/schema/preview`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({schema:o})});if(!n.ok){let r=await n.text();throw new Error(`Failed to preview changes: ${r}`)}return n.json()}async function Ct(t,e,o){let n=await fetch(`${xe}/v1/projects/${e}/schema/apply`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({schema:o})});if(!n.ok){let r=await n.text();throw new Error(`Failed to apply changes: ${r}`)}return n.json()}function Rt(t){if(console.log(""),console.log(f__default.default.bold("Schema Changes:")),console.log(""),t.added.length===0&&t.modified.length===0&&t.removed.length===0){console.log(f__default.default.gray(" No changes detected. Schema is up to date."));return}if(t.added.length>0){console.log(f__default.default.green.bold(" + Added:"));for(let e of t.added)console.log(f__default.default.green(` + ${e.type}: ${e.name}`));console.log("");}if(t.modified.length>0){console.log(f__default.default.yellow.bold(" ~ Modified:"));for(let e of t.modified){console.log(f__default.default.yellow(` ~ ${e.type}: ${e.name}`));for(let o of e.changes)console.log(f__default.default.gray(` ${o}`));}console.log("");}if(t.removed.length>0){console.log(f__default.default.red.bold(" - Removed:"));for(let e of t.removed)console.log(f__default.default.red(` - ${e.type}: ${e.name}`));console.log("");}}async function Te(t){let e=J__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;e.start("Loading configuration...");try{r=await I(n);}catch(l){e.fail("Failed to load config"),console.log(f__default.default.red(`
|
|
3717
|
+
Error: ${l}`)),process.exit(1);}r||(e.fail("No configuration found"),console.log(f__default.default.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let s=t.projectId||r.projectId||process.env.VAIF_PROJECT_ID||o.projectId;s||(e.fail("No project ID specified"),console.log(f__default.default.yellow(`
|
|
3718
|
+
Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1));let i=t.schema||A__default.default.resolve("vaif.schema.json");D__default.default.existsSync(i)||(e.fail("No local schema found"),console.log(f__default.default.yellow(`
|
|
3719
|
+
Expected schema file at: ${i}`)),console.log(f__default.default.gray("Run `vaif pull` first to fetch the current schema.")),process.exit(1));let a;try{let l=D__default.default.readFileSync(i,"utf-8");a=JSON.parse(l);}catch(l){e.fail("Failed to parse schema file"),l instanceof Error&&console.log(f__default.default.red(`
|
|
3720
|
+
Error: ${l.message}`)),process.exit(1);}e.text="Calculating schema changes...";try{let{diff:l,sql:c}=await jt(o.token,s,a);if(e.stop(),Rt(l),l.added.length===0&&l.modified.length===0&&l.removed.length===0){console.log("");return}if(c.length>0){console.log(f__default.default.bold("SQL Migrations:")),console.log("");for(let p of c)console.log(f__default.default.gray(` ${p}`));console.log("");}if(t.dryRun){console.log(f__default.default.yellow("Dry run mode - no changes applied.")),console.log(f__default.default.gray("Remove --dry-run to apply these changes."));return}if(!t.force){l.removed.length>0&&(console.log(f__default.default.red.bold("\u26A0\uFE0F Warning: This will remove tables/columns from your database.")),console.log(f__default.default.red(" This action cannot be undone!")),console.log(""));let u=await Pt(f__default.default.cyan("Apply these changes? [y/N] "));if(u.toLowerCase()!=="y"&&u.toLowerCase()!=="yes"){console.log(f__default.default.yellow(`
|
|
3721
|
+
Cancelled. No changes applied.`));return}}e.start("Applying schema changes...");let d=await Ct(o.token,s,a);if(d.success){if(e.succeed("Schema changes applied successfully"),console.log(""),d.migrations.length>0){console.log(f__default.default.gray("Migrations applied:"));for(let p of d.migrations)console.log(f__default.default.gray(` - ${p}`));console.log("");}console.log(f__default.default.green("Your database schema is now up to date.")),console.log(f__default.default.gray("Run `vaif generate` to update your TypeScript types.")),console.log("");}else e.fail("Failed to apply some changes");}catch(l){e.fail("Failed to push schema changes"),l instanceof Error&&console.log(f__default.default.red(`
|
|
3722
|
+
Error: ${l.message}`)),process.exit(1);}}var Y=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Nt(t,e,o,n){let r=new URL(`${Y}/functions/project/${e}`);n&&r.searchParams.set("envId",n);let s=await fetch(r.toString(),{headers:{Authorization:`Bearer ${t}`}});if(!s.ok)return null;let i=await s.json(),a=i.functions||i;return Array.isArray(a)&&a.find(l=>l.name===o)||null}async function Dt(t,e,o){let n=await fetch(`${Y}/functions/`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({projectId:e,name:o.name,runtime:o.runtime,entrypoint:o.entrypoint,envId:o.envId})});if(!n.ok){let r=await n.text();throw new Error(`Failed to create function: ${r}`)}return n.json()}async function Vt(t,e,o){let n=await fetch(`${Y}/functions/${e}/source`,{method:"PUT",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({sourceCode:o})});if(!n.ok){let r=await n.text();throw new Error(`Failed to deploy source: ${r}`)}}async function Lt(t,e,o){let n=new URL(`${Y}/functions/project/${e}`);o&&n.searchParams.set("envId",o);let r=await fetch(n.toString(),{headers:{Authorization:`Bearer ${t}`}});if(!r.ok){let i=await r.text();throw new Error(`Failed to list functions: ${i}`)}let s=await r.json();return s.functions||s}function Fe(t){switch(A__default.default.extname(t).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(t){let e=[],o=[".ts",".js",".mjs",".py",".go",".rs"],n=["drizzle.config.ts","tsconfig.json","package.json"];if(!D__default.default.existsSync(t))return e;let r=D__default.default.readdirSync(t,{withFileTypes:true});for(let s of r){let i=A__default.default.join(t,s.name);if(s.isDirectory()){if(s.name!=="node_modules"&&!s.name.startsWith(".")){let a=D__default.default.readdirSync(i,{withFileTypes:true});for(let l of a)if(l.isFile()){let c=A__default.default.extname(l.name).toLowerCase();if(o.includes(c)){e.push(A__default.default.join(i,l.name));break}}}}else if(s.isFile()){let a=A__default.default.extname(s.name).toLowerCase();o.includes(a)&&!n.includes(s.name)&&e.push(i);}}return e}async function Ce(t){let e=J__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let s=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;s||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(f__default.default.bold("VAIF Functions Deploy")),console.log(""),e.start("Scanning for function files...");let i=A__default.default.resolve("functions"),a=A__default.default.resolve("src/functions"),l=[];if(t.entrypoint){let u=A__default.default.resolve(t.entrypoint);D__default.default.existsSync(u)||(e.fail(`File not found: ${t.entrypoint}`),process.exit(1)),l=[u];}else l=[...Pe(i),...Pe(a)];l.length===0&&(e.fail("No function files found"),console.log(f__default.default.yellow(`
|
|
3723
3723
|
Place your functions in:`)),console.log(f__default.default.gray(" - ./functions/")),console.log(f__default.default.gray(" - ./src/functions/")),console.log(f__default.default.gray(`
|
|
3724
|
-
Or specify an entrypoint with --entrypoint`)),process.exit(1)),
|
|
3725
|
-
No functions matching "${
|
|
3726
|
-
No functions found`)),console.log(f__default.default.gray("Deploy your first function with: vaif functions deploy"));return}console.log(""),console.log(f__default.default.bold(`Functions (${i.length}):`)),console.log(""),console.log(f__default.default.gray(" "+"NAME".padEnd(25)+"RUNTIME".padEnd(15)+"
|
|
3727
|
-
Error: ${i.message}`)),process.exit(1);}}var
|
|
3724
|
+
Or specify an entrypoint with --entrypoint`)),process.exit(1)),e.succeed(`Found ${l.length} function(s)`),t.name&&(l=l.filter(u=>A__default.default.basename(u,A__default.default.extname(u)).includes(t.name)),l.length===0&&(console.log(f__default.default.yellow(`
|
|
3725
|
+
No functions matching "${t.name}" found`)),process.exit(1))),console.log(""),console.log(f__default.default.gray("Functions to deploy:"));for(let u of l){let m=A__default.default.basename(A__default.default.dirname(u)),y=m==="functions"||m==="src"?A__default.default.basename(u,A__default.default.extname(u)):m,R=t.runtime||Fe(u);console.log(f__default.default.gray(` - ${y} (${R})`));}if(console.log(""),t.dryRun){console.log(f__default.default.yellow("Dry run mode - no functions deployed."));return}let c=[];for(let u of l){let m=A__default.default.basename(A__default.default.dirname(u)),y=m==="functions"||m==="src"?A__default.default.basename(u,A__default.default.extname(u)):m,R=t.runtime||Fe(u);e.start(`Deploying ${y}...`);try{let O=D__default.default.readFileSync(u,"utf-8"),$=await Nt(o.token,s,y,t.envId);$||(e.text=`Creating ${y}...`,$=await Dt(o.token,s,{name:y,runtime:R,entrypoint:A__default.default.basename(u),envId:t.envId})),e.text=`Deploying ${y}...`,await Vt(o.token,$.id,O),e.succeed(`Deployed ${y}`),c.push({name:y,success:!0});}catch(O){let $=O instanceof Error?O.message:"Unknown error";e.fail(`Failed to deploy ${y}`),c.push({name:y,success:false,error:$});}}console.log("");let d=c.filter(u=>u.success).length;if(c.filter(u=>!u.success).length===0)console.log(f__default.default.green(`\u2713 Successfully deployed ${d} function(s)`));else {console.log(f__default.default.yellow(`Deployed ${d}/${c.length} function(s)`)),console.log(""),console.log(f__default.default.red("Failed deployments:"));for(let u of c.filter(m=>!m.success))console.log(f__default.default.red(` - ${u.name}: ${u.error}`));}console.log("");}async function Re(t){let e=J__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let s=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;s||(console.log(f__default.default.red("No project ID specified")),process.exit(1)),e.start("Fetching functions...");try{let i=await Lt(o.token,s,t.envId);if(e.stop(),i.length===0){console.log(f__default.default.yellow(`
|
|
3726
|
+
No functions found`)),console.log(f__default.default.gray("Deploy your first function with: vaif functions deploy"));return}console.log(""),console.log(f__default.default.bold(`Functions (${i.length}):`)),console.log(""),console.log(f__default.default.gray(" "+"NAME".padEnd(25)+"RUNTIME".padEnd(15)+"STATUS".padEnd(12)+"INVOCATIONS".padEnd(14)+"LAST DEPLOYED")),console.log(f__default.default.gray(" "+"-".repeat(80)));for(let a of i){let l=a.deployStatus==="deployed"?f__default.default.green:a.deployStatus==="deploying"?f__default.default.yellow:a.deployStatus==="failed"?f__default.default.red:f__default.default.gray;console.log(" "+a.name.padEnd(25)+a.runtime.padEnd(15)+l(a.deployStatus.padEnd(12))+String(a.invocationCount??0).padEnd(14)+(a.deployedAt?new Date(a.deployedAt).toLocaleDateString():"-"));}console.log("");}catch(i){e.fail("Failed to fetch functions"),i instanceof Error&&console.log(f__default.default.red(`
|
|
3727
|
+
Error: ${i.message}`)),process.exit(1);}}var G=process.env.VAIF_API_URL||"https://api.vaif.studio";async function kt(t,e,o,n,r){let s=await fetch(`${G}/v1/projects/${e}/db/seed`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({table:o,records:n,truncate:r?.truncate??false})});if(!s.ok){let i=await s.text();throw new Error(`Failed to seed ${o}: ${i}`)}return s.json()}async function Ut(t,e){let o=await fetch(`${G}/v1/projects/${e}/db/reset`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}});if(!o.ok){let n=await o.text();throw new Error(`Failed to reset database: ${n}`)}return o.json()}function ce(t){let e=[];if(!D__default.default.existsSync(t))return e;let o=D__default.default.readdirSync(t,{withFileTypes:true});for(let n of o)if(n.isFile()){let r=A__default.default.extname(n.name).toLowerCase();(r===".json"||r===".ts"||r===".js")&&e.push(A__default.default.join(t,n.name));}return e.sort()}async function Ne(t){let e=A__default.default.extname(t).toLowerCase();if(e===".json"){let o=D__default.default.readFileSync(t,"utf-8"),n=JSON.parse(o);return Array.isArray(n)?[{table:A__default.default.basename(t,e),data:n}]:n.table&&n.data?[n]:Object.entries(n).map(([r,s])=>({table:r,data:s}))}else if(e===".ts"||e===".js"){let o=await import(t),n=o.default||o;return typeof n=="function"?n():n}throw new Error(`Unsupported file format: ${e}`)}async function De(t){let e=J__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let s=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;s||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(f__default.default.bold("VAIF Database Seed")),console.log("");let i=[];if(t.file){let d=A__default.default.resolve(t.file);D__default.default.existsSync(d)||(console.log(f__default.default.red(`File not found: ${t.file}`)),process.exit(1)),i=[d];}else {let d=A__default.default.resolve("seeds"),p=A__default.default.resolve("prisma/seed"),u=A__default.default.resolve("db/seeds");i=[...ce(d),...ce(p),...ce(u)];}i.length===0&&(console.log(f__default.default.yellow("No seed files found")),console.log(f__default.default.gray(`
|
|
3728
3728
|
Place your seed files in one of these directories:`)),console.log(f__default.default.gray(" - ./seeds/")),console.log(f__default.default.gray(" - ./prisma/seed/")),console.log(f__default.default.gray(" - ./db/seeds/")),console.log(f__default.default.gray(`
|
|
3729
3729
|
Or specify a file with --file`)),console.log(f__default.default.gray(`
|
|
3730
|
-
Example seed file (seeds/users.json):`)),console.log(f__default.default.gray(" [")),console.log(f__default.default.gray(' { "name": "John Doe", "email": "john@example.com" },')),console.log(f__default.default.gray(' { "name": "Jane Doe", "email": "jane@example.com" }')),console.log(f__default.default.gray(" ]")),process.exit(1)),console.log(f__default.default.gray("Seed files found:"));for(let d of i)console.log(f__default.default.gray(` - ${A__default.default.relative(process.cwd(),d)}`));if(console.log(""),
|
|
3730
|
+
Example seed file (seeds/users.json):`)),console.log(f__default.default.gray(" [")),console.log(f__default.default.gray(' { "name": "John Doe", "email": "john@example.com" },')),console.log(f__default.default.gray(' { "name": "Jane Doe", "email": "jane@example.com" }')),console.log(f__default.default.gray(" ]")),process.exit(1)),console.log(f__default.default.gray("Seed files found:"));for(let d of i)console.log(f__default.default.gray(` - ${A__default.default.relative(process.cwd(),d)}`));if(console.log(""),t.truncate&&(console.log(f__default.default.yellow("\u26A0\uFE0F Tables will be truncated before seeding")),console.log("")),t.dryRun){console.log(f__default.default.yellow("Dry run mode - no data will be inserted.")),console.log("");for(let d of i){e.start(`Loading ${A__default.default.basename(d)}...`);try{let p=await Ne(d);e.stop();for(let u of p)t.table&&u.table!==t.table||(console.log(f__default.default.cyan(`Table: ${u.table}`)),console.log(f__default.default.gray(` Records: ${u.data.length}`)),u.data.length>0&&console.log(f__default.default.gray(` Sample: ${JSON.stringify(u.data[0],null,2).slice(0,100)}...`)),console.log(""));}catch(p){e.fail(`Failed to load ${A__default.default.basename(d)}`),p instanceof Error&&console.log(f__default.default.red(` Error: ${p.message}`));}}return}let a=[];for(let d of i){e.start(`Processing ${A__default.default.basename(d)}...`);try{let p=await Ne(d);e.stop();for(let u of p)if(!(t.table&&u.table!==t.table)){if(u.data.length===0){console.log(f__default.default.gray(` Skipping ${u.table} (no records)`));continue}e.start(`Seeding ${u.table} (${u.data.length} records)...`);try{let m=await kt(o.token,s,u.table,u.data,{truncate:t.truncate});e.succeed(`Seeded ${u.table}: ${m.inserted} records`),a.push({table:u.table,inserted:m.inserted});}catch(m){let y=m instanceof Error?m.message:"Unknown error";e.fail(`Failed to seed ${u.table}`),a.push({table:u.table,inserted:0,error:y});}}}catch(p){e.fail(`Failed to load ${A__default.default.basename(d)}`),p instanceof Error&&console.log(f__default.default.red(` Error: ${p.message}`));}}console.log("");let l=a.reduce((d,p)=>d+p.inserted,0),c=a.filter(d=>d.error).length;if(c===0)console.log(f__default.default.green(`\u2713 Successfully seeded ${l} records across ${a.length} table(s)`));else {console.log(f__default.default.yellow(`Seeded ${l} records with ${c} error(s)`)),console.log(""),console.log(f__default.default.red("Errors:"));for(let d of a.filter(p=>p.error))console.log(f__default.default.red(` - ${d.table}: ${d.error}`));}console.log("");}async function Ve(t){let e=J__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let s=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;s||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=A__default.default.resolve(t.dir||"./drizzle");if(console.log(""),console.log(f__default.default.bold("VAIF Database Push")),console.log(""),!D__default.default.existsSync(i)){let p=A__default.default.resolve("./migrations");D__default.default.existsSync(p)?console.log(f__default.default.gray(`Using migrations from: ${p}`)):(console.log(f__default.default.red(`Migrations directory not found: ${i}`)),console.log(f__default.default.gray(`
|
|
3731
3731
|
Expected one of:`)),console.log(f__default.default.gray(" - ./drizzle/")),console.log(f__default.default.gray(" - ./migrations/")),console.log(f__default.default.gray(`
|
|
3732
|
-
Or specify with: vaif db push --dir <path>`)),process.exit(1));}let a=[],l=D__default.default.readdirSync(i,{withFileTypes:true});for(let p of l)if(p.isFile()&&p.name.endsWith(".sql"))a.push(A__default.default.join(i,p.name));else if(p.isDirectory()){let u=D__default.default.readdirSync(A__default.default.join(i,p.name),{withFileTypes:true});for(let m of u)m.isFile()&&m.name.endsWith(".sql")&&a.push(A__default.default.join(i,p.name,m.name));}a.sort(),a.length===0&&(console.log(f__default.default.yellow("No SQL migration files found")),process.exit(1)),console.log(f__default.default.gray(`Found ${a.length} migration(s):`));for(let p of a)console.log(f__default.default.gray(` - ${A__default.default.relative(process.cwd(),p)}`));if(console.log(""),
|
|
3733
|
-
Error: ${a.message}`)),process.exit(1);}}async function ke(
|
|
3734
|
-
Error: ${i.message}`)),process.exit(1);}}var Oe=process.env.VAIF_API_URL||"https://api.vaif.studio";function $e(e,
|
|
3735
|
-
Error: ${a.message}`)),process.exit(1);}}async function ze(
|
|
3736
|
-
Generate one with: vaif keys generate`));return}let c=Math.max(8,...l.map(p=>(p.name||"").length)),d=` ${"Name".padEnd(c)} ${"Key".padEnd(24)} Created`;console.log(f__default.default.gray(d)),console.log(f__default.default.gray(" "+"-".repeat(d.length-2)));for(let p of l){let u=(p.name||"unnamed").padEnd(c),m=p.maskedKey||p.prefix||`${(p.key||"").slice(0,12)}...`,
|
|
3737
|
-
Error: ${i.message}`)),process.exit(1);}}var U=process.env.VAIF_API_URL||"https://api.vaif.studio";function
|
|
3738
|
-
Error: ${l.message}`)),process.exit(1);}}async function Be(
|
|
3739
|
-
Create one with: vaif secrets set <name> <value>`));return}let l=Math.max(8,...a.map(d=>d.key.length)),c=` ${"Name".padEnd(l)} Created`;console.log(f__default.default.gray(c)),console.log(f__default.default.gray(" "+"-".repeat(c.length-2)));for(let d of a){let p=d.key.padEnd(l),u=d.createdAt?new Date(d.createdAt).toLocaleDateString():"N/A";console.log(` ${p} ${u}`);}console.log(""),console.log(f__default.default.gray(` ${a.length} secret(s) total`)),console.log(f__default.default.gray(" Values are hidden. Use `vaif secrets get <name>` to reveal.")),console.log("");}catch(s){
|
|
3740
|
-
Error: ${s.message}`)),process.exit(1);}}async function qe(e
|
|
3741
|
-
Error: ${i.message}`)),process.exit(1);}}async function Ye(e
|
|
3742
|
-
Error: ${i.message}`)),process.exit(1);}}var Je=process.env.VAIF_API_URL||"https://api.vaif.studio";function
|
|
3743
|
-
Error: ${i.message}`)),process.exit(1);}}var
|
|
3744
|
-
Error: ${i.message}`)),process.exit(1);}}commander.program.name("vaif").description("VAIF CLI - Type generation and development tools").version("1.6.
|
|
3732
|
+
Or specify with: vaif db push --dir <path>`)),process.exit(1));}let a=[],l=D__default.default.readdirSync(i,{withFileTypes:true});for(let p of l)if(p.isFile()&&p.name.endsWith(".sql"))a.push(A__default.default.join(i,p.name));else if(p.isDirectory()){let u=D__default.default.readdirSync(A__default.default.join(i,p.name),{withFileTypes:true});for(let m of u)m.isFile()&&m.name.endsWith(".sql")&&a.push(A__default.default.join(i,p.name,m.name));}a.sort(),a.length===0&&(console.log(f__default.default.yellow("No SQL migration files found")),process.exit(1)),console.log(f__default.default.gray(`Found ${a.length} migration(s):`));for(let p of a)console.log(f__default.default.gray(` - ${A__default.default.relative(process.cwd(),p)}`));if(console.log(""),t.dryRun){console.log(f__default.default.yellow("Dry run mode - no migrations will be applied.")),console.log("");for(let p of a){let u=D__default.default.readFileSync(p,"utf-8");console.log(f__default.default.cyan(`--- ${A__default.default.basename(p)} ---`)),console.log(f__default.default.gray(u.slice(0,500))),u.length>500&&console.log(f__default.default.gray("...")),console.log("");}return}let c=0,d=0;for(let p of a){let u=D__default.default.readFileSync(p,"utf-8"),m=A__default.default.relative(process.cwd(),p);e.start(`Applying ${m}...`);try{let y=await fetch(`${G}/schema-engine/query/${s}`,{method:"POST",headers:{Authorization:`Bearer ${o.token}`,"Content-Type":"application/json"},body:JSON.stringify({sql:u})});if(!y.ok){let R=await y.text();throw new Error(R)}e.succeed(`Applied ${m}`),c++;}catch(y){let R=y instanceof Error?y.message:"Unknown error";e.fail(`Failed ${m}: ${R}`),d++;}}console.log(""),console.log(d===0?f__default.default.green(`Successfully applied ${c} migration(s)`):f__default.default.yellow(`Applied ${c}, failed ${d} migration(s)`)),console.log("");}async function Le(t){let e=J__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let s=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;s||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=A__default.default.resolve(t.output||"vaif.schema.json");console.log(""),console.log(f__default.default.bold("VAIF Database Pull")),console.log(""),e.start("Pulling schema from remote...");try{let a=await fetch(`${G}/schema-engine/introspect/${s}`,{headers:{Authorization:`Bearer ${o.token}`}});if(!a.ok){let d=await a.text();throw new Error(`Failed to pull schema: ${d}`)}let l=await a.json();D__default.default.writeFileSync(i,JSON.stringify(l,null,2),"utf-8"),e.succeed(`Schema written to ${A__default.default.relative(process.cwd(),i)}`);let c=l.tables?.length??Object.keys(l).length;console.log(f__default.default.gray(` ${c} table(s) pulled`)),console.log("");}catch(a){e.fail("Failed to pull schema"),a instanceof Error&&console.log(f__default.default.red(`
|
|
3733
|
+
Error: ${a.message}`)),process.exit(1);}}async function ke(t){let e=J__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let s=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;s||(console.log(f__default.default.red("No project ID specified")),process.exit(1)),console.log(""),console.log(f__default.default.red.bold("\u26A0\uFE0F DATABASE RESET")),console.log(""),console.log(f__default.default.red("This will:")),console.log(f__default.default.red(" - Drop all tables")),console.log(f__default.default.red(" - Delete all data")),console.log(f__default.default.red(" - Reset migrations")),console.log(""),console.log(f__default.default.red.bold("This action cannot be undone!")),console.log(""),t.force||(console.log(f__default.default.yellow("Use --force to confirm this action.")),process.exit(1)),e.start("Resetting database...");try{await Ut(o.token,s),e.succeed("Database reset complete"),console.log(""),console.log(f__default.default.gray("Your database is now empty.")),console.log(f__default.default.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__default.default.red(`
|
|
3734
|
+
Error: ${i.message}`)),process.exit(1);}}var Oe=process.env.VAIF_API_URL||"https://api.vaif.studio";function $e(t,e,o){return t.projectId||e?.projectId||process.env.VAIF_PROJECT_ID||o.projectId||null}async function Me(t){let e=J__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let s=$e(t,r,o);s||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1));let i=t.name||`cli-key-${Date.now()}`;console.log(""),console.log(f__default.default.bold("VAIF Generate API Key")),console.log(""),e.start("Generating API key...");try{let a=await fetch(`${Oe}/v1/projects/${s}/api-keys`,{method:"POST",headers:{Authorization:`Bearer ${o.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:i})});if(!a.ok){let c=await a.text();throw new Error(`Failed to generate key: ${c}`)}let l=await a.json();e.succeed("API key generated"),console.log(""),console.log(f__default.default.green(` Name: ${l.name}`)),console.log(f__default.default.green(` Key: ${l.key}`)),console.log(""),console.log(f__default.default.yellow.bold(" Save this key now - it will not be shown again!")),console.log("");}catch(a){e.fail("Failed to generate API key"),a instanceof Error&&console.log(f__default.default.red(`
|
|
3735
|
+
Error: ${a.message}`)),process.exit(1);}}async function ze(t){let e=J__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let s=$e(t,r,o);s||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),console.log(""),console.log(f__default.default.bold("VAIF API Keys")),console.log(""),e.start("Fetching API keys...");try{let i=await fetch(`${Oe}/v1/projects/${s}/api-keys`,{headers:{Authorization:`Bearer ${o.token}`}});if(!i.ok){let p=await i.text();throw new Error(`Failed to list keys: ${p}`)}let a=await i.json(),l=a.keys||a;if(e.stop(),!Array.isArray(l)||l.length===0){console.log(f__default.default.yellow("No API keys found")),console.log(f__default.default.gray(`
|
|
3736
|
+
Generate one with: vaif keys generate`));return}let c=Math.max(8,...l.map(p=>(p.name||"").length)),d=` ${"Name".padEnd(c)} ${"Key".padEnd(24)} Created`;console.log(f__default.default.gray(d)),console.log(f__default.default.gray(" "+"-".repeat(d.length-2)));for(let p of l){let u=(p.name||"unnamed").padEnd(c),m=p.maskedKey||p.prefix||`${(p.key||"").slice(0,12)}...`,y=p.createdAt?new Date(p.createdAt).toLocaleDateString():"N/A";console.log(` ${u} ${m.padEnd(24)} ${y}`);}console.log(""),console.log(f__default.default.gray(` ${l.length} key(s) total`)),console.log("");}catch(i){e.fail("Failed to list API keys"),i instanceof Error&&console.log(f__default.default.red(`
|
|
3737
|
+
Error: ${i.message}`)),process.exit(1);}}var U=process.env.VAIF_API_URL||"https://api.vaif.studio";function $t(t,e,o){return t.projectId||e?.projectId||process.env.VAIF_PROJECT_ID||o.projectId||null}function W(){let t=w();return (!t||!t.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1)),t}async function X(t){try{return await I(t||"vaif.config.json")}catch{return null}}function Q(t,e,o){let n=$t(t,e,o);return n||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.yellow("Set projectId in vaif.config.json or use --project-id flag.")),process.exit(1)),n}async function Ke(t,e,o){let n=J__default.default(),r=W(),s=await X(o.config),i=Q(o,s,r),a=e;if(o.fromFile)try{a=D__default.default.readFileSync(o.fromFile,"utf-8");}catch(l){console.log(f__default.default.red(`Failed to read file: ${o.fromFile}`)),l instanceof Error&&console.log(f__default.default.gray(l.message)),process.exit(1);}a||(console.log(f__default.default.red("No value provided")),console.log(f__default.default.gray("Provide a value as argument or use --from-file <path>")),process.exit(1)),console.log(""),console.log(f__default.default.bold("VAIF Set Secret")),console.log(""),n.start("Checking for existing secret...");try{let l=new URL(`${U}/functions/secrets/project/${i}`);o.envId&&l.searchParams.set("envId",o.envId);let c=await fetch(l.toString(),{headers:{Authorization:`Bearer ${r.token}`}});if(!c.ok)throw new Error(`Failed to check existing secrets: ${await c.text()}`);let p=(await c.json()).find(u=>u.key===t);if(p){n.text=`Updating secret "${t}"...`;let u=await fetch(`${U}/functions/secrets/${p.id}`,{method:"PUT",headers:{Authorization:`Bearer ${r.token}`,"Content-Type":"application/json"},body:JSON.stringify({value:a})});if(!u.ok)throw new Error(`Failed to update secret: ${await u.text()}`);n.succeed(`Updated secret "${t}"`);}else {n.text=`Creating secret "${t}"...`;let u=await fetch(`${U}/functions/secrets`,{method:"POST",headers:{Authorization:`Bearer ${r.token}`,"Content-Type":"application/json"},body:JSON.stringify({projectId:i,envId:o.envId,key:t,value:a})});if(!u.ok)throw new Error(`Failed to create secret: ${await u.text()}`);n.succeed(`Created secret "${t}"`);}console.log("");}catch(l){n.fail("Failed to set secret"),l instanceof Error&&console.log(f__default.default.red(`
|
|
3738
|
+
Error: ${l.message}`)),process.exit(1);}}async function Be(t){let e=J__default.default(),o=W(),n=await X(t.config),r=Q(t,n,o);console.log(""),console.log(f__default.default.bold("VAIF Secrets")),console.log(""),e.start("Fetching secrets...");try{let s=new URL(`${U}/functions/secrets/project/${r}`);t.envId&&s.searchParams.set("envId",t.envId);let i=await fetch(s.toString(),{headers:{Authorization:`Bearer ${o.token}`}});if(!i.ok)throw new Error(`Failed to list secrets: ${await i.text()}`);let a=await i.json();if(e.stop(),a.length===0){console.log(f__default.default.yellow("No secrets found")),console.log(f__default.default.gray(`
|
|
3739
|
+
Create one with: vaif secrets set <name> <value>`));return}let l=Math.max(8,...a.map(d=>d.key.length)),c=` ${"Name".padEnd(l)} Created`;console.log(f__default.default.gray(c)),console.log(f__default.default.gray(" "+"-".repeat(c.length-2)));for(let d of a){let p=d.key.padEnd(l),u=d.createdAt?new Date(d.createdAt).toLocaleDateString():"N/A";console.log(` ${p} ${u}`);}console.log(""),console.log(f__default.default.gray(` ${a.length} secret(s) total`)),console.log(f__default.default.gray(" Values are hidden. Use `vaif secrets get <name>` to reveal.")),console.log("");}catch(s){e.fail("Failed to list secrets"),s instanceof Error&&console.log(f__default.default.red(`
|
|
3740
|
+
Error: ${s.message}`)),process.exit(1);}}async function qe(t,e){let o=J__default.default(),n=W(),r=await X(e.config),s=Q(e,r,n);console.log(""),o.start("Fetching secret...");try{let i=new URL(`${U}/functions/secrets/project/${s}`);e.envId&&i.searchParams.set("envId",e.envId);let a=await fetch(i.toString(),{headers:{Authorization:`Bearer ${n.token}`}});if(!a.ok)throw new Error(`Failed to fetch secrets: ${await a.text()}`);let c=(await a.json()).find(u=>u.key===t);c||(o.fail(`Secret "${t}" not found`),process.exit(1));let d=await fetch(`${U}/functions/secrets/${c.id}/value`,{headers:{Authorization:`Bearer ${n.token}`}});if(!d.ok)throw new Error(`Failed to get secret value: ${await d.text()}`);let p=await d.json();o.stop(),console.log(p.value);}catch(i){o.fail("Failed to get secret"),i instanceof Error&&console.log(f__default.default.red(`
|
|
3741
|
+
Error: ${i.message}`)),process.exit(1);}}async function Ye(t,e){let o=J__default.default(),n=W(),r=await X(e.config),s=Q(e,r,n);console.log(""),console.log(f__default.default.bold("VAIF Delete Secret")),console.log(""),o.start("Finding secret...");try{let i=new URL(`${U}/functions/secrets/project/${s}`);e.envId&&i.searchParams.set("envId",e.envId);let a=await fetch(i.toString(),{headers:{Authorization:`Bearer ${n.token}`}});if(!a.ok)throw new Error(`Failed to fetch secrets: ${await a.text()}`);let c=(await a.json()).find(p=>p.key===t);c||(o.fail(`Secret "${t}" not found`),process.exit(1)),o.text=`Deleting secret "${t}"...`;let d=await fetch(`${U}/functions/secrets/${c.id}`,{method:"DELETE",headers:{Authorization:`Bearer ${n.token}`}});if(!d.ok)throw new Error(`Failed to delete secret: ${await d.text()}`);o.succeed(`Deleted secret "${t}"`),console.log("");}catch(i){o.fail("Failed to delete secret"),i instanceof Error&&console.log(f__default.default.red(`
|
|
3742
|
+
Error: ${i.message}`)),process.exit(1);}}var Je=process.env.VAIF_API_URL||"https://api.vaif.studio";function zt(t){try{let e=new URL(t);return e.password&&(e.password="****"),e.toString()}catch{return t.replace(/:[^@/]+@/,":****@")}}async function Ge(t){let e=J__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let s=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;s||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.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(`${Je}/v1/projects/${s}`,{headers:{Authorization:`Bearer ${o.token}`}});if(!i.ok){let d=await i.text();throw new Error(`Failed to fetch project: ${d}`)}let a=await i.json();e.stop(),console.log(""),console.log(f__default.default.bold("VAIF Project Info")),console.log("");let l=16,c=(d,p)=>{console.log(` ${f__default.default.gray(d.padEnd(l))} ${p}`);};c("Name:",f__default.default.white(a.name||"N/A")),c("Project ID:",f__default.default.white(s)),c("Region:",f__default.default.white(a.region||"us-east-1")),c("Plan:",f__default.default.white(a.plan||a.tier||"free")),c("Created:",f__default.default.white(a.createdAt?new Date(a.createdAt).toLocaleDateString():"N/A")),console.log(""),c("API URL:",f__default.default.cyan(a.apiUrl||`${Je}/v1`)),c("WS URL:",f__default.default.cyan(a.wsUrl||a.realtimeUrl||"N/A")),c("DB URL:",f__default.default.cyan(a.databaseUrl?zt(a.databaseUrl):"N/A")),c("Storage URL:",f__default.default.cyan(a.storageUrl||"N/A")),console.log("");}catch(i){e.fail("Failed to fetch project info"),i instanceof Error&&console.log(f__default.default.red(`
|
|
3743
|
+
Error: ${i.message}`)),process.exit(1);}}var Bt=process.env.VAIF_API_URL||"https://api.vaif.studio";async function He(t){let e=J__default.default(),o=w();(!o||!o.token)&&(console.log(f__default.default.red("Not logged in")),console.log(f__default.default.gray("Run `vaif login` first to authenticate")),process.exit(1));let n=t.config||"vaif.config.json",r=null;try{r=await I(n);}catch{}let s=t.projectId||r?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;s||(console.log(f__default.default.red("No project ID specified")),console.log(f__default.default.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(`${Bt}/v1/projects/${s}?include=tables,functions,storage,connections`,{headers:{Authorization:`Bearer ${o.token}`}});if(!i.ok){let y=await i.text();throw new Error(`Failed to fetch project status: ${y}`)}let a=await i.json();e.stop(),console.log(""),console.log(f__default.default.bold("VAIF Project Status")),console.log("");let l=22,c=(y,R)=>{console.log(` ${f__default.default.gray(y.padEnd(l))} ${R}`);};c("Project:",f__default.default.white(a.name||s)),c("Plan:",f__default.default.white(a.plan||a.tier||"free")),console.log(""),console.log(f__default.default.gray(" --- Resources ---")),console.log("");let d=a.tableCount??a.tables?.length??"N/A",p=a.functionCount??a.functions?.length??"N/A",u=a.bucketCount??a.storage?.buckets?.length??"N/A",m=a.activeConnections??a.connections??"N/A";c("Tables:",f__default.default.white(String(d))),c("Functions:",f__default.default.white(String(p))),c("Storage Buckets:",f__default.default.white(String(u))),c("Active Connections:",f__default.default.white(String(m))),a.usage&&(console.log(""),console.log(f__default.default.gray(" --- Usage ---")),console.log(""),a.usage.dbSize&&c("Database Size:",f__default.default.white(a.usage.dbSize)),a.usage.storageSize&&c("Storage Size:",f__default.default.white(a.usage.storageSize)),a.usage.bandwidth&&c("Bandwidth:",f__default.default.white(a.usage.bandwidth)),a.usage.functionInvocations!=null&&c("Function Invocations:",f__default.default.white(String(a.usage.functionInvocations)))),console.log("");}catch(i){e.fail("Failed to fetch project status"),i instanceof Error&&console.log(f__default.default.red(`
|
|
3744
|
+
Error: ${i.message}`)),process.exit(1);}}commander.program.name("vaif").description("VAIF CLI - Type generation and development tools").version("1.6.6");commander.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(Ae);commander.program.command("logout").description("Log out and remove stored credentials").action(we);commander.program.command("whoami").description("Show current authenticated user").action(Se);commander.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(ye);commander.program.command("templates").alias("tpl").description("List available project templates").action(he);commander.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(Ge);commander.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(He);commander.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(Ee);commander.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(Te);commander.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(fe);var We=commander.program.command("functions").alias("fn").description("Manage serverless functions");We.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(Ce);We.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(Re);var Z=commander.program.command("db").description("Database management commands");Z.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(Ve);Z.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(Le);Z.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(De);Z.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(ke);var Xe=commander.program.command("keys").description("Manage API keys");Xe.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(Me);Xe.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(ze);var ee=commander.program.command("secrets").alias("sec").description("Manage function secrets");ee.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(Ke);ee.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(Be);ee.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(qe);ee.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(Ye);commander.program.parse(process.argv);process.argv.slice(2).length||commander.program.outputHelp();
|
package/dist/cli.js
CHANGED
|
@@ -1,42 +1,42 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {d,c,b,a}from'./chunk-OB2QEQ2L.js';import'dotenv/config';import {program}from'commander';import k from'fs';import
|
|
3
|
-
Could not connect to VAIF API. Please try again later.`)),process.exit(1));let
|
|
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
|
|
5
|
-
The authentication session expired. Please try again.`)),process.exit(1));continue}let
|
|
6
|
-
Timed out waiting for browser authentication.`)),console.log(l.gray("Try again or use: vaif login --email")),process.exit(1);}async function
|
|
2
|
+
import {d,c,b,a}from'./chunk-OB2QEQ2L.js';import'dotenv/config';import {program}from'commander';import k from'fs';import j from'path';import Ne from'os';import {exec}from'child_process';import z from'ora';import l from'chalk';import te from'readline';var Y=j.join(Ne.homedir(),".vaif"),O=j.join(Y,"auth.json"),_=process.env.VAIF_API_URL||"https://api.vaif.studio";function Te(){k.existsSync(Y)||k.mkdirSync(Y,{recursive:true});}function ne(e){Te(),k.writeFileSync(O,JSON.stringify(e,null,2),"utf-8"),k.chmodSync(O,384);}function I(){if(!k.existsSync(O))return null;try{let e=k.readFileSync(O,"utf-8");return JSON.parse(e)}catch{return null}}function Le(e){let o=te.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=te.createInterface({input:process.stdin,output:process.stdout});process.stdin;let c=process.stdout.write.bind(process.stdout),r=false;process.stdout.write=((...i)=>r?true:c(...i)),t.question(e,i=>{r=false,process.stdout.write=c,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=z();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 a=await n.json();t=a.code,s=a.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 c=12e4,r=2e3,i=Date.now();for(;Date.now()-i<c;){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 a=await n.json();if(a.ok&&a.accessToken){let f={token:a.accessToken,email:a.user?.email,projectId:e,expiresAt:new Date(Date.now()+a.expiresIn*1e3).toISOString()};ne(f),o.succeed("Logged in successfully"),console.log(""),a.user?.email&&console.log(l.green(` Authenticated as: ${a.user.email}`)),console.log(l.gray(` Config saved to: ${O}`)),console.log("");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 Me(e){console.log(""),console.log(l.bold("VAIF CLI Login")),console.log(l.gray("Enter your VAIF account credentials")),console.log("");let o=await Le(l.cyan(" Email: "));(!o||o.trim()==="")&&(console.log(l.red(`
|
|
7
7
|
No email provided. Login cancelled.`)),process.exit(1));let t=await _e(l.cyan(" Password: "));(!t||t.trim()==="")&&(console.log(l.red(`
|
|
8
|
-
No password provided. Login cancelled.`)),process.exit(1));let s=
|
|
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()};
|
|
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: ${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
|
|
12
|
-
Error: ${i}`)),process.exit(1);}
|
|
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||
|
|
14
|
-
Error: ${i.message}`)),process.exit(1);}}var
|
|
15
|
-
Error: ${
|
|
16
|
-
Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1));let i=e.schema||
|
|
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
|
|
18
|
-
Error: ${
|
|
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(
|
|
20
|
-
Error: ${
|
|
8
|
+
No password provided. Login cancelled.`)),process.exit(1));let s=z("Authenticating...").start();try{let c=await fetch(`${_}/auth/cli/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:o.trim(),password:t})}),r=await c.json();(!c.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()};ne(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 se(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 Me(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 ie(){k.existsSync(O)?(k.unlinkSync(O),console.log(l.green("Logged out successfully"))):console.log(l.yellow("Not currently logged in"));}async function re(){let e=I();(!e||!e.token)&&(console.log(l.yellow("Not logged in")),console.log(l.gray("Run `vaif login` to authenticate")),process.exit(1));let o=z("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 c=await s.text();throw new Error(`Failed to fetch schema: ${c}`)}return s.json()}async function ce(e){let o=z(),t=I();(!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",c=null;o.start("Loading configuration...");try{c=await a(s);}catch(i){o.fail("Failed to load config"),console.log(l.red(`
|
|
12
|
+
Error: ${i}`)),process.exit(1);}c||(o.fail("No configuration found"),console.log(l.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let r=e.projectId||c.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||c.database?.schema||"public",n=await Ye(t.token,r,i);o.succeed("Schema fetched successfully");let a=e.output||j.resolve("vaif.schema.json"),f={$schema:"https://vaif.studio/schemas/schema.json",projectId:r,schema:i,pulledAt:new Date().toISOString(),...n};k.writeFileSync(a,JSON.stringify(f,null,2),"utf-8"),console.log(""),console.log(l.green(`Schema saved to: ${a}`)),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 le=process.env.VAIF_API_URL||"https://api.vaif.studio";function Ze(e){let o=te.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(`${le}/v1/projects/${o}/schema/preview`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({schema:t})});if(!s.ok){let c=await s.text();throw new Error(`Failed to preview changes: ${c}`)}return s.json()}async function oo(e,o,t){let s=await fetch(`${le}/v1/projects/${o}/schema/apply`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({schema:t})});if(!s.ok){let c=await s.text();throw new Error(`Failed to apply changes: ${c}`)}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 ge(e){let o=z(),t=I();(!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",c=null;o.start("Loading configuration...");try{c=await a(s);}catch(a){o.fail("Failed to load config"),console.log(l.red(`
|
|
15
|
+
Error: ${a}`)),process.exit(1);}c||(o.fail("No configuration found"),console.log(l.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let r=e.projectId||c.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||j.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 a=k.readFileSync(i,"utf-8");n=JSON.parse(a);}catch(a){o.fail("Failed to parse schema file"),a instanceof Error&&console.log(l.red(`
|
|
18
|
+
Error: ${a.message}`)),process.exit(1);}o.text="Calculating schema changes...";try{let{diff:a,sql:f}=await eo(t.token,r,n);if(o.stop(),to(a),a.added.length===0&&a.modified.length===0&&a.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){a.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(a){o.fail("Failed to push schema changes"),a instanceof Error&&console.log(l.red(`
|
|
20
|
+
Error: ${a.message}`)),process.exit(1);}}var U=process.env.VAIF_API_URL||"https://api.vaif.studio";async function no(e,o,t,s){let c=new URL(`${U}/functions/project/${o}`);s&&c.searchParams.set("envId",s);let r=await fetch(c.toString(),{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)return null;let i=await r.json(),n=i.functions||i;return Array.isArray(n)&&n.find(a=>a.name===t)||null}async function so(e,o,t){let s=await fetch(`${U}/functions/`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({projectId:o,name:t.name,runtime:t.runtime,entrypoint:t.entrypoint,envId:t.envId})});if(!s.ok){let c=await s.text();throw new Error(`Failed to create function: ${c}`)}return s.json()}async function io(e,o,t){let s=await fetch(`${U}/functions/${o}/source`,{method:"PUT",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({sourceCode:t})});if(!s.ok){let c=await s.text();throw new Error(`Failed to deploy source: ${c}`)}}async function ro(e,o,t){let s=new URL(`${U}/functions/project/${o}`);t&&s.searchParams.set("envId",t);let c=await fetch(s.toString(),{headers:{Authorization:`Bearer ${e}`}});if(!c.ok){let i=await c.text();throw new Error(`Failed to list functions: ${i}`)}let r=await c.json();return r.functions||r}function fe(e){switch(j.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 de(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 c=k.readdirSync(e,{withFileTypes:true});for(let r of c){let i=j.join(e,r.name);if(r.isDirectory()){if(r.name!=="node_modules"&&!r.name.startsWith(".")){let n=k.readdirSync(i,{withFileTypes:true});for(let a of n)if(a.isFile()){let f=j.extname(a.name).toLowerCase();if(t.includes(f)){o.push(j.join(i,a.name));break}}}}else if(r.isFile()){let n=j.extname(r.name).toLowerCase();t.includes(n)&&!s.includes(r.name)&&o.push(i);}}return o}async function ue(e){let o=z(),t=I();(!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",c=null;try{c=await a(s);}catch{}let r=e.projectId||c?.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=j.resolve("functions"),n=j.resolve("src/functions"),a$1=[];if(e.entrypoint){let g=j.resolve(e.entrypoint);k.existsSync(g)||(o.fail(`File not found: ${e.entrypoint}`),process.exit(1)),a$1=[g];}else a$1=[...de(i),...de(n)];a$1.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
|
-
Or specify an entrypoint with --entrypoint`)),process.exit(1)),o.succeed(`Found ${
|
|
23
|
-
No functions matching "${e.name}" found`)),process.exit(1))),console.log(""),console.log(l.gray("Functions to deploy:"));for(let g of
|
|
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)+"
|
|
25
|
-
Error: ${i.message}`)),process.exit(1);}}var
|
|
22
|
+
Or specify an entrypoint with --entrypoint`)),process.exit(1)),o.succeed(`Found ${a$1.length} function(s)`),e.name&&(a$1=a$1.filter(g=>j.basename(g,j.extname(g)).includes(e.name)),a$1.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 a$1){let y=j.basename(j.dirname(g)),w=y==="functions"||y==="src"?j.basename(g,j.extname(g)):y,C=e.runtime||fe(g);console.log(l.gray(` - ${w} (${C})`));}if(console.log(""),e.dryRun){console.log(l.yellow("Dry run mode - no functions deployed."));return}let f=[];for(let g of a$1){let y=j.basename(j.dirname(g)),w=y==="functions"||y==="src"?j.basename(g,j.extname(g)):y,C=e.runtime||fe(g);o.start(`Deploying ${w}...`);try{let L=k.readFileSync(g,"utf-8"),V=await no(t.token,r,w,e.envId);V||(o.text=`Creating ${w}...`,V=await so(t.token,r,{name:w,runtime:C,entrypoint:j.basename(g),envId:e.envId})),o.text=`Deploying ${w}...`,await io(t.token,V.id,L),o.succeed(`Deployed ${w}`),f.push({name:w,success:!0});}catch(L){let V=L instanceof Error?L.message:"Unknown error";o.fail(`Failed to deploy ${w}`),f.push({name:w,success:false,error:V});}}console.log("");let p=f.filter(g=>g.success).length;if(f.filter(g=>!g.success).length===0)console.log(l.green(`\u2713 Successfully deployed ${p} function(s)`));else {console.log(l.yellow(`Deployed ${p}/${f.length} function(s)`)),console.log(""),console.log(l.red("Failed deployments:"));for(let g of f.filter(y=>!y.success))console.log(l.red(` - ${g.name}: ${g.error}`));}console.log("");}async function me(e){let o=z(),t=I();(!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",c=null;try{c=await a(s);}catch{}let r=e.projectId||c?.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 ro(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)+"STATUS".padEnd(12)+"INVOCATIONS".padEnd(14)+"LAST DEPLOYED")),console.log(l.gray(" "+"-".repeat(80)));for(let n of i){let a=n.deployStatus==="deployed"?l.green:n.deployStatus==="deploying"?l.yellow:n.deployStatus==="failed"?l.red:l.gray;console.log(" "+n.name.padEnd(25)+n.runtime.padEnd(15)+a(n.deployStatus.padEnd(12))+String(n.invocationCount??0).padEnd(14)+(n.deployedAt?new Date(n.deployedAt).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 J=process.env.VAIF_API_URL||"https://api.vaif.studio";async function co(e,o,t,s,c){let r=await fetch(`${J}/v1/projects/${o}/db/seed`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({table:t,records:s,truncate:c?.truncate??false})});if(!r.ok){let i=await r.text();throw new Error(`Failed to seed ${t}: ${i}`)}return r.json()}async function ao(e,o){let t=await fetch(`${J}/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 Q(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 c=j.extname(s.name).toLowerCase();(c===".json"||c===".ts"||c===".js")&&o.push(j.join(e,s.name));}return o.sort()}async function he(e){let o=j.extname(e).toLowerCase();if(o===".json"){let t=k.readFileSync(e,"utf-8"),s=JSON.parse(t);return Array.isArray(s)?[{table:j.basename(e,o),data:s}]:s.table&&s.data?[s]:Object.entries(s).map(([c,r])=>({table:c,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=z(),t=I();(!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",c=null;try{c=await a(s);}catch{}let r=e.projectId||c?.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=j.resolve(e.file);k.existsSync(p)||(console.log(l.red(`File not found: ${e.file}`)),process.exit(1)),i=[p];}else {let p=j.resolve("seeds"),d=j.resolve("prisma/seed"),g=j.resolve("db/seeds");i=[...Q(p),...Q(d),...Q(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 i)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 i)console.log(l.gray(` - ${j.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 ${j.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 ${j.basename(p)}`),d instanceof Error&&console.log(l.red(` Error: ${d.message}`));}}return}let n=[];for(let p of i){o.start(`Processing ${j.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 co(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 w=y instanceof Error?y.message:"Unknown error";o.fail(`Failed to seed ${g.table}`),n.push({table:g.table,inserted:0,error:w});}}}catch(d){o.fail(`Failed to load ${j.basename(p)}`),d instanceof Error&&console.log(l.red(` Error: ${d.message}`));}}console.log("");let a$1=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 ${a$1} records across ${n.length} table(s)`));else {console.log(l.yellow(`Seeded ${a$1} 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=z(),t=I();(!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",c=null;try{c=await a(s);}catch{}let r=e.projectId||c?.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=j.resolve(e.dir||"./drizzle");if(console.log(""),console.log(l.bold("VAIF Database Push")),console.log(""),!k.existsSync(i)){let d=j.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=[],
|
|
31
|
-
Error: ${n.message}`)),process.exit(1);}}async function
|
|
32
|
-
Error: ${i.message}`)),process.exit(1);}}var $e=process.env.VAIF_API_URL||"https://api.vaif.studio";function
|
|
33
|
-
Error: ${n.message}`)),process.exit(1);}}async function
|
|
34
|
-
Generate one with: vaif keys generate`));return}let f=Math.max(8,...
|
|
35
|
-
Error: ${i.message}`)),process.exit(1);}}var
|
|
36
|
-
Error: ${
|
|
37
|
-
Create one with: vaif secrets set <name> <value>`));return}let
|
|
38
|
-
Error: ${r.message}`)),process.exit(1);}}async function Fe(e,o){let t=
|
|
39
|
-
Error: ${i.message}`)),process.exit(1);}}async function ke(e,o){let t=
|
|
40
|
-
Error: ${i.message}`)),process.exit(1);}}var Ce=process.env.VAIF_API_URL||"https://api.vaif.studio";function
|
|
41
|
-
Error: ${i.message}`)),process.exit(1);}}var
|
|
42
|
-
Error: ${i.message}`)),process.exit(1);}}program.name("vaif").description("VAIF CLI - Type generation and development tools").version("1.6.
|
|
30
|
+
Or specify with: vaif db push --dir <path>`)),process.exit(1));}let n=[],a$1=k.readdirSync(i,{withFileTypes:true});for(let d of a$1)if(d.isFile()&&d.name.endsWith(".sql"))n.push(j.join(i,d.name));else if(d.isDirectory()){let g=k.readdirSync(j.join(i,d.name),{withFileTypes:true});for(let y of g)y.isFile()&&y.name.endsWith(".sql")&&n.push(j.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(` - ${j.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(`--- ${j.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=j.relative(process.cwd(),d);o.start(`Applying ${y}...`);try{let w=await fetch(`${J}/schema-engine/query/${r}`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({sql:g})});if(!w.ok){let C=await w.text();throw new Error(C)}o.succeed(`Applied ${y}`),f++;}catch(w){let C=w instanceof Error?w.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=z(),t=I();(!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",c=null;try{c=await a(s);}catch{}let r=e.projectId||c?.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=j.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(`${J}/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 a=await n.json();k.writeFileSync(i,JSON.stringify(a,null,2),"utf-8"),o.succeed(`Schema written to ${j.relative(process.cwd(),i)}`);let f=a.tables?.length??Object.keys(a).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 Ie(e){let o=z(),t=I();(!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",c=null;try{c=await a(s);}catch{}let r=e.projectId||c?.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 ao(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 Ae(e,o,t){return e.projectId||o?.projectId||process.env.VAIF_PROJECT_ID||t.projectId||null}async function Se(e){let o=z(),t=I();(!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",c=null;try{c=await a(s);}catch{}let r=Ae(e,c,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 a=await n.json();o.succeed("API key generated"),console.log(""),console.log(l.green(` Name: ${a.name}`)),console.log(l.green(` Key: ${a.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 be(e){let o=z(),t=I();(!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",c=null;try{c=await a(s);}catch{}let r=Ae(e,c,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(),a=n.keys||n;if(o.stop(),!Array.isArray(a)||a.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,...a.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 a){let g=(d.name||"unnamed").padEnd(f),y=d.maskedKey||d.prefix||`${(d.key||"").slice(0,12)}...`,w=d.createdAt?new Date(d.createdAt).toLocaleDateString():"N/A";console.log(` ${g} ${y.padEnd(24)} ${w}`);}console.log(""),console.log(l.gray(` ${a.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 N=process.env.VAIF_API_URL||"https://api.vaif.studio";function go(e,o,t){return e.projectId||o?.projectId||process.env.VAIF_PROJECT_ID||t.projectId||null}function M(){let e=I();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 q(e,o,t){let s=go(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=z(),c=M(),r=await K(t.config),i=q(t,r,c),n=o;if(t.fromFile)try{n=k.readFileSync(t.fromFile,"utf-8");}catch(a){console.log(l.red(`Failed to read file: ${t.fromFile}`)),a instanceof Error&&console.log(l.gray(a.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 a=new URL(`${N}/functions/secrets/project/${i}`);t.envId&&a.searchParams.set("envId",t.envId);let f=await fetch(a.toString(),{headers:{Authorization:`Bearer ${c.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(`${N}/functions/secrets/${d.id}`,{method:"PUT",headers:{Authorization:`Bearer ${c.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(`${N}/functions/secrets`,{method:"POST",headers:{Authorization:`Bearer ${c.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(a){s.fail("Failed to set secret"),a instanceof Error&&console.log(l.red(`
|
|
36
|
+
Error: ${a.message}`)),process.exit(1);}}async function xe(e){let o=z(),t=M(),s=await K(e.config),c=q(e,s,t);console.log(""),console.log(l.bold("VAIF Secrets")),console.log(""),o.start("Fetching secrets...");try{let r=new URL(`${N}/functions/secrets/project/${c}`);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 a=Math.max(8,...n.map(p=>p.key.length)),f=` ${"Name".padEnd(a)} Created`;console.log(l.gray(f)),console.log(l.gray(" "+"-".repeat(f.length-2)));for(let p of n){let d=p.key.padEnd(a),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=z(),s=M(),c=await K(o.config),r=q(o,c,s);console.log(""),t.start("Fetching secret...");try{let i=new URL(`${N}/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(`${N}/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=z(),s=M(),c=await K(o.config),r=q(o,c,s);console.log(""),console.log(l.bold("VAIF Delete Secret")),console.log(""),t.start("Finding secret...");try{let i=new URL(`${N}/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(`${N}/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 po(e){try{let o=new URL(e);return o.password&&(o.password="****"),o.toString()}catch{return e.replace(/:[^@/]+@/,":****@")}}async function De(e){let o=z(),t=I();(!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",c=null;try{c=await a(s);}catch{}let r=e.projectId||c?.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 a=16,f=(p,d)=>{console.log(` ${l.gray(p.padEnd(a))} ${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?po(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 mo=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Ee(e){let o=z(),t=I();(!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",c=null;try{c=await a(s);}catch{}let r=e.projectId||c?.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(`${mo}/v1/projects/${r}?include=tables,functions,storage,connections`,{headers:{Authorization:`Bearer ${t.token}`}});if(!i.ok){let w=await i.text();throw new Error(`Failed to fetch project status: ${w}`)}let n=await i.json();o.stop(),console.log(""),console.log(l.bold("VAIF Project Status")),console.log("");let a=22,f=(w,C)=>{console.log(` ${l.gray(w.padEnd(a))} ${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.6");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(se);program.command("logout").description("Log out and remove stored credentials").action(ie);program.command("whoami").description("Show current authenticated user").action(re);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(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(ge);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 W=program.command("db").description("Database management commands");W.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);W.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);W.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);W.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 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(Se);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(be);var G=program.command("secrets").alias("sec").description("Manage function secrets");G.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);G.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);G.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);G.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();
|