@unreal-orm/cli 1.0.0-alpha.4 → 1.0.0-alpha.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +83 -81
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,30 +1,30 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as B2}from"node:module";var $2=Object.create;var{getPrototypeOf:Q2,defineProperty:v0,getOwnPropertyNames:J2}=Object;var X2=Object.prototype.hasOwnProperty;var X0=($,X,Q)=>{Q=$!=null?$2(Q2($)):{};let J=X||!$||!$.__esModule?v0(Q,"default",{value:$,enumerable:!0}):Q;for(let Z of J2($))if(!X2.call(J,Z))v0(J,Z,{get:()=>$[Z],enumerable:!0});return J};var Z2=($,X)=>{for(var Q in X)v0($,Q,{get:X[Q],enumerable:!0,configurable:!0,set:(J)=>X[Q]=()=>J})};var N0=($,X)=>()=>($&&(X=$($=0)),X);var Z0=B2(import.meta.url);class e0{lineCount=0;log($=""){console.log($),this.lineCount+=$.split(`
3
- `).length}clear(){if(this.lineCount>0)process.stdout.moveCursor(0,-this.lineCount),process.stdout.clearScreenDown(),this.lineCount=0}reset(){this.lineCount=0}}var $1;var Q1=N0(()=>{$1=new e0});import l from"chalk";import Y2 from"ora";var Q0,x,B;var m=N0(()=>{Q1();Q0={success:"✅",error:"❌",warning:"⚠️",info:"ℹ️",step:"\uD83D\uDD39",arrow:"➜",line:"─",corner:"└─"},x={primary:l.hex("#FF00A0"),secondary:l.cyan,success:l.green,error:l.red,warning:l.yellow,info:l.blue,dim:l.gray,code:l.hex("#E0E0E0"),url:l.underline.cyan},B={header($,X){if(console.log(""),console.log(x.primary.bold(` ${$} `)),X)console.log(x.dim(` ${X}`));console.log("")},divider(){console.log(x.dim(Q0.line.repeat(60)))},success($){console.log(x.success(`${Q0.success} ${$}`))},error($,X){if(console.log(x.error(`${Q0.error} ${$}`)),X)if(X instanceof Error)console.log(x.dim(` ${X.stack||X.message}`));else console.log(x.dim(` ${String(X)}`))},warn($){console.log(x.warning(`${Q0.warning} ${$}`))},info($){console.log(x.info(`${Q0.info} ${$}`))},step($,X){console.log(x.secondary(`${Q0.step} ${$}`)+(X?x.dim(` ${X}`):""))},spin($){return Y2({text:$,color:"cyan",spinner:"dots"}).start()},code($){return x.code($)},cmd($){return x.code(`$ ${$}`)},link($,X){return x.url(X||$)},dim($){return x.dim($)},bold($){return l.bold($)},newline(){console.log("")},get printer(){return $1},theme:x,symbols:Q0}});var B1={};Z2(B1,{promptText:()=>O0,promptSelectWithDisabled:()=>k0,promptSelect:()=>S0,promptForConnection:()=>V0,promptFileReview:()=>j0,confirm:()=>K2});import B0 from"prompts";async function V0($){let X=$.embedded,Q=await B0([{type:!X&&!$.url?"text":null,name:"url",message:"Database URL:",initial:"http://localhost:8000"},{type:!X&&!$.username?"text":null,name:"username",message:"Username:",initial:"root"},{type:!X&&!$.password?"password":null,name:"password",message:"Password:"},{type:!X&&!$.authLevel?"select":null,name:"authLevel",message:"Auth level:",choices:[{title:"Root",value:"root"},{title:"Namespace",value:"namespace"},{title:"Database",value:"database"}],initial:0},{type:!$.namespace?"text":null,name:"namespace",message:"Namespace:"},{type:!$.database?"text":null,name:"database",message:"Database:"}],{onCancel:()=>{B.newline(),B.warn("Operation cancelled."),process.exit(0)}});if(X)return{embedded:X==="memory"?"memory":`file://${X}`,namespace:$.namespace||Q.namespace,database:$.database||Q.database};let J=$.url||Q.url,Z=$.username||Q.username,Y=$.password||Q.password,_=$.authLevel||Q.authLevel||"root",G=$.namespace||Q.namespace,j=$.database||Q.database,U;if(_==="database")U={username:Z,password:Y,namespace:G,database:j};else if(_==="namespace")U={username:Z,password:Y,namespace:G};else U={username:Z,password:Y};return{url:J,namespace:G,database:j,authentication:U}}async function K2($,X=!0){return(await B0({type:"confirm",name:"value",message:$,initial:X},{onCancel:()=>{console.log(`
4
- Operation cancelled.`),process.exit(0)}})).value}async function O0($,X){return(await B0({type:"text",name:"value",message:$,initial:X},{onCancel:()=>{B.newline(),B.warn("Operation cancelled."),process.exit(0)}})).value||""}async function S0($,X){return(await B0({type:"select",name:"value",message:$,choices:X},{onCancel:()=>{console.log(`
5
- Operation cancelled.`),process.exit(0)}})).value}async function k0($,X){return(await B0({type:"select",name:"value",message:$,choices:X.map((J)=>({title:J.title,value:J.value,disabled:J.disabled}))},{onCancel:()=>{console.log(`
6
- Operation cancelled.`),process.exit(0)}})).value}async function j0($,X,Q){let Z=(await B0({type:"text",name:"action",message:`[${X}/${Q}] Apply this change? (y)es / (n)o / (a)ccept all / (c)ancel`,validate:(Y)=>{let _=Y.toLowerCase().trim();if(["y","yes","n","no","a","all","c","cancel"].includes(_))return!0;return"Please enter: y/yes, n/no, a/all, or c/cancel"}},{onCancel:()=>{B.newline(),B.warn("Operation cancelled."),process.exit(0)}})).action.toLowerCase().trim();if(Z==="y"||Z==="yes")return"yes";if(Z==="n"||Z==="no")return"no";if(Z==="a"||Z==="all")return"all";if(Z==="c"||Z==="cancel")return"cancel";return"no"}var Y0=N0(()=>{m()});import{Command as g4}from"@commander-js/extra-typings";m();import{Command as G2}from"@commander-js/extra-typings";import g from"prompts";import T from"node:fs/promises";import f from"node:path";import{execSync as J1}from"node:child_process";var __dirname="E:\\GitHub\\unreal-orm\\packages\\unreal-cli\\src\\commands",h=()=>{B.newline(),B.warn("Operation cancelled."),process.exit(0)},Z1=new G2("init").description("Initialize UnrealORM in your project").option("--url <url>","SurrealDB URL").option("-u, --username <username>","Database username").option("-p, --password <password>","Database password").option("-n, --namespace <ns>","Namespace").option("-d, --database <db>","Database").option("-e, --embedded <mode>","Embedded mode (memory or file path)").option("--sample","Generate sample schema tables").option("--from-db","Import schema from existing database").option("--from-surql <file>","Import schema from .surql file").option("--install","Install dependencies automatically").option("--no-install","Skip dependency installation").option("--pm <manager>","Package manager (npm, yarn, pnpm, bun)").action(async($)=>{B.header("\uD83D\uDE80 UnrealORM Setup","Initialize your project with UnrealORM");let X,Q;if($.url)Q="remote";else if($.embedded)Q=$.embedded==="memory"?"memory":"file";else Q=(await g({type:"select",name:"connectionMode",message:"How will you connect to SurrealDB?",choices:[{title:"Remote (URL)",value:"remote",description:"Connect via WebSocket/HTTP"},{title:"Embedded (Memory)",value:"memory",description:"In-memory, great for dev/testing"},{title:"Embedded (File)",value:"file",description:"Persist to local file"}]},{onCancel:h})).connectionMode;if(!Q)B.error("Operation cancelled."),process.exit(1);if(Q==="remote"){let I=$.url||(await g({type:"text",name:"url",message:"SurrealDB URL:",initial:"ws://localhost:8000"},{onCancel:h})).url,E=$.username,w=$.password,P="root";if(!E||!w){let b=await g([{type:$.username?null:"select",name:"authLevel",message:"Authentication level:",choices:[{title:"Root",value:"root"},{title:"Namespace",value:"namespace"},{title:"Database",value:"database"}]},{type:$.username?null:"text",name:"username",message:"Username:",initial:"root"},{type:$.password?null:"password",name:"password",message:"Password:"}],{onCancel:h});E=$.username||b.username,w=$.password||b.password,P=b.authLevel||"root"}let{namespace:F,database:L}=$,N=[];if(!F&&(P!=="root"||!L))N.push({type:"text",name:"namespace",message:"Namespace:",initial:"test"});if(!L)N.push({type:"text",name:"database",message:"Database:",initial:"test"});if(N.length>0){let b=await g(N,{onCancel:h});F=F||b.namespace,L=L||b.database}let v,C=E||"",S=w||"";if(P==="database"&&F&&L)v={username:C,password:S,namespace:F,database:L};else if(P==="namespace"&&F)v={username:C,password:S,namespace:F};else v={username:C,password:S};X={url:I,authentication:v,namespace:F,database:L}}else if(Q==="memory"){let{namespace:I,database:E}=$;if(!I||!E){let w=await g([{type:I?null:"text",name:"namespace",message:"Namespace:",initial:"test"},{type:E?null:"text",name:"database",message:"Database:",initial:"test"}],{onCancel:h});I=I||w.namespace,E=E||w.database}X={embedded:"memory",namespace:I,database:E},B.newline(),B.warn("Note: Embedded mode requires @surrealdb/node package")}else{let I=$.embedded!=="surrealkv"?$.embedded:void 0,E=$.namespace,w=$.database;if(!I)I=(await g({type:"text",name:"path",message:"Database file path:",initial:"./data/local"},{onCancel:h})).path;if(!E||!w){let P=await g([{type:E?null:"text",name:"namespace",message:"Namespace:",initial:"test"},{type:w?null:"text",name:"database",message:"Database:",initial:"test"}],{onCancel:h});E=E||P.namespace,w=w||P.database}X={embedded:I?.startsWith("surrealkv://")?I:`surrealkv://${I}`,namespace:E,database:w},B.newline(),B.warn("Note: Embedded mode requires @surrealdb/node package"),B.newline()}let Z=await T.access(f.join(process.cwd(),"src")).then(()=>!0).catch(()=>!1)?"./src/unreal":"./unreal",_=(await g({type:"text",name:"path",message:"Where should the unreal folder be created?",initial:Z},{onCancel:h})).path||Z,G=f.resolve(process.cwd(),_),j=f.join(G,"tables");await T.mkdir(j,{recursive:!0}),B.success(`Created ${_}/ folder structure`);let U=j2(_);await T.writeFile(f.join(process.cwd(),"unreal.config.json"),JSON.stringify(U,null,"\t")),B.success("Created unreal.config.json");let W=U2(Q);await T.writeFile(f.join(G,"surreal.ts"),W),B.success(`Created ${_}/surreal.ts`);let H=z2(X,Q),q=f.join(process.cwd(),".env"),z=await T.access(q).then(()=>!0).catch(()=>!1);if(B.newline(),z){if((await g({type:"confirm",name:"appendEnv",message:"Append SurrealDB config to existing .env file?",initial:!0},{onCancel:h})).appendEnv)if((await T.readFile(q,"utf-8")).includes("SURREAL_URL"))B.warn(".env already contains SURREAL_* variables, skipping append");else await T.appendFile(q,`
7
-
8
- ${H}
9
- `),B.success("Appended SurrealDB config to .env")}else if((await g({type:"confirm",name:"createEnv",message:"Create .env file with SurrealDB config?",initial:!0},{onCancel:h})).createEnv)await T.writeFile(q,`${H}
10
- `),B.success("Created .env file"),B.info(" Remember to add .env to your .gitignore!");let K=_2(),A=["unreal-orm@alpha","surrealdb@alpha"],D=["@unreal-orm/cli@alpha"];if(Q==="memory"||Q==="file")A.push("@surrealdb/node@alpha");let O=$.install;if(O===void 0){let I=[...A,...D.map((w)=>`${w} (dev)`)],{install:E}=await g({type:"confirm",name:"install",message:`Install dependencies? (${I.join(", ")})`,initial:!0},{onCancel:h});O=E}if(O){let I=$.pm??"";if(!I){let P=[{title:"npm",value:"npm"},{title:"yarn",value:"yarn"},{title:"pnpm",value:"pnpm"},{title:"bun",value:"bun"}],F=P.findIndex((N)=>N.value===K),{pm:L}=await g({type:"select",name:"pm",message:"Package manager:",choices:P,initial:F>=0?F:0},{onCancel:h});I=L??K}let E=X1(I,A,!1);B.newline(),B.info(`Running: ${E}...`);try{J1(E,{stdio:"inherit"})}catch(P){B.error("Failed to install dependencies")}let w=X1(I,D,!0);B.info(`Running: ${w}...`);try{J1(w,{stdio:"inherit"}),B.success("Dependencies installed")}catch(P){B.error("Failed to install dev dependencies")}}let V="none";if($.sample)V="sample";else if($.fromDb)V="from-db";else if($.fromSurql)V="from-surql";else V=(await g({type:"select",name:"action",message:"What would you like to do next?",choices:[{title:"Generate sample tables",value:"sample",description:"User, Post, Follow tables with indexes & relations"},{title:"Import from Database",value:"from-db",description:"Introspect existing DB"},{title:"Import from .surql file",value:"from-surql",description:"Parse SurrealQL file"},{title:"Nothing for now",value:"none"}]},{onCancel:h})).action;if(V==="sample"){let I=f.resolve(__dirname,"../../examples/simple"),E=["User.ts","Post.ts","Follow.ts"];for(let w of E){let P=await T.readFile(f.join(I,w),"utf-8");await T.writeFile(f.join(j,w),P)}B.success("Generated sample tables:"),console.log(B.dim(" • User.ts - Basic user table with indexes")),console.log(B.dim(" • Post.ts - Posts with record links, arrays, and methods")),console.log(B.dim(" • Follow.ts - Relation table (graph edge) example"))}else if(V==="from-db")B.info("Run 'unreal pull' to import schema from database");else if(V==="from-surql")B.info("Run 'unreal pull --file <path>' to import schema");if(B.newline(),(await g({type:"confirm",name:"addImport",message:"Add import to your entry point? (e.g., index.ts, main.ts)",initial:!0},{onCancel:h})).addImport){let I=["src/index.ts","src/main.ts","src/app.ts","index.ts","main.ts","app.ts"],E=null;for(let F of I){let L=f.join(process.cwd(),F);if(await T.access(L).then(()=>!0).catch(()=>!1)){E=F;break}}let P=(await g({type:"text",name:"entryPoint",message:"Entry point file:",initial:E||"src/index.ts"},{onCancel:h})).entryPoint;if(P){let F=f.join(process.cwd(),P),L=await T.access(F).then(()=>!0).catch(()=>!1),N=f.dirname(F),v=f.relative(N,G);if(!v.startsWith("."))v=`./${v}`;v=v.replace(/\\/g,"/");let C=`// Initialize database connection and configure ORM (must be first import)
11
- import "${v}/surreal";`;if(L){let S=await T.readFile(F,"utf-8");if(S.includes("/surreal"))B.warn("Entry point already imports surreal.ts, skipping");else{let b=`${C}
12
- ${S}`;await T.writeFile(F,b),B.success(`Added import to ${P}`)}}else{let S=`${C}
2
+ import{createRequire as B2}from"node:module";var $2=Object.create;var{getPrototypeOf:Q2,defineProperty:v0,getOwnPropertyNames:J2}=Object;var X2=Object.prototype.hasOwnProperty;var Z0=($,J,Q)=>{Q=$!=null?$2(Q2($)):{};let X=J||!$||!$.__esModule?v0(Q,"default",{value:$,enumerable:!0}):Q;for(let Z of J2($))if(!X2.call(X,Z))v0(X,Z,{get:()=>$[Z],enumerable:!0});return X};var Z2=($,J)=>{for(var Q in J)v0($,Q,{get:J[Q],enumerable:!0,configurable:!0,set:(X)=>J[Q]=()=>X})};var N0=($,J)=>()=>($&&(J=$($=0)),J);var B0=B2(import.meta.url);class Q1{lineCount=0;log($=""){console.log($),this.lineCount+=$.split(`
3
+ `).length}clear(){if(this.lineCount>0)process.stdout.moveCursor(0,-this.lineCount),process.stdout.clearScreenDown(),this.lineCount=0}reset(){this.lineCount=0}}var J1;var X1=N0(()=>{J1=new Q1});import r from"chalk";import Y2 from"ora";var J0,y,Y;var u=N0(()=>{X1();J0={success:"✅",error:"❌",warning:"⚠️",info:"ℹ️",step:"\uD83D\uDD39",arrow:"➜",line:"─",corner:"└─"},y={primary:r.hex("#FF00A0"),secondary:r.cyan,success:r.green,error:r.red,warning:r.yellow,info:r.blue,dim:r.gray,code:r.hex("#E0E0E0"),url:r.underline.cyan},Y={header($,J){if(console.log(""),console.log(y.primary.bold(` ${$} `)),J)console.log(y.dim(` ${J}`));console.log("")},divider(){console.log(y.dim(J0.line.repeat(60)))},success($){console.log(y.success(`${J0.success} ${$}`))},error($,J){if(console.log(y.error(`${J0.error} ${$}`)),J)if(J instanceof Error)console.log(y.dim(` ${J.stack||J.message}`));else console.log(y.dim(` ${String(J)}`))},warn($){console.log(y.warning(`${J0.warning} ${$}`))},info($){console.log(y.info(`${J0.info} ${$}`))},step($,J){console.log(y.secondary(`${J0.step} ${$}`)+(J?y.dim(` ${J}`):""))},spin($){return Y2({text:$,color:"cyan",spinner:"dots"}).start()},code($){return y.code($)},cmd($){return y.code(`$ ${$}`)},link($,J){return y.url(J||$)},dim($){return y.dim($)},bold($){return r.bold($)},newline(){console.log("")},get printer(){return J1},theme:y,symbols:J0}});var G1={};Z2(G1,{promptText:()=>E0,promptSelectWithDisabled:()=>k0,promptSelect:()=>S0,promptForConnection:()=>O0,promptFileReview:()=>U0,confirm:()=>z2});import Y0 from"prompts";async function O0($){let J=$.embedded,Q=await Y0([{type:!J&&!$.url?"text":null,name:"url",message:"Database URL:",initial:"http://localhost:8000"},{type:!J&&!$.username?"text":null,name:"username",message:"Username:",initial:"root"},{type:!J&&!$.password?"password":null,name:"password",message:"Password:"},{type:!J&&!$.authLevel?"select":null,name:"authLevel",message:"Auth level:",choices:[{title:"Root",value:"root"},{title:"Namespace",value:"namespace"},{title:"Database",value:"database"}],initial:0},{type:!$.namespace?"text":null,name:"namespace",message:"Namespace:"},{type:!$.database?"text":null,name:"database",message:"Database:"}],{onCancel:()=>{Y.newline(),Y.warn("Operation cancelled."),process.exit(0)}});if(J)return{embedded:J==="memory"?"memory":`file://${J}`,namespace:$.namespace||Q.namespace,database:$.database||Q.database};let X=$.url||Q.url,Z=$.username||Q.username,B=$.password||Q.password,_=$.authLevel||Q.authLevel||"root",G=$.namespace||Q.namespace,j=$.database||Q.database,U;if(_==="database")U={username:Z,password:B,namespace:G,database:j};else if(_==="namespace")U={username:Z,password:B,namespace:G};else U={username:Z,password:B};return{url:X,namespace:G,database:j,authentication:U}}async function z2($,J=!0){return(await Y0({type:"confirm",name:"value",message:$,initial:J},{onCancel:()=>{console.log(`
4
+ Operation cancelled.`),process.exit(0)}})).value}async function E0($,J){return(await Y0({type:"text",name:"value",message:$,initial:J},{onCancel:()=>{Y.newline(),Y.warn("Operation cancelled."),process.exit(0)}})).value||""}async function S0($,J){return(await Y0({type:"select",name:"value",message:$,choices:J},{onCancel:()=>{console.log(`
5
+ Operation cancelled.`),process.exit(0)}})).value}async function k0($,J){return(await Y0({type:"select",name:"value",message:$,choices:J.map((X)=>({title:X.title,value:X.value,disabled:X.disabled}))},{onCancel:()=>{console.log(`
6
+ Operation cancelled.`),process.exit(0)}})).value}async function U0($,J,Q){let Z=(await Y0({type:"text",name:"action",message:`[${J}/${Q}] Apply this change? (y)es / (n)o / (a)ccept all / (c)ancel`,validate:(B)=>{let _=B.toLowerCase().trim();if(["y","yes","n","no","a","all","c","cancel"].includes(_))return!0;return"Please enter: y/yes, n/no, a/all, or c/cancel"}},{onCancel:()=>{Y.newline(),Y.warn("Operation cancelled."),process.exit(0)}})).action.toLowerCase().trim();if(Z==="y"||Z==="yes")return"yes";if(Z==="n"||Z==="no")return"no";if(Z==="a"||Z==="all")return"all";if(Z==="c"||Z==="cancel")return"cancel";return"no"}var G0=N0(()=>{u()});import{Command as h4}from"@commander-js/extra-typings";u();import{Command as G2}from"@commander-js/extra-typings";import f from"prompts";import T from"node:fs/promises";import h from"node:path";import{execSync as Z1}from"node:child_process";var __dirname="E:\\GitHub\\unreal-orm\\packages\\unreal-cli\\src\\commands",m=()=>{Y.newline(),Y.warn("Operation cancelled."),process.exit(0)},Y1=new G2("init").description("Initialize UnrealORM in your project").option("--url <url>","SurrealDB URL").option("-u, --username <username>","Database username").option("-p, --password <password>","Database password").option("-n, --namespace <ns>","Namespace").option("-d, --database <db>","Database").option("-e, --embedded <mode>","Embedded mode (memory or file path)").option("--sample","Generate sample schema tables").option("--from-db","Import schema from existing database").option("--from-surql <file>","Import schema from .surql file").option("--install","Install dependencies automatically").option("--no-install","Skip dependency installation").option("--pm <manager>","Package manager (npm, yarn, pnpm, bun)").action(async($)=>{Y.header("\uD83D\uDE80 UnrealORM Setup","Initialize your project with UnrealORM");let J,Q;if($.url)Q="remote";else if($.embedded)Q=$.embedded==="memory"?"memory":"file";else Q=(await f({type:"select",name:"connectionMode",message:"How will you connect to SurrealDB?",choices:[{title:"Remote (URL)",value:"remote",description:"Connect via WebSocket/HTTP"},{title:"Embedded (Memory)",value:"memory",description:"In-memory, great for dev/testing"},{title:"Embedded (File)",value:"file",description:"Persist to local file"}]},{onCancel:m})).connectionMode;if(!Q)Y.error("Operation cancelled."),process.exit(1);if(Q==="remote"){let I=$.url||(await f({type:"text",name:"url",message:"SurrealDB URL:",initial:"ws://localhost:8000"},{onCancel:m})).url,O=$.username,w=$.password,P="root";if(!O||!w){let g=await f([{type:$.username?null:"select",name:"authLevel",message:"Authentication level:",choices:[{title:"Root",value:"root"},{title:"Namespace",value:"namespace"},{title:"Database",value:"database"}]},{type:$.username?null:"text",name:"username",message:"Username:",initial:"root"},{type:$.password?null:"password",name:"password",message:"Password:"}],{onCancel:m});O=$.username||g.username,w=$.password||g.password,P=g.authLevel||"root"}let{namespace:F,database:L}=$,N=[];if(!F&&(P!=="root"||!L))N.push({type:"text",name:"namespace",message:"Namespace:",initial:"test"});if(!L)N.push({type:"text",name:"database",message:"Database:",initial:"test"});if(N.length>0){let g=await f(N,{onCancel:m});F=F||g.namespace,L=L||g.database}let v,x=O||"",S=w||"";if(P==="database"&&F&&L)v={username:x,password:S,namespace:F,database:L};else if(P==="namespace"&&F)v={username:x,password:S,namespace:F};else v={username:x,password:S};J={url:I,authentication:v,namespace:F,database:L}}else if(Q==="memory"){let{namespace:I,database:O}=$;if(!I||!O){let w=await f([{type:I?null:"text",name:"namespace",message:"Namespace:",initial:"test"},{type:O?null:"text",name:"database",message:"Database:",initial:"test"}],{onCancel:m});I=I||w.namespace,O=O||w.database}J={embedded:"memory",namespace:I,database:O},Y.newline(),Y.warn("Note: Embedded mode requires @surrealdb/node package")}else{let I=$.embedded!=="surrealkv"?$.embedded:void 0,O=$.namespace,w=$.database;if(!I)I=(await f({type:"text",name:"path",message:"Database file path:",initial:"./data/local"},{onCancel:m})).path;if(!O||!w){let P=await f([{type:O?null:"text",name:"namespace",message:"Namespace:",initial:"test"},{type:w?null:"text",name:"database",message:"Database:",initial:"test"}],{onCancel:m});O=O||P.namespace,w=w||P.database}J={embedded:I?.startsWith("surrealkv://")?I:`surrealkv://${I}`,namespace:O,database:w},Y.newline(),Y.warn("Note: Embedded mode requires @surrealdb/node package"),Y.newline()}let Z=await T.access(h.join(process.cwd(),"src")).then(()=>!0).catch(()=>!1)?"./src/unreal":"./unreal",_=(await f({type:"text",name:"path",message:"Where should the unreal folder be created?",initial:Z},{onCancel:m})).path||Z,G=h.resolve(process.cwd(),_),j=h.join(G,"tables");await T.mkdir(j,{recursive:!0}),Y.success(`Created ${_}/ folder structure`);let U=j2(_);await T.writeFile(h.join(process.cwd(),"unreal.config.json"),JSON.stringify(U,null,"\t")),Y.success("Created unreal.config.json");let W=K2(Q);await T.writeFile(h.join(G,"surreal.ts"),W),Y.success(`Created ${_}/surreal.ts`);let V=U2(J,Q),q=h.join(process.cwd(),".env"),H=await T.access(q).then(()=>!0).catch(()=>!1);if(Y.newline(),H){if((await f({type:"confirm",name:"appendEnv",message:"Append SurrealDB config to existing .env file?",initial:!0},{onCancel:m})).appendEnv)if((await T.readFile(q,"utf-8")).includes("SURREAL_URL"))Y.warn(".env already contains SURREAL_* variables, skipping append");else await T.appendFile(q,`
7
+
8
+ ${V}
9
+ `),Y.success("Appended SurrealDB config to .env")}else if((await f({type:"confirm",name:"createEnv",message:"Create .env file with SurrealDB config?",initial:!0},{onCancel:m})).createEnv)await T.writeFile(q,`${V}
10
+ `),Y.success("Created .env file"),Y.info(" Remember to add .env to your .gitignore!");let K=_2(),z=["unreal-orm@latest","surrealdb@alpha"],M=["@unreal-orm/cli"];if(Q==="memory"||Q==="file")z.push("@surrealdb/node@alpha");let E=$.install;if(E===void 0){let I=[...z,...M.map((w)=>`${w} (dev)`)],{install:O}=await f({type:"confirm",name:"install",message:`Install dependencies? (${I.join(", ")})`,initial:!0},{onCancel:m});E=O}if(E){let I=$.pm??"";if(!I){let P=[{title:"npm",value:"npm"},{title:"yarn",value:"yarn"},{title:"pnpm",value:"pnpm"},{title:"bun",value:"bun"}],F=P.findIndex((N)=>N.value===K),{pm:L}=await f({type:"select",name:"pm",message:"Package manager:",choices:P,initial:F>=0?F:0},{onCancel:m});I=L??K}let O=B1(I,z,!1);Y.newline(),Y.info(`Running: ${O}...`);try{Z1(O,{stdio:"inherit"})}catch(P){Y.error("Failed to install dependencies")}let w=B1(I,M,!0);Y.info(`Running: ${w}...`);try{Z1(w,{stdio:"inherit"}),Y.success("Dependencies installed")}catch(P){Y.error("Failed to install dev dependencies")}}let A="none";if($.sample)A="sample";else if($.fromDb)A="from-db";else if($.fromSurql)A="from-surql";else A=(await f({type:"select",name:"action",message:"What would you like to do next?",choices:[{title:"Generate sample tables",value:"sample",description:"User, Post, Follow tables with indexes & relations"},{title:"Import from Database",value:"from-db",description:"Introspect existing DB"},{title:"Import from .surql file",value:"from-surql",description:"Parse SurrealQL file"},{title:"Nothing for now",value:"none"}]},{onCancel:m})).action;if(A==="sample"){let I=h.resolve(__dirname,"../../examples/simple"),O=["User.ts","Post.ts","Follow.ts"];for(let w of O){let P=await T.readFile(h.join(I,w),"utf-8");await T.writeFile(h.join(j,w),P)}Y.success("Generated sample tables:"),console.log(Y.dim(" • User.ts - Basic user table with indexes")),console.log(Y.dim(" • Post.ts - Posts with record links, arrays, and methods")),console.log(Y.dim(" • Follow.ts - Relation table (graph edge) example"))}else if(A==="from-db")Y.info("Run 'unreal pull' to import schema from database");else if(A==="from-surql")Y.info("Run 'unreal pull --file <path>' to import schema");if(Y.newline(),(await f({type:"confirm",name:"addImport",message:"Add import to your entry point? (e.g., index.ts, main.ts)",initial:!0},{onCancel:m})).addImport){let I=["src/index.ts","src/main.ts","src/app.ts","index.ts","main.ts","app.ts"],O=null;for(let F of I){let L=h.join(process.cwd(),F);if(await T.access(L).then(()=>!0).catch(()=>!1)){O=F;break}}let P=(await f({type:"text",name:"entryPoint",message:"Entry point file:",initial:O||"src/index.ts"},{onCancel:m})).entryPoint;if(P){let F=h.join(process.cwd(),P),L=await T.access(F).then(()=>!0).catch(()=>!1),N=h.dirname(F),v=h.relative(N,G);if(!v.startsWith("."))v=`./${v}`;v=v.replace(/\\/g,"/");let x=`// Initialize database connection and configure ORM (must be first import)
11
+ import "${v}/surreal";`;if(L){let S=await T.readFile(F,"utf-8");if(S.includes("/surreal"))Y.warn("Entry point already imports surreal.ts, skipping");else{let g=`${x}
12
+ ${S}`;await T.writeFile(F,g),Y.success(`Added import to ${P}`)}}else{let S=`${x}
13
13
 
14
14
  // Your app code here
15
15
  console.log("Hello from UnrealORM!");
16
- `;await T.mkdir(f.dirname(F),{recursive:!0}),await T.writeFile(F,S),B.success(`Created ${P} with import`)}}}B.header("UnrealORM setup complete!","You are ready to build!"),console.log(B.dim("Project structure:")),console.log(B.dim(" unreal.config.json - Path configuration")),console.log(B.dim(` ${_}/`)),console.log(B.dim(" surreal.ts - Database connection & ORM config")),console.log(B.dim(" tables/ - Table definitions")),B.newline(),console.log(B.dim("Quick start:")),console.log(B.dim(` 1. Import "${_}/surreal" in your entry point`)),console.log(B.dim(" 2. Define tables in tables/ directory")),console.log(B.dim(" 3. Use models: await User.select({ limit: 10 })")),B.newline(),console.log(B.dim("CLI commands:")),console.log(B.dim(" • unreal pull - Import schema from database")),console.log(B.dim(" • unreal push - Apply local schema to database")),console.log(B.dim(" • unreal diff - Compare schemas")),B.newline(),B.warn("⭐ If you find UnrealORM useful, please give us a star on GitHub!"),console.log(B.dim(` https://github.com/Jimpex/unreal-orm
17
- `))});function _2(){let $=process.env.npm_config_user_agent;if($?.startsWith("bun"))return"bun";if($?.startsWith("pnpm"))return"pnpm";if($?.startsWith("yarn"))return"yarn";return"npm"}function X1($,X,Q){let J=X.join(" "),Z=Q?" -D":"";switch($){case"bun":return`bun add${Z} ${J}`;case"pnpm":return`pnpm add${Z} ${J}`;case"yarn":return`yarn add${Z} ${J}`;default:return`npm install${Q?" --save-dev":""} ${J}`}}function j2($){return{$schema:"./node_modules/unreal-orm/schema.json",path:$}}function z2($,X){let Q=X==="memory"||X==="file",J=["# SurrealDB Connection (generated by UnrealORM)"];if(Q){let Z="embedded"in $?$.embedded:"mem://",Y=Z==="memory"?"mem://":Z;J.push(`SURREAL_URL=${Y}`),J.push(`SURREAL_NS=${$.namespace}`),J.push(`SURREAL_DB=${$.database}`)}else{let Z="url"in $?$.url:"ws://localhost:8000",Y="authentication"in $&&$.authentication&&typeof $.authentication==="object"?$.authentication:null,_=Y&&"username"in Y?Y.username:"",G=Y&&"password"in Y?Y.password:"";J.push(`SURREAL_URL=${Z}`),J.push(`SURREAL_NS=${$.namespace}`),J.push(`SURREAL_DB=${$.database}`),J.push(`SURREAL_USER=${_}`),J.push(`SURREAL_PASS=${G}`)}return J.join(`
18
- `)}function U2($){let X=$==="memory"||$==="file",Q=X?"Embedded":"Remote",J=X?"mem://, surrealkv://./data":"ws://localhost:8000",Z=["SURREAL_URL","SURREAL_NS","SURREAL_DB"];if(!X)Z.push("SURREAL_USER","SURREAL_PASS");let Y=X?`import { Unreal } from "unreal-orm";
16
+ `;await T.mkdir(h.dirname(F),{recursive:!0}),await T.writeFile(F,S),Y.success(`Created ${P} with import`)}}}Y.header("UnrealORM setup complete!","You are ready to build!"),console.log(Y.dim("Project structure:")),console.log(Y.dim(" unreal.config.json - Path configuration")),console.log(Y.dim(` ${_}/`)),console.log(Y.dim(" surreal.ts - Database connection & ORM config")),console.log(Y.dim(" tables/ - Table definitions")),Y.newline(),console.log(Y.dim("Quick start:")),console.log(Y.dim(` 1. Import "${_}/surreal" in your entry point`)),console.log(Y.dim(" 2. Define tables in tables/ directory")),console.log(Y.dim(" 3. Use models: await User.select({ limit: 10 })")),Y.newline(),console.log(Y.dim("CLI commands:")),console.log(Y.dim(" • unreal pull - Import schema from database")),console.log(Y.dim(" • unreal push - Apply local schema to database")),console.log(Y.dim(" • unreal diff - Compare schemas")),Y.newline(),Y.warn("⭐ If you find UnrealORM useful, please give us a star on GitHub!"),console.log(Y.dim(` https://github.com/Jimpex/unreal-orm
17
+ `))});function _2(){let $=process.env.npm_config_user_agent;if($?.startsWith("bun"))return"bun";if($?.startsWith("pnpm"))return"pnpm";if($?.startsWith("yarn"))return"yarn";return"npm"}function B1($,J,Q){let X=J.join(" "),Z=Q?" -D":"";switch($){case"bun":return`bun add${Z} ${X}`;case"pnpm":return`pnpm add${Z} ${X}`;case"yarn":return`yarn add${Z} ${X}`;default:return`npm install${Q?" --save-dev":""} ${X}`}}function j2($){return{$schema:"./node_modules/unreal-orm/schema.json",path:$}}function U2($,J){let Q=J==="memory"||J==="file",X=["# SurrealDB Connection (generated by UnrealORM)"];if(Q){let Z="embedded"in $?$.embedded:"mem://",B=Z==="memory"?"mem://":Z;X.push(`SURREAL_URL=${B}`),X.push(`SURREAL_NS=${$.namespace}`),X.push(`SURREAL_DB=${$.database}`)}else{let Z="url"in $?$.url:"ws://localhost:8000",B="authentication"in $&&$.authentication&&typeof $.authentication==="object"?$.authentication:null,_=B&&"username"in B?B.username:"",G=B&&"password"in B?B.password:"";X.push(`SURREAL_URL=${Z}`),X.push(`SURREAL_NS=${$.namespace}`),X.push(`SURREAL_DB=${$.database}`),X.push(`SURREAL_USER=${_}`),X.push(`SURREAL_PASS=${G}`)}return X.join(`
18
+ `)}function K2($){let J=$==="memory"||$==="file",Q=J?"Embedded":"Remote",X=J?"mem://, surrealkv://./data":"ws://localhost:8000",Z=["SURREAL_URL","SURREAL_NS","SURREAL_DB"];if(!J)Z.push("SURREAL_USER","SURREAL_PASS");let B=J?`import { Unreal } from "unreal-orm";
19
19
  import { createRemoteEngines, Surreal } from "surrealdb";
20
20
  import { createNodeEngines } from "@surrealdb/node";`:`import { Unreal } from "unreal-orm";
21
21
  import { Surreal } from "surrealdb";`,_=Z.map((q)=>`const ${q} = process.env.${q};`).join(`
22
- `),G=Z.join(" || !"),j=Z.join(", "),U=X?`db = new Surreal({
22
+ `),G=Z.join(" || !"),j=Z.join(", "),U=J?`db = new Surreal({
23
23
  engines: {
24
24
  ...createRemoteEngines(),
25
25
  ...createNodeEngines(),
26
26
  },
27
- });`:"db = new Surreal();",W=X?`{
27
+ });`:"db = new Surreal();",W=J?`{
28
28
  namespace: SURREAL_NS,
29
29
  database: SURREAL_DB,
30
30
  }`:`{
@@ -34,7 +34,7 @@ import { Surreal } from "surrealdb";`,_=Z.map((q)=>`const ${q} = process.env.${q
34
34
  username: SURREAL_USER,
35
35
  password: SURREAL_PASS,
36
36
  },
37
- }`,H=X?"SURREAL_URL!":"SURREAL_URL";return`/**
37
+ }`,V=J?"SURREAL_URL!":"SURREAL_URL";return`/**
38
38
  * SurrealDB Client Configuration (${Q} Mode)
39
39
  *
40
40
  * This file manages your database connection and configures the ORM.
@@ -65,14 +65,14 @@ import { Surreal } from "surrealdb";`,_=Z.map((q)=>`const ${q} = process.env.${q
65
65
  *
66
66
  * ## Required Environment Variables
67
67
  *
68
- ${Z.map((q)=>` * - \`${q}\`${q==="SURREAL_URL"?` - Connection URL (e.g., ${J})`:""}`).join(`
68
+ ${Z.map((q)=>` * - \`${q}\`${q==="SURREAL_URL"?` - Connection URL (e.g., ${X})`:""}`).join(`
69
69
  `)}
70
70
  *
71
71
  * Note: Bun, Vite, and Next.js auto-load .env files.
72
72
  * For Node.js, use \`dotenv\` or set variables manually.
73
73
  */
74
74
 
75
- ${Y}
75
+ ${B}
76
76
 
77
77
  // =============================================================================
78
78
  // Environment Configuration
@@ -124,7 +124,7 @@ export async function connect(): Promise<Surreal> {
124
124
 
125
125
  ${U}
126
126
 
127
- await db.connect(${H}, ${W});
127
+ await db.connect(${V}, ${W});
128
128
 
129
129
  return db;
130
130
  }
@@ -150,10 +150,10 @@ export async function close(): Promise<void> {
150
150
  // This enables implicit database usage in model methods:
151
151
  // await User.select({ limit: 10 }) // No need to pass db
152
152
  Unreal.configure({ getDatabase });
153
- `}import{Command as l2}from"@commander-js/extra-typings";import{existsSync as f0,mkdirSync as r2,writeFileSync as o2,readFileSync as s2,readdirSync as i2,unlinkSync as a2}from"node:fs";import{join as D1}from"node:path";import{Surreal as _1}from"surrealdb";import{existsSync as j1}from"node:fs";import{resolve as C0}from"node:path";m();import{existsSync as Y1,readFileSync as q2}from"node:fs";import{join as E0}from"node:path";import{createJiti as W2}from"jiti";var H2=W2(import.meta.url,{interopDefault:!0});async function T0($){return H2.import($)}async function r($=process.cwd()){let X=E0($,"unreal.config.json"),Q=E0($,"unreal.config.ts");if(Y1(X))try{let J=q2(X,"utf-8");return{path:JSON.parse(J).path||"./unreal"}}catch(J){console.warn("Warning: Found unreal.config.json but failed to load it:",J instanceof Error?J.message:String(J))}if(Y1(Q))try{return{path:(await T0(Q)).default.schema?.output?.replace("/tables","")||"./unreal"}}catch(J){console.warn("Warning: Found unreal.config.ts but failed to load it:",J instanceof Error?J.message:String(J))}return null}function A2($){return E0($.path||"./unreal","tables")}function M0($){return E0($.path||"./unreal","surreal.ts")}function G1(){B.error("No configuration found."),B.info("Please run 'unreal init' to create a configuration file first."),B.newline(),process.exit(1)}async function n($){let{cliOutput:X,config:Q,allowPrompt:J=!0}=$;if(X)return X;if(Q?.path)return B.dim("✓ Loaded configuration from unreal.config.json"),B.newline(),A2(Q);if(Q&&!Q.path)B.warn("Configuration found but 'path' is not set."),B.dim("Tip: Run 'unreal init' to set up your project properly"),B.newline();else if(!Q)B.dim("No configuration found."),B.dim("Tip: Run 'unreal init' to set up a project with saved settings"),B.newline();if(J){let{promptText:Z}=await Promise.resolve().then(() => (Y0(),B1));return await Z("Schema directory path:","./unreal/tables")||"./unreal/tables"}return"./unreal/tables"}Y0();m();async function o($){let{cliOptions:X,config:Q,allowPrompt:J=!0,exitOnFailure:Z=!0,skipAutoConfig:Y=!1}=$;if(X.url||X.username||X.password||X.namespace||X.database||X.authLevel||X.embedded){let G={url:X.url,username:X.username,password:X.password,namespace:X.namespace,database:X.database,authLevel:X.authLevel,embedded:X.embedded},j=await V0(G);return U1(j)}if(Q&&!Y){let G=C0(process.cwd(),M0(Q));if(j1(G))return z1(G)}if(J){let G=Q?j1(C0(process.cwd(),M0(Q))):!1,j=await k0("Connection method:",[{title:G?"Use config (surreal.ts)":"Use config (surreal.ts) - not found",value:"config",disabled:!G},{title:"Enter connection details manually",value:"manual"}]);if(!j)process.exit(0);if(j==="config"&&Q){let W=C0(process.cwd(),M0(Q));return z1(W)}let U=await V0({});return U1(U)}if(Z)G1();return null}async function z1($){let X=B.spin("Loading database client from surreal.ts...");try{try{(await import("dotenv")).config({quiet:!0})}catch{}let Q=await T0($),J;if(Q.getDatabase)J=await Q.getDatabase();else if(Q.connect)J=await Q.connect();else if(Q.default&&typeof Q.default==="object"&&"getDatabase"in Q.default){let Z=Q.default;if(Z.getDatabase)J=await Z.getDatabase()}else if(Q.default)J=Q.default;if(!J)X.fail("surreal.ts must export getDatabase() or connect()"),process.exit(1);return X.succeed("Connected using surreal.ts"),J}catch(Q){X.fail("Failed to load surreal.ts"),B.error(Q instanceof Error?Q.message:String(Q)),B.newline(),B.dim("Tip: You can also provide connection flags directly:"),B.dim(" unreal <command> --url ws://localhost:8000 -u root -p root -n test -d test"),B.newline(),process.exit(1)}}async function U1($){let X;if("embedded"in $)try{let{createNodeEngines:Q}=await import("@surrealdb/node"),J=$.embedded==="memory"?"mem://":$.embedded;X=new _1({engines:Q()}),await X.connect(J,$)}catch(Q){throw Error(`Failed to initialize embedded SurrealDB. Make sure @surrealdb/node is installed and your environment supports native bindings.
154
- Original Error: ${Q}`)}else X=new _1,await X.connect($.url,$);if($.namespace&&$.database)await X.use({namespace:$.namespace,database:$.database});return X}import{parseFieldDefinition as V2,parseIndexDefinition as O2,parseTableDefinition as E2}from"unreal-orm";function x0($,X){if(!$)throw Error(`${X}: No data returned`);return $}import y0 from"chalk";var D0=[];function i($,X,Q){D0.push({feature:$,reason:X,suggestion:Q})}function t($,X,Q){if($==="field"){if(Q.includes("TYPE object")&&Q.includes("{"))return i(`Field '${X}'`,"Object field with inline schema definition","Object fields are parsed as Field.object({}) - you may need to manually define the schema"),!1;if(Q.includes("TYPE geometry<")){let Z=Q.match(/geometry<(\w+)>/)?.[1];if(Z&&!["point","linestring","polygon","multipoint","multilinestring","multipolygon","collection","feature"].includes(Z.toLowerCase()))i(`Field '${X}'`,`Uncommon geometry type: ${Z}`,"Verify the generated Field.geometry() call is correct")}}if($==="index"){if(Q.includes("MTREE")||Q.includes("HNSW"))return i(`Index '${X}'`,"Vector index (MTREE/HNSW) detected","Vector indexes are not yet fully supported in code generation"),!1;if(Q.includes("SEARCH ANALYZER"))i(`Index '${X}'`,"Search analyzer index detected","Search indexes are parsed but may need manual configuration")}if($==="table"){if(Q.includes("CHANGEFEED"))i(`Table '${X}'`,"Changefeed configuration detected","Changefeeds are not yet supported in code generation")}if($==="event")return i(`Event '${X}'`,"Events/triggers are not yet supported","You'll need to manually create event definitions"),!1;if($==="analyzer")return i(`Analyzer '${X}'`,"Analyzers are not yet supported","Analyzer definitions will be skipped"),!1;if($==="function")return i(`Function '${X}'`,"Custom functions are not yet supported","Function definitions will be skipped"),!1;if($==="param")return i(`Parameter '${X}'`,"Database parameters are not yet supported","Parameter definitions will be skipped"),!1;return!0}function G0(){if(D0.length===0)return;console.log(y0.yellow(`
153
+ `}import{Command as r2}from"@commander-js/extra-typings";import{existsSync as m0,mkdirSync as o2,writeFileSync as s2,readFileSync as i2,readdirSync as a2,unlinkSync as n2}from"node:fs";import{join as D1}from"node:path";import{Surreal as U1}from"surrealdb";import{existsSync as K1}from"node:fs";import{resolve as C0}from"node:path";u();import{existsSync as _1,readFileSync as q2}from"node:fs";import{join as M0}from"node:path";import{createJiti as H2}from"jiti";var W2=H2(import.meta.url,{interopDefault:!0});async function T0($){return W2.import($)}async function o($=process.cwd()){let J=M0($,"unreal.config.json"),Q=M0($,"unreal.config.ts");if(_1(J))try{let X=q2(J,"utf-8");return{path:JSON.parse(X).path||"./unreal"}}catch(X){console.warn("Warning: Found unreal.config.json but failed to load it:",X instanceof Error?X.message:String(X))}if(_1(Q))try{return{path:(await T0(Q)).default.schema?.output?.replace("/tables","")||"./unreal"}}catch(X){console.warn("Warning: Found unreal.config.ts but failed to load it:",X instanceof Error?X.message:String(X))}return null}function A2($){return M0($.path||"./unreal","tables")}function D0($){return M0($.path||"./unreal","surreal.ts")}function j1(){Y.error("No configuration found."),Y.info("Please run 'unreal init' to create a configuration file first."),Y.newline(),process.exit(1)}async function n($){let{cliOutput:J,config:Q,allowPrompt:X=!0}=$;if(J)return J;if(Q?.path)return Y.dim("✓ Loaded configuration from unreal.config.json"),Y.newline(),A2(Q);if(Q&&!Q.path)Y.warn("Configuration found but 'path' is not set."),Y.dim("Tip: Run 'unreal init' to set up your project properly"),Y.newline();else if(!Q)Y.dim("No configuration found."),Y.dim("Tip: Run 'unreal init' to set up a project with saved settings"),Y.newline();if(X){let{promptText:Z}=await Promise.resolve().then(() => (G0(),G1));return await Z("Schema directory path:","./unreal/tables")||"./unreal/tables"}return"./unreal/tables"}G0();u();async function s($){let{cliOptions:J,config:Q,allowPrompt:X=!0,exitOnFailure:Z=!0,skipAutoConfig:B=!1}=$;if(J.url||J.username||J.password||J.namespace||J.database||J.authLevel||J.embedded){let G={url:J.url,username:J.username,password:J.password,namespace:J.namespace,database:J.database,authLevel:J.authLevel,embedded:J.embedded},j=await O0(G);return q1(j)}if(Q&&!B){let G=C0(process.cwd(),D0(Q));if(K1(G))return z1(G)}if(X){let G=Q?K1(C0(process.cwd(),D0(Q))):!1,j=await k0("Connection method:",[{title:G?"Use config (surreal.ts)":"Use config (surreal.ts) - not found",value:"config",disabled:!G},{title:"Enter connection details manually",value:"manual"}]);if(!j)process.exit(0);if(j==="config"&&Q){let W=C0(process.cwd(),D0(Q));return z1(W)}let U=await O0({});return q1(U)}if(Z)j1();return null}async function z1($){let J=Y.spin("Loading database client from surreal.ts...");try{try{(await import("dotenv")).config({quiet:!0})}catch{}let Q=await T0($),X;if(Q.getDatabase)X=await Q.getDatabase();else if(Q.connect)X=await Q.connect();else if(Q.default&&typeof Q.default==="object"&&"getDatabase"in Q.default){let Z=Q.default;if(Z.getDatabase)X=await Z.getDatabase()}else if(Q.default)X=Q.default;if(!X)J.fail("surreal.ts must export getDatabase() or connect()"),process.exit(1);return J.succeed("Connected using surreal.ts"),X}catch(Q){J.fail("Failed to load surreal.ts"),Y.error(Q instanceof Error?Q.message:String(Q)),Y.newline(),Y.dim("Tip: You can also provide connection flags directly:"),Y.dim(" unreal <command> --url ws://localhost:8000 -u root -p root -n test -d test"),Y.newline(),process.exit(1)}}async function q1($){let J;if("embedded"in $)try{let{createNodeEngines:Q}=await import("@surrealdb/node"),X=$.embedded==="memory"?"mem://":$.embedded;J=new U1({engines:Q()}),await J.connect(X,$)}catch(Q){throw Error(`Failed to initialize embedded SurrealDB. Make sure @surrealdb/node is installed and your environment supports native bindings.
154
+ Original Error: ${Q}`)}else J=new U1,await J.connect($.url,$);if($.namespace&&$.database)await J.use({namespace:$.namespace,database:$.database});return J}import{parseFieldDefinition as V2,parseIndexDefinition as O2,parseTableDefinition as E2}from"unreal-orm";function x0($,J){if(!$)throw Error(`${J}: No data returned`);return $}import y0 from"chalk";var R0=[];function C($,J,Q){R0.push({feature:$,reason:J,suggestion:Q})}function t($,J,Q){if($==="field"){if(Q.includes("TYPE object")&&Q.includes("{"))return C(`Field '${J}'`,"Object field with inline schema definition","Object fields are parsed as Field.object({}) - you may need to manually define the schema"),!1;if(Q.includes("TYPE geometry<")){let Z=Q.match(/geometry<(\w+)>/)?.[1];if(Z&&!["point","linestring","polygon","multipoint","multilinestring","multipolygon","collection","feature"].includes(Z.toLowerCase()))C(`Field '${J}'`,`Uncommon geometry type: ${Z}`,"Verify the generated Field.geometry() call is correct")}}if($==="index"){if(Q.includes("MTREE")||Q.includes("HNSW"))return C(`Index '${J}'`,"Vector index (MTREE/HNSW) detected","Vector indexes are not yet fully supported in code generation"),!1;if(Q.includes("SEARCH ANALYZER"))C(`Index '${J}'`,"Search analyzer index detected","Search indexes are parsed but may need manual configuration")}if($==="table"){if(Q.includes("CHANGEFEED"))C(`Table '${J}'`,"Changefeed configuration detected","Changefeeds are not yet supported in code generation")}if($==="event")return C(`Event '${J}'`,"Events/triggers are not yet supported","You'll need to manually create event definitions"),!1;if($==="analyzer")return C(`Analyzer '${J}'`,"Analyzers are not yet supported","Analyzer definitions will be skipped"),!1;if($==="function")return C(`Function '${J}'`,"Custom functions are not yet supported","Function definitions will be skipped"),!1;if($==="param")return C(`Parameter '${J}'`,"Database parameters are not yet supported","Parameter definitions will be skipped"),!1;return!0}function e(){if(R0.length===0)return;console.log(y0.yellow(`
155
155
  ⚠️ Warnings:
156
- `));for(let $ of D0)if(console.log(y0.yellow(` • ${$.feature}: ${$.reason}`)),$.suggestion)console.log(y0.dim(` → ${$.suggestion}`));console.log()}function R0(){D0.length=0}async function e($){let[X]=await $.query("INFO FOR DB").collect(),Q=x0(X,"Failed to get DB info"),J=Q.tables||{};if(Q.analyzers&&Object.keys(Q.analyzers).length>0)for(let Y of Object.keys(Q.analyzers))t("analyzer",Y,Q.analyzers[Y]||"");if(Q.functions&&Object.keys(Q.functions).length>0)for(let Y of Object.keys(Q.functions))t("function",Y,Q.functions[Y]||"");if(Q.params&&Object.keys(Q.params).length>0)for(let Y of Object.keys(Q.params))t("param",Y,Q.params[Y]||"");let Z=[];for(let Y of Object.keys(J)){let _;try{let[A]=await $.query(`INFO FOR TABLE ${Y}`).collect();_=x0(A,`Failed to get info for table ${Y}`)}catch(A){console.warn(`Failed to get info for table ${Y}:`,A instanceof Error?A.message:String(A));continue}let G=J[Y];if(!G){console.warn(`No DDL found for table ${Y}`);continue}t("table",Y,G);let j=E2(G),U=[],W=_.fields||{};for(let A of Object.keys(W)){let D=W[A];if(D){t("field",A,D);try{U.push(V2(D))}catch(O){console.warn(`Failed to parse field ${A} on table ${Y}`,O)}}}let H=[],q=_.indexes||{};for(let A of Object.keys(q)){let D=q[A];if(D){if(t("index",A,D))try{H.push(O2(D))}catch(V){console.warn(`Failed to parse index ${A} on table ${Y}`,V)}}}let z=[],K=_.events||{};for(let A of Object.keys(K)){let D=K[A];if(D)t("event",A,D)}if(j.name&&j.type)Z.push({name:j.name,type:j.type,drop:j.drop||!1,schemafull:j.schemafull||!1,viewQuery:j.viewQuery,permissions:j.permissions||{},fields:U,indexes:H,events:z})}return{tables:Z}}Y0();import{compareSchemas as C2}from"unreal-orm";function I0($){let X=new Map;for(let Q of $.tables){let J=D2(Q);X.set(`${U0(Q.name)}.ts`,J)}return X}function M2($,X,Q){let J=$.matchAll(/record<(\w+)>/g);for(let Z of J){let Y=Z[1];if(Y&&Y!==X)Q.add(`import { ${U0(Y)} } from './${U0(Y)}';`)}}function D2($){let X=new Set;X.add("import { Table, Field, Index } from 'unreal-orm';"),X.add("import { surql } from 'surrealdb';");for(let Y of $.fields)M2(Y.type,$.name,X);let Q=U0($.name),J=[],Z=`${Array.from(X).join(`
156
+ `));for(let $ of R0)if(console.log(y0.yellow(` • ${$.feature}: ${$.reason}`)),$.suggestion)console.log(y0.dim(` → ${$.suggestion}`));console.log()}function _0(){R0.length=0}async function $0($){let[J]=await $.query("INFO FOR DB").collect(),Q=x0(J,"Failed to get DB info"),X=Q.tables||{};if(Q.analyzers&&Object.keys(Q.analyzers).length>0)for(let B of Object.keys(Q.analyzers))t("analyzer",B,Q.analyzers[B]||"");if(Q.functions&&Object.keys(Q.functions).length>0)for(let B of Object.keys(Q.functions))t("function",B,Q.functions[B]||"");if(Q.params&&Object.keys(Q.params).length>0)for(let B of Object.keys(Q.params))t("param",B,Q.params[B]||"");let Z=[];for(let B of Object.keys(X)){let _;try{let[z]=await $.query(`INFO FOR TABLE ${B}`).collect();_=x0(z,`Failed to get info for table ${B}`)}catch(z){console.warn(`Failed to get info for table ${B}:`,z instanceof Error?z.message:String(z));continue}let G=X[B];if(!G){console.warn(`No DDL found for table ${B}`);continue}t("table",B,G);let j=E2(G),U=[],W=_.fields||{};for(let z of Object.keys(W)){let M=W[z];if(M){t("field",z,M);try{U.push(V2(M))}catch(E){console.warn(`Failed to parse field ${z} on table ${B}`,E)}}}let V=[],q=_.indexes||{};for(let z of Object.keys(q)){let M=q[z];if(M){if(t("index",z,M))try{V.push(O2(M))}catch(A){console.warn(`Failed to parse index ${z} on table ${B}`,A)}}}let H=[],K=_.events||{};for(let z of Object.keys(K)){let M=K[z];if(M)t("event",z,M)}if(j.name&&j.type)Z.push({name:j.name,type:j.type,drop:j.drop||!1,schemafull:j.schemafull||!1,viewQuery:j.viewQuery,permissions:j.permissions||{},fields:U,indexes:V,events:H})}return{tables:Z}}G0();import{compareSchemas as x2}from"unreal-orm";function I0($){let J=new Map;for(let Q of $.tables){let X=D2(Q);J.set(`${z0(Q.name)}.ts`,X)}return J}function M2($,J,Q){let X=$.matchAll(/record<(\w+)>/g);for(let Z of X){let B=Z[1];if(B&&B!==J)Q.add(`import { ${z0(B)} } from './${z0(B)}';`)}}function D2($){let J=new Set;J.add("import { Table, Field, Index } from 'unreal-orm';"),J.add("import { surql } from 'surrealdb';");for(let B of $.fields)M2(B.type,$.name,J);let Q=z0($.name),X=[],Z=`${Array.from(J).join(`
157
157
  `)}
158
158
 
159
159
  `;if($.type==="VIEW"){if(Z+=`export class ${Q} extends Table.view({
@@ -164,73 +164,75 @@ Original Error: ${Q}`)}else X=new _1,await X.connect($.url,$);if($.namespace&&$.
164
164
  `,Z+=` name: "${$.name}",
165
165
  `,$.schemafull)Z+=` schemafull: true,
166
166
  `;Z+=` fields: {
167
- `,Z+=K1($.fields," "),Z+=` },
167
+ `,Z+=H1($.fields," "),Z+=` },
168
168
  `,Z+=`}) {}
169
169
  `}else{if(Z+=`export class ${Q} extends Table.normal({
170
170
  `,Z+=` name: "${$.name}",
171
171
  `,$.schemafull)Z+=` schemafull: true,
172
172
  `;Z+=` fields: {
173
- `,Z+=K1($.fields," "),Z+=` },
173
+ `,Z+=H1($.fields," "),Z+=` },
174
174
  `,Z+=`}) {}
175
175
  `}if($.indexes.length>0){Z+=`
176
- `;for(let Y of $.indexes){let G=(Y.name.includes($.name)?Y.name:`${$.name}_${Y.name}`).replace(/[^a-zA-Z0-9_]/g,"_");Z+=P2(Y,Q,G),J.push(G)}}return Z+=`
177
- export const ${Q}Definitions = [${Q}${J.length>0?`, ${J.join(", ")}`:""}];
178
- `,Z}function R2($){let X={children:new Map};for(let Q of $){let J=Q.name.split("."),Z=X;for(let Y of J)if(!Z.children.has(Y)){let _={children:new Map};Z.children.set(Y,_),Z=_}else Z=Z.children.get(Y);Z.field=Q}return X}function K1($,X){let Q=$.filter((Z)=>!Z.name.endsWith(".*")),J=R2(Q);return q1(J,X)}function q1($,X){let Q="";for(let[J,Z]of $.children)if(Z.children.size>0){let Y=Z.field?W1(Z.field):"";Q+=`${X}${J}: Field.object({
179
- `,Q+=q1(Z,`${X} `),Q+=`${X}}${Y?`, ${Y}`:""}),
180
- `}else if(Z.field)Q+=`${X}${J}: ${I2(Z.field)},
181
- `;return Q}function W1($){let X=[];if($.default)X.push(`default: surql\`${$.default}\``);if($.value)X.push(`value: surql\`${$.value}\``);if($.assert)X.push(`assert: surql\`${$.assert}\``);return X.length>0?`{ ${X.join(", ")} }`:""}function I2($){let X=W1($),Q=$.type;if(Q.startsWith("option<")){let J=Q.match(/option<(.+)>/)?.[1];if(J)return`Field.option(${z0(J,X||"")})`}if(Q.includes(" | ")){let J=Q.split(" | ").map((Z)=>Z.trim());if(J.includes("none")){let Z=J.filter((Y)=>Y!=="none");if(Z.length===1&&Z[0])return`Field.option(${z0(Z[0],X||"")})`}return`Field.custom('${Q}'${X?`, ${X}`:""}) /* TODO: Specify union type */`}return z0(Q,X||"")}function z0($,X){let Q=X?X:"";if($==="string")return`Field.string(${Q})`;if($==="int")return`Field.int(${Q})`;if($==="float")return`Field.float(${Q})`;if($==="number")return`Field.number(${Q})`;if($==="bool")return`Field.bool(${Q})`;if($==="datetime")return`Field.datetime(${Q})`;if($==="duration")return`Field.duration(${Q})`;if($==="decimal")return`Field.decimal(${Q})`;if($==="uuid")return`Field.uuid(${Q})`;if($==="bytes")return`Field.bytes(${Q})`;if($==="any")return`Field.any(${Q})`;if($.startsWith("array<")){let J=$.slice(6,-1);return`Field.array(${z0(J,"")}${Q?`, ${Q}`:""})`}if($.startsWith("set<")){let J=$.slice(4,-1);return`Field.set(${z0(J,"")}${Q?`, ${Q}`:""})`}if($.startsWith("record<")){let J=$.match(/record<(\w+)>/);if(J?.[1]){let Z=J[1];return`Field.record(() => ${U0(Z)}${Q?`, ${Q}`:""})`}return`Field.record(() => Object${Q?`, ${Q}`:""})`}if($.startsWith("geometry<")){let J=$.match(/geometry<(\w+)>/);if(J?.[1])return`Field.geometry('${J[1]}'${Q?`, ${Q}`:""})`}if($==="geometry")return`Field.geometry('feature'${Q?`, ${Q}`:""})`;if($==="object")return`Field.object({} /* Schema not inferred */${Q?`, ${Q}`:""})`;return`Field.custom('${$}'${Q?`, ${Q}`:""}) /* TODO: Specify type, e.g., Field.custom<YourType>(...) */`}function P2($,X,Q){let J=`export const ${Q} = Index.define(() => ${X}, {
182
- `;if(J+=` name: "${$.name}",
183
- `,J+=` fields: [${$.columns.map((Z)=>`"${Z}"`).join(", ")}],
184
- `,$.unique)J+=` unique: true,
185
- `;return J+=`});
186
- `,J}function U0($){return $.split("_").map((X)=>X.charAt(0).toUpperCase()+X.slice(1)).join("")}import{compareSchemas as F2}from"unreal-orm";function H1($,X,Q){let J=w2(X,Q);if(J.length===0)return{content:$,addedFields:[],addedIndexes:[],removedFields:[],removedIndexes:[]};let Z=$,Y=[],_=[],G=[],j=[],U=J.filter((z)=>z.type==="field_added");for(let z of U){if(!z.field)continue;let K=X.fields.find((D)=>D.name===z.field);if(!K)continue;if(K.name.includes("."))continue;if(K.name.includes("[*]"))continue;let A=L2(K);Z=v2(Z,K.name,A),Y.push(K.name)}let W=J.filter((z)=>z.type==="index_added");for(let z of W){if(!z.index)continue;let K=X.indexes.find((O)=>O.name===z.index);if(!K)continue;let A=A1(X.name),D=S2(K,A);Z=N2(Z,K.name,D,A),_.push(K.name)}let H=J.filter((z)=>z.type==="field_removed");for(let z of H){if(!z.field)continue;if(z.field.includes("."))continue;if(z.field.includes("[*]"))continue;Z=k2(Z,z.field),G.push(z.field)}let q=J.filter((z)=>z.type==="index_removed");for(let z of q){if(!z.index)continue;Z=T2(Z,z.index),j.push(z.index)}return{content:Z,addedFields:Y,addedIndexes:_,removedFields:G,removedIndexes:j}}function w2($,X){return F2({tables:[$]},{tables:[X]})}function L2($){let X=[];if($.default)X.push(`default: surql\`${$.default}\``);if($.value)X.push(`value: surql\`${$.value}\``);if($.assert)X.push(`assert: surql\`${$.assert}\``);let Q=X.length>0?`{ ${X.join(", ")} }`:"";return K0($.type,Q)}function K0($,X){let Q=X||"";if($.startsWith("option<")){let J=$.match(/option<(.+)>/)?.[1];if(J)return`Field.option(${K0(J,"")})${Q?`, ${Q}`:""}`}if($.includes(" | ")){let J=$.split(" | ").map((Z)=>Z.trim());if(J.includes("none")){let Z=J.filter((Y)=>Y!=="none");if(Z.length===1&&Z[0])return`Field.option(${K0(Z[0],"")})${Q?`, ${Q}`:""}`}}if($==="string")return`Field.string(${Q})`;if($==="int")return`Field.int(${Q})`;if($==="float")return`Field.float(${Q})`;if($==="number")return`Field.number(${Q})`;if($==="bool")return`Field.bool(${Q})`;if($==="datetime")return`Field.datetime(${Q})`;if($==="duration")return`Field.duration(${Q})`;if($==="decimal")return`Field.decimal(${Q})`;if($==="uuid")return`Field.uuid(${Q})`;if($==="bytes")return`Field.bytes(${Q})`;if($==="any")return`Field.any(${Q})`;if($.startsWith("array<")){let J=$.slice(6,-1);return`Field.array(${K0(J,"")}${Q?`, ${Q}`:""})`}if($.startsWith("set<")){let J=$.slice(4,-1);return`Field.set(${K0(J,"")}${Q?`, ${Q}`:""})`}if($.startsWith("record<")){let J=$.match(/record<(\w+)>/);if(J?.[1]){let Z=J[1];return`Field.record(() => ${A1(Z)}${Q?`, ${Q}`:""})`}}return`Field.custom('${$}'${Q?`, ${Q}`:""})`}function v2($,X,Q){let J=$.match(/fields:\s*\{/);if(!J||J.index===void 0)return $;let Z=J.index+J[0].length,Y=1,_=Z;for(let A=Z;A<$.length&&Y>0;A++){if($[A]==="{")Y++;if($[A]==="}")Y--;if(Y===0){_=A;break}}let G=$.slice(Z,_),j=G.match(/\n(\s+)\w+:/),U=j?j[1]:" ",W=G.trim(),H=W.length>0&&!W.endsWith(","),q=$,z=_;if(H){let A=G.match(/\S\s*$/);if(A&&A.index!==void 0){let D=Z+A.index+1;q=`${$.slice(0,D)},${$.slice(D)}`,z++}}let K=`
176
+ `;for(let B of $.indexes){let G=(B.name.includes($.name)?B.name:`${$.name}_${B.name}`).replace(/[^a-zA-Z0-9_]/g,"_");Z+=F2(B,Q,G),X.push(G)}}return Z+=`
177
+ export const ${Q}Definitions = [${Q}${X.length>0?`, ${X.join(", ")}`:""}];
178
+ `,Z}function R2($){let J=[],Q="";for(let X=0;X<$.length;X++){let Z=$[X];if(Z==="."){if(Q)J.push(Q);Q=""}else if(Z==="["&&$.slice(X,X+3)==="[*]"){if(Q)J.push(Q);J.push("[*]"),Q="",X+=2}else Q+=Z}if(Q)J.push(Q);return J}function I2($){let J=$.filter((X)=>!X.name.endsWith(".*")),Q={children:new Map};for(let X of J){let Z=R2(X.name),B=Q;for(let _=0;_<Z.length;_++){let G=Z[_];if(G==="[*]"){if(!B.arrayElement)B.arrayElement={children:new Map};B=B.arrayElement}else if(G){if(!B.children.has(G))B.children.set(G,{children:new Map});B=B.children.get(G)}}B.field=X}return Q}function H1($,J){let Q=I2($);return b0(Q,J)}function b0($,J){let Q="";for(let[X,Z]of $.children)if(Z.arrayElement&&Z.arrayElement.children.size>0){let B=Z.field?g0(Z.field):"";Q+=`${J}${X}: Field.array(Field.object({
179
+ `,Q+=b0(Z.arrayElement,`${J} `),Q+=`${J}})${B?`, ${B}`:""}),
180
+ `}else if(Z.children.size>0){let B=Z.field?g0(Z.field):"";Q+=`${J}${X}: Field.object({
181
+ `,Q+=b0(Z,`${J} `),Q+=`${J}}${B?`, ${B}`:""}),
182
+ `}else if(Z.field)Q+=`${J}${X}: ${P2(Z.field)},
183
+ `;return Q}function g0($){let J=[];if($.default)J.push(`default: surql\`${$.default}\``);if($.value)J.push(`value: surql\`${$.value}\``);if($.assert)J.push(`assert: surql\`${$.assert}\``);if($.readonly)J.push("readonly: true");return J.length>0?`{ ${J.join(", ")} }`:""}function P2($){let J=g0($),Q=$.type;if(Q.startsWith("option<")){let X=Q.match(/option<(.+)>/)?.[1];if(X)return`Field.option(${K0(X,J||"")})`}if(Q.includes(" | ")){let X=Q.split(" | ").map((B)=>B.trim());if(X.includes("none")){let B=X.filter((_)=>_!=="none");if(B.length===1&&B[0])return`Field.option(${K0(B[0],J||"")})`}return`Field.custom('${Q.replace(/'/g,"\\'")}'${J?`, ${J}`:""}) /* TODO: Specify union type */`}return K0(Q,J||"")}function K0($,J){let Q=J?J:"";if($==="string")return`Field.string(${Q})`;if($==="int")return`Field.int(${Q})`;if($==="float")return`Field.float(${Q})`;if($==="number")return`Field.number(${Q})`;if($==="bool")return`Field.bool(${Q})`;if($==="datetime")return`Field.datetime(${Q})`;if($==="duration")return`Field.duration(${Q})`;if($==="decimal")return`Field.decimal(${Q})`;if($==="uuid")return`Field.uuid(${Q})`;if($==="bytes")return`Field.bytes(${Q})`;if($==="any")return`Field.any(${Q})`;if($.startsWith("array<")){let X=$.slice(6,-1);return`Field.array(${K0(X,"")}${Q?`, ${Q}`:""})`}if($.startsWith("set<")){let X=$.slice(4,-1);return`Field.set(${K0(X,"")}${Q?`, ${Q}`:""})`}if($.startsWith("record<")){let X=$.match(/record<(\w+)>/);if(X?.[1]){let Z=X[1];return`Field.record(() => ${z0(Z)}${Q?`, ${Q}`:""})`}return`Field.record(() => Object${Q?`, ${Q}`:""})`}if($.startsWith("geometry<")){let X=$.match(/geometry<(\w+)>/);if(X?.[1])return`Field.geometry('${X[1]}'${Q?`, ${Q}`:""})`}if($==="geometry")return`Field.geometry('feature'${Q?`, ${Q}`:""})`;if($==="object")return`Field.object({}${Q?`, ${Q}`:""})`;return`Field.custom('${$}'${Q?`, ${Q}`:""}) /* TODO: Specify type, e.g., Field.custom<YourType>(...) */`}function F2($,J,Q){let X=`export const ${Q} = Index.define(() => ${J}, {
184
+ `;if(X+=` name: "${$.name}",
185
+ `,X+=` fields: [${$.columns.map((Z)=>`"${Z}"`).join(", ")}],
186
+ `,$.unique)X+=` unique: true,
187
+ `;return X+=`});
188
+ `,X}function z0($){return $.split("_").map((J)=>J.charAt(0).toUpperCase()+J.slice(1)).join("")}import{compareSchemas as w2}from"unreal-orm";function W1($,J,Q){let X=L2(J,Q);if(X.length===0)return{content:$,addedFields:[],addedIndexes:[],removedFields:[],removedIndexes:[]};let Z=$,B=[],_=[],G=[],j=[],U=X.filter((H)=>H.type==="field_added");for(let H of U){if(!H.field)continue;let K=J.fields.find((M)=>M.name===H.field);if(!K)continue;if(K.name.includes("."))continue;if(K.name.includes("[*]"))continue;let z=v2(K);Z=N2(Z,K.name,z),B.push(K.name)}let W=X.filter((H)=>H.type==="index_added");for(let H of W){if(!H.index)continue;let K=J.indexes.find((E)=>E.name===H.index);if(!K)continue;let z=A1(J.name),M=k2(K,z);Z=S2(Z,K.name,M,z),_.push(K.name)}let V=X.filter((H)=>H.type==="field_removed");for(let H of V){if(!H.field)continue;if(H.field.includes("."))continue;if(H.field.includes("[*]"))continue;Z=T2(Z,H.field),G.push(H.field)}let q=X.filter((H)=>H.type==="index_removed");for(let H of q){if(!H.index)continue;Z=C2(Z,H.index),j.push(H.index)}return{content:Z,addedFields:B,addedIndexes:_,removedFields:G,removedIndexes:j}}function L2($,J){return w2({tables:[$]},{tables:[J]})}function v2($){let J=[];if($.default)J.push(`default: surql\`${$.default}\``);if($.value)J.push(`value: surql\`${$.value}\``);if($.assert)J.push(`assert: surql\`${$.assert}\``);let Q=J.length>0?`{ ${J.join(", ")} }`:"";return q0($.type,Q)}function q0($,J){let Q=J||"";if($.startsWith("option<")){let X=$.match(/option<(.+)>/)?.[1];if(X)return`Field.option(${q0(X,"")})${Q?`, ${Q}`:""}`}if($.includes(" | ")){let X=$.split(" | ").map((Z)=>Z.trim());if(X.includes("none")){let Z=X.filter((B)=>B!=="none");if(Z.length===1&&Z[0])return`Field.option(${q0(Z[0],"")})${Q?`, ${Q}`:""}`}}if($==="string")return`Field.string(${Q})`;if($==="int")return`Field.int(${Q})`;if($==="float")return`Field.float(${Q})`;if($==="number")return`Field.number(${Q})`;if($==="bool")return`Field.bool(${Q})`;if($==="datetime")return`Field.datetime(${Q})`;if($==="duration")return`Field.duration(${Q})`;if($==="decimal")return`Field.decimal(${Q})`;if($==="uuid")return`Field.uuid(${Q})`;if($==="bytes")return`Field.bytes(${Q})`;if($==="any")return`Field.any(${Q})`;if($.startsWith("array<")){let X=$.slice(6,-1);return`Field.array(${q0(X,"")}${Q?`, ${Q}`:""})`}if($.startsWith("set<")){let X=$.slice(4,-1);return`Field.set(${q0(X,"")}${Q?`, ${Q}`:""})`}if($.startsWith("record<")){let X=$.match(/record<(\w+)>/);if(X?.[1]){let Z=X[1];return`Field.record(() => ${A1(Z)}${Q?`, ${Q}`:""})`}}return`Field.custom('${$}'${Q?`, ${Q}`:""})`}function N2($,J,Q){let X=$.match(/fields:\s*\{/);if(!X||X.index===void 0)return $;let Z=X.index+X[0].length,B=1,_=Z;for(let z=Z;z<$.length&&B>0;z++){if($[z]==="{")B++;if($[z]==="}")B--;if(B===0){_=z;break}}let G=$.slice(Z,_),j=G.match(/\n(\s+)\w+:/),U=j?j[1]:" ",W=G.trim(),V=W.length>0&&!W.endsWith(","),q=$,H=_;if(V){let z=G.match(/\S\s*$/);if(z&&z.index!==void 0){let M=Z+z.index+1;q=`${$.slice(0,M)},${$.slice(M)}`,H++}}let K=`
187
189
  ${U}// Added from database
188
- ${U}${X}: ${Q},`;return`${q.slice(0,z)}${K}
189
- ${q.slice(z)}`}function N2($,X,Q,J){let Z=$.match(new RegExp(`export const ${J}Definitions\\s*=`));if(Z&&Z.index!==void 0){let Y=Z.index,_=`// Added from database
190
+ ${U}${J}: ${Q},`;return`${q.slice(0,H)}${K}
191
+ ${q.slice(H)}`}function S2($,J,Q,X){let Z=$.match(new RegExp(`export const ${X}Definitions\\s*=`));if(Z&&Z.index!==void 0){let B=Z.index,_=`// Added from database
190
192
  ${Q}
191
- `,G=$.slice(0,Y)+_+$.slice(Y),j=X.replace(/[^a-zA-Z0-9_]/g,"_");return G=G.replace(new RegExp(`(export const ${J}Definitions\\s*=\\s*\\[${J})([,\\s\\w]*)(\\])`),`$1$2, ${j}$3`),G}return`${$}
193
+ `,G=$.slice(0,B)+_+$.slice(B),j=J.replace(/[^a-zA-Z0-9_]/g,"_");return G=G.replace(new RegExp(`(export const ${X}Definitions\\s*=\\s*\\[${X})([,\\s\\w]*)(\\])`),`$1$2, ${j}$3`),G}return`${$}
192
194
  // Added from database
193
- ${Q}`}function S2($,X){let J=`export const ${$.name.replace(/[^a-zA-Z0-9_]/g,"_")} = Index.define(() => ${X}, {
194
- `;if(J+=` name: "${$.name}",
195
- `,J+=` fields: [${$.columns.map((Z)=>`"${Z}"`).join(", ")}],
196
- `,$.unique)J+=` unique: true,
197
- `;return J+=`});
198
- `,J}function k2($,X){let Q=new RegExp(`([ \\t]*)(${b0(X)}\\s*:\\s*(?:Field\\.|\\{))`),J=$.match(Q);if(!J||J.index===void 0)return $;let Z=J[1]??"",Y=J.index+Z.length,_=0,G=0,j=0,U=Y,W=!1,H="",q=!1;for(let O=Y;O<$.length;O++){let V=$[O],R=O>0?$[O-1]:"";if((V==='"'||V==="'"||V==="`")&&R!=="\\"){if(!W&&!q)if(V==="`")q=!0;else W=!0,H=V;else if(q&&V==="`")q=!1;else if(W&&V===H)W=!1;continue}if(W||q)continue;if(V==="(")_++;if(V===")")_--;if(V==="{")G++;if(V==="}")G--;if(V==="[")j++;if(V==="]")j--;if(_===0&&j===0){if(G===0&&V===","){U=O+1;break}if(G===-1&&V==="}"){U=O;while(U>Y&&/\s/.test($[U-1]||""))U--;break}}}let A=$.slice(Y,U).split(`
199
- `).map((O,V)=>{if(V===0)return`${Z}// ${O}`;let I=O.match(/^(\s*)/)?.[1]??"",E=O.slice(I.length);return`${I}// ${E}`}).join(`
200
- `),D=`${Z}// Removed from database - uncomment if needed
201
- `;return $.slice(0,Y)+D+A+$.slice(U)}function T2($,X){let Q=X.replace(/[^a-zA-Z0-9_]/g,"_"),J=new RegExp(`export\\s+const\\s+${b0(Q)}\\s*=\\s*Index\\.define`),Z=$.match(J);if(!Z||Z.index===void 0)return $;let Y=Z.index,_=0,G=0,j=Y,U=!1;for(let D=Y;D<$.length;D++){let O=$[D];if(O==="(")G++,U=!0;if(O===")")G--;if(O==="{")_++;if(O==="}")_--;if(U&&G===0&&_===0){if(j=D+1,$[D+1]===";")j=D+2;break}}let z=`// Removed from database - uncomment if needed
202
- ${$.slice(Y,j).split(`
203
- `).map((D)=>{let V=D.match(/^(\s*)/)?.[1]??"",R=D.slice(V.length);return`${V}// ${R}`}).join(`
204
- `)}`,K=$.slice(0,Y)+z+$.slice(j),A=new RegExp(`,\\s*${b0(Q)}(?=[\\s,\\]])`);return K=K.replace(A,""),K}function b0($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function A1($){return $.split("_").map((X)=>X.charAt(0).toUpperCase()+X.slice(1)).join("")}import L6 from"chalk";function V1($,X,Q){let J=[],Z=I0($),Y=new Set,_=Q?C2($,Q):[];for(let G of _)Y.add(G.table);for(let[G,j]of Z){let U=X.get(G),W=G.replace(".ts","").toLowerCase();if(!U)J.push({filename:G,type:"create",newContent:j});else if(U!==j)if(Q){if(Y.has(W)){let H=$.tables.find((z)=>z.name===W),q=Q.tables.find((z)=>z.name===W);if(H&&q){let z=H1(U,H,q);J.push({filename:G,type:"update",oldContent:U,newContent:z.content,addedFields:z.addedFields,addedIndexes:z.addedIndexes,removedFields:z.removedFields,removedIndexes:z.removedIndexes})}else J.push({filename:G,type:"update",oldContent:U,newContent:j})}}else J.push({filename:G,type:"update",oldContent:U,newContent:j})}for(let G of X.keys())if(!Z.has(G))J.push({filename:G,type:"delete",oldContent:X.get(G),newContent:""});return J}import{extractTableFromModel as x2,extractIndexFromDefinition as y2,isModelClass as b2,isIndexDefinition as g2}from"unreal-orm";import{readdirSync as f2}from"node:fs";import{join as h2,resolve as m2}from"node:path";import{createJiti as p2}from"jiti";var u2=p2(import.meta.url,{interopDefault:!0});async function $0($){let X=[];for(let Q of f2($).filter((J)=>J.endsWith(".ts"))){let J=m2(h2($,Q));try{let Z=await u2.import(J),Y=new Map,_=[];for(let[,G]of Object.entries(Z))if(b2(G)){let j=x2(G);Y.set(j.name,j)}else if(g2(G)){let{index:j,tableName:U}=y2(G);_.push({index:j,tableName:U})}for(let{index:G,tableName:j}of _){let U=Y.get(j);if(U)U.indexes.push(G)}X.push(...Y.values())}catch(Z){console.warn(`Failed to import ${Q}:`,Z)}}return{tables:X}}import y from"chalk";import{diffLines as O1}from"diff";var g0=3;function E1($,X,Q){let J=[];if(!X){J.push(y.bold.green(`
205
- +++ ${$} (new file)`)),J.push(y.dim("─".repeat(60)));let _=Q.split(`
206
- `).slice(0,20);for(let G of _)J.push(y.green(`+ ${G}`));if(Q.split(`
207
- `).length>20)J.push(y.dim(`... ${Q.split(`
208
- `).length-20} more lines`));return J.push(y.dim("─".repeat(60))),J.join(`
209
- `)}J.push(y.bold(`
210
- --- ${$}`)),J.push(y.bold(`+++ ${$}`)),J.push(y.dim("─".repeat(60)));let Z=O1(X,Q),Y=c2(Z);if(Y.length===0)J.push(y.dim(" (no changes)"));for(let _ of Y){J.push(y.cyan(`@@ -${_.oldStart},${_.oldLines} +${_.newStart},${_.newLines} @@`));for(let G of _.lines)if(G.type==="added")J.push(y.green(`+ ${G.content}`));else if(G.type==="removed")J.push(y.red(`- ${G.content}`));else J.push(y.dim(` ${G.content}`));J.push("")}return J.push(y.dim("─".repeat(60))),J.join(`
211
- `)}function c2($){return d2($)}function d2($){let X=[],Q=null,J=[],Z=1,Y=1;for(let _ of $){if(!_)continue;let G=_.value.split(`
212
- `);if(G[G.length-1]==="")G.pop();for(let j of G){let U=_.added?"added":_.removed?"removed":"context";if(J.push({type:U,content:j,oldLine:U!=="added"?Z:void 0,newLine:U!=="removed"?Y:void 0}),U!=="added")Z++;if(U!=="removed")Y++}}for(let _=0;_<J.length;_++){let G=J[_];if(!G)continue;if(G.type==="added"||G.type==="removed"){if(!Q){let j=Math.max(0,_-g0),U=J.slice(j,_),W=U[0],H=W?.oldLine??G.oldLine??1,q=W?.newLine??G.newLine??1;Q={oldStart:H,newStart:q,oldLines:0,newLines:0,lines:[]};for(let z of U)if(z)Q.lines.push({type:"context",content:z.content}),Q.oldLines++,Q.newLines++}if(Q.lines.push({type:G.type,content:G.content}),G.type!=="added")Q.oldLines++;if(G.type!=="removed")Q.newLines++}else if(Q){let j=-1;for(let W=_+1;W<J.length;W++){let H=J[W];if(H&&H.type!=="context"){j=W;break}}if(j!==-1){if(j-_<=g0*2){Q.lines.push({type:"context",content:G.content}),Q.oldLines++,Q.newLines++;continue}}if(Q.lines.slice().reverse().findIndex((W)=>W.type!=="context")<g0)Q.lines.push({type:"context",content:G.content}),Q.oldLines++,Q.newLines++;else X.push(Q),Q=null}}if(Q)X.push(Q);return X}function M1($,X){if(!$)return`New file (${X.split(`
213
- `).length} lines)`;let Q=O1($,X),J=0,Z=0;for(let _ of Q){let G=_.value.split(`
214
- `).length-1;if(_.added)J+=G;else if(_.removed)Z+=G}if(J===0&&Z===0)return"No changes";let Y=[];if(J>0)Y.push(y.green(`+${J}`));if(Z>0)Y.push(y.red(`-${Z}`));return Y.join(" ")}m();var R1=new l2().name("pull").description("Introspect database and generate TypeScript schema").option("--url <url>","Database URL (e.g., http://localhost:8000)").option("-u, --username <username>","Database username").option("-p, --password <password>","Database password").option("-n, --namespace <namespace>","Database namespace").option("-d, --database <database>","Database name").option("--auth-level <level>","Auth level: root, namespace, or database").option("-s, --schema-dir <path>","Schema directory path").option("--embedded <mode>","Use embedded mode (memory or file path)").option("-y, --yes","Skip confirmation prompt").action(async($)=>{B.header("UnrealORM Pull","Introspect database and generate schema"),R0();let X=await r(),Q=await n({cliOutput:$.schemaDir,config:X}),J=await o({cliOptions:{url:$.url,username:$.username,password:$.password,namespace:$.namespace,database:$.database,authLevel:$.authLevel,embedded:$.embedded},config:X,skipAutoConfig:!0});if(!J)B.error("Failed to establish database connection."),process.exit(1);let Z=B.spin("Introspecting database schema..."),Y;try{Y=await e(J),Z.succeed(`Found ${Y.tables.length} table(s)`)}catch(z){Z.fail("Failed to introspect database"),B.error(z instanceof Error?z.message:String(z)),await J.close(),process.exit(1)}Z.start("Planning file changes...");let _=new Map;if(f0(Q))try{let z=i2(Q).filter((K)=>K.endsWith(".ts"));for(let K of z){let A=s2(D1(Q,K),"utf-8");_.set(K,A)}}catch(z){}let G;if(f0(Q))try{G=await $0(Q)}catch{}let j;try{j=V1(Y,_,G),Z.succeed("File changes planned")}catch(z){Z.fail("Failed to plan file changes"),B.error(z instanceof Error?z.message:String(z)),await J.close(),process.exit(1)}if(j.length===0)B.success("All files are up to date!"),await J.close(),G0(),process.exit(0);let U=j.filter((z)=>z.type==="create").length,W=j.filter((z)=>z.type==="delete").length,H=j.filter((z)=>z.type==="update").length;if(B.divider(),B.info("FILE CHANGE SUMMARY (Database -> Code)"),B.divider(),B.newline(),B.printer.log(` Total files: ${B.bold(String(j.length))}`),U>0)B.printer.log(` ${B.theme.success("+")} New files: ${U}`);if(W>0)B.printer.log(` ${B.theme.error("-")} Deleted files: ${W}`);if(H>0)B.printer.log(` ${B.theme.warning("~")} Updated files: ${H}`);B.newline();for(let z of j){let K=z.type==="create"?B.theme.success("+"):z.type==="delete"?B.theme.error("-"):B.theme.warning("~");B.printer.log(` ${K} ${z.filename}`)}B.newline();let q=[];if(!$.yes){let z=!1;B.divider(),B.info("FILE REVIEW"),B.divider(),B.newline();for(let K of j){if(!K)continue;if(z){q.push(K);continue}B.printer.clear();let A=K.type==="create"?B.theme.success("CREATE"):K.type==="delete"?B.theme.error("DELETE"):B.theme.warning("UPDATE");B.printer.log(B.bold(`[${j.indexOf(K)+1}/${j.length}] ${A}: ${K.filename}`)),B.printer.log(B.dim(` ${M1(K.oldContent,K.newContent)}`)),B.printer.log(E1(K.filename,K.oldContent,K.newContent));let D=await j0(K.filename,j.indexOf(K)+1,j.length);if(D==="cancel")B.newline(),B.warn("Operation cancelled."),await J.close(),process.exit(0);if(D==="all"){z=!0,q.push(K);for(let O of j.slice(j.indexOf(K)+1))if(O)q.push(O);break}if(D==="yes")q.push(K)}if(B.printer.clear(),q.length===0)B.warn("No files selected. Operation cancelled."),await J.close(),process.exit(0);B.divider(),B.success("APPLYING SELECTED CHANGES"),B.divider(),B.info(`Will apply ${q.length} of ${j.length} file changes`),B.newline()}else B.divider(),B.success("APPLYING ALL CHANGES (--yes flag)"),B.divider(),B.info(`Applying all ${j.length} file changes`),B.newline(),q.push(...j);Z.start("Applying file changes...");try{if(!f0(Q))r2(Q,{recursive:!0});for(let z of q){let K=D1(Q,z.filename);if(z.type==="delete")a2(K);else o2(K,z.newContent,"utf-8")}Z.succeed(`Applied ${q.length} file change(s) to ${Q}`)}catch(z){Z.fail("Failed to apply file changes"),B.error(z instanceof Error?z.message:String(z)),await J.close(),process.exit(1)}await J.close(),G0(),B.header("Schema pull complete!"),B.dim("Changes applied:");for(let z of q){let K=z.type==="create"?"+":z.type==="delete"?"-":"~";console.log(B.dim(` ${K} ${z.filename}`))}B.newline()});import{Command as e2}from"@commander-js/extra-typings";import{existsSync as $4}from"node:fs";Y0();import{compareSchemas as Q4}from"unreal-orm";function p0($,X,Q){return n2($,X,Q)}function n2($,X,Q){let J=X.tables.find((Y)=>Y.name===$.table),Z=Q.tables.find((Y)=>Y.name===$.table);switch($.type){case"table_added":{if(!J)return null;return t2(J)}case"table_removed":return`REMOVE TABLE ${$.table};`;case"table_type_changed":{if(!J)return null;return I1(J,!0)}case"field_added":{if(!J||!$.field)return null;let Y=J.fields.find((_)=>_.name===$.field);if(!Y)return null;return h0($.table,Y)}case"field_removed":return`REMOVE FIELD ${$.field} ON TABLE ${$.table};`;case"field_type_changed":case"field_default_changed":case"field_assertion_changed":{if(!J||!$.field)return null;let Y=J.fields.find((_)=>_.name===$.field);if(!Y)return null;return h0($.table,Y,!0)}case"index_added":{if(!J||!$.index)return null;let Y=J.indexes.find((_)=>_.name===$.index);if(!Y)return null;return m0($.table,Y)}case"index_removed":return`REMOVE INDEX ${$.index} ON TABLE ${$.table};`;case"index_modified":{if(!J||!$.index)return null;let Y=J.indexes.find((_)=>_.name===$.index);if(!Y)return null;return m0($.table,Y,!0)}default:return null}}function t2($){let X=[];X.push(I1($));for(let Q of $.fields){if(Q.name.includes("[*]"))continue;let J=$.type==="RELATION"&&(Q.name==="in"||Q.name==="out");X.push(h0($.name,Q,J))}for(let Q of $.indexes)X.push(m0($.name,Q));return X.join(`
215
- `)}function I1($,X=!1){let J=[`${X?"DEFINE TABLE OVERWRITE":"DEFINE TABLE"} ${$.name}`];if($.type==="RELATION")J.push("TYPE RELATION");else if($.type==="VIEW"){if(J.push("TYPE ANY"),$.viewQuery)J.push(`AS ${$.viewQuery}`)}if($.schemafull)J.push("SCHEMAFULL");let Z=[];if($.permissions.select)Z.push(`FOR select ${$.permissions.select}`);if($.permissions.create)Z.push(`FOR create ${$.permissions.create}`);if($.permissions.update)Z.push(`FOR update ${$.permissions.update}`);if($.permissions.delete)Z.push(`FOR delete ${$.permissions.delete}`);if(Z.length>0)J.push(`PERMISSIONS ${Z.join(", ")}`);return`${J.join(" ")};`}function h0($,X,Q=!1){let Z=[`${Q?"DEFINE FIELD OVERWRITE":"DEFINE FIELD"} ${X.name} ON TABLE ${$}`];if(X.flex)Z.push("FLEXIBLE");if(X.type)Z.push(`TYPE ${X.type}`);if(X.value)Z.push(`VALUE ${X.value}`);if(X.assert)Z.push(`ASSERT ${X.assert}`);if(X.default)Z.push(`DEFAULT ${X.default}`);let Y=[];if(X.permissions.select)Y.push(`FOR select ${X.permissions.select}`);if(X.permissions.create)Y.push(`FOR create ${X.permissions.create}`);if(X.permissions.update)Y.push(`FOR update ${X.permissions.update}`);if(X.permissions.delete)Y.push(`FOR delete ${X.permissions.delete}`);if(Y.length>0)Z.push(`PERMISSIONS ${Y.join(", ")}`);return`${Z.join(" ")};`}function m0($,X,Q=!1){let Z=[`${Q?"DEFINE INDEX OVERWRITE":"DEFINE INDEX"} ${X.name} ON TABLE ${$}`];if(X.columns&&X.columns.length>0)Z.push(`FIELDS ${X.columns.join(", ")}`);if(X.unique)Z.push("UNIQUE");if(X.search)Z.push("SEARCH ANALYZER");return`${Z.join(" ")};`}m();var P1=new e2().name("push").description("Apply TypeScript schema to database").option("--url <url>","Database URL (e.g., http://localhost:8000)").option("-u, --username <username>","Database username").option("-p, --password <password>","Database password").option("-n, --namespace <namespace>","Database namespace").option("-d, --database <database>","Database name").option("--auth-level <level>","Auth level: root, namespace, or database").option("-s, --schema-dir <path>","Schema directory path").option("--embedded <mode>","Use embedded mode (memory or file path)").option("-y, --yes","Skip confirmation prompt").action(async($)=>{B.header("UnrealORM Push","Apply code schema to database"),R0();let X=await r(),Q=await n({cliOutput:$.schemaDir,config:X});if(!$4(Q))B.error(`Schema directory not found: ${Q}`),B.info("Run 'unreal pull' first to generate schema files."),B.newline(),process.exit(1);let J=await o({cliOptions:{url:$.url,username:$.username,password:$.password,namespace:$.namespace,database:$.database,authLevel:$.authLevel,embedded:$.embedded},config:X,skipAutoConfig:!0});if(!J)B.error("Failed to establish database connection."),process.exit(1);let Z=B.spin("Loading code schema..."),Y;try{Y=await $0(Q),Z.succeed(`Loaded ${Y.tables.length} table(s) from ${Q}`)}catch(z){Z.fail("Failed to load code schema"),B.error(z instanceof Error?z.message:String(z)),process.exit(1)}Z=B.spin("Introspecting database schema...");let _;try{_=await e(J),Z.succeed(`Found ${_.tables.length} table(s) in database`)}catch(z){Z.fail("Failed to introspect database"),B.error(z instanceof Error?z.message:String(z)),await J.close(),process.exit(1)}Z.start("Comparing schemas...");let G=Q4(Y,_,!0);if(Z.succeed("Comparison complete"),G.length===0)B.success("Schemas are identical. Nothing to push."),await J.close(),G0(),process.exit(0);let j=G.filter((z)=>z.type.includes("added")).length,U=G.filter((z)=>z.type.includes("removed")).length,W=G.length-j-U;if(B.divider(),B.info("CHANGE SUMMARY (Code -> Database)"),B.divider(),B.newline(),B.printer.log(` Total changes: ${B.bold(String(G.length))}`),j>0)B.printer.log(` ${B.theme.success("+")} Additions: ${j}`);if(U>0)B.printer.log(` ${B.theme.error("-")} Removals: ${U}`);if(W>0)B.printer.log(` ${B.theme.warning("~")} Modifications: ${W}`);B.newline();for(let z of G){let K=z.type.includes("added")?B.theme.success("+"):z.type.includes("removed")?B.theme.error("-"):B.theme.warning("~");B.printer.log(` ${K} ${z.description}`)}B.newline();let H=[];if(!$.yes){let z=!1;B.divider(),B.info("CHANGE REVIEW"),B.divider(),B.newline();for(let K=0;K<G.length;K++){let A=G[K];if(!A)continue;if(z){H.push(A);continue}B.printer.clear();let D=A.type.includes("added")?B.theme.success("ADD"):A.type.includes("removed")?B.theme.error("REMOVE"):B.theme.warning("MODIFY");B.printer.log(B.bold(`[${K+1}/${G.length}] ${D}: ${A.description}`));let O=p0(A,Y,_);if(O)B.printer.log(B.dim(`
216
- \uD83D\uDCDD SurrealQL Statement:`)),B.printer.log(B.theme.secondary(` ${O}
217
- `));else B.printer.log(B.dim(`
195
+ ${Q}`}function k2($,J){let X=`export const ${$.name.replace(/[^a-zA-Z0-9_]/g,"_")} = Index.define(() => ${J}, {
196
+ `;if(X+=` name: "${$.name}",
197
+ `,X+=` fields: [${$.columns.map((Z)=>`"${Z}"`).join(", ")}],
198
+ `,$.unique)X+=` unique: true,
199
+ `;return X+=`});
200
+ `,X}function T2($,J){let Q=new RegExp(`([ \\t]*)(${f0(J)}\\s*:\\s*(?:Field\\.|\\{))`),X=$.match(Q);if(!X||X.index===void 0)return $;let Z=X[1]??"",B=X.index+Z.length,_=0,G=0,j=0,U=B,W=!1,V="",q=!1;for(let E=B;E<$.length;E++){let A=$[E],R=E>0?$[E-1]:"";if((A==='"'||A==="'"||A==="`")&&R!=="\\"){if(!W&&!q)if(A==="`")q=!0;else W=!0,V=A;else if(q&&A==="`")q=!1;else if(W&&A===V)W=!1;continue}if(W||q)continue;if(A==="(")_++;if(A===")")_--;if(A==="{")G++;if(A==="}")G--;if(A==="[")j++;if(A==="]")j--;if(_===0&&j===0){if(G===0&&A===","){U=E+1;break}if(G===-1&&A==="}"){U=E;while(U>B&&/\s/.test($[U-1]||""))U--;break}}}let z=$.slice(B,U).split(`
201
+ `).map((E,A)=>{if(A===0)return`${Z}// ${E}`;let I=E.match(/^(\s*)/)?.[1]??"",O=E.slice(I.length);return`${I}// ${O}`}).join(`
202
+ `),M=`${Z}// Removed from database - uncomment if needed
203
+ `;return $.slice(0,B)+M+z+$.slice(U)}function C2($,J){let Q=J.replace(/[^a-zA-Z0-9_]/g,"_"),X=new RegExp(`export\\s+const\\s+${f0(Q)}\\s*=\\s*Index\\.define`),Z=$.match(X);if(!Z||Z.index===void 0)return $;let B=Z.index,_=0,G=0,j=B,U=!1;for(let M=B;M<$.length;M++){let E=$[M];if(E==="(")G++,U=!0;if(E===")")G--;if(E==="{")_++;if(E==="}")_--;if(U&&G===0&&_===0){if(j=M+1,$[M+1]===";")j=M+2;break}}let H=`// Removed from database - uncomment if needed
204
+ ${$.slice(B,j).split(`
205
+ `).map((M)=>{let A=M.match(/^(\s*)/)?.[1]??"",R=M.slice(A.length);return`${A}// ${R}`}).join(`
206
+ `)}`,K=$.slice(0,B)+H+$.slice(j),z=new RegExp(`,\\s*${f0(Q)}(?=[\\s,\\]])`);return K=K.replace(z,""),K}function f0($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function A1($){return $.split("_").map((J)=>J.charAt(0).toUpperCase()+J.slice(1)).join("")}import N6 from"chalk";function V1($,J,Q){let X=[],Z=I0($),B=new Set,_=Q?x2($,Q):[];for(let G of _)B.add(G.table);for(let[G,j]of Z){let U=J.get(G),W=G.replace(".ts","").toLowerCase();if(!U)X.push({filename:G,type:"create",newContent:j});else if(U!==j)if(Q){if(B.has(W)){let V=$.tables.find((H)=>H.name===W),q=Q.tables.find((H)=>H.name===W);if(V&&q){let H=W1(U,V,q);X.push({filename:G,type:"update",oldContent:U,newContent:H.content,addedFields:H.addedFields,addedIndexes:H.addedIndexes,removedFields:H.removedFields,removedIndexes:H.removedIndexes})}else X.push({filename:G,type:"update",oldContent:U,newContent:j})}}else X.push({filename:G,type:"update",oldContent:U,newContent:j})}for(let G of J.keys())if(!Z.has(G))X.push({filename:G,type:"delete",oldContent:J.get(G),newContent:""});return X}import{extractTableFromModel as y2,extractIndexFromDefinition as b2,isModelClass as g2,isIndexDefinition as f2}from"unreal-orm";import{readdirSync as h2}from"node:fs";import{join as m2,resolve as u2}from"node:path";import{createJiti as p2}from"jiti";var c2=p2(import.meta.url,{interopDefault:!0});async function Q0($){let J=[];for(let Q of h2($).filter((X)=>X.endsWith(".ts"))){let X=u2(m2($,Q));try{let Z=await c2.import(X),B=new Map,_=[];for(let[,G]of Object.entries(Z))if(g2(G)){let j=y2(G);B.set(j.name,j)}else if(f2(G)){let{index:j,tableName:U}=b2(G);_.push({index:j,tableName:U})}for(let{index:G,tableName:j}of _){let U=B.get(j);if(U)U.indexes.push(G)}J.push(...B.values())}catch(Z){console.warn(`Failed to import ${Q}:`,Z)}}return{tables:J}}import b from"chalk";import{diffLines as O1}from"diff";var h0=3;function E1($,J,Q){let X=[];if(!J){X.push(b.bold.green(`
207
+ +++ ${$} (new file)`)),X.push(b.dim("─".repeat(60)));let _=Q.split(`
208
+ `).slice(0,20);for(let G of _)X.push(b.green(`+ ${G}`));if(Q.split(`
209
+ `).length>20)X.push(b.dim(`... ${Q.split(`
210
+ `).length-20} more lines`));return X.push(b.dim("─".repeat(60))),X.join(`
211
+ `)}X.push(b.bold(`
212
+ --- ${$}`)),X.push(b.bold(`+++ ${$}`)),X.push(b.dim("─".repeat(60)));let Z=O1(J,Q),B=d2(Z);if(B.length===0)X.push(b.dim(" (no changes)"));for(let _ of B){X.push(b.cyan(`@@ -${_.oldStart},${_.oldLines} +${_.newStart},${_.newLines} @@`));for(let G of _.lines)if(G.type==="added")X.push(b.green(`+ ${G.content}`));else if(G.type==="removed")X.push(b.red(`- ${G.content}`));else X.push(b.dim(` ${G.content}`));X.push("")}return X.push(b.dim("─".repeat(60))),X.join(`
213
+ `)}function d2($){return l2($)}function l2($){let J=[],Q=null,X=[],Z=1,B=1;for(let _ of $){if(!_)continue;let G=_.value.split(`
214
+ `);if(G[G.length-1]==="")G.pop();for(let j of G){let U=_.added?"added":_.removed?"removed":"context";if(X.push({type:U,content:j,oldLine:U!=="added"?Z:void 0,newLine:U!=="removed"?B:void 0}),U!=="added")Z++;if(U!=="removed")B++}}for(let _=0;_<X.length;_++){let G=X[_];if(!G)continue;if(G.type==="added"||G.type==="removed"){if(!Q){let j=Math.max(0,_-h0),U=X.slice(j,_),W=U[0],V=W?.oldLine??G.oldLine??1,q=W?.newLine??G.newLine??1;Q={oldStart:V,newStart:q,oldLines:0,newLines:0,lines:[]};for(let H of U)if(H)Q.lines.push({type:"context",content:H.content}),Q.oldLines++,Q.newLines++}if(Q.lines.push({type:G.type,content:G.content}),G.type!=="added")Q.oldLines++;if(G.type!=="removed")Q.newLines++}else if(Q){let j=-1;for(let W=_+1;W<X.length;W++){let V=X[W];if(V&&V.type!=="context"){j=W;break}}if(j!==-1){if(j-_<=h0*2){Q.lines.push({type:"context",content:G.content}),Q.oldLines++,Q.newLines++;continue}}if(Q.lines.slice().reverse().findIndex((W)=>W.type!=="context")<h0)Q.lines.push({type:"context",content:G.content}),Q.oldLines++,Q.newLines++;else J.push(Q),Q=null}}if(Q)J.push(Q);return J}function M1($,J){if(!$)return`New file (${J.split(`
215
+ `).length} lines)`;let Q=O1($,J),X=0,Z=0;for(let _ of Q){let G=_.value.split(`
216
+ `).length-1;if(_.added)X+=G;else if(_.removed)Z+=G}if(X===0&&Z===0)return"No changes";let B=[];if(X>0)B.push(b.green(`+${X}`));if(Z>0)B.push(b.red(`-${Z}`));return B.join(" ")}u();var R1=new r2().name("pull").description("Introspect database and generate TypeScript schema").option("--url <url>","Database URL (e.g., http://localhost:8000)").option("-u, --username <username>","Database username").option("-p, --password <password>","Database password").option("-n, --namespace <namespace>","Database namespace").option("-d, --database <database>","Database name").option("--auth-level <level>","Auth level: root, namespace, or database").option("-s, --schema-dir <path>","Schema directory path").option("--embedded <mode>","Use embedded mode (memory or file path)").option("-y, --yes","Skip confirmation prompt").action(async($)=>{Y.header("UnrealORM Pull","Introspect database and generate schema"),_0();let J=await o(),Q=await n({cliOutput:$.schemaDir,config:J}),X=$.url||$.username||$.password||$.namespace||$.database||$.authLevel||$.embedded,Z=await s({cliOptions:{url:$.url,username:$.username,password:$.password,namespace:$.namespace,database:$.database,authLevel:$.authLevel,embedded:$.embedded},config:J,skipAutoConfig:!$.yes&&!X});if(!Z)Y.error("Failed to establish database connection."),process.exit(1);let B=Y.spin("Introspecting database schema..."),_;try{_=await $0(Z),B.succeed(`Found ${_.tables.length} table(s)`)}catch(K){B.fail("Failed to introspect database"),Y.error(K instanceof Error?K.message:String(K)),await Z.close(),process.exit(1)}B.start("Planning file changes...");let G=new Map;if(m0(Q))try{let K=a2(Q).filter((z)=>z.endsWith(".ts"));for(let z of K){let M=i2(D1(Q,z),"utf-8");G.set(z,M)}}catch(K){}let j;if(m0(Q))try{j=await Q0(Q)}catch{}let U;try{U=V1(_,G,j),B.succeed("File changes planned")}catch(K){B.fail("Failed to plan file changes"),Y.error(K instanceof Error?K.message:String(K)),await Z.close(),process.exit(1)}if(U.length===0)Y.success("All files are up to date!"),await Z.close(),e(),process.exit(0);let W=U.filter((K)=>K.type==="create").length,V=U.filter((K)=>K.type==="delete").length,q=U.filter((K)=>K.type==="update").length;if(Y.divider(),Y.info("FILE CHANGE SUMMARY (Database -> Code)"),Y.divider(),Y.newline(),Y.printer.log(` Total files: ${Y.bold(String(U.length))}`),W>0)Y.printer.log(` ${Y.theme.success("+")} New files: ${W}`);if(V>0)Y.printer.log(` ${Y.theme.error("-")} Deleted files: ${V}`);if(q>0)Y.printer.log(` ${Y.theme.warning("~")} Updated files: ${q}`);Y.newline();for(let K of U){let z=K.type==="create"?Y.theme.success("+"):K.type==="delete"?Y.theme.error("-"):Y.theme.warning("~");Y.printer.log(` ${z} ${K.filename}`)}Y.newline();let H=[];if(!$.yes){let K=!1;Y.divider(),Y.info("FILE REVIEW"),Y.divider(),Y.newline();for(let z of U){if(!z)continue;if(K){H.push(z);continue}Y.printer.clear();let M=z.type==="create"?Y.theme.success("CREATE"):z.type==="delete"?Y.theme.error("DELETE"):Y.theme.warning("UPDATE");Y.printer.log(Y.bold(`[${U.indexOf(z)+1}/${U.length}] ${M}: ${z.filename}`)),Y.printer.log(Y.dim(` ${M1(z.oldContent,z.newContent)}`)),Y.printer.log(E1(z.filename,z.oldContent,z.newContent));let E=await U0(z.filename,U.indexOf(z)+1,U.length);if(E==="cancel")Y.newline(),Y.warn("Operation cancelled."),await Z.close(),process.exit(0);if(E==="all"){K=!0,H.push(z);for(let A of U.slice(U.indexOf(z)+1))if(A)H.push(A);break}if(E==="yes")H.push(z)}if(Y.printer.clear(),H.length===0)Y.warn("No files selected. Operation cancelled."),await Z.close(),process.exit(0);Y.divider(),Y.success("APPLYING SELECTED CHANGES"),Y.divider(),Y.info(`Will apply ${H.length} of ${U.length} file changes`),Y.newline()}else Y.divider(),Y.success("APPLYING ALL CHANGES (--yes flag)"),Y.divider(),Y.info(`Applying all ${U.length} file changes`),Y.newline(),H.push(...U);B.start("Applying file changes...");try{if(!m0(Q))o2(Q,{recursive:!0});for(let K of H){let z=D1(Q,K.filename);if(K.type==="delete")n2(z);else s2(z,K.newContent,"utf-8")}B.succeed(`Applied ${H.length} file change(s) to ${Q}`)}catch(K){B.fail("Failed to apply file changes"),Y.error(K instanceof Error?K.message:String(K)),await Z.close(),process.exit(1)}await Z.close(),e(),Y.header("Schema pull complete!"),Y.dim("Changes applied:");for(let K of H){let z=K.type==="create"?"+":K.type==="delete"?"-":"~";console.log(Y.dim(` ${z} ${K.filename}`))}Y.newline()});import{Command as $4}from"@commander-js/extra-typings";import{existsSync as Q4}from"node:fs";G0();import{compareSchemas as J4}from"unreal-orm";function c0($,J,Q){return t2($,J,Q)}function t2($,J,Q){let X=J.tables.find((B)=>B.name===$.table),Z=Q.tables.find((B)=>B.name===$.table);switch($.type){case"table_added":{if(!X)return null;return e2(X)}case"table_removed":return`REMOVE TABLE ${$.table};`;case"table_type_changed":{if(!X)return null;return I1(X,!0)}case"field_added":{if(!X||!$.field)return null;let B=X.fields.find((_)=>_.name===$.field);if(!B)return null;return u0($.table,B)}case"field_removed":return`REMOVE FIELD ${$.field} ON TABLE ${$.table};`;case"field_type_changed":case"field_default_changed":case"field_assertion_changed":{if(!X||!$.field)return null;let B=X.fields.find((_)=>_.name===$.field);if(!B)return null;return u0($.table,B,!0)}case"index_added":{if(!X||!$.index)return null;let B=X.indexes.find((_)=>_.name===$.index);if(!B)return null;return p0($.table,B)}case"index_removed":return`REMOVE INDEX ${$.index} ON TABLE ${$.table};`;case"index_modified":{if(!X||!$.index)return null;let B=X.indexes.find((_)=>_.name===$.index);if(!B)return null;return p0($.table,B,!0)}default:return null}}function e2($){let J=[];J.push(I1($));for(let Q of $.fields){if(Q.name.includes("[*]"))continue;let X=$.type==="RELATION"&&(Q.name==="in"||Q.name==="out");J.push(u0($.name,Q,X))}for(let Q of $.indexes)J.push(p0($.name,Q));return J.join(`
217
+ `)}function I1($,J=!1){let X=[`${J?"DEFINE TABLE OVERWRITE":"DEFINE TABLE"} ${$.name}`];if($.type==="RELATION")X.push("TYPE RELATION");else if($.type==="VIEW"){if(X.push("TYPE ANY"),$.viewQuery)X.push(`AS ${$.viewQuery}`)}if($.schemafull)X.push("SCHEMAFULL");let Z=[];if($.permissions.select)Z.push(`FOR select ${$.permissions.select}`);if($.permissions.create)Z.push(`FOR create ${$.permissions.create}`);if($.permissions.update)Z.push(`FOR update ${$.permissions.update}`);if($.permissions.delete)Z.push(`FOR delete ${$.permissions.delete}`);if(Z.length>0)X.push(`PERMISSIONS ${Z.join(", ")}`);return`${X.join(" ")};`}function u0($,J,Q=!1){let Z=[`${Q?"DEFINE FIELD OVERWRITE":"DEFINE FIELD"} ${J.name} ON TABLE ${$}`];if(J.flex)Z.push("FLEXIBLE");if(J.type)Z.push(`TYPE ${J.type}`);if(J.value)Z.push(`VALUE ${J.value}`);if(J.assert)Z.push(`ASSERT ${J.assert}`);if(J.default)Z.push(`DEFAULT ${J.default}`);let B=[];if(J.permissions.select)B.push(`FOR select ${J.permissions.select}`);if(J.permissions.create)B.push(`FOR create ${J.permissions.create}`);if(J.permissions.update)B.push(`FOR update ${J.permissions.update}`);if(J.permissions.delete)B.push(`FOR delete ${J.permissions.delete}`);if(B.length>0)Z.push(`PERMISSIONS ${B.join(", ")}`);return`${Z.join(" ")};`}function p0($,J,Q=!1){let Z=[`${Q?"DEFINE INDEX OVERWRITE":"DEFINE INDEX"} ${J.name} ON TABLE ${$}`];if(J.columns&&J.columns.length>0)Z.push(`FIELDS ${J.columns.join(", ")}`);if(J.unique)Z.push("UNIQUE");if(J.search)Z.push("SEARCH ANALYZER");return`${Z.join(" ")};`}u();var P1=new $4().name("push").description("Apply TypeScript schema to database").option("--url <url>","Database URL (e.g., http://localhost:8000)").option("-u, --username <username>","Database username").option("-p, --password <password>","Database password").option("-n, --namespace <namespace>","Database namespace").option("-d, --database <database>","Database name").option("--auth-level <level>","Auth level: root, namespace, or database").option("-s, --schema-dir <path>","Schema directory path").option("--embedded <mode>","Use embedded mode (memory or file path)").option("-y, --yes","Skip confirmation prompt").action(async($)=>{Y.header("UnrealORM Push","Apply code schema to database"),_0();let J=await o(),Q=await n({cliOutput:$.schemaDir,config:J});if(!Q4(Q))Y.error(`Schema directory not found: ${Q}`),Y.info("Run 'unreal pull' first to generate schema files."),Y.newline(),process.exit(1);let X=$.url||$.username||$.password||$.namespace||$.database||$.authLevel||$.embedded,Z=await s({cliOptions:{url:$.url,username:$.username,password:$.password,namespace:$.namespace,database:$.database,authLevel:$.authLevel,embedded:$.embedded},config:J,skipAutoConfig:!$.yes&&!X});if(!Z)Y.error("Failed to establish database connection."),process.exit(1);let B=Y.spin("Loading code schema..."),_;try{_=await Q0(Q),B.succeed(`Loaded ${_.tables.length} table(s) from ${Q}`)}catch(K){B.fail("Failed to load code schema"),Y.error(K instanceof Error?K.message:String(K)),process.exit(1)}B=Y.spin("Introspecting database schema...");let G;try{G=await $0(Z),B.succeed(`Found ${G.tables.length} table(s) in database`)}catch(K){B.fail("Failed to introspect database"),Y.error(K instanceof Error?K.message:String(K)),await Z.close(),process.exit(1)}B.start("Comparing schemas...");let j=J4(_,G,!0);if(B.succeed("Comparison complete"),j.length===0)Y.success("Schemas are identical. Nothing to push."),await Z.close(),e(),process.exit(0);let U=j.filter((K)=>K.type.includes("added")).length,W=j.filter((K)=>K.type.includes("removed")).length,V=j.length-U-W;if(Y.divider(),Y.info("CHANGE SUMMARY (Code -> Database)"),Y.divider(),Y.newline(),Y.printer.log(` Total changes: ${Y.bold(String(j.length))}`),U>0)Y.printer.log(` ${Y.theme.success("+")} Additions: ${U}`);if(W>0)Y.printer.log(` ${Y.theme.error("-")} Removals: ${W}`);if(V>0)Y.printer.log(` ${Y.theme.warning("~")} Modifications: ${V}`);Y.newline();for(let K of j){let z=K.type.includes("added")?Y.theme.success("+"):K.type.includes("removed")?Y.theme.error("-"):Y.theme.warning("~");Y.printer.log(` ${z} ${K.description}`)}Y.newline();let q=[];if(!$.yes){let K=!1;Y.divider(),Y.info("CHANGE REVIEW"),Y.divider(),Y.newline();for(let z=0;z<j.length;z++){let M=j[z];if(!M)continue;if(K){q.push(M);continue}Y.printer.clear();let E=M.type.includes("added")?Y.theme.success("ADD"):M.type.includes("removed")?Y.theme.error("REMOVE"):Y.theme.warning("MODIFY");Y.printer.log(Y.bold(`[${z+1}/${j.length}] ${E}: ${M.description}`));let A=c0(M,_,G);if(A)Y.printer.log(Y.dim(`
218
+ \uD83D\uDCDD SurrealQL Statement:`)),Y.printer.log(Y.theme.secondary(` ${A}
219
+ `));else Y.printer.log(Y.dim(`
218
220
  ⚠️ No SurrealQL generated for this change
219
- `));let V=await j0("this change",K+1,G.length);if(V==="cancel")B.newline(),B.warn("Operation cancelled."),await J.close(),process.exit(0);if(V==="all"){z=!0,H.push(A);for(let R=K+1;R<G.length;R++){let I=G[R];if(I)H.push(I)}break}if(V==="yes")H.push(A)}if(B.printer.clear(),H.length===0)B.warn("No changes selected. Operation cancelled."),await J.close(),process.exit(0);B.divider(),B.success("APPLYING SELECTED CHANGES"),B.divider(),B.info(`Will apply ${H.length} of ${G.length} change(s)`),B.newline()}else B.divider(),B.success("APPLYING ALL CHANGES (--yes flag)"),B.divider(),B.info(`Applying all ${G.length} change(s)`),B.newline(),H.push(...G);let q=[];for(let z of H){let K=p0(z,Y,_);if(K)q.push(K)}Z.start("Applying schema changes...");try{let z=q.flatMap((K)=>K.split(`
220
- `).filter((A)=>A.trim())).join("");await J.query(`BEGIN;${z}COMMIT;`),Z.succeed("Schema changes applied successfully")}catch(z){Z.fail("Failed to apply schema changes"),B.error(z instanceof Error?z.message:String(z)),await J.close(),process.exit(1)}await J.close(),G0(),B.header("Schema push complete!"),B.dim(`Applied ${H.length} of ${G.length} change(s) to database`),B.newline()});import{Command as X4}from"@commander-js/extra-typings";import{existsSync as u0,readFileSync as Z4,readdirSync as B4}from"node:fs";import{join as Y4}from"node:path";import p from"chalk";function w1($,X=!1){if($.length===0)return p.green("✓ Schemas are identical");let Q=[],J=new Map;for(let Z of $){let Y=J.get(Z.table)||[];Y.push(Z),J.set(Z.table,Y)}for(let[Z,Y]of J){Q.push(p.bold(`
221
- ${Z}:`));for(let _ of Y){let G=J4(_.type),j=_.description;if(_.type.includes("added"))j=p.green(_.description);else if(_.type.includes("removed"))j=p.red(_.description);else j=p.yellow(_.description);if(Q.push(` ${G} ${j}`),X&&(_.oldValue!==void 0||_.newValue!==void 0)){if(_.oldValue!==void 0)Q.push(p.dim(" Old: ")+p.red(F1(_.oldValue)));if(_.newValue!==void 0)Q.push(p.dim(" New: ")+p.green(F1(_.newValue)))}}}return Q.join(`
222
- `)}function J4($){if($.includes("added"))return p.green("+");if($.includes("removed"))return p.red("-");return p.yellow("~")}function F1($){if(Array.isArray($))return`[${$.join(", ")}]`;if(typeof $==="object"&&$!==null){if("query"in $&&typeof $.query==="string")return $.query;let X=JSON.stringify($);if(X.length<50)return X;return JSON.stringify($,null,2)}return String($)}m();import{compareSchemas as G4}from"unreal-orm";function _4($,X){let Q={added:[],removed:[],modified:[],unchanged:[]};for(let[J,Z]of $){let Y=Y4(X,J);if(!u0(Y))Q.added.push(J);else{let _=Z4(Y,"utf-8");if(_.trim()!==Z.trim())Q.modified.push({filename:J,databaseContent:Z,codeContent:_});else Q.unchanged.push(J)}}if(u0(X)){let J=B4(X).filter((Z)=>Z.endsWith(".ts"));for(let Z of J)if(!$.has(Z))Q.removed.push(Z)}return Q}function j4($){let X=$.databaseContent.split(`
221
+ `));let R=await U0("this change",z+1,j.length);if(R==="cancel")Y.newline(),Y.warn("Operation cancelled."),await Z.close(),process.exit(0);if(R==="all"){K=!0,q.push(M);for(let I=z+1;I<j.length;I++){let O=j[I];if(O)q.push(O)}break}if(R==="yes")q.push(M)}if(Y.printer.clear(),q.length===0)Y.warn("No changes selected. Operation cancelled."),await Z.close(),process.exit(0);Y.divider(),Y.success("APPLYING SELECTED CHANGES"),Y.divider(),Y.info(`Will apply ${q.length} of ${j.length} change(s)`),Y.newline()}else Y.divider(),Y.success("APPLYING ALL CHANGES (--yes flag)"),Y.divider(),Y.info(`Applying all ${j.length} change(s)`),Y.newline(),q.push(...j);let H=[];for(let K of q){let z=c0(K,_,G);if(z)H.push(z)}B.start("Applying schema changes...");try{let K=H.flatMap((z)=>z.split(`
222
+ `).filter((M)=>M.trim())).join("");await Z.query(`BEGIN;${K}COMMIT;`),B.succeed("Schema changes applied successfully")}catch(K){B.fail("Failed to apply schema changes"),Y.error(K instanceof Error?K.message:String(K)),await Z.close(),process.exit(1)}await Z.close(),e(),Y.header("Schema push complete!"),Y.dim(`Applied ${q.length} of ${j.length} change(s) to database`),Y.newline()});import{Command as Z4}from"@commander-js/extra-typings";import{existsSync as d0,readFileSync as B4,readdirSync as Y4}from"node:fs";import{join as G4}from"node:path";import p from"chalk";function w1($,J=!1){if($.length===0)return p.green("✓ Schemas are identical");let Q=[],X=new Map;for(let Z of $){let B=X.get(Z.table)||[];B.push(Z),X.set(Z.table,B)}for(let[Z,B]of X){Q.push(p.bold(`
223
+ ${Z}:`));for(let _ of B){let G=X4(_.type),j=_.description;if(_.type.includes("added"))j=p.green(_.description);else if(_.type.includes("removed"))j=p.red(_.description);else j=p.yellow(_.description);if(Q.push(` ${G} ${j}`),J&&(_.oldValue!==void 0||_.newValue!==void 0)){if(_.oldValue!==void 0)Q.push(p.dim(" Old: ")+p.red(F1(_.oldValue)));if(_.newValue!==void 0)Q.push(p.dim(" New: ")+p.green(F1(_.newValue)))}}}return Q.join(`
224
+ `)}function X4($){if($.includes("added"))return p.green("+");if($.includes("removed"))return p.red("-");return p.yellow("~")}function F1($){if(Array.isArray($))return`[${$.join(", ")}]`;if(typeof $==="object"&&$!==null){if("query"in $&&typeof $.query==="string")return $.query;let J=JSON.stringify($);if(J.length<50)return J;return JSON.stringify($,null,2)}return String($)}u();import{compareSchemas as _4}from"unreal-orm";function j4($,J){let Q={added:[],removed:[],modified:[],unchanged:[]};for(let[X,Z]of $){let B=G4(J,X);if(!d0(B))Q.added.push(X);else{let _=B4(B,"utf-8");if(_.trim()!==Z.trim())Q.modified.push({filename:X,databaseContent:Z,codeContent:_});else Q.unchanged.push(X)}}if(d0(J)){let X=Y4(J).filter((Z)=>Z.endsWith(".ts"));for(let Z of X)if(!$.has(Z))Q.removed.push(Z)}return Q}function U4($){let J=$.databaseContent.split(`
223
225
  `).length,Q=$.codeContent.split(`
224
- `).length,J=X-Q;if(J>0)return`+${J} lines`;if(J<0)return`${J} lines`;return"content changed"}function z4($){let X={total:$.length,tables:0,fields:0,indexes:0};for(let Q of $)if(Q.type.startsWith("table_"))X.tables++;else if(Q.type.startsWith("field_"))X.fields++;else if(Q.type.startsWith("index_"))X.indexes++;return X}function U4($){let{added:X,removed:Q,modified:J,unchanged:Z}=$;if(B.header("Schema Diff Summary"),X.length>0){console.log(B.theme.success(`+ Added (${X.length}):`));for(let _ of X)console.log(` + ${_}`);B.newline()}if(Q.length>0){console.log(B.theme.error(`- Removed (${Q.length}):`));for(let _ of Q)console.log(` - ${_}`);B.newline()}if(J.length>0){console.log(B.theme.warning(`~ Modified (${J.length}):`));for(let _ of J)console.log(` ~ ${_.filename}`),console.log(B.dim(` Database: from database (${j4(_)})`)),console.log(B.dim(" Code: current file"));B.newline()}if(Z.length>0){console.log(B.theme.dim(`= Unchanged (${Z.length}):`));let _=Z.join(", ");console.log(B.dim(` ${_}`)),B.newline()}if(X.length>0||Q.length>0||J.length>0)console.log(B.bold(`${X.length+Q.length+J.length} file(s) changed, ${Z.length} unchanged`)),B.newline(),B.info('Run "unreal pull" to sync your code schema with the database.');else B.success("Code schema is in sync with database")}var L1=new X4().name("diff").description("Compare TypeScript schema with database schema").option("--url <url>","Database URL (e.g., http://localhost:8000)").option("-u, --username <username>","Database username").option("-p, --password <password>","Database password").option("-n, --namespace <namespace>","Database namespace").option("-d, --database <database>","Database name").option("--auth-level <level>","Auth level: root, namespace, or database").option("-s, --schema-dir <path>","Schema directory path").option("-e, --embedded <mode>","Use embedded mode (memory or file path)").option("--detailed","Show detailed field-level changes").action(async($)=>{try{B.header("UnrealORM Diff","Compare code vs database schema");let X=await r(),Q=await n({cliOutput:$.schemaDir,config:X}),J=await o({cliOptions:{url:$.url,username:$.username,password:$.password,namespace:$.namespace,database:$.database,authLevel:$.authLevel,embedded:$.embedded},config:X,skipAutoConfig:!0});if(!J)B.error("Failed to establish database connection."),process.exit(1);let Z=B.spin("Introspecting database schema"),Y=await e(J);Z.succeed("Introspected database schema");let _=null;if(u0(Q)){let G=B.spin("Parsing code schema");try{_=await $0(Q),G.succeed("Parsed code schema")}catch(j){G.fail("Could not parse code schema"),B.warn(`${j instanceof Error?j.message:String(j)}`),B.dim("Falling back to file-based comparison"),B.newline()}}if(_){let G=G4(Y,_);if(G.length===0){B.success("No schema differences detected. Code and database schemas are in sync."),await J.close();return}let j=z4(G),U=w1(G,$.detailed);B.divider(),B.info("Schema Changes"),B.divider(),B.newline(),console.log(U);let W=[];if(j.fields>0)W.push(B.theme.warning(`${j.fields} field(s)`));if(j.indexes>0)W.push(B.theme.info(`${j.indexes} index(es)`));if(j.tables>0)W.push(B.theme.primary(`${j.tables} table(s)`));if(B.newline(),console.log(B.bold(`${j.total} change(s): ${W.join(", ")}`)),!$.detailed&&j.total>0)B.newline(),B.dim("Tip: Use --detailed flag to see old/new values for changes");B.newline(),console.log(B.theme.secondary("Run"),B.bold("unreal pull"),B.theme.secondary("or"),B.bold("unreal push"),B.theme.secondary("to sync your code schema with the database.")),B.newline()}else{let G=I0(Y),j=_4(G,Q);U4(j)}await J.close()}catch(X){B.error("Error:",X),process.exit(1)}});import{Command as V4}from"@commander-js/extra-typings";import{promises as O4,existsSync as E4}from"node:fs";import c0 from"node:path";import{promises as K4}from"node:fs";import{parseTableDefinition as q4,parseFieldDefinition as W4,parseIndexDefinition as H4}from"unreal-orm";var N1={};function v1($){return{name:$,type:"NORMAL",schemafull:!0,drop:!1,permissions:N1,fields:[],indexes:[],events:[]}}async function S1($){let X=await K4.readFile($,"utf-8");return A4(X)}function A4($){let X=new Map,Q=$.split(";").map((J)=>J.trim()).filter((J)=>J.length>0);for(let J of Q){let Z=J.replace(/\s+/g," ").trim();if(Z.toUpperCase().startsWith("DEFINE TABLE")){let Y=q4(J);if(Y.name)X.set(Y.name,{name:Y.name,type:Y.type??"NORMAL",schemafull:Y.schemafull??!0,drop:Y.drop??!1,permissions:Y.permissions??N1,viewQuery:Y.viewQuery,fields:[],indexes:[],events:[]})}else if(Z.toUpperCase().startsWith("DEFINE FIELD")){let Y=W4(J),_=J.match(/ON\s+(?:TABLE\s+)?(\w+)/i);if(_?.[1]){let G=_[1],j=X.get(G);if(!j)j=v1(G),X.set(G,j);j.fields.push(Y)}}else if(Z.toUpperCase().startsWith("DEFINE INDEX")){let Y=H4(J),_=J.match(/ON\s+(?:TABLE\s+)?(\w+)/i);if(_?.[1]){let G=_[1],j=X.get(G);if(!j)j=v1(G),X.set(G,j);j.indexes.push(Y)}}}return{tables:Array.from(X.values())}}Y0();m();var T1=new V4("mermaid").description("Generate a Mermaid ERD diagram from TypeScript schema, database, or .surql file").option("-o, --output <path>","Output file path for .mermaid file").option("-s, --schema-dir <path>","Schema directory path (for --code mode)").option("-c, --config <path>","Path to config file").option("--stdout","Print to stdout instead of file").option("--code","Use TypeScript schema definitions").option("--db","Use database connection (introspect live database)").option("--surql <path>","Use a .surql schema file").option("--url <url>","Database URL (implies --db)").option("-u, --username <username>","Database username").option("-p, --password <password>","Database password").option("-n, --namespace <namespace>","Database namespace").option("-d, --database <database>","Database name").option("--auth-level <level>","Auth level: root, namespace, or database").option("--embedded <mode>","Use embedded mode (memory or file path)").action(async($)=>{B.header("Mermaid ERD Generator","Visualize your schema");let X=B.spin("Loading configuration...");try{let Q=await r($.config);if(Q)X.succeed("Configuration loaded");else X.info("No configuration file found (using defaults/flags)");let J=$.output;if(!J&&!$.stdout)X.stop(),J=await O0("Output file path:",Q?c0.join(Q.path,"schema.mermaid"):"./unreal/schema.mermaid");let Z=$.url||$.username||$.password||$.namespace||$.database||$.embedded,Y;if($.surql)Y="surql";else if($.db||Z)Y="database";else if($.code)Y="code";if(!Y){if(X.stop(),Y=await S0("Schema source:",[{title:"TypeScript schema (./unreal/tables/)",value:"code"},{title:"Database (introspect live database)",value:"database"},{title:"SurrealQL file (.surql)",value:"surql"}]),!Y)process.exit(0)}let _;if(Y==="code"){X.stop();let j=await n({cliOutput:$.schemaDir,config:Q});X.start(`Extracting schema from ${j}...`),_=await $0(j),X.succeed(`Found ${_.tables.length} tables from TypeScript schema`)}else if(Y==="database"){X.stop();let j=await o({cliOptions:{url:$.url,username:$.username,password:$.password,namespace:$.namespace,database:$.database,authLevel:$.authLevel,embedded:$.embedded},config:Q,skipAutoConfig:!0});if(!j)B.error("Failed to establish database connection."),process.exit(1);X.start("Introspecting database schema...");try{_=await e(j),X.succeed(`Found ${_.tables.length} tables from database`)}finally{await j.close()}}else{let j=typeof $.surql==="string"?$.surql:"";if(!j)X.stop(),j=await O0("Path to .surql file:","./schema.surql");let U=c0.resolve(process.cwd(),j);if(!E4(U))X.fail(`File not found: ${U}`),process.exit(1);X.start(`Parsing ${j}...`),_=await S1(U),X.succeed(`Found ${_.tables.length} tables from .surql file`)}X.start("Generating Mermaid diagram...");let G=M4(_);if(X.succeed("Diagram generated"),$.stdout)console.log(`
225
- ${G}`);else{let j=c0.resolve(process.cwd(),J||"./unreal/schema.mermaid");await O4.writeFile(j,G),B.success(`Saved to ${j}`),B.dim(`Tip: Preview with VS Code Mermaid extension,
226
- https://mermiko.com, or https://mermaid.live`)}}catch(Q){X.fail("Failed to generate diagram"),B.error(Q instanceof Error?Q.message:String(Q)),process.exit(1)}});function M4($){let X=["erDiagram"],Q=$.tables.filter((G)=>G.type==="NORMAL"),J=$.tables.filter((G)=>G.type==="RELATION"),Z=$.tables.filter((G)=>G.type==="VIEW"),Y=[],_=new Map;for(let G of $.tables){let j=new Set;for(let U of G.indexes){let W=U.columns[0];if(U.unique&&U.columns.length===1&&W)j.add(W)}if(j.size>0&&G.name)_.set(G.name,j)}if(Q.length>0){X.push(" %% === TABLES ===");for(let G of Q){let j=k1(G,_);X.push(...j.lines),Y.push(...j.relationships)}}if(J.length>0){X.push(" %% === RELATIONS (Graph Edges) ===");for(let G of J){let j=D4(G,_);X.push(...j.lines),Y.push(...j.relationships)}}if(Z.length>0){X.push(" %% === VIEWS ===");for(let G of Z){let j=k1(G,_);X.push(...j.lines)}}if(Y.length>0)X.push(""),X.push(" %% === RELATIONSHIPS ==="),X.push(...Y);return X.join(`
227
- `)}function k1($,X){let Q=[],J=[],Z=$.fields.filter((G)=>!G.name.includes(".")&&!G.name.includes("[")),Y=u($.name),_=X.get($.name)??new Set;Q.push(` ${Y} {`);for(let G of Z){let j=q0(G.type),U=u(G.name),W=C1(G,_),q=G.name==="id"||G.assert?.includes("!= NONE")?`*${U}`:U,z=` ${j} ${q}`;if(W)z+=` ${W}`;Q.push(z);let K=G.type.match(/^record<(\w+)>$/);if(K?.[1]){let A=u(K[1]),D=G.assert?.includes("!= NONE"),O=_.has(G.name),V=D?"--":"..",E=`${O?"|":"}"}${D?"|":"o"}`,w="||";J.push(` ${Y} ${E}${V}|| ${A} : "${G.name}"`)}}return Q.push(" }"),Q.push(""),{lines:Q,relationships:J}}function D4($,X){let Q=[],J=[],Z=u($.name),Y=X.get($.name)??new Set,_=$.fields.find((H)=>H.name==="in"),G=$.fields.find((H)=>H.name==="out"),j=_?.type.match(/^record<(\w+)>$/)?.[1],U=G?.type.match(/^record<(\w+)>$/)?.[1],W=$.fields.filter((H)=>H.name!=="in"&&H.name!=="out"&&!H.name.includes(".")&&!H.name.includes("["));if(W.length===0){if(j&&U){let H=u(j),q=u(U);J.push(` ${H} }|--|{ ${q} : "${$.name}"`)}return{lines:[],relationships:J}}if(Q.push(` ${Z} {`),_&&j)Q.push(` ${u(j)} *in FK`);if(G&&U)Q.push(` ${u(U)} *out FK`);for(let H of W){let q=q0(H.type),z=u(H.name),K=C1(H,Y),D=H.name==="id"||H.assert?.includes("!= NONE")?`*${z}`:z,O=` ${q} ${D}`;if(K)O+=` ${K}`;Q.push(O)}if(Q.push(" }"),Q.push(""),j&&U){let H=u(j),q=u(U);J.push(` ${H} ||--o{ ${Z} : "in"`),J.push(` ${Z} }o--|| ${q} : "out"`)}return{lines:Q,relationships:J}}function u($){return $.replace(/[^a-zA-Z0-9_]/g,"_")}function q0($){if($.startsWith("record<"))return"record";if($==="record")return"record";if($.startsWith("array<")){let Q=$.slice(6,-1);return`array_${q0(Q)}`}if($==="array")return"array";if($.startsWith("option<")){let Q=$.slice(7,-1);return q0(Q)}if($.startsWith("set<")){let Q=$.slice(4,-1);return`set_${q0(Q)}`}if($.startsWith("geometry<"))return`geo_${$.slice(9,-1)}`;if($.startsWith("range<"))return"range";if($.includes("|"))return"enum";return{string:"string",int:"int",float:"float",bool:"bool",datetime:"datetime",duration:"duration",decimal:"decimal",number:"number",object:"object",array:"array",any:"any",bytes:"bytes",uuid:"uuid",ulid:"ulid",geometry:"geometry",point:"point",line:"line",polygon:"polygon",multipoint:"multipoint",multiline:"multiline",multipolygon:"multipolygon",collection:"collection",null:"null",none:"none"}[$]||$}function C1($,X){let Q=[];if($.name==="id")Q.push("PK");if($.type.startsWith("record<"))Q.push("FK");if(X.has($.name))Q.push("UK");return Q.join(",")}m();import{Command as R4}from"@commander-js/extra-typings";var x1="https://github.com/Jimpex/unreal-orm",y1=new R4("github").description("Open the UnrealORM GitHub repository").action(async()=>{let{exec:$}=await import("node:child_process"),{platform:X}=await import("node:os"),Q=X()==="win32"?"start":X()==="darwin"?"open":"xdg-open";$(`${Q} ${x1}`,(J)=>{if(J)B.info(`Visit: ${x1}`)})});m();import{Command as I4}from"@commander-js/extra-typings";var b1="https://unreal-orm.jimpex.dev",g1=new I4("docs").description("Open the UnrealORM documentation").action(async()=>{let{exec:$}=await import("node:child_process"),{platform:X}=await import("node:os"),Q=X()==="win32"?"start":X()==="darwin"?"open":"xdg-open";$(`${Q} ${b1}`,(J)=>{if(J)B.info(`Visit: ${b1}`)})});import{Command as S4}from"@commander-js/extra-typings";m();var f1="\x1B[?25l",d0="\x1B[?25h";function h1(){process.stdout.write("\x1B[?1049h\x1B[?7l\x1B[H\x1B[J")}function l0(){process.stdout.write("\x1B[?7h\x1B[?1049l")}function c(){let $=process.stdout.rows||24;process.stdout.write(`\x1B[1;${$}r\x1B[H\x1B[J`)}function J0(){let $=process.stdout.rows||24;process.stdout.write(`\x1B[1;${$}r\x1B[H\x1B[J`)}async function d(){return new Promise(($)=>{let X=process.stdin,Q=X.isRaw;X.setRawMode(!0),X.resume(),X.setEncoding("utf8");let J=(Z)=>{if(X.setRawMode(Q),X.pause(),X.removeListener("data",J),Z==="\x03")process.stdout.write("\x1B[?25h"),process.exit(0);$(Z)};X.once("data",J)})}var r0="\x1BCANCEL";async function P0($,X=""){process.stdout.write("\x1B[?25h"),process.stdout.write($);let Q=X;if(X)process.stdout.write(X);return new Promise((J)=>{let Z=process.stdin;Z.setRawMode(!0),Z.resume(),Z.setEncoding("utf8");let Y=(_)=>{if(_==="\x03")process.stdout.write("\x1B[?25h"),process.exit(0);if(_==="\r"||_===`
228
- `)Z.setRawMode(!1),Z.pause(),Z.removeListener("data",Y),process.stdout.write(`
229
- `),process.stdout.write("\x1B[?25l"),J(Q);else if(_==="\x1B")Z.setRawMode(!1),Z.pause(),Z.removeListener("data",Y),process.stdout.write(`
230
- `),process.stdout.write("\x1B[?25l"),J(r0);else if(_===""||_==="\b"){if(Q.length>0)Q=Q.slice(0,-1),process.stdout.write("\b \b")}else if(_>=" "&&_<="~")Q+=_,process.stdout.write(_)};Z.on("data",Y)})}function F0($){return $===r0}async function w0($,X){let Q=$.split(`
231
- `),J=0,Z=0,Y=0,_=-1,G=process.stdout.rows||24,j=process.stdout.columns||80,U=G-6,W=3,H=(O,V)=>{process.stdout.write(`\x1B[${O};${V}H`)},q=(O,V)=>{H(O,1),process.stdout.write(`\x1B[2K${V}`)},z=()=>{J0(),console.log(` \x1B[1m${X.title}\x1B[0m`),console.log(` \x1B[90m${X.subtitle}\x1B[0m`),console.log(`\x1B[90m${"─".repeat(Math.min(j,80))}\x1B[0m`);let O=Math.min(Y+U,Q.length);for(let V=Y;V<O;V++)K(V);for(let V=O-Y;V<U;V++)console.log("\x1B[90m ~\x1B[0m");D(),_=Y},K=(O)=>{let V=Q[O]??"",R=String(O+1).padStart(3," "),I=O===J,E=V;if(E.length>j-8)E=`${E.slice(0,j-11)}...`;if(I){let w=E.slice(0,Z),P=E[Z]??" ",F=E.slice(Z+1);console.log(`\x1B[90m${R}\x1B[0m \x1B[36m${w}\x1B[7m${P}\x1B[0m${F}`)}else console.log(`\x1B[90m${R}\x1B[0m ${E}`)},A=(O)=>{let V=Y;if(J<Y)Y=J;else if(J>=Y+U)Y=J-U+1;if(Y!==V||Y!==_){z();return}if(O!==void 0&&O!==J&&O>=Y&&O<Y+U){let N=W+1+(O-Y),v=Q[O]??"",C=String(O+1).padStart(3," "),S=v;if(S.length>j-8)S=`${S.slice(0,j-11)}...`;q(N,`\x1B[90m${C}\x1B[0m ${S}`)}let R=W+1+(J-Y),I=Q[J]??"",E=String(J+1).padStart(3," "),w=I;if(w.length>j-8)w=`${w.slice(0,j-11)}...`;let P=w.slice(0,Z),F=w[Z]??" ",L=w.slice(Z+1);q(R,`\x1B[90m${E}\x1B[0m \x1B[36m${P}\x1B[7m${F}\x1B[0m${L}`),D()},D=()=>{let O=W+U+1,V=Math.min(Y+U,Q.length),R=`Ln ${J+1}, Col ${Z+1}`,I=Q.length>U?` | ${Y+1}-${V}/${Q.length}`:"";q(O,`\x1B[90m ${R}${I} | Ctrl+S save | Esc cancel\x1B[0m`)};return process.stdout.write("\x1B[?25h"),z(),new Promise((O)=>{let V=process.stdin;V.setRawMode(!0),V.resume(),V.setEncoding("utf8");let R=(E)=>{V.setRawMode(!1),V.pause(),V.removeListener("data",I),process.stdout.write("\x1B[?25l"),O(E)},I=(E)=>{let w=J,P=Q[J]??"",F=!1;if(E==="\x03")process.stdout.write("\x1B[?25h"),process.exit(0);if(E==="\x13"){R(Q.join(`
232
- `));return}if(E==="\x1B"&&E.length===1){R(r0);return}if(E==="\x1B[A"){if(J>0)J--,Z=Math.min(Z,(Q[J]??"").length)}else if(E==="\x1B[B"){if(J<Q.length-1)J++,Z=Math.min(Z,(Q[J]??"").length)}else if(E==="\x1B[C"){if(Z<P.length)Z++;else if(J<Q.length-1)J++,Z=0}else if(E==="\x1B[D"){if(Z>0)Z--;else if(J>0)J--,Z=(Q[J]??"").length}else if(E==="\x1B[H"||E==="\x1B[1~")Z=0;else if(E==="\x1B[F"||E==="\x1B[4~")Z=P.length;else if(E==="\x1B[5~")J=Math.max(0,J-U),Z=Math.min(Z,(Q[J]??"").length);else if(E==="\x1B[6~")J=Math.min(Q.length-1,J+U),Z=Math.min(Z,(Q[J]??"").length);else if(E==="\r"||E===`
233
- `){let L=P.slice(0,Z),N=P.slice(Z);Q[J]=L,Q.splice(J+1,0,N),J++,Z=0,F=!0}else if(E===""||E==="\b"){if(Z>0)Q[J]=P.slice(0,Z-1)+P.slice(Z),Z--;else if(J>0){let L=Q[J-1]??"";Z=L.length,Q[J-1]=L+P,Q.splice(J,1),J--,F=!0}}else if(E==="\x1B[3~"){if(Z<P.length)Q[J]=P.slice(0,Z)+P.slice(Z+1);else if(J<Q.length-1)Q[J]=`${P}${Q[J+1]??""}`,Q.splice(J+1,1),F=!0}else if(E==="\t")Q[J]=`${P.slice(0,Z)} ${P.slice(Z)}`,Z+=2;else if(E.length===1&&E>=" "&&E<="~")Q[J]=`${P.slice(0,Z)}${E}${P.slice(Z)}`,Z++;if(F)z();else A(w)};V.on("data",I)})}import _0 from"chalk";var M={primary:_0.hex("#FF00A0"),dim:_0.gray,highlight:_0.cyan,success:_0.green,warning:_0.yellow,error:_0.red},k={topLeft:"┌",topRight:"┐",bottomLeft:"└",bottomRight:"┘",horizontal:"─",vertical:"│",teeRight:"├",teeLeft:"┤",teeDown:"┬",teeUp:"┴",cross:"┼"};import P4 from"chalk";function s($,X){let Q=Math.min(process.stdout.columns||80,80);if(console.log(M.primary.bold(` ${$}`)),X)console.log(M.dim(` ${X}`));console.log(M.dim(k.horizontal.repeat(Q)))}function p1($,X,Q,J){console.log(M.dim(` ${k.topLeft}${Q.map((Y)=>k.horizontal.repeat(Y)).join(k.teeDown)}${k.topRight}`));let Z=$.map((Y,_)=>m1(Y,Q[_]??10)).join(M.dim(k.vertical));console.log(`${M.dim(` ${k.vertical}`)}${P4.bold(Z)}${M.dim(k.vertical)}`),console.log(M.dim(` ${k.teeRight}${Q.map((Y)=>k.horizontal.repeat(Y)).join(k.cross)}${k.teeLeft}`));for(let Y=0;Y<X.length;Y++){let _=X[Y];if(!_)continue;let j=Y===J?M.primary("▸ "):" ",U=_.map((W,H)=>m1(W,Q[H]??10)).join(M.dim(k.vertical));console.log(`${j}${M.dim(k.vertical)}${U}${M.dim(k.vertical)}`)}console.log(M.dim(` ${k.bottomLeft}${Q.map((Y)=>k.horizontal.repeat(Y)).join(k.teeUp)}${k.bottomRight}`))}function m1($,X){let Q=L0($);if(Q.length>=X)return`${F4($,X-1)}…`;return $+" ".repeat(X-Q.length)}function F4($,X){let Q=0,J=0,Z=/\x1b\[[0-9;]*m/g;while(J<$.length&&Q<X){Z.lastIndex=J;let _=Z.exec($);if(_&&_.index===J)J=Z.lastIndex;else Q++,J++}let Y=$.slice(0,J);if($.includes("\x1B[")&&!Y.endsWith("\x1B[0m"))return`${Y}\x1B[0m`;return Y}function L0($){return $.replace(/\x1b\[[0-9;]*m/g,"")}async function W0($){c(),s("Confirm",""),console.log(""),console.log(M.warning(` ${$}`)),console.log(""),console.log(M.dim(" y yes • n no"));let X=await d();return X==="y"||X==="Y"}async function u1($,X){return c(),s("Confirm Action",""),console.log(""),console.log(M.warning(` ${$}`)),console.log(""),await P0(" > ")===X}async function H0($){c(),s("Error",""),console.log(""),console.log(M.error(` ${$}`)),console.log(""),console.log(M.dim(" Press any key to continue...")),await d()}async function c1($){c(),s("Success",""),console.log(""),console.log(M.success(` ${$}`)),console.log(""),console.log(M.dim(" Press any key to continue...")),await d()}function l1($){if($==="timeout")return M.warning("timeout");if($==="?")return M.dim("?");if($>=1e6)return M.highlight(`${($/1e6).toFixed(1)}M`);if($>=1000)return M.highlight(`${($/1000).toFixed(1)}K`);return M.highlight(String($))}function A0($,X=40){if($===void 0||$===null)return M.dim("null");if(Array.isArray($)){if($.length===0)return M.dim("[]");if($.length<=5){let Z=`[${$.map((Y)=>d1(Y)).join(", ")}]`;if(Z.length>X)return M.dim(`[${$.length} items]`);return M.dim(Z)}return M.dim(`[${$.length} items]`)}if(typeof $==="object"){let J=String($);if(J!=="[object Object]"){if(J.length>X)return M.dim(`${J.slice(0,X-3)}...`);return M.dim(J)}let Z=Object.keys($);if(Z.length===0)try{let Y=JSON.stringify($);if(Y.length>X)return M.dim(`${Y.slice(0,X-3)}...`);return M.dim(Y)}catch{return M.dim("{}")}if(Z.length<=5){let _=`{${Z.map((G)=>`${G}: ${d1($[G])}`).join(", ")}}`;if(_.length>X)return M.dim(`{${Z.length} fields}`);return M.dim(_)}return M.dim(`{${Z.length} fields}`)}if(typeof $==="boolean")return $?M.success("true"):M.error("false");if(typeof $==="number")return M.highlight(String($));let Q=String($).replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t");if(Q.length>X)return`${Q.slice(0,X-3)}...`;return Q}function d1($){if($===void 0||$===null)return"null";if(Array.isArray($))return`[${$.length}]`;if(typeof $==="object"){let X=String($);if(X!=="[object Object]"){if(X.length>15)return`${X.slice(0,12)}...`;return X}let Q=Object.keys($);if(Q.length===0)try{let J=JSON.stringify($);if(J.length>15)return`${J.slice(0,12)}...`;return J}catch{return"{}"}return`{${Q.length}}`}if(typeof $==="string"){let X=$.replace(/\n/g,"\\n");if(X.length>15)return`"${X.slice(0,12)}..."`;return`"${X}"`}return String($)}function o0($){if(!$)return"";try{return JSON.parse($)}catch{if($==="true")return!0;if($==="false")return!1;if($==="null")return null;let X=Number($);if(!Number.isNaN(X)&&$.trim()!=="")return X;return $}}async function r1($,X,Q){let J=Q.id?String(Q.id):"unknown",Z=0,Y={...Q},_={...Q},G=[],j=()=>Object.keys(_).sort((q,z)=>{if(q==="id")return-1;if(z==="id")return 1;return q.localeCompare(z)}),U=(q)=>{for(let z of G){if(z.type==="add"&&z.key===q)return"added";if(z.type==="edit"&&z.key===q)return"edited";if(z.type==="remove"&&z.key===q)return"removed"}return null},W=()=>G.length>0,H=(q=!1)=>{if(q)c();else J0();let z=process.stdout.rows||24,K=process.stdout.columns||80,A=Math.max(3,z-5),D=G.length,O=D>0?`${D} changes • s save • x discard`:X;s(`Record: ${J}`,O);let V=j(),R=Math.min(Math.max(...V.map((F)=>F.length),8),20),I=K-R-6,E=0;if(Z>=A)E=Z-A+1;let w=Math.min(E+A,V.length);for(let F=E;F<w;F++){let L=V[F];if(!L)continue;let N=_[L],v=F===Z,C=U(L),S=v?M.primary("▸ "):" ",b;if(C==="added")b=M.success(`+ ${L.slice(0,R-2).padEnd(R-2)}`);else if(C==="edited")b=M.warning(`~ ${L.slice(0,R-2).padEnd(R-2)}`);else if(C==="removed")b=M.error(`- ${L.slice(0,R-2).padEnd(R-2)}`);else if(v)b=M.primary.bold(L.slice(0,R).padEnd(R));else b=M.highlight(L.slice(0,R).padEnd(R));let e1=A0(N,I);console.log(`${S}${b} ${e1}`)}let P=V.length>A?`${E+1}-${w}/${V.length} • `:"";console.log(M.dim(` ${P}↑↓ nav • e edit • + add • - del • d delete • b back • q quit`))};H(!0);while(!0){let q=await d(),z=j();if(q==="q"){if(W()){if(!await W0("Discard unsaved changes?")){H();continue}}throw Error("EXIT")}if(q==="b"||q==="\x1B"){if(W()){if(!await W0("Discard unsaved changes?")){H();continue}}return"back"}if(q==="\x1B[A"||q==="k")Z=Math.max(0,Z-1),H();else if(q==="\x1B[B"||q==="j")Z=Math.min(z.length-1,Z+1),H();else if(q==="e"||q==="\r"||q===`
234
- `){let K=z[Z];if(K&&K!=="id"){let A=_[K],D=await w4(K,A);if(D!==void 0){let O=Y[K];if(JSON.stringify(D)!==JSON.stringify(O)){let V=G.findIndex((R)=>R.type==="edit"&&R.key===K);if(V>=0)G.splice(V,1);G.push({type:"edit",key:K,oldValue:O,newValue:D})}else{let V=G.findIndex((R)=>R.type==="edit"&&R.key===K);if(V>=0)G.splice(V,1)}_[K]=D}H()}else if(K==="id")await H0("Cannot edit the id field"),H()}else if(q==="+"||q==="="){let K=await L4();if(K)_[K.key]=K.value,G.push({type:"add",key:K.key,value:K.value});H()}else if(q==="-"||q==="_"){let K=z[Z];if(K&&K!=="id"){if(U(K)==="added"){let D=G.findIndex((O)=>O.type==="add"&&O.key===K);if(D>=0)G.splice(D,1);delete _[K]}else G.push({type:"remove",key:K,oldValue:Y[K]}),delete _[K];Z=Math.min(Z,z.length-2),H()}else if(K==="id")await H0("Cannot remove the id field"),H()}else if(q==="u"||q==="U"){let K=G.pop();if(K){if(K.type==="edit")_[K.key]=K.oldValue;else if(K.type==="add")delete _[K.key];else if(K.type==="remove")_[K.key]=K.oldValue}H()}else if(q==="x"||q==="X"){if(W()){if(await W0("Discard all changes?")){G.length=0;for(let A of Object.keys(_))delete _[A];Object.assign(_,Y)}H()}}else if(q==="s"||q==="S"){if(W()){if(await W0(`Save ${G.length} change${G.length>1?"s":""}?`))try{let A=[],D=[],O={};for(let R of G)if(R.type==="edit"||R.type==="add"){let I=`p_${R.key.replace(/[^a-zA-Z0-9]/g,"_")}`;A.push(`\`${R.key}\` = $${I}`),O[I]=R.type==="edit"?R.newValue:R.value}else if(R.type==="remove")D.push(`\`${R.key}\``);let V=`UPDATE ${J}`;if(A.length>0)V+=` SET ${A.join(", ")}`;if(D.length>0)V+=` UNSET ${D.join(", ")}`;V+=` TIMEOUT ${$.timeout}s`,await $.db.query(V,O).collect(),G.length=0;for(let R of Object.keys(Y))delete Y[R];Object.assign(Y,_),await c1("Changes saved successfully")}catch(A){await H0(`Failed to save: ${A instanceof Error?A.message:String(A)}`)}H()}}else if(q==="d"||q==="D")if(await u1(`Delete record ${J}? Type "delete" to confirm:`,"delete"))try{return await $.db.query(`DELETE ${J} TIMEOUT ${$.timeout}s`).collect(),"deleted"}catch(A){await H0(`Failed to delete: ${A instanceof Error?A.message:String(A)}`),H()}else H()}}async function w4($,X){let Q=typeof X==="object"?JSON.stringify(X,null,2):String(X??""),J=await w0(Q,{title:`Edit: ${$}`,subtitle:"Arrows to move • Type to edit • Ctrl+S save • Esc cancel"});if(F0(J))return;return o0(J)}async function L4(){let $=await w0("",{title:"Add Field - Enter Name",subtitle:"Type field name • Ctrl+S confirm • Esc cancel"});if(F0($)||!$.trim())return null;let X=await w0("",{title:`Add Field: ${$.trim()}`,subtitle:"Type value (JSON for objects/arrays) • Ctrl+S confirm • Esc cancel"});if(F0(X))return null;return{key:$.trim(),value:o0(X)}}async function o1($,X,Q){let J=0,Z=0,Y=[],_=[],G=!0,j=!0,U=Q,W=async()=>{G=!0,H(j),j=!1;let[q]=await $.db.query(`SELECT * FROM \`${X}\` LIMIT ${$.pageSize} START ${J} TIMEOUT ${$.timeout}s`).collect();Y=q||[];let z=new Set(["id"]);for(let K of Y)for(let A of Object.keys(K))z.add(A);_=Array.from(z),Z=Math.min(Z,Math.max(0,Y.length-1)),G=!1,H()},H=(q=!1)=>{if(q)c();else J0();let z=process.stdout.rows||24,K=Math.max(3,z-9),A=Y.slice(0,K),D=U!==void 0?` (${U} records)`:"",O=Math.floor(J/$.pageSize)+1,V=U!==void 0?Math.ceil(U/$.pageSize):"?";if(s(`Table: ${X}${D}`,`Page ${O}/${V}`),G){console.log(M.dim(" Loading records..."));return}if(Y.length===0){console.log(M.dim(" No records found.")),console.log(M.dim(" b back • q quit"));return}let R=process.stdout.columns||80,I=Math.floor(R/_.length)-1,E=_.map((N)=>{let v=N.length;for(let C of A){let S=A0(C[N]);v=Math.max(v,L0(S).length)}return Math.min(v+2,I)}),w=A.map((N,v)=>_.map((C)=>{let S=A0(N[C]);return v===Z?M.primary(L0(S)):S}));p1(_,w,E,Z);let P=J+A.length,F=U!==void 0?`/${U}`:"",L=J+Z+1;console.log(M.dim(` ${L}${F} • ${J+1}-${P} • ↑↓ select • Enter view • ←→ page • b back • q quit`))};await W();while(!0){let q=await d();if(q==="q")throw Error("EXIT");if(q==="b"||q==="\x1B")return;if(q==="\x1B[A"||q==="k"){if(Z>0)Z--,H();else if(J>0)J=Math.max(0,J-$.pageSize),Z=$.pageSize-1,await W()}else if(q==="\x1B[B"||q==="j"){if(Z<Y.length-1)Z++,H();else if(U===void 0||J+Y.length<U)J+=$.pageSize,Z=0,await W()}else if(q==="\x1B[D"||q==="h"||q==="["){if(J>0)J=Math.max(0,J-$.pageSize),Z=0,await W()}else if(q==="\x1B[C"||q==="l"||q==="]"){if(U===void 0||J+$.pageSize<U)J+=$.pageSize,Z=0,await W()}else if(q==="\r"||q===`
235
- `){let z=Y[Z];if(z)if(await r1($,X,z)==="deleted")await W();else await W()}else if(q==="g")J=0,Z=0,await W();else if(q==="G"&&U!==void 0)J=Math.max(0,Math.floor((U-1)/$.pageSize)*$.pageSize),Z=0,await W()}}async function v4($,X,Q){return $.query(`SELECT count() FROM \`${X}\` GROUP ALL TIMEOUT ${Q}s`).collect().then((J)=>J[0]?.[0]?.count??"timeout").catch(()=>"timeout")}async function N4($,X,Q,J,Z){let Y=0,_=async()=>{while(Y<X.length){let j=Y++,U=X[j];if(!U)continue;U.count=await v4($,U.name,Q),Z()}},G=Array.from({length:Math.min(J,X.length)},()=>_());await Promise.all(G)}async function s1($){let X=0,Q=[],J=[],Z=!0,Y="",_=async()=>{Z=!0,G(!0);let[U]=await $.db.query("INFO FOR DB").collect(),W=U;if(!W?.tables)throw Error("Failed to retrieve database info");Q=Object.keys(W.tables).sort().map((q)=>({name:q,count:"?"})),J=Q,Z=!1,G(),await N4($.db,Q,$.timeout,$.concurrency,G)},G=(U=!1)=>{if(U)c();else J0();let W=process.stdout.rows||24,H=Math.max(5,W-4),q=Y?` ${M.highlight(`[filter: ${Y}]`)}`:"";if(s(`Tables${q}`,`${J.length} tables`),Z){console.log(M.dim(" Loading tables..."));return}if(J.length===0){if(Y)console.log(M.warning(` No tables matching "${Y}"`)),console.log(M.dim(" Press Esc to clear filter"));else console.log(M.warning(" No tables found in database."));return}let z=0;if(X>=H)z=X-H+1;let K=Math.min(z+H,J.length);for(let D=z;D<K;D++){let O=J[D];if(!O)continue;let V=D===X,R=V?M.primary("▸ "):" ",I=V?M.primary.bold(O.name):O.name,E=l1(O.count);console.log(`${R}${I} ${M.dim("(")}${E}${M.dim(")")}`)}let A=J.length>H?`${z+1}-${K}/${J.length} • `:"";console.log(M.dim(` ${A}↑↓ nav • Enter select • / filter • r refresh • q quit`))};if(await _(),J.length===0&&!Y){await d();return}let j=()=>{if(Y){let U=Y.toLowerCase();J=Q.filter((W)=>W.name.toLowerCase().includes(U))}else J=Q;X=Math.min(X,Math.max(0,J.length-1))};while(!0){let U=await d();if(U==="q")throw Error("EXIT");if(U==="\x1B"){if(Y)Y="",j(),G();else throw Error("EXIT");continue}if(U==="\x1B[A"||U==="k")X=Math.max(0,X-1),G();else if(U==="\x1B[B"||U==="j")X=Math.min(J.length-1,X+1),G();else if(U==="\r"||U===`
236
- `){let W=J[X];if(W){let H=typeof W.count==="number"?W.count:void 0;await o1($,W.name,H),G(!0)}}else if(U==="g")X=0,G();else if(U==="G")X=J.length-1,G();else if(U==="r"||U==="R")Y="",X=0,await _();else if(U==="/")G(),Y=await P0(M.highlight(" Filter: ")),j(),G()}}var k4=15,s0=5,i1=100,i0=3,a0=5,a1=new S4("view").description("Interactive TUI for browsing database tables and records").option("--url <url>","Database URL").option("-u, --username <username>","Database username").option("-p, --password <password>","Database password").option("-n, --namespace <namespace>","Database namespace").option("-d, --database <database>","Database name").option("--auth-level <level>","Authentication level (root, namespace, database)").option("-e, --embedded <mode>","Use embedded mode (memory or file path)").option("--page-size <size>",`Records per page (${s0}-${i1}, default: auto)`).option("--timeout <seconds>",`Query timeout in seconds (default: ${i0})`).option("--concurrency <count>",`Max concurrent count queries (default: ${a0})`).action(async($)=>{B.header("Database Viewer","Interactive table browser");let X=await r(),Q=await o({cliOptions:{url:$.url,username:$.username,password:$.password,namespace:$.namespace,database:$.database,authLevel:$.authLevel,embedded:$.embedded},config:X,skipAutoConfig:!0});if(!Q)return;let J=process.stdout.rows||24,Z=k4;if($.pageSize){let j=Number.parseInt($.pageSize,10);if(!Number.isNaN(j))Z=Math.max(s0,Math.min(i1,j))}else Z=Math.max(s0,Math.min(J-10,30));let Y=$.timeout?Math.max(1,Number.parseInt($.timeout,10)||i0):i0,_=$.concurrency?Math.max(1,Number.parseInt($.concurrency,10)||a0):a0,G={db:Q,pageSize:Z,terminalHeight:J,timeout:Y,concurrency:_};h1(),process.stdout.write(f1);try{await s1(G)}catch(j){if(j instanceof Error&&j.message==="EXIT");else{process.stdout.write(d0),l0(),B.error(j instanceof Error?j.message:String(j)),await Q.close();return}}process.stdout.write(d0),l0(),await Q.close()});m();import{createRequire as T4}from"node:module";var n0=T4(import.meta.url);function C4(){try{return n0("../../package.json").version}catch{return"unknown"}}var t0=C4(),x4="https://registry.npmjs.org";async function y4($,X="alpha"){try{let Q=await fetch(`${x4}/${$}`);if(!Q.ok)return null;let J=await Q.json();return J["dist-tags"][X]??J["dist-tags"].latest??null}catch{return null}}async function n1($,X,Q="alpha"){let J=await y4($,Q);if(!J)return null;return{current:X,latest:J,isOutdated:J!==X}}function b4(){try{let $=n0.resolve("unreal-orm/package.json",{paths:[process.cwd()]});return n0($).version}catch{return null}}async function t1(){if(process.env.CI||process.env.UNREAL_SKIP_UPDATE_CHECK)return;try{let[$,X]=await Promise.all([n1("@unreal-orm/cli",t0,"alpha"),(async()=>{let J=b4();if(!J)return null;return n1("unreal-orm",J,"alpha")})()]),Q=[];if($?.isOutdated)Q.push(` @unreal-orm/cli: ${B.dim($.current)} → ${B.theme.success($.latest)}`);if(X?.isOutdated)Q.push(` unreal-orm: ${B.dim(X.current)} → ${B.theme.success(X.latest)}`);if(Q.length>0){B.newline(),B.warn("\uD83D\uDCE6 Updates available:");for(let J of Q)console.log(J);B.dim("\n Run `npm update @unreal-orm/cli unreal-orm` to update\n")}}catch{}}var a=new g4().name("unreal").description("UnrealORM CLI for SurrealDB").version(t0).hook("postAction",async()=>{await t1()});a.addCommand(Z1);a.addCommand(R1);a.addCommand(P1);a.addCommand(L1);a.addCommand(T1);a.addCommand(g1);a.addCommand(a1);a.addCommand(y1);a.parse();
226
+ `).length,X=J-Q;if(X>0)return`+${X} lines`;if(X<0)return`${X} lines`;return"content changed"}function K4($){let J={total:$.length,tables:0,fields:0,indexes:0};for(let Q of $)if(Q.type.startsWith("table_"))J.tables++;else if(Q.type.startsWith("field_"))J.fields++;else if(Q.type.startsWith("index_"))J.indexes++;return J}function z4($){let{added:J,removed:Q,modified:X,unchanged:Z}=$;if(Y.header("Schema Diff Summary"),J.length>0){console.log(Y.theme.success(`+ Added (${J.length}):`));for(let _ of J)console.log(` + ${_}`);Y.newline()}if(Q.length>0){console.log(Y.theme.error(`- Removed (${Q.length}):`));for(let _ of Q)console.log(` - ${_}`);Y.newline()}if(X.length>0){console.log(Y.theme.warning(`~ Modified (${X.length}):`));for(let _ of X)console.log(` ~ ${_.filename}`),console.log(Y.dim(` Database: from database (${U4(_)})`)),console.log(Y.dim(" Code: current file"));Y.newline()}if(Z.length>0){console.log(Y.theme.dim(`= Unchanged (${Z.length}):`));let _=Z.join(", ");console.log(Y.dim(` ${_}`)),Y.newline()}if(J.length>0||Q.length>0||X.length>0)console.log(Y.bold(`${J.length+Q.length+X.length} file(s) changed, ${Z.length} unchanged`)),Y.newline(),Y.info('Run "unreal pull" to sync your code schema with the database.');else Y.success("Code schema is in sync with database")}var L1=new Z4().name("diff").description("Compare TypeScript schema with database schema").option("--url <url>","Database URL (e.g., http://localhost:8000)").option("-u, --username <username>","Database username").option("-p, --password <password>","Database password").option("-n, --namespace <namespace>","Database namespace").option("-d, --database <database>","Database name").option("--auth-level <level>","Auth level: root, namespace, or database").option("-s, --schema-dir <path>","Schema directory path").option("-e, --embedded <mode>","Use embedded mode (memory or file path)").option("--detailed","Show detailed field-level changes").action(async($)=>{try{Y.header("UnrealORM Diff","Compare code vs database schema");let J=await o(),Q=await n({cliOutput:$.schemaDir,config:J}),X=await s({cliOptions:{url:$.url,username:$.username,password:$.password,namespace:$.namespace,database:$.database,authLevel:$.authLevel,embedded:$.embedded},config:J,skipAutoConfig:!0});if(!X)Y.error("Failed to establish database connection."),process.exit(1);let Z=Y.spin("Introspecting database schema"),B=await $0(X);Z.succeed("Introspected database schema");let _=null;if(d0(Q)){let G=Y.spin("Parsing code schema");try{_=await Q0(Q),G.succeed("Parsed code schema")}catch(j){G.fail("Could not parse code schema"),Y.warn(`${j instanceof Error?j.message:String(j)}`),Y.dim("Falling back to file-based comparison"),Y.newline()}}if(_){let G=_4(B,_);if(G.length===0){Y.success("No schema differences detected. Code and database schemas are in sync."),await X.close();return}let j=K4(G),U=w1(G,$.detailed);Y.divider(),Y.info("Schema Changes"),Y.divider(),Y.newline(),console.log(U);let W=[];if(j.fields>0)W.push(Y.theme.warning(`${j.fields} field(s)`));if(j.indexes>0)W.push(Y.theme.info(`${j.indexes} index(es)`));if(j.tables>0)W.push(Y.theme.primary(`${j.tables} table(s)`));if(Y.newline(),console.log(Y.bold(`${j.total} change(s): ${W.join(", ")}`)),!$.detailed&&j.total>0)Y.newline(),Y.dim("Tip: Use --detailed flag to see old/new values for changes");Y.newline(),console.log(Y.theme.secondary("Run"),Y.bold("unreal pull"),Y.theme.secondary("or"),Y.bold("unreal push"),Y.theme.secondary("to sync your code schema with the database.")),Y.newline()}else{let G=I0(B),j=j4(G,Q);z4(j)}await X.close()}catch(J){Y.error("Error:",J),process.exit(1)}});import{Command as E4}from"@commander-js/extra-typings";import{promises as M4,existsSync as D4}from"node:fs";import l0 from"node:path";import{promises as q4}from"node:fs";import{parseTableDefinition as H4,parseFieldDefinition as W4,parseIndexDefinition as A4}from"unreal-orm";var N1={};function v1($){return{name:$,type:"NORMAL",schemafull:!0,drop:!1,permissions:N1,fields:[],indexes:[],events:[]}}async function S1($){let J=await q4.readFile($,"utf-8");return O4(J)}function V4($){let J=$.replace(/--.*$/gm,"");return J=J.replace(/\/\*[\s\S]*?\*\//g,""),J}function O4($){let J=new Map,X=V4($).split(";").map((Z)=>Z.trim()).filter((Z)=>Z.length>0);for(let Z of X){let _=Z.replace(/\s+/g," ").trim().toUpperCase();try{if(_.startsWith("DEFINE TABLE")){let G=H4(Z);if(G.name)J.set(G.name,{name:G.name,type:G.type??"NORMAL",schemafull:G.schemafull??!0,drop:G.drop??!1,permissions:G.permissions??N1,viewQuery:G.viewQuery,fields:[],indexes:[],events:[]});else C("DEFINE TABLE","Could not extract table name",`Statement: ${Z.slice(0,80)}...`)}else if(_.startsWith("DEFINE FIELD")){let G=W4(Z),j=Z.match(/\bON\s+(?:TABLE\s+)?(\w+)/i);if(j?.[1]){let U=j[1],W=J.get(U);if(!W)W=v1(U),J.set(U,W);W.fields.push(G)}else C("DEFINE FIELD","Could not extract table name from field definition",`Statement: ${Z.slice(0,80)}...`)}else if(_.startsWith("DEFINE INDEX")){let G=A4(Z),j=Z.match(/\bON\s+(?:TABLE\s+)?(\w+)/i);if(j?.[1]){let U=j[1],W=J.get(U);if(!W)W=v1(U),J.set(U,W);W.indexes.push(G)}else C("DEFINE INDEX","Could not extract table name from index definition",`Statement: ${Z.slice(0,80)}...`)}else if(_.startsWith("DEFINE EVENT"))C("DEFINE EVENT","Events are not yet supported","Event definitions will be skipped");else if(_.startsWith("DEFINE ANALYZER"));else if(_.startsWith("DEFINE FUNCTION"))C("DEFINE FUNCTION","Custom functions are not yet supported","Function definitions will be skipped");else if(_.startsWith("DEFINE PARAM"))C("DEFINE PARAM","Database parameters are not yet supported","Parameter definitions will be skipped");else if(_.startsWith("DEFINE USER"));else if(_.startsWith("DEFINE ACCESS"));else if(_.startsWith("OPTION"));}catch(G){let j=G instanceof Error?G.message:String(G);C("Parse error",j,`Statement: ${Z.slice(0,80)}${Z.length>80?"...":""}`)}}return{tables:Array.from(J.values())}}G0();u();var T1=new E4("mermaid").description("Generate a Mermaid ERD diagram from TypeScript schema, database, or .surql file").option("-o, --output <path>","Output file path for .mermaid file").option("-s, --schema-dir <path>","Schema directory path (for --code mode)").option("-c, --config <path>","Path to config file").option("--stdout","Print to stdout instead of file").option("--code","Use TypeScript schema definitions").option("--db","Use database connection (introspect live database)").option("--surql <path>","Use a .surql schema file").option("--url <url>","Database URL (implies --db)").option("-u, --username <username>","Database username").option("-p, --password <password>","Database password").option("-n, --namespace <namespace>","Database namespace").option("-d, --database <database>","Database name").option("--auth-level <level>","Auth level: root, namespace, or database").option("--embedded <mode>","Use embedded mode (memory or file path)").action(async($)=>{Y.header("Mermaid ERD Generator","Visualize your schema"),_0();let J=Y.spin("Loading configuration...");try{let Q=await o($.config);if(Q)J.succeed("Configuration loaded");else J.info("No configuration file found (using defaults/flags)");let X=$.output;if(!X&&!$.stdout)J.stop(),X=await E0("Output file path:",Q?l0.join(Q.path,"schema.mermaid"):"./unreal/schema.mermaid");let Z=$.url||$.username||$.password||$.namespace||$.database||$.embedded,B;if($.surql)B="surql";else if($.db||Z)B="database";else if($.code)B="code";if(!B){if(J.stop(),B=await S0("Schema source:",[{title:"TypeScript schema (./unreal/tables/)",value:"code"},{title:"Database (introspect live database)",value:"database"},{title:"SurrealQL file (.surql)",value:"surql"}]),!B)process.exit(0)}let _;if(B==="code"){J.stop();let j=await n({cliOutput:$.schemaDir,config:Q});J.start(`Extracting schema from ${j}...`),_=await Q0(j),J.succeed(`Found ${_.tables.length} tables from TypeScript schema`)}else if(B==="database"){J.stop();let j=await s({cliOptions:{url:$.url,username:$.username,password:$.password,namespace:$.namespace,database:$.database,authLevel:$.authLevel,embedded:$.embedded},config:Q,skipAutoConfig:!0});if(!j)Y.error("Failed to establish database connection."),process.exit(1);J.start("Introspecting database schema...");try{_=await $0(j),J.succeed(`Found ${_.tables.length} tables from database`)}finally{await j.close()}}else{let j=typeof $.surql==="string"?$.surql:"";if(!j)J.stop(),j=await E0("Path to .surql file:","./schema.surql");let U=l0.resolve(process.cwd(),j);if(!D4(U))J.fail(`File not found: ${U}`),process.exit(1);J.start(`Parsing ${j}...`),_=await S1(U),J.succeed(`Found ${_.tables.length} tables from .surql file`)}J.start("Generating Mermaid diagram...");let G=R4(_);if(J.succeed("Diagram generated"),$.stdout)console.log(`
227
+ ${G}`);else{let j=l0.resolve(process.cwd(),X||"./unreal/schema.mermaid");await M4.writeFile(j,G),Y.success(`Saved to ${j}`),Y.dim(`Tip: Preview with VS Code Mermaid extension,
228
+ https://mermiko.com, or https://mermaid.live`)}e()}catch(Q){J.fail("Failed to generate diagram"),Y.error(Q instanceof Error?Q.message:String(Q)),process.exit(1)}});function R4($){let J=["erDiagram"],Q=$.tables.filter((G)=>G.type==="NORMAL"),X=$.tables.filter((G)=>G.type==="RELATION"),Z=$.tables.filter((G)=>G.type==="VIEW"),B=[],_=new Map;for(let G of $.tables){let j=new Set;for(let U of G.indexes){let W=U.columns[0];if(U.unique&&U.columns.length===1&&W)j.add(W)}if(j.size>0&&G.name)_.set(G.name,j)}if(Q.length>0){J.push(" %% === TABLES ===");for(let G of Q){let j=k1(G,_);J.push(...j.lines),B.push(...j.relationships)}}if(X.length>0){J.push(" %% === RELATIONS (Graph Edges) ===");for(let G of X){let j=I4(G,_);J.push(...j.lines),B.push(...j.relationships)}}if(Z.length>0){J.push(" %% === VIEWS ===");for(let G of Z){let j=k1(G,_);J.push(...j.lines)}}if(B.length>0)J.push(""),J.push(" %% === RELATIONSHIPS ==="),J.push(...B);return J.join(`
229
+ `)}function k1($,J){let Q=[],X=[],Z=$.fields.filter((G)=>!G.name.includes(".")&&!G.name.includes("[")),B=c($.name),_=J.get($.name)??new Set;Q.push(` ${B} {`);for(let G of Z){let j=H0(G.type),U=c(G.name),W=C1(G,_),q=G.name==="id"||G.assert?.includes("!= NONE")?`*${U}`:U,H=` ${j} ${q}`;if(W)H+=` ${W}`;Q.push(H);let K=G.type.match(/^record<(\w+)>$/);if(K?.[1]){let z=c(K[1]),M=G.assert?.includes("!= NONE"),E=_.has(G.name),A=M?"--":"..",O=`${E?"|":"}"}${M?"|":"o"}`,w="||";X.push(` ${B} ${O}${A}|| ${z} : "${G.name}"`)}}return Q.push(" }"),Q.push(""),{lines:Q,relationships:X}}function I4($,J){let Q=[],X=[],Z=c($.name),B=J.get($.name)??new Set,_=$.fields.find((V)=>V.name==="in"),G=$.fields.find((V)=>V.name==="out"),j=_?.type.match(/^record<(\w+)>$/)?.[1],U=G?.type.match(/^record<(\w+)>$/)?.[1],W=$.fields.filter((V)=>V.name!=="in"&&V.name!=="out"&&!V.name.includes(".")&&!V.name.includes("["));if(W.length===0){if(j&&U){let V=c(j),q=c(U);X.push(` ${V} }|--|{ ${q} : "${$.name}"`)}return{lines:[],relationships:X}}if(Q.push(` ${Z} {`),_&&j)Q.push(` ${c(j)} *in FK`);if(G&&U)Q.push(` ${c(U)} *out FK`);for(let V of W){let q=H0(V.type),H=c(V.name),K=C1(V,B),M=V.name==="id"||V.assert?.includes("!= NONE")?`*${H}`:H,E=` ${q} ${M}`;if(K)E+=` ${K}`;Q.push(E)}if(Q.push(" }"),Q.push(""),j&&U){let V=c(j),q=c(U);X.push(` ${V} ||--o{ ${Z} : "in"`),X.push(` ${Z} }o--|| ${q} : "out"`)}return{lines:Q,relationships:X}}function c($){return $.replace(/[^a-zA-Z0-9_]/g,"_")}function H0($){if($.startsWith("record<"))return"record";if($==="record")return"record";if($.startsWith("array<")){let Q=$.slice(6,-1);return`array_${H0(Q)}`}if($==="array")return"array";if($.startsWith("option<")){let Q=$.slice(7,-1);return H0(Q)}if($.startsWith("set<")){let Q=$.slice(4,-1);return`set_${H0(Q)}`}if($.startsWith("geometry<"))return`geo_${$.slice(9,-1)}`;if($.startsWith("range<"))return"range";if($.includes("|"))return"enum";return{string:"string",int:"int",float:"float",bool:"bool",datetime:"datetime",duration:"duration",decimal:"decimal",number:"number",object:"object",array:"array",any:"any",bytes:"bytes",uuid:"uuid",ulid:"ulid",geometry:"geometry",point:"point",line:"line",polygon:"polygon",multipoint:"multipoint",multiline:"multiline",multipolygon:"multipolygon",collection:"collection",null:"null",none:"none"}[$]||$}function C1($,J){let Q=[];if($.name==="id")Q.push("PK");if($.type.startsWith("record<"))Q.push("FK");if(J.has($.name))Q.push("UK");return Q.join(",")}u();import{Command as P4}from"@commander-js/extra-typings";var x1="https://github.com/Jimpex/unreal-orm",y1=new P4("github").description("Open the UnrealORM GitHub repository").action(async()=>{let{exec:$}=await import("node:child_process"),{platform:J}=await import("node:os"),Q=J()==="win32"?"start":J()==="darwin"?"open":"xdg-open";$(`${Q} ${x1}`,(X)=>{if(X)Y.info(`Visit: ${x1}`)})});u();import{Command as F4}from"@commander-js/extra-typings";var b1="https://unreal-orm.jimpex.dev",g1=new F4("docs").description("Open the UnrealORM documentation").action(async()=>{let{exec:$}=await import("node:child_process"),{platform:J}=await import("node:os"),Q=J()==="win32"?"start":J()==="darwin"?"open":"xdg-open";$(`${Q} ${b1}`,(X)=>{if(X)Y.info(`Visit: ${b1}`)})});import{Command as T4}from"@commander-js/extra-typings";u();var f1="\x1B[?25l",r0="\x1B[?25h";function h1(){process.stdout.write("\x1B[?1049h\x1B[?7l\x1B[H\x1B[J")}function o0(){process.stdout.write("\x1B[?7h\x1B[?1049l")}function d(){let $=process.stdout.rows||24;process.stdout.write(`\x1B[1;${$}r\x1B[H\x1B[J`)}function X0(){let $=process.stdout.rows||24;process.stdout.write(`\x1B[1;${$}r\x1B[H\x1B[J`)}async function l(){return new Promise(($)=>{let J=process.stdin,Q=J.isRaw;J.setRawMode(!0),J.resume(),J.setEncoding("utf8");let X=(Z)=>{if(J.setRawMode(Q),J.pause(),J.removeListener("data",X),Z==="\x03")process.stdout.write("\x1B[?25h"),process.exit(0);$(Z)};J.once("data",X)})}var s0="\x1BCANCEL";async function P0($,J=""){process.stdout.write("\x1B[?25h"),process.stdout.write($);let Q=J;if(J)process.stdout.write(J);return new Promise((X)=>{let Z=process.stdin;Z.setRawMode(!0),Z.resume(),Z.setEncoding("utf8");let B=(_)=>{if(_==="\x03")process.stdout.write("\x1B[?25h"),process.exit(0);if(_==="\r"||_===`
230
+ `)Z.setRawMode(!1),Z.pause(),Z.removeListener("data",B),process.stdout.write(`
231
+ `),process.stdout.write("\x1B[?25l"),X(Q);else if(_==="\x1B")Z.setRawMode(!1),Z.pause(),Z.removeListener("data",B),process.stdout.write(`
232
+ `),process.stdout.write("\x1B[?25l"),X(s0);else if(_===""||_==="\b"){if(Q.length>0)Q=Q.slice(0,-1),process.stdout.write("\b \b")}else if(_>=" "&&_<="~")Q+=_,process.stdout.write(_)};Z.on("data",B)})}function F0($){return $===s0}async function w0($,J){let Q=$.split(`
233
+ `),X=0,Z=0,B=0,_=-1,G=process.stdout.rows||24,j=process.stdout.columns||80,U=G-6,W=3,V=(E,A)=>{process.stdout.write(`\x1B[${E};${A}H`)},q=(E,A)=>{V(E,1),process.stdout.write(`\x1B[2K${A}`)},H=()=>{X0(),console.log(` \x1B[1m${J.title}\x1B[0m`),console.log(` \x1B[90m${J.subtitle}\x1B[0m`),console.log(`\x1B[90m${"─".repeat(Math.min(j,80))}\x1B[0m`);let E=Math.min(B+U,Q.length);for(let A=B;A<E;A++)K(A);for(let A=E-B;A<U;A++)console.log("\x1B[90m ~\x1B[0m");M(),_=B},K=(E)=>{let A=Q[E]??"",R=String(E+1).padStart(3," "),I=E===X,O=A;if(O.length>j-8)O=`${O.slice(0,j-11)}...`;if(I){let w=O.slice(0,Z),P=O[Z]??" ",F=O.slice(Z+1);console.log(`\x1B[90m${R}\x1B[0m \x1B[36m${w}\x1B[7m${P}\x1B[0m${F}`)}else console.log(`\x1B[90m${R}\x1B[0m ${O}`)},z=(E)=>{let A=B;if(X<B)B=X;else if(X>=B+U)B=X-U+1;if(B!==A||B!==_){H();return}if(E!==void 0&&E!==X&&E>=B&&E<B+U){let N=W+1+(E-B),v=Q[E]??"",x=String(E+1).padStart(3," "),S=v;if(S.length>j-8)S=`${S.slice(0,j-11)}...`;q(N,`\x1B[90m${x}\x1B[0m ${S}`)}let R=W+1+(X-B),I=Q[X]??"",O=String(X+1).padStart(3," "),w=I;if(w.length>j-8)w=`${w.slice(0,j-11)}...`;let P=w.slice(0,Z),F=w[Z]??" ",L=w.slice(Z+1);q(R,`\x1B[90m${O}\x1B[0m \x1B[36m${P}\x1B[7m${F}\x1B[0m${L}`),M()},M=()=>{let E=W+U+1,A=Math.min(B+U,Q.length),R=`Ln ${X+1}, Col ${Z+1}`,I=Q.length>U?` | ${B+1}-${A}/${Q.length}`:"";q(E,`\x1B[90m ${R}${I} | Ctrl+S save | Esc cancel\x1B[0m`)};return process.stdout.write("\x1B[?25h"),H(),new Promise((E)=>{let A=process.stdin;A.setRawMode(!0),A.resume(),A.setEncoding("utf8");let R=(O)=>{A.setRawMode(!1),A.pause(),A.removeListener("data",I),process.stdout.write("\x1B[?25l"),E(O)},I=(O)=>{let w=X,P=Q[X]??"",F=!1;if(O==="\x03")process.stdout.write("\x1B[?25h"),process.exit(0);if(O==="\x13"){R(Q.join(`
234
+ `));return}if(O==="\x1B"&&O.length===1){R(s0);return}if(O==="\x1B[A"){if(X>0)X--,Z=Math.min(Z,(Q[X]??"").length)}else if(O==="\x1B[B"){if(X<Q.length-1)X++,Z=Math.min(Z,(Q[X]??"").length)}else if(O==="\x1B[C"){if(Z<P.length)Z++;else if(X<Q.length-1)X++,Z=0}else if(O==="\x1B[D"){if(Z>0)Z--;else if(X>0)X--,Z=(Q[X]??"").length}else if(O==="\x1B[H"||O==="\x1B[1~")Z=0;else if(O==="\x1B[F"||O==="\x1B[4~")Z=P.length;else if(O==="\x1B[5~")X=Math.max(0,X-U),Z=Math.min(Z,(Q[X]??"").length);else if(O==="\x1B[6~")X=Math.min(Q.length-1,X+U),Z=Math.min(Z,(Q[X]??"").length);else if(O==="\r"||O===`
235
+ `){let L=P.slice(0,Z),N=P.slice(Z);Q[X]=L,Q.splice(X+1,0,N),X++,Z=0,F=!0}else if(O===""||O==="\b"){if(Z>0)Q[X]=P.slice(0,Z-1)+P.slice(Z),Z--;else if(X>0){let L=Q[X-1]??"";Z=L.length,Q[X-1]=L+P,Q.splice(X,1),X--,F=!0}}else if(O==="\x1B[3~"){if(Z<P.length)Q[X]=P.slice(0,Z)+P.slice(Z+1);else if(X<Q.length-1)Q[X]=`${P}${Q[X+1]??""}`,Q.splice(X+1,1),F=!0}else if(O==="\t")Q[X]=`${P.slice(0,Z)} ${P.slice(Z)}`,Z+=2;else if(O.length===1&&O>=" "&&O<="~")Q[X]=`${P.slice(0,Z)}${O}${P.slice(Z)}`,Z++;if(F)H();else z(w)};A.on("data",I)})}import j0 from"chalk";var D={primary:j0.hex("#FF00A0"),dim:j0.gray,highlight:j0.cyan,success:j0.green,warning:j0.yellow,error:j0.red},k={topLeft:"┌",topRight:"┐",bottomLeft:"└",bottomRight:"┘",horizontal:"─",vertical:"│",teeRight:"├",teeLeft:"┤",teeDown:"┬",teeUp:"┴",cross:"┼"};import w4 from"chalk";function i($,J){let Q=Math.min(process.stdout.columns||80,80);if(console.log(D.primary.bold(` ${$}`)),J)console.log(D.dim(` ${J}`));console.log(D.dim(k.horizontal.repeat(Q)))}function u1($,J,Q,X){console.log(D.dim(` ${k.topLeft}${Q.map((B)=>k.horizontal.repeat(B)).join(k.teeDown)}${k.topRight}`));let Z=$.map((B,_)=>m1(B,Q[_]??10)).join(D.dim(k.vertical));console.log(`${D.dim(` ${k.vertical}`)}${w4.bold(Z)}${D.dim(k.vertical)}`),console.log(D.dim(` ${k.teeRight}${Q.map((B)=>k.horizontal.repeat(B)).join(k.cross)}${k.teeLeft}`));for(let B=0;B<J.length;B++){let _=J[B];if(!_)continue;let j=B===X?D.primary("▸ "):" ",U=_.map((W,V)=>m1(W,Q[V]??10)).join(D.dim(k.vertical));console.log(`${j}${D.dim(k.vertical)}${U}${D.dim(k.vertical)}`)}console.log(D.dim(` ${k.bottomLeft}${Q.map((B)=>k.horizontal.repeat(B)).join(k.teeUp)}${k.bottomRight}`))}function m1($,J){let Q=L0($);if(Q.length>=J)return`${L4($,J-1)}…`;return $+" ".repeat(J-Q.length)}function L4($,J){let Q=0,X=0,Z=/\x1b\[[0-9;]*m/g;while(X<$.length&&Q<J){Z.lastIndex=X;let _=Z.exec($);if(_&&_.index===X)X=Z.lastIndex;else Q++,X++}let B=$.slice(0,X);if($.includes("\x1B[")&&!B.endsWith("\x1B[0m"))return`${B}\x1B[0m`;return B}function L0($){return $.replace(/\x1b\[[0-9;]*m/g,"")}async function W0($){d(),i("Confirm",""),console.log(""),console.log(D.warning(` ${$}`)),console.log(""),console.log(D.dim(" y yes • n no"));let J=await l();return J==="y"||J==="Y"}async function p1($,J){return d(),i("Confirm Action",""),console.log(""),console.log(D.warning(` ${$}`)),console.log(""),await P0(" > ")===J}async function A0($){d(),i("Error",""),console.log(""),console.log(D.error(` ${$}`)),console.log(""),console.log(D.dim(" Press any key to continue...")),await l()}async function c1($){d(),i("Success",""),console.log(""),console.log(D.success(` ${$}`)),console.log(""),console.log(D.dim(" Press any key to continue...")),await l()}function l1($){if($==="timeout")return D.warning("timeout");if($==="?")return D.dim("?");if($>=1e6)return D.highlight(`${($/1e6).toFixed(1)}M`);if($>=1000)return D.highlight(`${($/1000).toFixed(1)}K`);return D.highlight(String($))}function V0($,J=40){if($===void 0||$===null)return D.dim("null");if(Array.isArray($)){if($.length===0)return D.dim("[]");if($.length<=5){let Z=`[${$.map((B)=>d1(B)).join(", ")}]`;if(Z.length>J)return D.dim(`[${$.length} items]`);return D.dim(Z)}return D.dim(`[${$.length} items]`)}if(typeof $==="object"){let X=String($);if(X!=="[object Object]"){if(X.length>J)return D.dim(`${X.slice(0,J-3)}...`);return D.dim(X)}let Z=Object.keys($);if(Z.length===0)try{let B=JSON.stringify($);if(B.length>J)return D.dim(`${B.slice(0,J-3)}...`);return D.dim(B)}catch{return D.dim("{}")}if(Z.length<=5){let _=`{${Z.map((G)=>`${G}: ${d1($[G])}`).join(", ")}}`;if(_.length>J)return D.dim(`{${Z.length} fields}`);return D.dim(_)}return D.dim(`{${Z.length} fields}`)}if(typeof $==="boolean")return $?D.success("true"):D.error("false");if(typeof $==="number")return D.highlight(String($));let Q=String($).replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t");if(Q.length>J)return`${Q.slice(0,J-3)}...`;return Q}function d1($){if($===void 0||$===null)return"null";if(Array.isArray($))return`[${$.length}]`;if(typeof $==="object"){let J=String($);if(J!=="[object Object]"){if(J.length>15)return`${J.slice(0,12)}...`;return J}let Q=Object.keys($);if(Q.length===0)try{let X=JSON.stringify($);if(X.length>15)return`${X.slice(0,12)}...`;return X}catch{return"{}"}return`{${Q.length}}`}if(typeof $==="string"){let J=$.replace(/\n/g,"\\n");if(J.length>15)return`"${J.slice(0,12)}..."`;return`"${J}"`}return String($)}function i0($){if(!$)return"";try{return JSON.parse($)}catch{if($==="true")return!0;if($==="false")return!1;if($==="null")return null;let J=Number($);if(!Number.isNaN(J)&&$.trim()!=="")return J;return $}}async function r1($,J,Q){let X=Q.id?String(Q.id):"unknown",Z=0,B={...Q},_={...Q},G=[],j=()=>Object.keys(_).sort((q,H)=>{if(q==="id")return-1;if(H==="id")return 1;return q.localeCompare(H)}),U=(q)=>{for(let H of G){if(H.type==="add"&&H.key===q)return"added";if(H.type==="edit"&&H.key===q)return"edited";if(H.type==="remove"&&H.key===q)return"removed"}return null},W=()=>G.length>0,V=(q=!1)=>{if(q)d();else X0();let H=process.stdout.rows||24,K=process.stdout.columns||80,z=Math.max(3,H-5),M=G.length,E=M>0?`${M} changes • s save • x discard`:J;i(`Record: ${X}`,E);let A=j(),R=Math.min(Math.max(...A.map((F)=>F.length),8),20),I=K-R-6,O=0;if(Z>=z)O=Z-z+1;let w=Math.min(O+z,A.length);for(let F=O;F<w;F++){let L=A[F];if(!L)continue;let N=_[L],v=F===Z,x=U(L),S=v?D.primary("▸ "):" ",g;if(x==="added")g=D.success(`+ ${L.slice(0,R-2).padEnd(R-2)}`);else if(x==="edited")g=D.warning(`~ ${L.slice(0,R-2).padEnd(R-2)}`);else if(x==="removed")g=D.error(`- ${L.slice(0,R-2).padEnd(R-2)}`);else if(v)g=D.primary.bold(L.slice(0,R).padEnd(R));else g=D.highlight(L.slice(0,R).padEnd(R));let e1=V0(N,I);console.log(`${S}${g} ${e1}`)}let P=A.length>z?`${O+1}-${w}/${A.length} • `:"";console.log(D.dim(` ${P}↑↓ nav • e edit • + add • - del • d delete • b back • q quit`))};V(!0);while(!0){let q=await l(),H=j();if(q==="q"){if(W()){if(!await W0("Discard unsaved changes?")){V();continue}}throw Error("EXIT")}if(q==="b"||q==="\x1B"){if(W()){if(!await W0("Discard unsaved changes?")){V();continue}}return"back"}if(q==="\x1B[A"||q==="k")Z=Math.max(0,Z-1),V();else if(q==="\x1B[B"||q==="j")Z=Math.min(H.length-1,Z+1),V();else if(q==="e"||q==="\r"||q===`
236
+ `){let K=H[Z];if(K&&K!=="id"){let z=_[K],M=await v4(K,z);if(M!==void 0){let E=B[K];if(JSON.stringify(M)!==JSON.stringify(E)){let A=G.findIndex((R)=>R.type==="edit"&&R.key===K);if(A>=0)G.splice(A,1);G.push({type:"edit",key:K,oldValue:E,newValue:M})}else{let A=G.findIndex((R)=>R.type==="edit"&&R.key===K);if(A>=0)G.splice(A,1)}_[K]=M}V()}else if(K==="id")await A0("Cannot edit the id field"),V()}else if(q==="+"||q==="="){let K=await N4();if(K)_[K.key]=K.value,G.push({type:"add",key:K.key,value:K.value});V()}else if(q==="-"||q==="_"){let K=H[Z];if(K&&K!=="id"){if(U(K)==="added"){let M=G.findIndex((E)=>E.type==="add"&&E.key===K);if(M>=0)G.splice(M,1);delete _[K]}else G.push({type:"remove",key:K,oldValue:B[K]}),delete _[K];Z=Math.min(Z,H.length-2),V()}else if(K==="id")await A0("Cannot remove the id field"),V()}else if(q==="u"||q==="U"){let K=G.pop();if(K){if(K.type==="edit")_[K.key]=K.oldValue;else if(K.type==="add")delete _[K.key];else if(K.type==="remove")_[K.key]=K.oldValue}V()}else if(q==="x"||q==="X"){if(W()){if(await W0("Discard all changes?")){G.length=0;for(let z of Object.keys(_))delete _[z];Object.assign(_,B)}V()}}else if(q==="s"||q==="S"){if(W()){if(await W0(`Save ${G.length} change${G.length>1?"s":""}?`))try{let z=[],M=[],E={};for(let R of G)if(R.type==="edit"||R.type==="add"){let I=`p_${R.key.replace(/[^a-zA-Z0-9]/g,"_")}`;z.push(`\`${R.key}\` = $${I}`),E[I]=R.type==="edit"?R.newValue:R.value}else if(R.type==="remove")M.push(`\`${R.key}\``);let A=`UPDATE ${X}`;if(z.length>0)A+=` SET ${z.join(", ")}`;if(M.length>0)A+=` UNSET ${M.join(", ")}`;A+=` TIMEOUT ${$.timeout}s`,await $.db.query(A,E).collect(),G.length=0;for(let R of Object.keys(B))delete B[R];Object.assign(B,_),await c1("Changes saved successfully")}catch(z){await A0(`Failed to save: ${z instanceof Error?z.message:String(z)}`)}V()}}else if(q==="d"||q==="D")if(await p1(`Delete record ${X}? Type "delete" to confirm:`,"delete"))try{return await $.db.query(`DELETE ${X} TIMEOUT ${$.timeout}s`).collect(),"deleted"}catch(z){await A0(`Failed to delete: ${z instanceof Error?z.message:String(z)}`),V()}else V()}}async function v4($,J){let Q=typeof J==="object"?JSON.stringify(J,null,2):String(J??""),X=await w0(Q,{title:`Edit: ${$}`,subtitle:"Arrows to move • Type to edit • Ctrl+S save • Esc cancel"});if(F0(X))return;return i0(X)}async function N4(){let $=await w0("",{title:"Add Field - Enter Name",subtitle:"Type field name • Ctrl+S confirm • Esc cancel"});if(F0($)||!$.trim())return null;let J=await w0("",{title:`Add Field: ${$.trim()}`,subtitle:"Type value (JSON for objects/arrays) • Ctrl+S confirm • Esc cancel"});if(F0(J))return null;return{key:$.trim(),value:i0(J)}}async function o1($,J,Q){let X=0,Z=0,B=[],_=[],G=!0,j=!0,U=Q,W=async()=>{G=!0,V(j),j=!1;let[q]=await $.db.query(`SELECT * FROM \`${J}\` LIMIT ${$.pageSize} START ${X} TIMEOUT ${$.timeout}s`).collect();B=q||[];let H=new Set(["id"]);for(let K of B)for(let z of Object.keys(K))H.add(z);_=Array.from(H),Z=Math.min(Z,Math.max(0,B.length-1)),G=!1,V()},V=(q=!1)=>{if(q)d();else X0();let H=process.stdout.rows||24,K=Math.max(3,H-9),z=B.slice(0,K),M=U!==void 0?` (${U} records)`:"",E=Math.floor(X/$.pageSize)+1,A=U!==void 0?Math.ceil(U/$.pageSize):"?";if(i(`Table: ${J}${M}`,`Page ${E}/${A}`),G){console.log(D.dim(" Loading records..."));return}if(B.length===0){console.log(D.dim(" No records found.")),console.log(D.dim(" b back • q quit"));return}let R=process.stdout.columns||80,I=Math.floor(R/_.length)-1,O=_.map((N)=>{let v=N.length;for(let x of z){let S=V0(x[N]);v=Math.max(v,L0(S).length)}return Math.min(v+2,I)}),w=z.map((N,v)=>_.map((x)=>{let S=V0(N[x]);return v===Z?D.primary(L0(S)):S}));u1(_,w,O,Z);let P=X+z.length,F=U!==void 0?`/${U}`:"",L=X+Z+1;console.log(D.dim(` ${L}${F} • ${X+1}-${P} • ↑↓ select • Enter view • ←→ page • b back • q quit`))};await W();while(!0){let q=await l();if(q==="q")throw Error("EXIT");if(q==="b"||q==="\x1B")return;if(q==="\x1B[A"||q==="k"){if(Z>0)Z--,V();else if(X>0)X=Math.max(0,X-$.pageSize),Z=$.pageSize-1,await W()}else if(q==="\x1B[B"||q==="j"){if(Z<B.length-1)Z++,V();else if(U===void 0||X+B.length<U)X+=$.pageSize,Z=0,await W()}else if(q==="\x1B[D"||q==="h"||q==="["){if(X>0)X=Math.max(0,X-$.pageSize),Z=0,await W()}else if(q==="\x1B[C"||q==="l"||q==="]"){if(U===void 0||X+$.pageSize<U)X+=$.pageSize,Z=0,await W()}else if(q==="\r"||q===`
237
+ `){let H=B[Z];if(H)if(await r1($,J,H)==="deleted")await W();else await W()}else if(q==="g")X=0,Z=0,await W();else if(q==="G"&&U!==void 0)X=Math.max(0,Math.floor((U-1)/$.pageSize)*$.pageSize),Z=0,await W()}}async function S4($,J,Q){return $.query(`SELECT count() FROM \`${J}\` GROUP ALL TIMEOUT ${Q}s`).collect().then((X)=>X[0]?.[0]?.count??"timeout").catch(()=>"timeout")}async function k4($,J,Q,X,Z){let B=0,_=async()=>{while(B<J.length){let j=B++,U=J[j];if(!U)continue;U.count=await S4($,U.name,Q),Z()}},G=Array.from({length:Math.min(X,J.length)},()=>_());await Promise.all(G)}async function s1($){let J=0,Q=[],X=[],Z=!0,B="",_=async()=>{Z=!0,G(!0);let[U]=await $.db.query("INFO FOR DB").collect(),W=U;if(!W?.tables)throw Error("Failed to retrieve database info");Q=Object.keys(W.tables).sort().map((q)=>({name:q,count:"?"})),X=Q,Z=!1,G(),await k4($.db,Q,$.timeout,$.concurrency,G)},G=(U=!1)=>{if(U)d();else X0();let W=process.stdout.rows||24,V=Math.max(5,W-4),q=B?` ${D.highlight(`[filter: ${B}]`)}`:"";if(i(`Tables${q}`,`${X.length} tables`),Z){console.log(D.dim(" Loading tables..."));return}if(X.length===0){if(B)console.log(D.warning(` No tables matching "${B}"`)),console.log(D.dim(" Press Esc to clear filter"));else console.log(D.warning(" No tables found in database."));return}let H=0;if(J>=V)H=J-V+1;let K=Math.min(H+V,X.length);for(let M=H;M<K;M++){let E=X[M];if(!E)continue;let A=M===J,R=A?D.primary("▸ "):" ",I=A?D.primary.bold(E.name):E.name,O=l1(E.count);console.log(`${R}${I} ${D.dim("(")}${O}${D.dim(")")}`)}let z=X.length>V?`${H+1}-${K}/${X.length} • `:"";console.log(D.dim(` ${z}↑↓ nav • Enter select • / filter • r refresh • q quit`))};if(await _(),X.length===0&&!B){await l();return}let j=()=>{if(B){let U=B.toLowerCase();X=Q.filter((W)=>W.name.toLowerCase().includes(U))}else X=Q;J=Math.min(J,Math.max(0,X.length-1))};while(!0){let U=await l();if(U==="q")throw Error("EXIT");if(U==="\x1B"){if(B)B="",j(),G();else throw Error("EXIT");continue}if(U==="\x1B[A"||U==="k")J=Math.max(0,J-1),G();else if(U==="\x1B[B"||U==="j")J=Math.min(X.length-1,J+1),G();else if(U==="\r"||U===`
238
+ `){let W=X[J];if(W){let V=typeof W.count==="number"?W.count:void 0;await o1($,W.name,V),G(!0)}}else if(U==="g")J=0,G();else if(U==="G")J=X.length-1,G();else if(U==="r"||U==="R")B="",J=0,await _();else if(U==="/")G(),B=await P0(D.highlight(" Filter: ")),j(),G()}}var C4=15,a0=5,i1=100,n0=3,t0=5,a1=new T4("view").description("Interactive TUI for browsing database tables and records").option("--url <url>","Database URL").option("-u, --username <username>","Database username").option("-p, --password <password>","Database password").option("-n, --namespace <namespace>","Database namespace").option("-d, --database <database>","Database name").option("--auth-level <level>","Authentication level (root, namespace, database)").option("-e, --embedded <mode>","Use embedded mode (memory or file path)").option("--page-size <size>",`Records per page (${a0}-${i1}, default: auto)`).option("--timeout <seconds>",`Query timeout in seconds (default: ${n0})`).option("--concurrency <count>",`Max concurrent count queries (default: ${t0})`).action(async($)=>{Y.header("Database Viewer","Interactive table browser");let J=await o(),Q=await s({cliOptions:{url:$.url,username:$.username,password:$.password,namespace:$.namespace,database:$.database,authLevel:$.authLevel,embedded:$.embedded},config:J,skipAutoConfig:!0});if(!Q)return;let X=process.stdout.rows||24,Z=C4;if($.pageSize){let j=Number.parseInt($.pageSize,10);if(!Number.isNaN(j))Z=Math.max(a0,Math.min(i1,j))}else Z=Math.max(a0,Math.min(X-10,30));let B=$.timeout?Math.max(1,Number.parseInt($.timeout,10)||n0):n0,_=$.concurrency?Math.max(1,Number.parseInt($.concurrency,10)||t0):t0,G={db:Q,pageSize:Z,terminalHeight:X,timeout:B,concurrency:_};h1(),process.stdout.write(f1);try{await s1(G)}catch(j){if(j instanceof Error&&j.message==="EXIT");else{process.stdout.write(r0),o0(),Y.error(j instanceof Error?j.message:String(j)),await Q.close();return}}process.stdout.write(r0),o0(),await Q.close()});u();import{createRequire as x4}from"node:module";var e0=x4(import.meta.url);function y4(){try{return e0("../../package.json").version}catch{return"unknown"}}var $1=y4(),b4="https://registry.npmjs.org";async function g4($,J="alpha"){try{let Q=await fetch(`${b4}/${$}`);if(!Q.ok)return null;let X=await Q.json();return X["dist-tags"][J]??X["dist-tags"].latest??null}catch{return null}}async function n1($,J,Q="alpha"){let X=await g4($,Q);if(!X)return null;return{current:J,latest:X,isOutdated:X!==J}}function f4(){try{let $=e0.resolve("unreal-orm/package.json",{paths:[process.cwd()]});return e0($).version}catch{return null}}async function t1(){if(process.env.CI||process.env.UNREAL_SKIP_UPDATE_CHECK)return;try{let[$,J]=await Promise.all([n1("@unreal-orm/cli",$1,"alpha"),(async()=>{let X=f4();if(!X)return null;return n1("unreal-orm",X,"alpha")})()]),Q=[];if($?.isOutdated)Q.push(` @unreal-orm/cli: ${Y.dim($.current)} → ${Y.theme.success($.latest)}`);if(J?.isOutdated)Q.push(` unreal-orm: ${Y.dim(J.current)} → ${Y.theme.success(J.latest)}`);if(Q.length>0){Y.newline(),Y.warn("\uD83D\uDCE6 Updates available:");for(let X of Q)console.log(X);Y.dim("\n Run `npm update @unreal-orm/cli unreal-orm` to update\n")}}catch{}}var a=new h4().name("unreal").description("UnrealORM CLI for SurrealDB").version($1).hook("postAction",async()=>{await t1()});a.addCommand(Y1);a.addCommand(R1);a.addCommand(P1);a.addCommand(L1);a.addCommand(T1);a.addCommand(g1);a.addCommand(a1);a.addCommand(y1);a.parse();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@unreal-orm/cli",
3
- "version": "1.0.0-alpha.4",
3
+ "version": "1.0.0-alpha.6",
4
4
  "description": "CLI tools for UnrealORM - schema introspection, diffing, and migrations for SurrealDB",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",