@vaiftech/cli 1.7.3 → 1.7.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/{chunk-M2UHM7B7.js → chunk-WYTLXCHQ.js} +125 -51
- package/dist/cli.cjs +167 -93
- package/dist/cli.js +2 -2
- package/dist/index.cjs +140 -66
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/cli.cjs
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
'use strict';require('dotenv/config');var commander=require('commander'),f=require('chalk'),
|
|
2
|
+
'use strict';require('dotenv/config');var commander=require('commander'),f=require('chalk'),k=require('fs'),w=require('path'),vt=require('pg'),H=require('ora'),It=require('prettier'),st=require('dotenv'),lt=require('os'),child_process=require('child_process'),Ie=require('readline');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var f__default=/*#__PURE__*/_interopDefault(f);var k__default=/*#__PURE__*/_interopDefault(k);var w__default=/*#__PURE__*/_interopDefault(w);var vt__default=/*#__PURE__*/_interopDefault(vt);var H__default=/*#__PURE__*/_interopDefault(H);var It__default=/*#__PURE__*/_interopDefault(It);var st__default=/*#__PURE__*/_interopDefault(st);var lt__default=/*#__PURE__*/_interopDefault(lt);var Ie__default=/*#__PURE__*/_interopDefault(Ie);st__default.default.config();async function A(t){let e=w__default.default.resolve(t);if(!k__default.default.existsSync(e))return null;try{let o=k__default.default.readFileSync(e,"utf-8"),n=JSON.parse(o);return n.database?.url&&(n.database.url=ve(n.database.url)),n.api?.apiKey&&(n.api.apiKey=ve(n.api.apiKey)),n}catch{throw new Error(`Failed to parse config file: ${t}`)}}function ve(t){return t.replace(/\$\{([^}]+)\}/g,(e,o)=>process.env[o]||e)}var ae=w__default.default.join(lt__default.default.homedir(),".vaif"),$=w__default.default.join(ae,"auth.json"),J=process.env.VAIF_API_URL||"https://api.vaif.studio";function dt(){k__default.default.existsSync(ae)||k__default.default.mkdirSync(ae,{recursive:true});}function Ae(t){dt(),k__default.default.writeFileSync($,JSON.stringify(t,null,2),"utf-8"),k__default.default.chmodSync($,384);}function I(){if(!k__default.default.existsSync($))return null;try{let t=k__default.default.readFileSync($,"utf-8");return JSON.parse(t)}catch{return null}}function pt(t){let e=Ie__default.default.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(t,n=>{e.close(),o(n);});})}function ut(t){return new Promise(e=>{let o=Ie__default.default.createInterface({input:process.stdin,output:process.stdout});process.stdin;let s=process.stdout.write.bind(process.stdout),r=false;process.stdout.write=((...i)=>r?true:s(...i)),o.question(t,i=>{r=false,process.stdout.write=s,console.log(""),o.close(),e(i);}),r=true;})}function ft(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 gt(t){return new Promise(e=>setTimeout(e,t))}async function mt(t){try{let e=await fetch(`${J}/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 ht(t){let e=H__default.default();e.start("Setting up authentication...");let o,n;try{let a=await fetch(`${J}/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(`
|
|
3
3
|
Could not connect to VAIF API. Please try again later.`)),process.exit(1));let c=await a.json();o=c.code,n=c.url;}catch{e.fail("Failed to connect to VAIF API"),console.log(f__default.default.red(`
|
|
4
|
-
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(""),ft(n),e.start("Waiting for browser authentication...");let
|
|
4
|
+
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(""),ft(n),e.start("Waiting for browser authentication...");let s=12e4,r=2e3,i=Date.now();for(;Date.now()-i<s;){await gt(r);try{let a=await fetch(`${J}/auth/cli/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:o})});if(!a.ok){let l=await a.json();(l.error==="ExpiredCode"||l.error==="InvalidCode")&&(e.fail("Authentication expired"),console.log(f__default.default.red(`
|
|
5
5
|
The authentication session expired. Please try again.`)),process.exit(1));continue}let c=await a.json();if(c.ok&&c.accessToken){let l={token:c.accessToken,email:c.user?.email,projectId:t,expiresAt:new Date(Date.now()+c.expiresIn*1e3).toISOString()};Ae(l),e.succeed("Logged in successfully"),console.log(""),c.user?.email&&console.log(f__default.default.green(` Authenticated as: ${c.user.email}`)),console.log(f__default.default.gray(` Config saved to: ${$}`)),console.log("");return}}catch{}}e.fail("Authentication timed out"),console.log(f__default.default.red(`
|
|
6
6
|
Timed out waiting for browser authentication.`)),console.log(f__default.default.gray("Try again or use: vaif login --email")),process.exit(1);}async function yt(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 pt(f__default.default.cyan(" Email: "));(!e||e.trim()==="")&&(console.log(f__default.default.red(`
|
|
7
7
|
No email provided. Login cancelled.`)),process.exit(1));let o=await ut(f__default.default.cyan(" Password: "));(!o||o.trim()==="")&&(console.log(f__default.default.red(`
|
|
8
|
-
No password provided. Login cancelled.`)),process.exit(1));let n=H__default.default("Authenticating...").start();try{let
|
|
9
|
-
${
|
|
10
|
-
Could not connect to VAIF API. Please try again later.`)),process.exit(1);}}async function we(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 yt(t.projectId):await ht(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 Se(){
|
|
11
|
-
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 At=process.env.VAIF_API_URL||"https://api.vaif.studio";async function wt(t,e){let o=await fetch(`${At}/schema-engine/introspect/${e}`,{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}});if(!o.ok){let a=await o.text();throw new Error(`API introspection failed: ${a}`)}let n=await o.json();if(!n.ok||!n.schemaExists)throw new Error("Project schema does not exist yet. Push a migration first with `vaif db push`.");let
|
|
8
|
+
No password provided. Login cancelled.`)),process.exit(1));let n=H__default.default("Authenticating...").start();try{let s=await fetch(`${J}/auth/cli/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e.trim(),password:o})}),r=await s.json();(!s.ok||!r.ok)&&(n.fail("Login failed"),console.log(f__default.default.red(`
|
|
9
|
+
${r.message||"Invalid email or password."}`)),process.exit(1));let i={token:r.accessToken,email:r.user?.email,projectId:t,expiresAt:new Date(Date.now()+r.expiresIn*1e3).toISOString()};Ae(i),n.succeed("Logged in successfully"),console.log(""),r.user?.email&&console.log(f__default.default.green(` Authenticated as: ${r.user.email}`)),console.log(f__default.default.gray(` Config saved to: ${$}`)),console.log("");}catch{n.fail("Failed to connect to VAIF API"),console.log(f__default.default.red(`
|
|
10
|
+
Could not connect to VAIF API. Please try again later.`)),process.exit(1);}}async function we(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 yt(t.projectId):await ht(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 Se(){k__default.default.existsSync($)?(k__default.default.unlinkSync($),console.log(f__default.default.green("Logged out successfully"))):console.log(f__default.default.yellow("Not currently logged in"));}async function xe(){let t=I();(!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=H__default.default("Checking authentication...").start(),{valid:o,email:n}=await mt(t.token);o||(e.fail("Session expired"),console.log(f__default.default.yellow(`
|
|
11
|
+
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 At=process.env.VAIF_API_URL||"https://api.vaif.studio";async function wt(t,e){let o=await fetch(`${At}/schema-engine/introspect/${e}`,{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}});if(!o.ok){let a=await o.text();throw new Error(`API introspection failed: ${a}`)}let n=await o.json();if(!n.ok||!n.schemaExists)throw new Error("Project schema does not exist yet. Push a migration first with `vaif db push`.");let s=new Map,r=[];for(let a of n.tables){let c=a.columns.map(l=>({column_name:l.name,data_type:l.type,is_nullable:l.nullable?"YES":"NO",column_default:l.default,udt_name:l.type,is_identity:l.primaryKey&&l.default?.includes("gen_random_uuid")?"YES":"NO",character_maximum_length:null,numeric_precision:null,numeric_scale:null}));s.set(a.name,c);for(let l of a.foreignKeys)r.push({constraint_name:l.constraintName,table_name:a.name,column_name:l.columnName,foreign_table_name:l.refTable,foreign_column_name:l.refColumn});}return {tables:s,enums:new Map,foreignKeys:r}}async function St(t,e){let o=await t.query(`
|
|
12
12
|
SELECT table_name, table_type
|
|
13
13
|
FROM information_schema.tables
|
|
14
14
|
WHERE table_schema = $1
|
|
@@ -29,7 +29,7 @@ Your session has expired. Please login again.`)),process.exit(1)),e.succeed("Aut
|
|
|
29
29
|
FROM information_schema.columns
|
|
30
30
|
WHERE table_schema = $1
|
|
31
31
|
ORDER BY table_name, ordinal_position
|
|
32
|
-
`,[e]),
|
|
32
|
+
`,[e]),s=await t.query(`
|
|
33
33
|
SELECT
|
|
34
34
|
tc.constraint_name,
|
|
35
35
|
tc.table_name,
|
|
@@ -45,7 +45,7 @@ Your session has expired. Please login again.`)),process.exit(1)),e.succeed("Aut
|
|
|
45
45
|
AND ccu.table_schema = tc.table_schema
|
|
46
46
|
WHERE tc.constraint_type = 'FOREIGN KEY'
|
|
47
47
|
AND tc.table_schema = $1
|
|
48
|
-
`,[e]),
|
|
48
|
+
`,[e]),r=await t.query(`
|
|
49
49
|
SELECT
|
|
50
50
|
t.typname as enum_name,
|
|
51
51
|
e.enumlabel as enum_value
|
|
@@ -54,22 +54,22 @@ Your session has expired. Please login again.`)),process.exit(1)),e.succeed("Aut
|
|
|
54
54
|
JOIN pg_namespace n ON n.oid = t.typnamespace
|
|
55
55
|
WHERE n.nspname = $1
|
|
56
56
|
ORDER BY t.typname, e.enumsortorder
|
|
57
|
-
`,[e]),i=new Map;for(let c of o.rows)i.set(c.table_name,[]);for(let c of n.rows){let l=i.get(c.table_name);l&&l.push(c);}let a=new Map;for(let c of
|
|
57
|
+
`,[e]),i=new Map;for(let c of o.rows)i.set(c.table_name,[]);for(let c of n.rows){let l=i.get(c.table_name);l&&l.push(c);}let a=new Map;for(let c of r.rows){let l=a.get(c.enum_name)||[];l.push(c.enum_value),a.set(c.enum_name,l);}return {tables:i,enums:a,foreignKeys:s.rows}}var se={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 xt(t,e){let{data_type:o,udt_name:n,is_nullable:s}=t;if(e.has(n)){let a=e.get(n).map(c=>`"${c}"`).join(" | ");return s==="YES"?`(${a}) | null`:a}if(o==="ARRAY"){let i=n.replace(/^_/,"");if(e.has(i)){let l=e.get(i).map(p=>`"${p}"`).join(" | ");return s==="YES"?`(${l})[] | null`:`(${l})[]`}let a=se[i]||"unknown";return s==="YES"?`${a}[] | null`:`${a}[]`}let r=se[o]||se[n]||"unknown";return s==="YES"&&(r=`${r} | null`),r}function le(t){return t.split(/[_\-\s]+/).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}function _t(t,e){let o=le(t),n=e.map(s=>` | "${s}"`).join(`
|
|
58
58
|
`);return `export type ${o} =
|
|
59
|
-
${n};`}function
|
|
60
|
-
${
|
|
59
|
+
${n};`}function Et(t,e,o){let n=le(t),s=[],r=[],i=[];for(let p of e){let u=xt(p,o),d=p.column_name,m=p.column_default!==null||p.is_identity==="YES",y=p.is_nullable==="YES";s.push(` ${d}: ${u};`),m||p.column_name==="id"?r.push(` ${d}?: ${u.replace(" | null","")} | null;`):y?r.push(` ${d}?: ${u};`):r.push(` ${d}: ${u.replace(" | null","")};`),i.push(` ${d}?: ${u.replace(" | null","")} | null;`);}let a=`export interface ${n} {
|
|
60
|
+
${s.join(`
|
|
61
61
|
`)}
|
|
62
62
|
}`,c=`export interface ${n}Insert {
|
|
63
|
-
${
|
|
63
|
+
${r.join(`
|
|
64
64
|
`)}
|
|
65
65
|
}`,l=`export interface ${n}Update {
|
|
66
66
|
${i.join(`
|
|
67
67
|
`)}
|
|
68
|
-
}`;return {base:a,insert:c,update:l}}function Tt(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[
|
|
69
|
-
`)}async function
|
|
68
|
+
}`;return {base:a,insert:c,update:l}}function Tt(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[r,i]of e)n.push(_t(r,i)),n.push("");}n.push("// ============ TABLES ============"),n.push("");let s=[];for(let[r,i]of t){let{base:a,insert:c,update:l}=Et(r,i,e);s.push(r),n.push(a),n.push(""),n.push(c),n.push(""),n.push(l),n.push("");}n.push("// ============ DATABASE SCHEMA ============"),n.push(""),n.push("export interface Database {");for(let r of s){let i=le(r);n.push(` ${r}: {`),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(`
|
|
69
|
+
`)}async function Ee(t){let e=H__default.default("Loading configuration...").start();try{let o=await A(t.config),n=t.connection||o?.database?.url||process.env.DATABASE_URL,s=n&&!n.includes("${"),r,i,a;if(s){e.text="Connecting to database...";let d=new vt__default.default.Client({connectionString:n});await d.connect(),e.text="Introspecting schema...",{tables:r,enums:i,foreignKeys:a}=await St(d,t.schema),await d.end();}else {let d=I();(!d||!d.token)&&(e.fail("No database connection and not logged in"),console.log(f__default.default.yellow(`
|
|
70
70
|
Either:`)),console.log(f__default.default.gray(" 1. Run `vaif login` to authenticate (no DATABASE_URL needed)")),console.log(f__default.default.gray(" 2. Set DATABASE_URL in your .env file")),console.log(f__default.default.gray(" 3. Pass --connection postgresql://user:pass@host:5432/db")),process.exit(1));let m=o?.projectId||process.env.VAIF_PROJECT_ID||d.projectId;m||(e.fail("No project ID specified"),console.log(f__default.default.yellow(`
|
|
71
|
-
Set projectId in vaif.config.json or use VAIF_PROJECT_ID env var.`)),process.exit(1)),e.text="Introspecting schema via API...",{tables:
|
|
72
|
-
Push a migration first: vaif db push`));return}e.text=`Generating types for ${
|
|
71
|
+
Set projectId in vaif.config.json or use VAIF_PROJECT_ID env var.`)),process.exit(1)),e.text="Introspecting schema via API...",{tables:r,enums:i,foreignKeys:a}=await wt(d.token,m);}if(r.size===0){e.warn("No tables found"),console.log(f__default.default.yellow(`
|
|
72
|
+
Push a migration first: vaif db push`));return}e.text=`Generating types for ${r.size} tables...`;let c=Tt(r,i,a),l=await It__default.default.format(c,{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(l),console.log(f__default.default.gray("\u2500".repeat(60)));return}let p=w__default.default.resolve(t.output),u=w__default.default.dirname(p);k__default.default.existsSync(u)||k__default.default.mkdirSync(u,{recursive:!0}),k__default.default.writeFileSync(p,l,"utf-8"),e.succeed(`Generated types for ${r.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: ${r.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(`
|
|
73
73
|
Error: ${o.message}`)),o.message.includes("ECONNREFUSED")&&console.log(f__default.default.yellow(`
|
|
74
74
|
Make sure your database is running and accessible.`))),process.exit(1);}}var B=[{name:"database",label:"Database",description:"CRUD queries, type-safe operations"},{name:"auth",label:"Authentication",description:"login, signup, OAuth, sessions"},{name:"realtime",label:"Realtime",description:"live subscriptions, presence"},{name:"storage",label:"Storage",description:"file uploads, signed URLs"},{name:"functions",label:"Functions",description:"serverless function calls"}],Fe={"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:`{
|
|
75
75
|
"name": "my-vaif-app",
|
|
@@ -288,7 +288,21 @@ A full-stack Next.js application powered by [VAIF Studio](https://vaif.studio),
|
|
|
288
288
|
## Documentation
|
|
289
289
|
|
|
290
290
|
Full documentation is available at <https://docs.vaif.studio>.
|
|
291
|
-
`}],featureFiles:{auth:[{path:"
|
|
291
|
+
`}],featureFiles:{auth:[{path:"app/page.tsx",content:`import Link from "next/link";
|
|
292
|
+
|
|
293
|
+
export default function Home() {
|
|
294
|
+
return (
|
|
295
|
+
<main style={{ maxWidth: 600, margin: "80px auto", textAlign: "center" }}>
|
|
296
|
+
<h1>Welcome to VAIF</h1>
|
|
297
|
+
<p>Your Next.js app is ready. Start building!</p>
|
|
298
|
+
<p style={{ marginTop: 24 }}>
|
|
299
|
+
<Link href="/login" style={{ marginRight: 16 }}>Log in</Link>
|
|
300
|
+
<Link href="/signup">Sign up</Link>
|
|
301
|
+
</p>
|
|
302
|
+
</main>
|
|
303
|
+
);
|
|
304
|
+
}
|
|
305
|
+
`},{path:"middleware.ts",content:`import { NextResponse, type NextRequest } from "next/server";
|
|
292
306
|
import { createVaifClient } from "@vaiftech/client";
|
|
293
307
|
import { authMiddleware } from "@vaiftech/auth/nextjs";
|
|
294
308
|
|
|
@@ -335,12 +349,12 @@ export default function LoginPage() {
|
|
|
335
349
|
setLoading(true);
|
|
336
350
|
setError(null);
|
|
337
351
|
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
setError(error.message);
|
|
341
|
-
setLoading(false);
|
|
342
|
-
} else {
|
|
352
|
+
try {
|
|
353
|
+
await vaif.auth.login(email, password);
|
|
343
354
|
router.push("/dashboard");
|
|
355
|
+
} catch (err: any) {
|
|
356
|
+
setError(err.message || "Login failed");
|
|
357
|
+
setLoading(false);
|
|
344
358
|
}
|
|
345
359
|
}
|
|
346
360
|
|
|
@@ -382,12 +396,12 @@ export default function SignupPage() {
|
|
|
382
396
|
setLoading(true);
|
|
383
397
|
setError(null);
|
|
384
398
|
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
setError(error.message);
|
|
388
|
-
setLoading(false);
|
|
389
|
-
} else {
|
|
399
|
+
try {
|
|
400
|
+
await vaif.auth.signUp(email, password);
|
|
390
401
|
router.push("/");
|
|
402
|
+
} catch (err: any) {
|
|
403
|
+
setError(err.message || "Sign up failed");
|
|
404
|
+
setLoading(false);
|
|
391
405
|
}
|
|
392
406
|
}
|
|
393
407
|
|
|
@@ -778,7 +792,33 @@ A single-page React application built with [Vite](https://vite.dev/) and powered
|
|
|
778
792
|
## Documentation
|
|
779
793
|
|
|
780
794
|
Full documentation is available at <https://docs.vaif.studio>.
|
|
781
|
-
`}],featureFiles:{auth:[{path:"src/
|
|
795
|
+
`}],featureFiles:{auth:[{path:"src/App.tsx",content:`import { Routes, Route, Link } from "react-router-dom";
|
|
796
|
+
import Login from "./pages/Login";
|
|
797
|
+
import Signup from "./pages/Signup";
|
|
798
|
+
|
|
799
|
+
export default function App() {
|
|
800
|
+
return (
|
|
801
|
+
<Routes>
|
|
802
|
+
<Route path="/" element={<Home />} />
|
|
803
|
+
<Route path="/login" element={<Login />} />
|
|
804
|
+
<Route path="/signup" element={<Signup />} />
|
|
805
|
+
</Routes>
|
|
806
|
+
);
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
function Home() {
|
|
810
|
+
return (
|
|
811
|
+
<div style={{ maxWidth: 600, margin: "80px auto", textAlign: "center" }}>
|
|
812
|
+
<h1>Welcome to VAIF</h1>
|
|
813
|
+
<p>Your app is ready. Start building!</p>
|
|
814
|
+
<p style={{ marginTop: 24 }}>
|
|
815
|
+
<Link to="/login" style={{ marginRight: 16 }}>Log in</Link>
|
|
816
|
+
<Link to="/signup">Sign up</Link>
|
|
817
|
+
</p>
|
|
818
|
+
</div>
|
|
819
|
+
);
|
|
820
|
+
}
|
|
821
|
+
`},{path:"src/pages/Login.tsx",content:`import { useState } from "react";
|
|
782
822
|
import { useNavigate } from "react-router-dom";
|
|
783
823
|
import { vaif } from "../lib/vaif";
|
|
784
824
|
|
|
@@ -794,12 +834,12 @@ export default function Login() {
|
|
|
794
834
|
setLoading(true);
|
|
795
835
|
setError(null);
|
|
796
836
|
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
setError(error.message);
|
|
800
|
-
setLoading(false);
|
|
801
|
-
} else {
|
|
837
|
+
try {
|
|
838
|
+
await vaif.auth.login(email, password);
|
|
802
839
|
navigate("/");
|
|
840
|
+
} catch (err: any) {
|
|
841
|
+
setError(err.message || "Login failed");
|
|
842
|
+
setLoading(false);
|
|
803
843
|
}
|
|
804
844
|
}
|
|
805
845
|
|
|
@@ -839,12 +879,12 @@ export default function Signup() {
|
|
|
839
879
|
setLoading(true);
|
|
840
880
|
setError(null);
|
|
841
881
|
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
setError(error.message);
|
|
845
|
-
setLoading(false);
|
|
846
|
-
} else {
|
|
882
|
+
try {
|
|
883
|
+
await vaif.auth.signUp(email, password);
|
|
847
884
|
navigate("/");
|
|
885
|
+
} catch (err: any) {
|
|
886
|
+
setError(err.message || "Sign up failed");
|
|
887
|
+
setLoading(false);
|
|
848
888
|
}
|
|
849
889
|
}
|
|
850
890
|
|
|
@@ -883,21 +923,15 @@ export function AuthGuard({ children, fallback }: AuthGuardProps) {
|
|
|
883
923
|
const [authenticated, setAuthenticated] = useState(false);
|
|
884
924
|
|
|
885
925
|
useEffect(() => {
|
|
886
|
-
vaif.auth.
|
|
887
|
-
|
|
926
|
+
vaif.auth.getUser()
|
|
927
|
+
.then(() => {
|
|
888
928
|
setAuthenticated(true);
|
|
889
|
-
|
|
929
|
+
setLoading(false);
|
|
930
|
+
})
|
|
931
|
+
.catch(() => {
|
|
890
932
|
navigate("/login");
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
});
|
|
894
|
-
|
|
895
|
-
const { data: { subscription } } = vaif.auth.onAuthStateChange((_event, session) => {
|
|
896
|
-
setAuthenticated(!!session);
|
|
897
|
-
if (!session) navigate("/login");
|
|
898
|
-
});
|
|
899
|
-
|
|
900
|
-
return () => subscription.unsubscribe();
|
|
933
|
+
setLoading(false);
|
|
934
|
+
});
|
|
901
935
|
}, [navigate]);
|
|
902
936
|
|
|
903
937
|
if (loading) return fallback ?? <div>Loading...</div>;
|
|
@@ -1445,7 +1479,39 @@ A React Native / Expo mobile application powered by [VAIF Studio](https://vaif.s
|
|
|
1445
1479
|
## Documentation
|
|
1446
1480
|
|
|
1447
1481
|
Full documentation is available at <https://docs.vaif.studio>.
|
|
1448
|
-
`}],featureFiles:{auth:[{path:"app/
|
|
1482
|
+
`}],featureFiles:{auth:[{path:"app/index.tsx",content:`import { View, Text, StyleSheet, TouchableOpacity } from "react-native";
|
|
1483
|
+
import { useRouter } from "expo-router";
|
|
1484
|
+
|
|
1485
|
+
export default function HomeScreen() {
|
|
1486
|
+
const router = useRouter();
|
|
1487
|
+
|
|
1488
|
+
return (
|
|
1489
|
+
<View style={styles.container}>
|
|
1490
|
+
<Text style={styles.title}>Welcome to VAIF</Text>
|
|
1491
|
+
<Text style={styles.subtitle}>Your mobile app is ready. Start building!</Text>
|
|
1492
|
+
<View style={styles.buttons}>
|
|
1493
|
+
<TouchableOpacity style={styles.button} onPress={() => router.push("/(auth)/login")}>
|
|
1494
|
+
<Text style={styles.buttonText}>Log In</Text>
|
|
1495
|
+
</TouchableOpacity>
|
|
1496
|
+
<TouchableOpacity style={[styles.button, styles.secondaryButton]} onPress={() => router.push("/(auth)/signup")}>
|
|
1497
|
+
<Text style={[styles.buttonText, styles.secondaryText]}>Sign Up</Text>
|
|
1498
|
+
</TouchableOpacity>
|
|
1499
|
+
</View>
|
|
1500
|
+
</View>
|
|
1501
|
+
);
|
|
1502
|
+
}
|
|
1503
|
+
|
|
1504
|
+
const styles = StyleSheet.create({
|
|
1505
|
+
container: { flex: 1, alignItems: "center", justifyContent: "center", padding: 24 },
|
|
1506
|
+
title: { fontSize: 28, fontWeight: "bold", marginBottom: 8 },
|
|
1507
|
+
subtitle: { fontSize: 16, color: "#666", textAlign: "center", marginBottom: 32 },
|
|
1508
|
+
buttons: { gap: 12, width: "100%" },
|
|
1509
|
+
button: { backgroundColor: "#0070f3", borderRadius: 8, padding: 14, alignItems: "center" },
|
|
1510
|
+
secondaryButton: { backgroundColor: "transparent", borderWidth: 1, borderColor: "#0070f3" },
|
|
1511
|
+
buttonText: { color: "#fff", fontSize: 16, fontWeight: "600" },
|
|
1512
|
+
secondaryText: { color: "#0070f3" },
|
|
1513
|
+
});
|
|
1514
|
+
`},{path:"app/(auth)/login.tsx",content:`import { useState } from "react";
|
|
1449
1515
|
import { View, Text, TextInput, TouchableOpacity, StyleSheet, Alert } from "react-native";
|
|
1450
1516
|
import { useRouter } from "expo-router";
|
|
1451
1517
|
import { vaif } from "../../lib/vaif";
|
|
@@ -1458,10 +1524,14 @@ export default function LoginScreen() {
|
|
|
1458
1524
|
|
|
1459
1525
|
async function handleLogin() {
|
|
1460
1526
|
setLoading(true);
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1527
|
+
try {
|
|
1528
|
+
await vaif.auth.login(email, password);
|
|
1529
|
+
router.replace("/");
|
|
1530
|
+
} catch (err: any) {
|
|
1531
|
+
Alert.alert("Error", err.message || "Login failed");
|
|
1532
|
+
} finally {
|
|
1533
|
+
setLoading(false);
|
|
1534
|
+
}
|
|
1465
1535
|
}
|
|
1466
1536
|
|
|
1467
1537
|
return (
|
|
@@ -1496,10 +1566,14 @@ export default function SignupScreen() {
|
|
|
1496
1566
|
|
|
1497
1567
|
async function handleSignup() {
|
|
1498
1568
|
setLoading(true);
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1569
|
+
try {
|
|
1570
|
+
await vaif.auth.signUp(email, password);
|
|
1571
|
+
router.replace("/");
|
|
1572
|
+
} catch (err: any) {
|
|
1573
|
+
Alert.alert("Error", err.message || "Sign up failed");
|
|
1574
|
+
} finally {
|
|
1575
|
+
setLoading(false);
|
|
1576
|
+
}
|
|
1503
1577
|
}
|
|
1504
1578
|
|
|
1505
1579
|
return (
|
|
@@ -1846,7 +1920,7 @@ class _LoginScreenState extends State<LoginScreen> {
|
|
|
1846
1920
|
setState(() { _loading = true; _error = null; });
|
|
1847
1921
|
|
|
1848
1922
|
try {
|
|
1849
|
-
await vaif.auth.
|
|
1923
|
+
await vaif.auth.login(
|
|
1850
1924
|
email: _emailController.text,
|
|
1851
1925
|
password: _passwordController.text,
|
|
1852
1926
|
);
|
|
@@ -3684,47 +3758,47 @@ export const posts = pgTable("posts", {
|
|
|
3684
3758
|
|
|
3685
3759
|
return Response.json({ message: \`Hello, \${name}!\` });
|
|
3686
3760
|
}
|
|
3687
|
-
`}]},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 Pe(){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(Fe))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 Ft(t){if(!process.stdin.isTTY||!process.stdout.isTTY)return t;let e=new Set(t.map(n=>B.findIndex(
|
|
3688
|
-
? Which VAIF features do you want to include?`)),B.forEach((a,c)=>{let l=e.has(c)?f__default.default.green("[x]"):"[ ]",p=c===o?f__default.default.cyan("> "):" ";console.log(`${p}${l} ${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,c)=>{if(c.name==="up"&&o>0)o--,
|
|
3761
|
+
`}]},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 Pe(){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(Fe))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 Ft(t){if(!process.stdin.isTTY||!process.stdout.isTTY)return t;let e=new Set(t.map(n=>B.findIndex(s=>s.name===n)).filter(n=>n>=0)),o=0;return new Promise(n=>{let s=Ie__default.default.createInterface({input:process.stdin,output:process.stdout});Ie__default.default.emitKeypressEvents(process.stdin,s),process.stdin.setRawMode&&process.stdin.setRawMode(true);function r(){let a=B.length+2;process.stdout.write(`\x1B[${a}A`),i();}function i(){console.log(f__default.default.bold(`
|
|
3762
|
+
? Which VAIF features do you want to include?`)),B.forEach((a,c)=>{let l=e.has(c)?f__default.default.green("[x]"):"[ ]",p=c===o?f__default.default.cyan("> "):" ";console.log(`${p}${l} ${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,c)=>{if(c.name==="up"&&o>0)o--,r();else if(c.name==="down"&&o<B.length-1)o++,r();else if(c.name==="space")e.has(o)?e.delete(o):e.add(o),r();else if(c.name==="return"){process.stdin.setRawMode&&process.stdin.setRawMode(false),s.close();let l=[...e].sort().map(p=>B[p].name);n(l.length>0?l:t);}else c.name==="c"&&c.ctrl&&(process.stdin.setRawMode&&process.stdin.setRawMode(false),s.close(),process.exit(0));});})}async function de(t,e={}){let o=Fe[t];o||(console.log(f__default.default.red(`
|
|
3689
3763
|
Unknown template: ${t}`)),console.log(f__default.default.yellow(`Run 'vaif templates' to see available templates.
|
|
3690
3764
|
`)),process.exit(1));let n;e.features&&e.features.length>0?n=e.features.filter(l=>B.some(p=>p.name===l)):e.addOnly?(console.log(f__default.default.red(`
|
|
3691
|
-
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 Ft(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
|
|
3692
|
-
`,"utf-8"),console.log(f__default.default.green(` merge ${l.path} (added dependencies)`)),
|
|
3765
|
+
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 Ft(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 s=e.addOnly?[]:[...o.files];if(o.featureFiles)for(let l of n){let p=o.featureFiles[l];p&&s.push(...p);}let r=0,i=0;for(let l of s){let p=w__default.default.resolve(l.path),u=w__default.default.dirname(p);if(k__default.default.existsSync(u)||k__default.default.mkdirSync(u,{recursive:true}),l.path==="package.json"&&k__default.default.existsSync(p)&&!e.force)try{let d=JSON.parse(k__default.default.readFileSync(p,"utf-8")),m=JSON.parse(l.content),y=L=>{if(!L)return {};let M={};for(let[z,G]of Object.entries(L))!G.startsWith("workspace:")&&!G.startsWith("link:")&&!G.startsWith("file:")&&(M[z]=G);return M};d.dependencies={...y(d.dependencies),...m.dependencies||{}},d.devDependencies={...y(d.devDependencies),...m.devDependencies||{}},m.scripts&&(d.scripts={...d.scripts||{},...m.scripts}),k__default.default.writeFileSync(p,JSON.stringify(d,null,2)+`
|
|
3766
|
+
`,"utf-8"),console.log(f__default.default.green(` merge ${l.path} (added dependencies)`)),r++;continue}catch{}if(k__default.default.existsSync(p)&&!e.force){console.log(f__default.default.yellow(` skip ${l.path} (already exists)`)),i++;continue}k__default.default.writeFileSync(p,l.content,"utf-8"),console.log(f__default.default.green(` create ${l.path}`)),r++;}console.log(""),r>0&&console.log(f__default.default.green(`Created ${r} file${r!==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:{}},c=w__default.default.resolve("package.json");if(k__default.default.existsSync(c)&&n.length>0)try{let l=JSON.parse(k__default.default.readFileSync(c,"utf-8")),p=!1;for(let u of n){let d=a[u];if(d)for(let[m,y]of Object.entries(d))l.dependencies?.[m]||(l.dependencies=l.dependencies||{},l.dependencies[m]=y,p=!0);}p&&k__default.default.writeFileSync(c,JSON.stringify(l,null,2)+`
|
|
3693
3767
|
`,"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(l=>{console.log(f__default.default.gray(` ${l}`));}),console.log(""),console.log(f__default.default.gray(" Get your project credentials at https://vaif.studio/app/security/api-keys")),console.log("");}var jt={$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 je(t){if(t.addFeatures){t.template||(console.log(f__default.default.red(`
|
|
3694
|
-
--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(
|
|
3695
|
-
Use --force to overwrite existing configuration.`)),process.exit(1));try{if(
|
|
3768
|
+
--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(s=>s.trim());await de(t.template,{force:t.force,features:n,addOnly:true});return}let e=H__default.default("Initializing VAIF configuration...").start(),o=w__default.default.resolve("vaif.config.json");k__default.default.existsSync(o)&&!t.force&&(e.fail("vaif.config.json already exists"),console.log(f__default.default.yellow(`
|
|
3769
|
+
Use --force to overwrite existing configuration.`)),process.exit(1));try{if(k__default.default.writeFileSync(o,JSON.stringify(jt,null,2),"utf-8"),e.succeed("Created vaif.config.json"),t.template){let n=t.features?t.features.split(",").map(s=>s.trim()):void 0;await de(t.template,{force:t.force,features:n});}else {let n=w__default.default.resolve(".env.example");if(k__default.default.existsSync(n)||(k__default.default.writeFileSync(n,`# VAIF Configuration
|
|
3696
3770
|
DATABASE_URL=postgresql://user:password@localhost:5432/database
|
|
3697
3771
|
VAIF_API_KEY=your-api-key
|
|
3698
|
-
`,"utf-8"),console.log(f__default.default.gray("Created .env.example"))),t.typescript){let
|
|
3699
|
-
Error: ${n.message}`)),process.exit(1);}}var Lt=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Vt(t,e,o="public"){let n=await fetch(`${Lt}/v1/projects/${e}/schema?schema=${o}`,{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}});if(!n.ok){let
|
|
3700
|
-
Error: ${i}`)),process.exit(1);}
|
|
3701
|
-
Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1)),e.text="Fetching remote schema...";try{let i=t.schema||
|
|
3702
|
-
Error: ${i.message}`)),process.exit(1);}}var Ne=process.env.VAIF_API_URL||"https://api.vaif.studio";function $t(t){let e=Ie__default.default.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(t,n=>{e.close(),o(n);});})}async function Ot(t,e,o){let n=await fetch(`${Ne}/v1/projects/${e}/schema/preview`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({schema:o})});if(!n.ok){let
|
|
3703
|
-
Error: ${c}`)),process.exit(1);}
|
|
3704
|
-
Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1));let i=t.schema||w__default.default.resolve("vaif.schema.json");
|
|
3705
|
-
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 c=
|
|
3706
|
-
Error: ${c.message}`)),process.exit(1);}e.text="Calculating schema changes...";try{let{diff:c,sql:l}=await Ot(o.token,
|
|
3707
|
-
Cancelled. No changes applied.`));return}}e.start("Applying schema changes...");let p=await Mt(o.token,
|
|
3708
|
-
Error: ${c.message}`)),process.exit(1);}}var W=process.env.VAIF_API_URL||"https://api.vaif.studio";async function
|
|
3772
|
+
`,"utf-8"),console.log(f__default.default.gray("Created .env.example"))),t.typescript){let s=w__default.default.resolve("src/types");k__default.default.existsSync(s)||(k__default.default.mkdirSync(s,{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(`
|
|
3773
|
+
Error: ${n.message}`)),process.exit(1);}}var Lt=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Vt(t,e,o="public"){let n=await fetch(`${Lt}/v1/projects/${e}/schema?schema=${o}`,{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}});if(!n.ok){let s=await n.text();throw new Error(`Failed to fetch schema: ${s}`)}return n.json()}async function Ce(t){let e=H__default.default(),o=I();(!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",s=null;e.start("Loading configuration...");try{s=await A(n);}catch(i){e.fail("Failed to load config"),console.log(f__default.default.red(`
|
|
3774
|
+
Error: ${i}`)),process.exit(1);}s||(e.fail("No configuration found"),console.log(f__default.default.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let r=t.projectId||s.projectId||process.env.VAIF_PROJECT_ID||o.projectId;r||(e.fail("No project ID specified"),console.log(f__default.default.yellow(`
|
|
3775
|
+
Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1)),e.text="Fetching remote schema...";try{let i=t.schema||s.database?.schema||"public",a=await Vt(o.token,r,i);e.succeed("Schema fetched successfully");let c=t.output||w__default.default.resolve("vaif.schema.json"),l={$schema:"https://vaif.studio/schemas/schema.json",projectId:r,schema:i,pulledAt:new Date().toISOString(),...a};k__default.default.writeFileSync(c,JSON.stringify(l,null,2),"utf-8"),console.log(""),console.log(f__default.default.green(`Schema saved to: ${c}`)),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(`
|
|
3776
|
+
Error: ${i.message}`)),process.exit(1);}}var Ne=process.env.VAIF_API_URL||"https://api.vaif.studio";function $t(t){let e=Ie__default.default.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(t,n=>{e.close(),o(n);});})}async function Ot(t,e,o){let n=await fetch(`${Ne}/v1/projects/${e}/schema/preview`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({schema:o})});if(!n.ok){let s=await n.text();throw new Error(`Failed to preview changes: ${s}`)}return n.json()}async function Mt(t,e,o){let n=await fetch(`${Ne}/v1/projects/${e}/schema/apply`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({schema:o})});if(!n.ok){let s=await n.text();throw new Error(`Failed to apply changes: ${s}`)}return n.json()}function zt(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 Le(t){let e=H__default.default(),o=I();(!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",s=null;e.start("Loading configuration...");try{s=await A(n);}catch(c){e.fail("Failed to load config"),console.log(f__default.default.red(`
|
|
3777
|
+
Error: ${c}`)),process.exit(1);}s||(e.fail("No configuration found"),console.log(f__default.default.yellow("\nRun `vaif init` to create a configuration file.")),process.exit(1));let r=t.projectId||s.projectId||process.env.VAIF_PROJECT_ID||o.projectId;r||(e.fail("No project ID specified"),console.log(f__default.default.yellow(`
|
|
3778
|
+
Set projectId in vaif.config.json or use --project-id flag.`)),process.exit(1));let i=t.schema||w__default.default.resolve("vaif.schema.json");k__default.default.existsSync(i)||(e.fail("No local schema found"),console.log(f__default.default.yellow(`
|
|
3779
|
+
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 c=k__default.default.readFileSync(i,"utf-8");a=JSON.parse(c);}catch(c){e.fail("Failed to parse schema file"),c instanceof Error&&console.log(f__default.default.red(`
|
|
3780
|
+
Error: ${c.message}`)),process.exit(1);}e.text="Calculating schema changes...";try{let{diff:c,sql:l}=await Ot(o.token,r,a);if(e.stop(),zt(c),c.added.length===0&&c.modified.length===0&&c.removed.length===0){console.log("");return}if(l.length>0){console.log(f__default.default.bold("SQL Migrations:")),console.log("");for(let u of l)console.log(f__default.default.gray(` ${u}`));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){c.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 d=await $t(f__default.default.cyan("Apply these changes? [y/N] "));if(d.toLowerCase()!=="y"&&d.toLowerCase()!=="yes"){console.log(f__default.default.yellow(`
|
|
3781
|
+
Cancelled. No changes applied.`));return}}e.start("Applying schema changes...");let p=await Mt(o.token,r,a);if(p.success){if(e.succeed("Schema changes applied successfully"),console.log(""),p.migrations.length>0){console.log(f__default.default.gray("Migrations applied:"));for(let u of p.migrations)console.log(f__default.default.gray(` - ${u}`));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(c){e.fail("Failed to push schema changes"),c instanceof Error&&console.log(f__default.default.red(`
|
|
3782
|
+
Error: ${c.message}`)),process.exit(1);}}var W=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Kt(t,e,o,n){let s=new URL(`${W}/functions/project/${e}`);n&&s.searchParams.set("envId",n);let r=await fetch(s.toString(),{headers:{Authorization:`Bearer ${t}`}});if(!r.ok)return null;let i=await r.json(),a=i.functions||i;return Array.isArray(a)&&a.find(c=>c.name===o)||null}async function Bt(t,e,o){let n=await fetch(`${W}/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 s=await n.text();throw new Error(`Failed to create function: ${s}`)}return n.json()}async function qt(t,e,o){let n=await fetch(`${W}/functions/${e}/source`,{method:"PUT",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({sourceCode:o})});if(!n.ok){let s=await n.text();throw new Error(`Failed to deploy source: ${s}`)}}async function Yt(t,e,o){let n=new URL(`${W}/functions/project/${e}`);o&&n.searchParams.set("envId",o);let s=await fetch(n.toString(),{headers:{Authorization:`Bearer ${t}`}});if(!s.ok){let i=await s.text();throw new Error(`Failed to list functions: ${i}`)}let r=await s.json();return r.functions||r}function Ve(t){switch(w__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 ke(t){let e=[],o=[".ts",".js",".mjs",".py",".go",".rs"],n=["drizzle.config.ts","tsconfig.json","package.json"];if(!k__default.default.existsSync(t))return e;let s=k__default.default.readdirSync(t,{withFileTypes:true});for(let r of s){let i=w__default.default.join(t,r.name);if(r.isDirectory()){if(r.name!=="node_modules"&&!r.name.startsWith(".")){let a=k__default.default.readdirSync(i,{withFileTypes:true});for(let c of a)if(c.isFile()){let l=w__default.default.extname(c.name).toLowerCase();if(o.includes(l)){e.push(w__default.default.join(i,c.name));break}}}}else if(r.isFile()){let a=w__default.default.extname(r.name).toLowerCase();o.includes(a)&&!n.includes(r.name)&&e.push(i);}}return e}async function De(t){let e=H__default.default(),o=I();(!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",s=null;try{s=await A(n);}catch{}let r=t.projectId||s?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;r||(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=w__default.default.resolve("functions"),a=w__default.default.resolve("src/functions"),c=[];if(t.entrypoint){let d=w__default.default.resolve(t.entrypoint);k__default.default.existsSync(d)||(e.fail(`File not found: ${t.entrypoint}`),process.exit(1)),c=[d];}else c=[...ke(i),...ke(a)];c.length===0&&(e.fail("No function files found"),console.log(f__default.default.yellow(`
|
|
3709
3783
|
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(`
|
|
3710
3784
|
Or specify an entrypoint with --entrypoint`)),process.exit(1)),e.succeed(`Found ${c.length} function(s)`),t.name&&(c=c.filter(d=>w__default.default.basename(d,w__default.default.extname(d)).includes(t.name)),c.length===0&&(console.log(f__default.default.yellow(`
|
|
3711
|
-
No functions matching "${t.name}" found`)),process.exit(1))),console.log(""),console.log(f__default.default.gray("Functions to deploy:"));for(let d of c){let m=w__default.default.basename(w__default.default.dirname(d)),y=m==="functions"||m==="src"?w__default.default.basename(d,w__default.default.extname(d)):m,L=t.runtime||Ve(d);console.log(f__default.default.gray(` - ${y} (${L})`));}if(console.log(""),t.dryRun){console.log(f__default.default.yellow("Dry run mode - no functions deployed."));return}let l=[];for(let d of c){let m=w__default.default.basename(w__default.default.dirname(d)),y=m==="functions"||m==="src"?w__default.default.basename(d,w__default.default.extname(d)):m,L=t.runtime||Ve(d);e.start(`Deploying ${y}...`);try{let M=
|
|
3785
|
+
No functions matching "${t.name}" found`)),process.exit(1))),console.log(""),console.log(f__default.default.gray("Functions to deploy:"));for(let d of c){let m=w__default.default.basename(w__default.default.dirname(d)),y=m==="functions"||m==="src"?w__default.default.basename(d,w__default.default.extname(d)):m,L=t.runtime||Ve(d);console.log(f__default.default.gray(` - ${y} (${L})`));}if(console.log(""),t.dryRun){console.log(f__default.default.yellow("Dry run mode - no functions deployed."));return}let l=[];for(let d of c){let m=w__default.default.basename(w__default.default.dirname(d)),y=m==="functions"||m==="src"?w__default.default.basename(d,w__default.default.extname(d)):m,L=t.runtime||Ve(d);e.start(`Deploying ${y}...`);try{let M=k__default.default.readFileSync(d,"utf-8"),z=await Kt(o.token,r,y,t.envId);z||(e.text=`Creating ${y}...`,z=await Bt(o.token,r,{name:y,runtime:L,entrypoint:w__default.default.basename(d),envId:t.envId})),e.text=`Deploying ${y}...`,await qt(o.token,z.id,M),e.succeed(`Deployed ${y}`),l.push({name:y,success:!0});}catch(M){let z=M instanceof Error?M.message:"Unknown error";e.fail(`Failed to deploy ${y}`),l.push({name:y,success:false,error:z});}}console.log("");let p=l.filter(d=>d.success).length;if(l.filter(d=>!d.success).length===0)console.log(f__default.default.green(`\u2713 Successfully deployed ${p} function(s)`));else {console.log(f__default.default.yellow(`Deployed ${p}/${l.length} function(s)`)),console.log(""),console.log(f__default.default.red("Failed deployments:"));for(let d of l.filter(m=>!m.success))console.log(f__default.default.red(` - ${d.name}: ${d.error}`));}console.log("");}async function $e(t){let e=H__default.default(),o=I();(!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",s=null;try{s=await A(n);}catch{}let r=t.projectId||s?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;r||(console.log(f__default.default.red("No project ID specified")),process.exit(1)),e.start("Fetching functions...");try{let i=await Yt(o.token,r,t.envId);if(e.stop(),i.length===0){console.log(f__default.default.yellow(`
|
|
3712
3786
|
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 c=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)+c(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(`
|
|
3713
|
-
Error: ${i.message}`)),process.exit(1);}}var X=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Gt(t,e,o,n,
|
|
3787
|
+
Error: ${i.message}`)),process.exit(1);}}var X=process.env.VAIF_API_URL||"https://api.vaif.studio";async function Gt(t,e,o,n,s){let r=await fetch(`${X}/v1/projects/${e}/db/seed`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({table:o,records:n,truncate:s?.truncate??false})});if(!r.ok){let i=await r.text();throw new Error(`Failed to seed ${o}: ${i}`)}return r.json()}async function Jt(t,e){let o=await fetch(`${X}/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 ue(t){let e=[];if(!k__default.default.existsSync(t))return e;let o=k__default.default.readdirSync(t,{withFileTypes:true});for(let n of o)if(n.isFile()){let s=w__default.default.extname(n.name).toLowerCase();(s===".json"||s===".ts"||s===".js")&&e.push(w__default.default.join(t,n.name));}return e.sort()}async function Oe(t){let e=w__default.default.extname(t).toLowerCase();if(e===".json"){let o=k__default.default.readFileSync(t,"utf-8"),n=JSON.parse(o);return Array.isArray(n)?[{table:w__default.default.basename(t,e),data:n}]:n.table&&n.data?[n]:Object.entries(n).map(([s,r])=>({table:s,data:r}))}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 Me(t){let e=H__default.default(),o=I();(!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",s=null;try{s=await A(n);}catch{}let r=t.projectId||s?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;r||(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 p=w__default.default.resolve(t.file);k__default.default.existsSync(p)||(console.log(f__default.default.red(`File not found: ${t.file}`)),process.exit(1)),i=[p];}else {let p=w__default.default.resolve("seeds"),u=w__default.default.resolve("prisma/seed"),d=w__default.default.resolve("db/seeds");i=[...ue(p),...ue(u),...ue(d)];}i.length===0&&(console.log(f__default.default.yellow("No seed files found")),console.log(f__default.default.gray(`
|
|
3714
3788
|
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(`
|
|
3715
3789
|
Or specify a file with --file`)),console.log(f__default.default.gray(`
|
|
3716
|
-
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 p of i)console.log(f__default.default.gray(` - ${w__default.default.relative(process.cwd(),p)}`));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 p of i){e.start(`Loading ${w__default.default.basename(p)}...`);try{let u=await Oe(p);e.stop();for(let d of u)t.table&&d.table!==t.table||(console.log(f__default.default.cyan(`Table: ${d.table}`)),console.log(f__default.default.gray(` Records: ${d.data.length}`)),d.data.length>0&&console.log(f__default.default.gray(` Sample: ${JSON.stringify(d.data[0],null,2).slice(0,100)}...`)),console.log(""));}catch(u){e.fail(`Failed to load ${w__default.default.basename(p)}`),u instanceof Error&&console.log(f__default.default.red(` Error: ${u.message}`));}}return}let a=[];for(let p of i){e.start(`Processing ${w__default.default.basename(p)}...`);try{let u=await Oe(p);e.stop();for(let d of u)if(!(t.table&&d.table!==t.table)){if(d.data.length===0){console.log(f__default.default.gray(` Skipping ${d.table} (no records)`));continue}e.start(`Seeding ${d.table} (${d.data.length} records)...`);try{let m=await Gt(o.token,
|
|
3790
|
+
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 p of i)console.log(f__default.default.gray(` - ${w__default.default.relative(process.cwd(),p)}`));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 p of i){e.start(`Loading ${w__default.default.basename(p)}...`);try{let u=await Oe(p);e.stop();for(let d of u)t.table&&d.table!==t.table||(console.log(f__default.default.cyan(`Table: ${d.table}`)),console.log(f__default.default.gray(` Records: ${d.data.length}`)),d.data.length>0&&console.log(f__default.default.gray(` Sample: ${JSON.stringify(d.data[0],null,2).slice(0,100)}...`)),console.log(""));}catch(u){e.fail(`Failed to load ${w__default.default.basename(p)}`),u instanceof Error&&console.log(f__default.default.red(` Error: ${u.message}`));}}return}let a=[];for(let p of i){e.start(`Processing ${w__default.default.basename(p)}...`);try{let u=await Oe(p);e.stop();for(let d of u)if(!(t.table&&d.table!==t.table)){if(d.data.length===0){console.log(f__default.default.gray(` Skipping ${d.table} (no records)`));continue}e.start(`Seeding ${d.table} (${d.data.length} records)...`);try{let m=await Gt(o.token,r,d.table,d.data,{truncate:t.truncate});e.succeed(`Seeded ${d.table}: ${m.inserted} records`),a.push({table:d.table,inserted:m.inserted});}catch(m){let y=m instanceof Error?m.message:"Unknown error";e.fail(`Failed to seed ${d.table}`),a.push({table:d.table,inserted:0,error:y});}}}catch(u){e.fail(`Failed to load ${w__default.default.basename(p)}`),u instanceof Error&&console.log(f__default.default.red(` Error: ${u.message}`));}}console.log("");let c=a.reduce((p,u)=>p+u.inserted,0),l=a.filter(p=>p.error).length;if(l===0)console.log(f__default.default.green(`\u2713 Successfully seeded ${c} records across ${a.length} table(s)`));else {console.log(f__default.default.yellow(`Seeded ${c} records with ${l} error(s)`)),console.log(""),console.log(f__default.default.red("Errors:"));for(let p of a.filter(u=>u.error))console.log(f__default.default.red(` - ${p.table}: ${p.error}`));}console.log("");}async function ze(t){let e=H__default.default(),o=I();(!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",s=null;try{s=await A(n);}catch{}let r=t.projectId||s?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;r||(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=w__default.default.resolve(t.dir||"./drizzle");if(console.log(""),console.log(f__default.default.bold("VAIF Database Push")),console.log(""),!k__default.default.existsSync(i)){let u=w__default.default.resolve("./migrations");k__default.default.existsSync(u)?console.log(f__default.default.gray(`Using migrations from: ${u}`)):(console.log(f__default.default.red(`Migrations directory not found: ${i}`)),console.log(f__default.default.gray(`
|
|
3717
3791
|
Expected one of:`)),console.log(f__default.default.gray(" - ./drizzle/")),console.log(f__default.default.gray(" - ./migrations/")),console.log(f__default.default.gray(`
|
|
3718
|
-
Or specify with: vaif db push --dir <path>`)),process.exit(1));}let a=[],c=
|
|
3719
|
-
Error: ${a.message}`)),process.exit(1);}}async function Be(t){let e=H__default.default(),o=I();(!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",
|
|
3720
|
-
Error: ${i.message}`)),process.exit(1);}}var Ye=process.env.VAIF_API_URL||"https://api.vaif.studio";function Ge(t,e,o){return t.projectId||e?.projectId||process.env.VAIF_PROJECT_ID||o.projectId||null}async function Je(t){let e=H__default.default(),o=I();(!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",
|
|
3721
|
-
Error: ${a.message}`)),process.exit(1);}}async function We(t){let e=H__default.default(),o=I();(!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",
|
|
3792
|
+
Or specify with: vaif db push --dir <path>`)),process.exit(1));}let a=[],c=k__default.default.readdirSync(i,{withFileTypes:true});for(let u of c)if(u.isFile()&&u.name.endsWith(".sql"))a.push(w__default.default.join(i,u.name));else if(u.isDirectory()){let d=k__default.default.readdirSync(w__default.default.join(i,u.name),{withFileTypes:true});for(let m of d)m.isFile()&&m.name.endsWith(".sql")&&a.push(w__default.default.join(i,u.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 u of a)console.log(f__default.default.gray(` - ${w__default.default.relative(process.cwd(),u)}`));if(console.log(""),t.dryRun){console.log(f__default.default.yellow("Dry run mode - no migrations will be applied.")),console.log("");for(let u of a){let d=k__default.default.readFileSync(u,"utf-8");console.log(f__default.default.cyan(`--- ${w__default.default.basename(u)} ---`)),console.log(f__default.default.gray(d.slice(0,500))),d.length>500&&console.log(f__default.default.gray("...")),console.log("");}return}let l=0,p=0;for(let u of a){let d=k__default.default.readFileSync(u,"utf-8"),m=w__default.default.relative(process.cwd(),u);e.start(`Applying ${m}...`);try{let y=await fetch(`${X}/schema-engine/query/${r}`,{method:"POST",headers:{Authorization:`Bearer ${o.token}`,"Content-Type":"application/json"},body:JSON.stringify({sql:d})});if(!y.ok){let L=await y.text();throw new Error(L)}e.succeed(`Applied ${m}`),l++;}catch(y){let L=y instanceof Error?y.message:"Unknown error";e.fail(`Failed ${m}: ${L}`),p++;}}console.log(""),console.log(p===0?f__default.default.green(`Successfully applied ${l} migration(s)`):f__default.default.yellow(`Applied ${l}, failed ${p} migration(s)`)),console.log("");}async function Ke(t){let e=H__default.default(),o=I();(!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",s=null;try{s=await A(n);}catch{}let r=t.projectId||s?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;r||(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=w__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(`${X}/schema-engine/introspect/${r}`,{headers:{Authorization:`Bearer ${o.token}`}});if(!a.ok){let p=await a.text();throw new Error(`Failed to pull schema: ${p}`)}let c=await a.json();k__default.default.writeFileSync(i,JSON.stringify(c,null,2),"utf-8"),e.succeed(`Schema written to ${w__default.default.relative(process.cwd(),i)}`);let l=c.tables?.length??Object.keys(c).length;console.log(f__default.default.gray(` ${l} table(s) pulled`)),console.log("");}catch(a){e.fail("Failed to pull schema"),a instanceof Error&&console.log(f__default.default.red(`
|
|
3793
|
+
Error: ${a.message}`)),process.exit(1);}}async function Be(t){let e=H__default.default(),o=I();(!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",s=null;try{s=await A(n);}catch{}let r=t.projectId||s?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;r||(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 Jt(o.token,r),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(`
|
|
3794
|
+
Error: ${i.message}`)),process.exit(1);}}var Ye=process.env.VAIF_API_URL||"https://api.vaif.studio";function Ge(t,e,o){return t.projectId||e?.projectId||process.env.VAIF_PROJECT_ID||o.projectId||null}async function Je(t){let e=H__default.default(),o=I();(!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",s=null;try{s=await A(n);}catch{}let r=Ge(t,s,o);r||(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(`${Ye}/v1/projects/${r}/api-keys`,{method:"POST",headers:{Authorization:`Bearer ${o.token}`,"Content-Type":"application/json"},body:JSON.stringify({name:i})});if(!a.ok){let l=await a.text();throw new Error(`Failed to generate key: ${l}`)}let c=await a.json();e.succeed("API key generated"),console.log(""),console.log(f__default.default.green(` Name: ${c.name}`)),console.log(f__default.default.green(` Key: ${c.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(`
|
|
3795
|
+
Error: ${a.message}`)),process.exit(1);}}async function We(t){let e=H__default.default(),o=I();(!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",s=null;try{s=await A(n);}catch{}let r=Ge(t,s,o);r||(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(`${Ye}/v1/projects/${r}/api-keys`,{headers:{Authorization:`Bearer ${o.token}`}});if(!i.ok){let u=await i.text();throw new Error(`Failed to list keys: ${u}`)}let a=await i.json(),c=a.keys||a;if(e.stop(),!Array.isArray(c)||c.length===0){console.log(f__default.default.yellow("No API keys found")),console.log(f__default.default.gray(`
|
|
3722
3796
|
Generate one with: vaif keys generate`));return}let l=Math.max(8,...c.map(u=>(u.name||"").length)),p=` ${"Name".padEnd(l)} ${"Key".padEnd(24)} Created`;console.log(f__default.default.gray(p)),console.log(f__default.default.gray(" "+"-".repeat(p.length-2)));for(let u of c){let d=(u.name||"unnamed").padEnd(l),m=u.maskedKey||u.prefix||`${(u.key||"").slice(0,12)}...`,y=u.createdAt?new Date(u.createdAt).toLocaleDateString():"N/A";console.log(` ${d} ${m.padEnd(24)} ${y}`);}console.log(""),console.log(f__default.default.gray(` ${c.length} key(s) total`)),console.log("");}catch(i){e.fail("Failed to list API keys"),i instanceof Error&&console.log(f__default.default.red(`
|
|
3723
|
-
Error: ${i.message}`)),process.exit(1);}}var O=process.env.VAIF_API_URL||"https://api.vaif.studio";function Ht(t,e,o){return t.projectId||e?.projectId||process.env.VAIF_PROJECT_ID||o.projectId||null}function Z(){let t=I();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 ee(t){try{return await A(t||"vaif.config.json")}catch{return null}}function te(t,e,o){let n=Ht(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 He(t,e,o){let n=H__default.default(),
|
|
3724
|
-
Error: ${c.message}`)),process.exit(1);}}async function Xe(t){let e=H__default.default(),o=Z(),n=await ee(t.config),
|
|
3725
|
-
Create one with: vaif secrets set <name> <value>`));return}let c=Math.max(8,...a.map(p=>p.key.length)),l=` ${"Name".padEnd(c)} Created`;console.log(f__default.default.gray(l)),console.log(f__default.default.gray(" "+"-".repeat(l.length-2)));for(let p of a){let u=p.key.padEnd(c),d=p.createdAt?new Date(p.createdAt).toLocaleDateString():"N/A";console.log(` ${u} ${d}`);}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(
|
|
3726
|
-
Error: ${
|
|
3727
|
-
Error: ${i.message}`)),process.exit(1);}}async function Ze(t,e){let o=H__default.default(),n=Z(),
|
|
3728
|
-
Error: ${i.message}`)),process.exit(1);}}var et=process.env.VAIF_API_URL||"https://api.vaif.studio";function Qt(t){try{let e=new URL(t);return e.password&&(e.password="****"),e.toString()}catch{return t.replace(/:[^@/]+@/,":****@")}}async function tt(t){let e=H__default.default(),o=I();(!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",
|
|
3729
|
-
Error: ${i.message}`)),process.exit(1);}}var eo=process.env.VAIF_API_URL||"https://api.vaif.studio";async function ot(t){let e=H__default.default(),o=I();(!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",
|
|
3730
|
-
Error: ${i.message}`)),process.exit(1);}}var nt="1.7.
|
|
3797
|
+
Error: ${i.message}`)),process.exit(1);}}var O=process.env.VAIF_API_URL||"https://api.vaif.studio";function Ht(t,e,o){return t.projectId||e?.projectId||process.env.VAIF_PROJECT_ID||o.projectId||null}function Z(){let t=I();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 ee(t){try{return await A(t||"vaif.config.json")}catch{return null}}function te(t,e,o){let n=Ht(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 He(t,e,o){let n=H__default.default(),s=Z(),r=await ee(o.config),i=te(o,r,s),a=e;if(o.fromFile)try{a=k__default.default.readFileSync(o.fromFile,"utf-8");}catch(c){console.log(f__default.default.red(`Failed to read file: ${o.fromFile}`)),c instanceof Error&&console.log(f__default.default.gray(c.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 c=new URL(`${O}/functions/secrets/project/${i}`);o.envId&&c.searchParams.set("envId",o.envId);let l=await fetch(c.toString(),{headers:{Authorization:`Bearer ${s.token}`}});if(!l.ok)throw new Error(`Failed to check existing secrets: ${await l.text()}`);let u=(await l.json()).find(d=>d.key===t);if(u){n.text=`Updating secret "${t}"...`;let d=await fetch(`${O}/functions/secrets/${u.id}`,{method:"PUT",headers:{Authorization:`Bearer ${s.token}`,"Content-Type":"application/json"},body:JSON.stringify({value:a})});if(!d.ok)throw new Error(`Failed to update secret: ${await d.text()}`);n.succeed(`Updated secret "${t}"`);}else {n.text=`Creating secret "${t}"...`;let d=await fetch(`${O}/functions/secrets`,{method:"POST",headers:{Authorization:`Bearer ${s.token}`,"Content-Type":"application/json"},body:JSON.stringify({projectId:i,envId:o.envId,key:t,value:a})});if(!d.ok)throw new Error(`Failed to create secret: ${await d.text()}`);n.succeed(`Created secret "${t}"`);}console.log("");}catch(c){n.fail("Failed to set secret"),c instanceof Error&&console.log(f__default.default.red(`
|
|
3798
|
+
Error: ${c.message}`)),process.exit(1);}}async function Xe(t){let e=H__default.default(),o=Z(),n=await ee(t.config),s=te(t,n,o);console.log(""),console.log(f__default.default.bold("VAIF Secrets")),console.log(""),e.start("Fetching secrets...");try{let r=new URL(`${O}/functions/secrets/project/${s}`);t.envId&&r.searchParams.set("envId",t.envId);let i=await fetch(r.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(`
|
|
3799
|
+
Create one with: vaif secrets set <name> <value>`));return}let c=Math.max(8,...a.map(p=>p.key.length)),l=` ${"Name".padEnd(c)} Created`;console.log(f__default.default.gray(l)),console.log(f__default.default.gray(" "+"-".repeat(l.length-2)));for(let p of a){let u=p.key.padEnd(c),d=p.createdAt?new Date(p.createdAt).toLocaleDateString():"N/A";console.log(` ${u} ${d}`);}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(r){e.fail("Failed to list secrets"),r instanceof Error&&console.log(f__default.default.red(`
|
|
3800
|
+
Error: ${r.message}`)),process.exit(1);}}async function Qe(t,e){let o=H__default.default(),n=Z(),s=await ee(e.config),r=te(e,s,n);console.log(""),o.start("Fetching secret...");try{let i=new URL(`${O}/functions/secrets/project/${r}`);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 l=(await a.json()).find(d=>d.key===t);l||(o.fail(`Secret "${t}" not found`),process.exit(1));let p=await fetch(`${O}/functions/secrets/${l.id}/value`,{headers:{Authorization:`Bearer ${n.token}`}});if(!p.ok)throw new Error(`Failed to get secret value: ${await p.text()}`);let u=await p.json();o.stop(),console.log(u.value);}catch(i){o.fail("Failed to get secret"),i instanceof Error&&console.log(f__default.default.red(`
|
|
3801
|
+
Error: ${i.message}`)),process.exit(1);}}async function Ze(t,e){let o=H__default.default(),n=Z(),s=await ee(e.config),r=te(e,s,n);console.log(""),console.log(f__default.default.bold("VAIF Delete Secret")),console.log(""),o.start("Finding secret...");try{let i=new URL(`${O}/functions/secrets/project/${r}`);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 l=(await a.json()).find(u=>u.key===t);l||(o.fail(`Secret "${t}" not found`),process.exit(1)),o.text=`Deleting secret "${t}"...`;let p=await fetch(`${O}/functions/secrets/${l.id}`,{method:"DELETE",headers:{Authorization:`Bearer ${n.token}`}});if(!p.ok)throw new Error(`Failed to delete secret: ${await p.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(`
|
|
3802
|
+
Error: ${i.message}`)),process.exit(1);}}var et=process.env.VAIF_API_URL||"https://api.vaif.studio";function Qt(t){try{let e=new URL(t);return e.password&&(e.password="****"),e.toString()}catch{return t.replace(/:[^@/]+@/,":****@")}}async function tt(t){let e=H__default.default(),o=I();(!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",s=null;try{s=await A(n);}catch{}let r=t.projectId||s?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;r||(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(`${et}/v1/projects/${r}`,{headers:{Authorization:`Bearer ${o.token}`}});if(!i.ok){let p=await i.text();throw new Error(`Failed to fetch project: ${p}`)}let a=await i.json();e.stop(),console.log(""),console.log(f__default.default.bold("VAIF Project Info")),console.log("");let c=16,l=(p,u)=>{console.log(` ${f__default.default.gray(p.padEnd(c))} ${u}`);};l("Name:",f__default.default.white(a.name||"N/A")),l("Project ID:",f__default.default.white(r)),l("Region:",f__default.default.white(a.region||"us-east-1")),l("Plan:",f__default.default.white(a.plan||a.tier||"free")),l("Created:",f__default.default.white(a.createdAt?new Date(a.createdAt).toLocaleDateString():"N/A")),console.log(""),l("API URL:",f__default.default.cyan(a.apiUrl||`${et}/v1`)),l("WS URL:",f__default.default.cyan(a.wsUrl||a.realtimeUrl||"N/A")),l("DB URL:",f__default.default.cyan(a.databaseUrl?Qt(a.databaseUrl):"N/A")),l("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(`
|
|
3803
|
+
Error: ${i.message}`)),process.exit(1);}}var eo=process.env.VAIF_API_URL||"https://api.vaif.studio";async function ot(t){let e=H__default.default(),o=I();(!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",s=null;try{s=await A(n);}catch{}let r=t.projectId||s?.projectId||process.env.VAIF_PROJECT_ID||o.projectId;r||(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(`${eo}/v1/projects/${r}?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 c=22,l=(y,L)=>{console.log(` ${f__default.default.gray(y.padEnd(c))} ${L}`);};l("Project:",f__default.default.white(a.name||r)),l("Plan:",f__default.default.white(a.plan||a.tier||"free")),console.log(""),console.log(f__default.default.gray(" --- Resources ---")),console.log("");let p=a.tableCount??a.tables?.length??"N/A",u=a.functionCount??a.functions?.length??"N/A",d=a.bucketCount??a.storage?.buckets?.length??"N/A",m=a.activeConnections??a.connections??"N/A";l("Tables:",f__default.default.white(String(p))),l("Functions:",f__default.default.white(String(u))),l("Storage Buckets:",f__default.default.white(String(d))),l("Active Connections:",f__default.default.white(String(m))),a.usage&&(console.log(""),console.log(f__default.default.gray(" --- Usage ---")),console.log(""),a.usage.dbSize&&l("Database Size:",f__default.default.white(a.usage.dbSize)),a.usage.storageSize&&l("Storage Size:",f__default.default.white(a.usage.storageSize)),a.usage.bandwidth&&l("Bandwidth:",f__default.default.white(a.usage.bandwidth)),a.usage.functionInvocations!=null&&l("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(`
|
|
3804
|
+
Error: ${i.message}`)),process.exit(1);}}var nt="1.7.5",fe=f__default.default.hex("#00f0ff"),ge=f__default.default.hex("#7b61ff"),me=f__default.default.hex("#ff3dff"),he=f__default.default.hex("#00ff9d"),S=f__default.default.hex("#555570"),K=f__default.default.hex("#00f0ff");function to(){console.log(""),console.log(fe(" \u2566 \u2566")+ge("\u2554\u2550\u2557\u2566")+me("\u2554\u2550\u2557 ")+he("\u2554\u2550\u2557\u2566 \u2566")),console.log(fe(" \u255A\u2557\u2554\u255D")+ge("\u2560\u2550\u2563\u2551")+me("\u2560\u2563 ")+he("\u2551 \u2551 \u2551")),console.log(fe(" \u255A\u255D ")+ge("\u2569 \u2569\u2569")+me("\u255A ")+he("\u255A\u2550\u255D\u2569\u2550\u255D\u2569")),console.log(""),console.log(S(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(K(" VAIF Studio CLI")+S(` v${nt}`)),console.log(S(" Build full-stack apps at lightning speed")),console.log(S(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(""),console.log(f__default.default.bold(" Quick Start")),console.log(S(" $ ")+K("vaif login")+S(" Authenticate")),console.log(S(" $ ")+K("vaif init -t react-spa")+S(" Scaffold project")),console.log(S(" $ ")+K("vaif db push")+S(" Push migrations")),console.log(S(" $ ")+K("vaif generate")+S(" Generate types")),console.log(S(" $ ")+K("vaif functions deploy")+S(" Deploy functions")),console.log(""),console.log(f__default.default.bold(" Categories")),console.log(S(" auth ")+f__default.default.white("login, logout, whoami")),console.log(S(" project ")+f__default.default.white("init, templates, info, status")),console.log(S(" schema ")+f__default.default.white("pull, push, generate")),console.log(S(" database ")+f__default.default.white("db push, db pull, db seed, db reset")),console.log(S(" deploy ")+f__default.default.white("functions deploy, functions list")),console.log(S(" security ")+f__default.default.white("keys, secrets")),console.log(""),console.log(S(" Run ")+K("vaif <command> --help")+S(" for details")),console.log(S(" Docs: ")+f__default.default.underline("https://docs.vaif.studio")),console.log("");}commander.program.name("vaif").description("VAIF CLI - Type generation and development tools").version(nt);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(we);commander.program.command("logout").description("Log out and remove stored credentials").action(Se);commander.program.command("whoami").description("Show current authenticated user").action(xe);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(je);commander.program.command("templates").alias("tpl").description("List available project templates").action(Pe);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(tt);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(ot);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(Ce);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(Le);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(Ee);var at=commander.program.command("functions").alias("fn").description("Manage serverless functions");at.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(De);at.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($e);var oe=commander.program.command("db").description("Database management commands");oe.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(ze);oe.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(Ke);oe.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(Me);oe.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(Be);var it=commander.program.command("keys").description("Manage API keys");it.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(Je);it.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(We);var ne=commander.program.command("secrets").alias("sec").description("Manage function secrets");ne.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(He);ne.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);ne.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);ne.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(Ze);process.argv.slice(2).length||(to(),process.exit(0));commander.program.parse(process.argv);
|