@unreal-orm/cli 1.0.0-alpha.7 → 1.0.0-alpha.9

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 (3) hide show
  1. package/README.md +21 -0
  2. package/dist/index.js +74 -74
  3. package/package.json +63 -51
package/README.md CHANGED
@@ -60,6 +60,7 @@ Options:
60
60
  -d, --database <database> Database name
61
61
  --auth-level <level> Auth level: root, namespace, or database
62
62
  --embedded <mode> Use embedded mode (memory or file path)
63
+ --log-level <level> Log output level: silent, normal, debug (default: normal)
63
64
  --skip-install Skip dependency installation
64
65
  ```
65
66
 
@@ -91,6 +92,7 @@ Options:
91
92
  -s, --schema-dir <path> Schema directory path
92
93
  --auth-level <level> Auth level: root, namespace, or database
93
94
  --embedded <mode> Use embedded mode (memory or file path)
95
+ --log-level <level> Log output level: silent, normal, debug (default: normal)
94
96
  -y, --yes Skip confirmation prompts
95
97
  ```
96
98
 
@@ -145,6 +147,7 @@ Options:
145
147
  -s, --schema-dir <path> Schema directory path
146
148
  --auth-level <level> Auth level: root, namespace, or database
147
149
  --embedded <mode> Use embedded mode (memory or file path)
150
+ --log-level <level> Log output level: silent, normal, debug (default: normal)
148
151
  -y, --yes Skip confirmation prompts
149
152
  ```
150
153
 
@@ -172,6 +175,7 @@ Options:
172
175
  -s, --schema-dir <path> Schema directory path
173
176
  --auth-level <level> Auth level: root, namespace, or database
174
177
  --embedded <mode> Use embedded mode (memory or file path)
178
+ --log-level <level> Log output level: silent, normal, debug (default: normal)
175
179
  --detailed Show detailed field-level changes
176
180
  ```
177
181
 
@@ -199,6 +203,7 @@ Options:
199
203
  --page-size <size> Records per page (5-100, default: auto)
200
204
  --timeout <seconds> Query timeout in seconds (default: 3)
201
205
  --concurrency <count> Max concurrent count queries (default: 5)
206
+ --log-level <level> Log output level: silent, normal, debug (default: normal)
202
207
  ```
203
208
 
204
209
  **Features:**
@@ -235,6 +240,22 @@ Options:
235
240
  --stdout Output to stdout instead of file
236
241
  --url <url> Database URL (for database source)
237
242
  -s, --schema-dir <path> Schema directory (for code source)
243
+ --log-level <level> Log output level: silent, normal, debug (default: normal)
244
+
245
+ ### `docs`
246
+
247
+ Open the UnrealORM documentation in the default browser.
248
+
249
+ ```bash
250
+ unreal docs
251
+ ```
252
+
253
+ ### `github`
254
+
255
+ Open the UnrealORM GitHub repository in the default browser.
256
+
257
+ ```bash
258
+ unreal github
238
259
  ```
239
260
 
240
261
  **Example output:**
package/dist/index.js CHANGED
@@ -1,25 +1,25 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as B2}from"node:module";var $2=Object.create;var{getPrototypeOf:Q2,defineProperty:N0,getOwnPropertyNames:J2}=Object;var X2=Object.prototype.hasOwnProperty;var Z0=($,J,Q)=>{Q=$!=null?$2(Q2($)):{};let X=J||!$||!$.__esModule?N0(Q,"default",{value:$,enumerable:!0}):Q;for(let Z of J2($))if(!X2.call(X,Z))N0(X,Z,{get:()=>$[Z],enumerable:!0});return X};var Z2=($,J)=>{for(var Q in J)N0($,Q,{get:J[Q],enumerable:!0,configurable:!0,set:(X)=>J[Q]=()=>X})};var S0=($,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=S0(()=>{J1=new Q1});import r from"chalk";import Y2 from"ora";var J0,y,Y;var u=S0(()=>{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:()=>M0,promptSelectWithDisabled:()=>T0,promptSelect:()=>k0,promptForConnection:()=>E0,promptFileReview:()=>U0,confirm:()=>z2});import Y0 from"prompts";async function E0($){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 M0($,J){return(await Y0({type:"text",name:"value",message:$,initial:J},{onCancel:()=>{Y.newline(),Y.warn("Operation cancelled."),process.exit(0)}})).value||""}async function k0($,J){return(await Y0({type:"select",name:"value",message:$,choices:J},{onCancel:()=>{console.log(`
5
- Operation cancelled.`),process.exit(0)}})).value}async function T0($,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=S0(()=>{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}
2
+ import{createRequire as U2}from"node:module";var G2=Object.defineProperty;var j2=($,J)=>{for(var Q in J)G2($,Q,{get:J[Q],enumerable:!0,configurable:!0,set:(X)=>J[Q]=()=>X})};var P0=($,J)=>()=>($&&(J=$($=0)),J);var U0=U2(import.meta.url);function Y1($){y0=$}function f(){return y0==="silent"}function G1(){return y0==="debug"}var y0="normal";var H0=()=>{};class j1{lineCount=0;log($=""){if(f())return;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 U1;var K1=P0(()=>{H0();U1=new j1});import a from"chalk";import K2 from"ora";var G0,b,e,Y;var c=P0(()=>{K1();H0();G0={success:"✅",error:"❌",warning:"⚠️",info:"ℹ️",step:"\uD83D\uDD39",arrow:"➜",line:"─",corner:"└─"},b={primary:a.hex("#FF00A0"),secondary:a.cyan,success:a.green,error:a.red,warning:a.yellow,info:a.blue,dim:a.gray,code:a.hex("#E0E0E0"),url:a.underline.cyan},e={succeed:()=>e,fail:()=>e,stop:()=>e,start:()=>e,warn:()=>e,info:()=>e,clear:()=>e,render:()=>e,frame:()=>"",get isSpinning(){return!1},get text(){return""},set text($){},get color(){return"cyan"},set color($){},get indent(){return 0},set indent($){},get spinner(){return{interval:0,frames:[]}},set spinner($){},get interval(){return 0},get prefixText(){return""},set prefixText($){},get suffixText(){return""},set suffixText($){},[Symbol.dispose]:()=>{}},Y={header($,J){if(f())return;if(console.log(""),console.log(b.primary.bold(` ${$} `)),J)console.log(b.dim(` ${J}`));console.log("")},divider(){if(f())return;console.log(b.dim(G0.line.repeat(60)))},success($){if(f())return;console.log(b.success(`${G0.success} ${$}`))},error($,J){if(f()){if(console.error($),J)console.error(J instanceof Error?J.message:String(J));return}if(console.log(b.error(`${G0.error} ${$}`)),J)if(J instanceof Error)console.log(b.dim(` ${J.stack||J.message}`));else console.log(b.dim(` ${String(J)}`))},warn($){if(f()){console.warn($);return}console.log(b.warning(`${G0.warning} ${$}`))},info($){if(f())return;console.log(b.info(`${G0.info} ${$}`))},step($,J){if(f())return;console.log(b.secondary(`${G0.step} ${$}`)+(J?b.dim(` ${J}`):""))},spin($){if(f())return e;return K2({text:$,color:"cyan",spinner:"dots"}).start()},code($){return b.code($)},cmd($){return b.code(`$ ${$}`)},link($,J){return b.url(J||$)},dim($){if(f())return"";return b.dim($)},bold($){return a.bold($)},newline(){if(f())return;console.log("")},get printer(){return U1},theme:b,symbols:G0}});var H1={};j2(H1,{promptText:()=>w0,promptSelectWithDisabled:()=>g0,promptSelect:()=>b0,promptForConnection:()=>F0,promptFileReview:()=>W0,confirm:()=>A2});import K0 from"prompts";async function F0($){let J=$.embedded,Q=await K0([{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,j=$.authLevel||Q.authLevel||"root",G=$.namespace||Q.namespace,U=$.database||Q.database,K;if(j==="database")K={username:Z,password:B,namespace:G,database:U};else if(j==="namespace")K={username:Z,password:B,namespace:G};else K={username:Z,password:B};return{url:X,namespace:G,database:U,authentication:K}}async function A2($,J=!0){return(await K0({type:"confirm",name:"value",message:$,initial:J},{onCancel:()=>{console.log(`
4
+ Operation cancelled.`),process.exit(0)}})).value}async function w0($,J){return(await K0({type:"text",name:"value",message:$,initial:J},{onCancel:()=>{Y.newline(),Y.warn("Operation cancelled."),process.exit(0)}})).value||""}async function b0($,J){return(await K0({type:"select",name:"value",message:$,choices:J},{onCancel:()=>{console.log(`
5
+ Operation cancelled.`),process.exit(0)}})).value}async function g0($,J){return(await K0({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 W0($,J,Q){let Z=(await K0({type:"text",name:"action",message:`[${J}/${Q}] Apply this change? (y)es / (n)o / (a)ccept all / (c)ancel`,validate:(B)=>{let j=B.toLowerCase().trim();if(["y","yes","n","no","a","all","c","cancel"].includes(j))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 _0=P0(()=>{c()});import{Command as c4}from"@commander-js/extra-typings";c();import{Command as _2}from"@commander-js/extra-typings";import h from"prompts";import C from"node:fs/promises";import m from"node:path";import{execSync as _1}from"node:child_process";var __dirname="E:\\GitHub\\unreal-orm\\packages\\unreal-cli\\src\\commands",p=()=>{Y.newline(),Y.warn("Operation cancelled."),process.exit(0)},q1=new _2("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 h({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:p})).connectionMode;if(!Q)Y.error("Operation cancelled."),process.exit(1);if(Q==="remote"){let P=$.url||(await h({type:"text",name:"url",message:"SurrealDB URL:",initial:"ws://localhost:8000"},{onCancel:p})).url,I=$.username,F=$.password,w="root";if(!I||!F){let Q0=await h([{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:p});I=$.username||Q0.username,F=$.password||Q0.password,w=Q0.authLevel||"root"}let{namespace:v,database:k}=$,x=[];if(!v&&(w!=="root"||!k))x.push({type:"text",name:"namespace",message:"Namespace:",initial:"test"});if(!k)x.push({type:"text",name:"database",message:"Database:",initial:"test"});if(x.length>0){let Q0=await h(x,{onCancel:p});v=v||Q0.namespace,k=k||Q0.database}let S,u=I||"",s=F||"";if(w==="database"&&v&&k)S={username:u,password:s,namespace:v,database:k};else if(w==="namespace"&&v)S={username:u,password:s,namespace:v};else S={username:u,password:s};J={url:P,authentication:S,namespace:v,database:k}}else if(Q==="memory"){let{namespace:P,database:I}=$;if(!P||!I){let F=await h([{type:P?null:"text",name:"namespace",message:"Namespace:",initial:"test"},{type:I?null:"text",name:"database",message:"Database:",initial:"test"}],{onCancel:p});P=P||F.namespace,I=I||F.database}J={embedded:"memory",namespace:P,database:I},Y.newline(),Y.warn("Note: Embedded mode requires @surrealdb/node package")}else{let P=$.embedded!=="surrealkv"?$.embedded:void 0,I=$.namespace,F=$.database;if(!P)P=(await h({type:"text",name:"path",message:"Database file path:",initial:"./data/local"},{onCancel:p})).path;if(!I||!F){let w=await h([{type:I?null:"text",name:"namespace",message:"Namespace:",initial:"test"},{type:F?null:"text",name:"database",message:"Database:",initial:"test"}],{onCancel:p});I=I||w.namespace,F=F||w.database}J={embedded:P?.startsWith("surrealkv://")?P:`surrealkv://${P}`,namespace:I,database:F},Y.newline(),Y.warn("Note: Embedded mode requires @surrealdb/node package"),Y.newline()}let Z=await C.access(m.join(process.cwd(),"src")).then(()=>!0).catch(()=>!1)?"./src/unreal":"./unreal",j=(await h({type:"text",name:"path",message:"Where should the unreal folder be created?",initial:Z},{onCancel:p})).path||Z,G=m.resolve(process.cwd(),j),U=m.join(G,"tables");await C.mkdir(U,{recursive:!0}),Y.success(`Created ${j}/ folder structure`);let K=q2(j);await C.writeFile(m.join(process.cwd(),"unreal.config.json"),JSON.stringify(K,null,"\t")),Y.success("Created unreal.config.json");let W=W2(Q);await C.writeFile(m.join(G,"surreal.ts"),W),Y.success(`Created ${j}/surreal.ts`);let A=H2(J,Q),q=m.join(process.cwd(),".env"),H=await C.access(q).then(()=>!0).catch(()=>!1);if(Y.newline(),H){if((await h({type:"confirm",name:"appendEnv",message:"Append SurrealDB config to existing .env file?",initial:!0},{onCancel:p})).appendEnv)if((await C.readFile(q,"utf-8")).includes("SURREAL_URL"))Y.warn(".env already contains SURREAL_* variables, skipping append");else await C.appendFile(q,`
7
+
8
+ ${A}
9
+ `),Y.success("Appended SurrealDB config to .env")}else if((await h({type:"confirm",name:"createEnv",message:"Create .env file with SurrealDB config?",initial:!0},{onCancel:p})).createEnv)await C.writeFile(q,`${A}
10
+ `),Y.success("Created .env file"),Y.info(" Remember to add .env to your .gitignore!");let _=z2(),z=$.pm??"";if(!z&&$.install!==!1){let P=[{title:"npm",value:"npm"},{title:"yarn",value:"yarn"},{title:"pnpm",value:"pnpm"},{title:"bun",value:"bun"}],I=P.findIndex((w)=>w.value===_),{pm:F}=await h({type:"select",name:"pm",message:"Package manager:",choices:P,initial:I>=0?I:0},{onCancel:p});z=F??_}let E=z||_,O=["unreal-orm@latest","surrealdb@2.0.0"],V=["@unreal-orm/cli",E==="bun"?"@types/bun":"@types/node"];if(Q==="memory"||Q==="file")O.push("@surrealdb/node@3.0.1");let D=$.install;if(D===void 0){let P=[...O,...V.map((F)=>`${F} (dev)`)],{install:I}=await h({type:"confirm",name:"install",message:`Install dependencies? (${P.join(", ")})`,initial:!0},{onCancel:p});D=I}if(D){let P=z1(z,O,!1);Y.newline(),Y.info(`Running: ${P}...`);try{_1(P,{stdio:"inherit"})}catch(F){Y.error("Failed to install dependencies")}let I=z1(z,V,!0);Y.info(`Running: ${I}...`);try{_1(I,{stdio:"inherit"}),Y.success("Dependencies installed")}catch(F){Y.error("Failed to install dev dependencies")}}let L="none";if($.sample)L="sample";else if($.fromDb)L="from-db";else if($.fromSurql)L="from-surql";else L=(await h({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:p})).action;if(L==="sample"){let P=m.resolve(__dirname,"../../examples/simple"),I=["User.ts","Post.ts","Follow.ts"];for(let F of I){let w=await C.readFile(m.join(P,F),"utf-8");await C.writeFile(m.join(U,F),w)}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(L==="from-db")Y.info("Run 'unreal pull' to import schema from database");else if(L==="from-surql")Y.info("Run 'unreal pull --file <path>' to import schema");if(Y.newline(),(await h({type:"confirm",name:"addImport",message:"Add import to your entry point? (e.g., index.ts, main.ts)",initial:!0},{onCancel:p})).addImport){let P=["src/index.ts","src/main.ts","src/app.ts","index.ts","main.ts","app.ts"],I=null;for(let v of P){let k=m.join(process.cwd(),v);if(await C.access(k).then(()=>!0).catch(()=>!1)){I=v;break}}let w=(await h({type:"text",name:"entryPoint",message:"Entry point file:",initial:I||"src/index.ts"},{onCancel:p})).entryPoint;if(w){let v=m.join(process.cwd(),w),k=await C.access(v).then(()=>!0).catch(()=>!1),x=m.dirname(v),S=m.relative(x,G);if(!S.startsWith("."))S=`./${S}`;S=S.replace(/\\/g,"/");let u=`// Initialize database connection and configure ORM (must be first import)
11
+ import "${S}/surreal";`;if(k){let s=await C.readFile(v,"utf-8");if(s.includes("/surreal"))Y.warn("Entry point already imports surreal.ts, skipping");else{let Q0=`${u}
12
+ ${s}`;await C.writeFile(v,Q0),Y.success(`Added import to ${w}`)}}else{let s=`${u}
13
13
 
14
14
  // Your app code here
15
15
  console.log("Hello from UnrealORM!");
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";
16
+ `;await C.mkdir(m.dirname(v),{recursive:!0}),await C.writeFile(v,s),Y.success(`Created ${w} 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(` ${j}/`)),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 "${j}/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 z2(){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 z1($,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 q2($){return{$schema:"https://raw.githubusercontent.com/Jimpex/unreal-orm/refs/heads/main/packages/unreal-orm/unreal.schema.json",path:$}}function H2($,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,j=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=${j}`),X.push(`SURREAL_PASS=${G}`)}return X.join(`
18
+ `)}function W2($){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
- import { Surreal } from "surrealdb";`,_=Z.map((q)=>`const ${q} = process.env.${q};`).join(`
22
- `),G=Z.join(" || !"),j=Z.join(", "),U=J?`db = new Surreal({
21
+ import { Surreal } from "surrealdb";`,j=Z.map((q)=>`const ${q} = process.env.${q};`).join(`
22
+ `),G=Z.join(" || !"),U=Z.join(", "),K=J?`db = new Surreal({
23
23
  engines: {
24
24
  ...createRemoteEngines(),
25
25
  ...createNodeEngines(),
@@ -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
- }`,V=J?"SURREAL_URL!":"SURREAL_URL";return`/**
37
+ }`,A=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.
@@ -78,11 +78,11 @@ ${B}
78
78
  // Environment Configuration
79
79
  // =============================================================================
80
80
 
81
- ${_}
81
+ ${j}
82
82
 
83
83
  if (!${G}) {
84
84
  throw new Error(
85
- "Missing required SurrealDB environment variables: ${j}\\n" +
85
+ "Missing required SurrealDB environment variables: ${U}\\n" +
86
86
  "Make sure your .env file exists and contains these variables."
87
87
  );
88
88
  }
@@ -122,9 +122,9 @@ export async function getDatabase(): Promise<Surreal> {
122
122
  export async function connect(): Promise<Surreal> {
123
123
  if (db) return db;
124
124
 
125
- ${U}
125
+ ${K}
126
126
 
127
- await db.connect(${V}, ${W});
127
+ await db.connect(${A}, ${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 r2}from"@commander-js/extra-typings";import{existsSync as u0,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 x0}from"node:path";u();import{existsSync as _1,readFileSync as q2}from"node:fs";import{join as D0}from"node:path";import{createJiti as H2}from"jiti";var W2=H2(import.meta.url,{interopDefault:!0});async function C0($){return W2.import($)}async function o($=process.cwd()){let J=D0($,"unreal.config.json"),Q=D0($,"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 C0(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 D0($.path||"./unreal","tables")}function R0($){return D0($.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 E0(G);return q1(j)}if(Q&&!B){let G=x0(process.cwd(),R0(Q));if(K1(G))return z1(G)}if(X){let G=Q?K1(x0(process.cwd(),R0(Q))):!1,j=await T0("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=x0(process.cwd(),R0(Q));return z1(W)}let U=await E0({});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 C0($),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 y0($,J){if(!$)throw Error(`${J}: No data returned`);return $}import b0 from"chalk";var I0=[];function C($,J,Q){I0.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(I0.length===0)return;console.log(b0.yellow(`
153
+ `}import{Command as i2}from"@commander-js/extra-typings";import{existsSync as r0,mkdirSync as n2,writeFileSync as t2,readFileSync as e2,readdirSync as $4,unlinkSync as Q4}from"node:fs";import{join as v1}from"node:path";import{Surreal as O1}from"surrealdb";import{existsSync as E1}from"node:fs";import{resolve as h0}from"node:path";c();import{existsSync as W1,readFileSync as V2}from"node:fs";import{join as L0}from"node:path";import{createJiti as O2}from"jiti";var E2=O2(import.meta.url,{interopDefault:!0});async function f0($){return E2.import($)}async function i($=process.cwd()){let J=L0($,"unreal.config.json"),Q=L0($,"unreal.config.ts");if(W1(J))try{let X=V2(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(W1(Q))try{return{path:(await f0(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 M2($){return L0($.path||"./unreal","tables")}function N0($){return L0($.path||"./unreal","surreal.ts")}function A1(){Y.error("No configuration found."),Y.info("Please run 'unreal init' to create a configuration file first."),Y.newline(),process.exit(1)}async function J0($){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(),M2(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(() => (_0(),H1));return await Z("Schema directory path:","./unreal/tables")||"./unreal/tables"}return"./unreal/tables"}_0();c();H0();var V1=performance.now();function N($){if(!G1())return;let J=performance.now(),Q=J-V1;V1=J,console.log(`[DEBUG +${Q.toFixed(0)}ms] ${$}`)}async function n($){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},U=await F0(G);return N("Connecting via CLI flags"),D1(U)}if(Q&&!B){let G=h0(process.cwd(),N0(Q));if(E1(G))return N("Connecting via surreal.ts config"),M1(G)}if(X){let G=Q?E1(h0(process.cwd(),N0(Q))):!1,U=await g0("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(!U)process.exit(0);if(U==="config"&&Q){let W=h0(process.cwd(),N0(Q));return M1(W)}let K=await F0({});return D1(K)}if(Z)A1();return null}async function M1($){let J=Y.spin("Loading database client from surreal.ts...");try{try{(await import("dotenv")).config({quiet:!0})}catch{}let Q=await f0($),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 D1($){let J;if("embedded"in $)try{let{createNodeEngines:Q}=await import("@surrealdb/node"),X=$.embedded==="memory"?"mem://":$.embedded;J=new O1({engines:Q()}),await J.connect(X,$),N("Embedded connection established")}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 O1,await J.connect($.url,$),N("Remote connection established");if($.namespace&&$.database)await J.use({namespace:$.namespace,database:$.database});return J}import{parseFieldDefinition as D2,parseIndexDefinition as R2,parseTableDefinition as I2}from"unreal-orm";function m0($,J){if(!$)throw Error(`${J}: No data returned`);return $}import p0 from"chalk";var v0=[];function y($,J,Q){v0.push({feature:$,reason:J,suggestion:Q})}function X0($,J,Q){if($==="field"){if(Q.includes("TYPE object")&&Q.includes("{"))return y(`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()))y(`Field '${J}'`,`Uncommon geometry type: ${Z}`,"Verify the generated Field.geometry() call is correct")}}if($==="index"){if(Q.includes("MTREE")||Q.includes("HNSW"))return y(`Index '${J}'`,"Vector index (MTREE/HNSW) detected","Vector indexes are not yet fully supported in code generation"),!1;if(Q.includes("SEARCH ANALYZER"))y(`Index '${J}'`,"Search analyzer index detected","Search indexes are parsed but may need manual configuration")}if($==="table"){if(Q.includes("CHANGEFEED"))y(`Table '${J}'`,"Changefeed configuration detected","Changefeeds are not yet supported in code generation")}if($==="event")return y(`Event '${J}'`,"Events/triggers are not yet supported","You'll need to manually create event definitions"),!1;if($==="analyzer")return y(`Analyzer '${J}'`,"Analyzers are not yet supported","Analyzer definitions will be skipped"),!1;if($==="function")return y(`Function '${J}'`,"Custom functions are not yet supported","Function definitions will be skipped"),!1;if($==="param")return y(`Parameter '${J}'`,"Database parameters are not yet supported","Parameter definitions will be skipped"),!1;return!0}function Z0(){if(v0.length===0)return;console.log(p0.yellow(`
155
155
  ⚠️ Warnings:
156
- `));for(let $ of I0)if(console.log(b0.yellow(` • ${$.feature}: ${$.reason}`)),$.suggestion)console.log(b0.dim(` → ${$.suggestion}`));console.log()}function _0(){I0.length=0}async function $0($){let[J]=await $.query("INFO FOR DB").collect(),Q=y0(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();_=y0(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 P0($){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(`
156
+ `));for(let $ of v0)if(console.log(p0.yellow(` • ${$.feature}: ${$.reason}`)),$.suggestion)console.log(p0.dim(` → ${$.suggestion}`));console.log()}function z0(){v0.length=0}async function B0($){let[J]=await $.query("INFO FOR DB").collect(),Q=m0(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))X0("analyzer",B,Q.analyzers[B]||"");if(Q.functions&&Object.keys(Q.functions).length>0)for(let B of Object.keys(Q.functions))X0("function",B,Q.functions[B]||"");if(Q.params&&Object.keys(Q.params).length>0)for(let B of Object.keys(Q.params))X0("param",B,Q.params[B]||"");let Z=[];for(let B of Object.keys(X)){let j;try{let[z]=await $.query(`INFO FOR TABLE ${B}`).collect();j=m0(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}X0("table",B,G);let U=I2(G),K=[],W=j.fields||{};for(let z of Object.keys(W)){let E=W[z];if(E){X0("field",z,E);try{K.push(D2(E))}catch(O){console.warn(`Failed to parse field ${z} on table ${B}`,O)}}}let A=[],q=j.indexes||{};for(let z of Object.keys(q)){let E=q[z];if(E){if(X0("index",z,E))try{A.push(R2(E))}catch(V){console.warn(`Failed to parse index ${z} on table ${B}`,V)}}}let H=[],_=j.events||{};for(let z of Object.keys(_)){let E=_[z];if(E)X0("event",z,E)}if(U.name&&U.type)Z.push({name:U.name,type:U.type,drop:U.drop||!1,schemafull:U.schemafull||!1,viewQuery:U.viewQuery,permissions:U.permissions||{},fields:K,indexes:A,events:H})}return{tables:Z}}_0();import{compareSchemas as f2}from"unreal-orm";function S0($){let J=new Map;for(let Q of $.tables){let X=F2(Q);J.set(`${V0(Q.name)}.ts`,X)}return J}function P2($,J,Q){let X=$.matchAll(/record<(\w+)>/g);for(let Z of X){let B=Z[1];if(B&&B!==J)Q.add(`import { ${V0(B)} } from './${V0(B)}';`)}}function F2($){let J=new Set;J.add("import { Table, Field, Index } from 'unreal-orm';"),J.add("import { surql } from 'surrealdb';");for(let B of $.fields)P2(B.type,$.name,J);let Q=V0($.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,75 +164,75 @@ Original Error: ${Q}`)}else J=new U1,await J.connect($.url,$);if($.namespace&&$.
164
164
  `,Z+=` name: "${$.name}",
165
165
  `,$.schemafull)Z+=` schemafull: true,
166
166
  `;Z+=` fields: {
167
- `,Z+=H1($.fields," "),Z+=` },
167
+ `,Z+=R1($.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+=H1($.fields," "),Z+=` },
173
+ `,Z+=R1($.fields," "),Z+=` },
174
174
  `,Z+=`}) {}
175
175
  `}if($.indexes.length>0){Z+=`
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+=`
176
+ `;for(let B of $.indexes){let G=(B.name.includes($.name)?B.name:`${$.name}_${B.name}`).replace(/[^a-zA-Z0-9_]/g,"_");Z+=v2(B,Q,G),X.push(G)}}return Z+=`
177
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 g0(Q,J)}function g0($,J){let Q="";for(let[X,Z]of $.children)if(Z.arrayElement&&Z.arrayElement.children.size>0){let B=Z.field?f0(Z.field):"";Q+=`${J}${X}: Field.array(Field.object({
179
- `,Q+=g0(Z.arrayElement,`${J} `),Q+=`${J}})${B?`, ${B}`:""}),
180
- `}else if(Z.children.size>0){let B=Z.field?f0(Z.field):"";Q+=`${J}${X}: Field.object({
181
- `,Q+=g0(Z,`${J} `),Q+=`${J}}${B?`, ${B}`:""}),
182
- `}else if(Z.field)Q+=`${J}${X}: ${P2(Z.field)},
183
- `;return Q}function f0($){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=f0($),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}, {
178
+ `,Z}function w2($){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 L2($){let J=$.filter((X)=>!X.name.endsWith(".*")),Q={children:new Map};for(let X of J){let Z=w2(X.name),B=Q;for(let j=0;j<Z.length;j++){let G=Z[j];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 R1($,J){let Q=L2($);return u0(Q,J)}function u0($,J){let Q="";for(let[X,Z]of $.children)if(Z.arrayElement&&Z.arrayElement.children.size>0){let B=Z.field?c0(Z.field):"";Q+=`${J}${X}: Field.array(Field.object({
179
+ `,Q+=u0(Z.arrayElement,`${J} `),Q+=`${J}})${B?`, ${B}`:""}),
180
+ `}else if(Z.children.size>0){let B=Z.field?c0(Z.field):"";Q+=`${J}${X}: Field.object({
181
+ `,Q+=u0(Z,`${J} `),Q+=`${J}}${B?`, ${B}`:""}),
182
+ `}else if(Z.field)Q+=`${J}${X}: ${N2(Z.field)},
183
+ `;return Q}function c0($){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 N2($){let J=c0($),Q=$.type;if(Q.startsWith("option<")){let X=Q.match(/option<(.+)>/)?.[1];if(X)return`Field.option(${A0(X,J||"")})`}if(Q.includes(" | ")){let X=Q.split(" | ").map((B)=>B.trim());if(X.includes("none")){let B=X.filter((j)=>j!=="none");if(B.length===1&&B[0])return`Field.option(${A0(B[0],J||"")})`}return`Field.custom('${Q.replace(/'/g,"\\'")}'${J?`, ${J}`:""}) /* TODO: Specify union type */`}return A0(Q,J||"")}function A0($,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(${A0(X,"")}${Q?`, ${Q}`:""})`}if($.startsWith("set<")){let X=$.slice(4,-1);return`Field.set(${A0(X,"")}${Q?`, ${Q}`:""})`}if($.startsWith("record<")){let X=$.match(/record<(\w+)>/);if(X?.[1]){let Z=X[1];return`Field.record(() => ${V0(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 v2($,J,Q){let X=`export const ${Q} = Index.define(() => ${J}, {
184
184
  `;if(X+=` name: "${$.name}",
185
185
  `,X+=` fields: [${$.columns.map((Z)=>`"${Z}"`).join(", ")}],
186
186
  `,$.unique)X+=` unique: true,
187
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=`
189
- ${U}// 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
188
+ `,X}function V0($){return $.split("_").map((J)=>J.charAt(0).toUpperCase()+J.slice(1)).join("")}import{compareSchemas as S2}from"unreal-orm";function I1($,J,Q){let X=k2(J,Q);if(X.length===0)return{content:$,addedFields:[],addedIndexes:[],removedFields:[],removedIndexes:[]};let Z=$,B=[],j=[],G=[],U=[],K=X.filter((H)=>H.type==="field_added");for(let H of K){if(!H.field)continue;let _=J.fields.find((E)=>E.name===H.field);if(!_)continue;if(_.name.includes("."))continue;if(_.name.includes("[*]"))continue;let z=T2(_);Z=x2(Z,_.name,z),B.push(_.name)}let W=X.filter((H)=>H.type==="index_added");for(let H of W){if(!H.index)continue;let _=J.indexes.find((O)=>O.name===H.index);if(!_)continue;let z=P1(J.name),E=y2(_,z);Z=C2(Z,_.name,E,z),j.push(_.name)}let A=X.filter((H)=>H.type==="field_removed");for(let H of A){if(!H.field)continue;if(H.field.includes("."))continue;if(H.field.includes("[*]"))continue;Z=b2(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=g2(Z,H.index),U.push(H.index)}return{content:Z,addedFields:B,addedIndexes:j,removedFields:G,removedIndexes:U}}function k2($,J){return S2({tables:[$]},{tables:[J]})}function T2($){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 O0($.type,Q)}function O0($,J){let Q=J||"";if($.startsWith("option<")){let X=$.match(/option<(.+)>/)?.[1];if(X)return`Field.option(${O0(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(${O0(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(${O0(X,"")}${Q?`, ${Q}`:""})`}if($.startsWith("set<")){let X=$.slice(4,-1);return`Field.set(${O0(X,"")}${Q?`, ${Q}`:""})`}if($.startsWith("record<")){let X=$.match(/record<(\w+)>/);if(X?.[1]){let Z=X[1];return`Field.record(() => ${P1(Z)}${Q?`, ${Q}`:""})`}}return`Field.custom('${$}'${Q?`, ${Q}`:""})`}function x2($,J,Q){let X=$.match(/fields:\s*\{/);if(!X||X.index===void 0)return $;let Z=X.index+X[0].length,B=1,j=Z;for(let z=Z;z<$.length&&B>0;z++){if($[z]==="{")B++;if($[z]==="}")B--;if(B===0){j=z;break}}let G=$.slice(Z,j),U=G.match(/\n(\s+)\w+:/),K=U?U[1]:" ",W=G.trim(),A=W.length>0&&!W.endsWith(","),q=$,H=j;if(A){let z=G.match(/\S\s*$/);if(z&&z.index!==void 0){let E=Z+z.index+1;q=`${$.slice(0,E)},${$.slice(E)}`,H++}}let _=`
189
+ ${K}// Added from database
190
+ ${K}${J}: ${Q},`;return`${q.slice(0,H)}${_}
191
+ ${q.slice(H)}`}function C2($,J,Q,X){let Z=$.match(new RegExp(`export const ${X}Definitions\\s*=`));if(Z&&Z.index!==void 0){let B=Z.index,j=`// Added from database
192
192
  ${Q}
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`${$}
193
+ `,G=$.slice(0,B)+j+$.slice(B),U=J.replace(/[^a-zA-Z0-9_]/g,"_");return G=G.replace(new RegExp(`(export const ${X}Definitions\\s*=\\s*\\[${X})([,\\s\\w]*)(\\])`),`$1$2, ${U}$3`),G}return`${$}
194
194
  // Added from database
195
- ${Q}`}function k2($,J){let X=`export const ${$.name.replace(/[^a-zA-Z0-9_]/g,"_")} = Index.define(() => ${J}, {
195
+ ${Q}`}function y2($,J){let X=`export const ${$.name.replace(/[^a-zA-Z0-9_]/g,"_")} = Index.define(() => ${J}, {
196
196
  `;if(X+=` name: "${$.name}",
197
197
  `,X+=` fields: [${$.columns.map((Z)=>`"${Z}"`).join(", ")}],
198
198
  `,$.unique)X+=` unique: true,
199
199
  `;return X+=`});
200
- `,X}function T2($,J){let Q=new RegExp(`([ \\t]*)(${h0(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+${h0(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*${h0(Q)}(?=[\\s,\\]])`);return K=K.replace(z,""),K}function h0($){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=P0($),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 m0=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,_-m0),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-_<=m0*2){Q.lines.push({type:"context",content:G.content}),Q.oldLines++,Q.newLines++;continue}}if(Q.lines.slice().reverse().findIndex((W)=>W.type!=="context")<m0)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(u0(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(u0(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(!u0(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 d0($,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 p0($.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 p0($.table,B,!0)}case"index_added":{if(!X||!$.index)return null;let B=X.indexes.find((_)=>_.name===$.index);if(!B)return null;return c0($.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 c0($.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(p0($.name,Q,X))}for(let Q of $.indexes)J.push(c0($.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 p0($,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 c0($,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=d0(M,_,G);if(A)Y.printer.log(Y.dim(`
218
- \uD83D\uDCDD SurrealQL Statement:`)),Y.printer.log(Y.theme.secondary(` ${A}
200
+ `,X}function b2($,J){let Q=new RegExp(`([ \\t]*)(${d0(J)}\\s*:\\s*(?:Field\\.|\\{))`),X=$.match(Q);if(!X||X.index===void 0)return $;let Z=X[1]??"",B=X.index+Z.length,j=0,G=0,U=0,K=B,W=!1,A="",q=!1;for(let O=B;O<$.length;O++){let V=$[O],D=O>0?$[O-1]:"";if((V==='"'||V==="'"||V==="`")&&D!=="\\"){if(!W&&!q)if(V==="`")q=!0;else W=!0,A=V;else if(q&&V==="`")q=!1;else if(W&&V===A)W=!1;continue}if(W||q)continue;if(V==="(")j++;if(V===")")j--;if(V==="{")G++;if(V==="}")G--;if(V==="[")U++;if(V==="]")U--;if(j===0&&U===0){if(G===0&&V===","){K=O+1;break}if(G===-1&&V==="}"){K=O;while(K>B&&/\s/.test($[K-1]||""))K--;break}}}let z=$.slice(B,K).split(`
201
+ `).map((O,V)=>{if(V===0)return`${Z}// ${O}`;let L=O.match(/^(\s*)/)?.[1]??"",R=O.slice(L.length);return`${L}// ${R}`}).join(`
202
+ `),E=`${Z}// Removed from database - uncomment if needed
203
+ `;return $.slice(0,B)+E+z+$.slice(K)}function g2($,J){let Q=J.replace(/[^a-zA-Z0-9_]/g,"_"),X=new RegExp(`export\\s+const\\s+${d0(Q)}\\s*=\\s*Index\\.define`),Z=$.match(X);if(!Z||Z.index===void 0)return $;let B=Z.index,j=0,G=0,U=B,K=!1;for(let E=B;E<$.length;E++){let O=$[E];if(O==="(")G++,K=!0;if(O===")")G--;if(O==="{")j++;if(O==="}")j--;if(K&&G===0&&j===0){if(U=E+1,$[E+1]===";")U=E+2;break}}let H=`// Removed from database - uncomment if needed
204
+ ${$.slice(B,U).split(`
205
+ `).map((E)=>{let V=E.match(/^(\s*)/)?.[1]??"",D=E.slice(V.length);return`${V}// ${D}`}).join(`
206
+ `)}`,_=$.slice(0,B)+H+$.slice(U),z=new RegExp(`,\\s*${d0(Q)}(?=[\\s,\\]])`);return _=_.replace(z,""),_}function d0($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function P1($){return $.split("_").map((J)=>J.charAt(0).toUpperCase()+J.slice(1)).join("")}import h6 from"chalk";function F1($,J,Q){let X=[],Z=S0($),B=new Set,j=Q?f2($,Q):[];for(let G of j)B.add(G.table);for(let[G,U]of Z){let K=J.get(G),W=G.replace(".ts","").toLowerCase();if(!K)X.push({filename:G,type:"create",newContent:U});else if(K!==U)if(Q){if(B.has(W)){let A=$.tables.find((H)=>H.name===W),q=Q.tables.find((H)=>H.name===W);if(A&&q){let H=I1(K,A,q);X.push({filename:G,type:"update",oldContent:K,newContent:H.content,addedFields:H.addedFields,addedIndexes:H.addedIndexes,removedFields:H.removedFields,removedIndexes:H.removedIndexes})}else X.push({filename:G,type:"update",oldContent:K,newContent:U})}}else X.push({filename:G,type:"update",oldContent:K,newContent:U})}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 h2,extractIndexFromDefinition as m2,isModelClass as p2,isIndexDefinition as u2}from"unreal-orm";import{readdirSync as c2}from"node:fs";import{join as d2,resolve as l2}from"node:path";import{createJiti as r2}from"jiti";var o2=r2(import.meta.url,{interopDefault:!0});async function Y0($){let J=[];for(let Q of c2($).filter((X)=>X.endsWith(".ts"))){let X=l2(d2($,Q));try{let Z=await o2.import(X),B=new Map,j=[];for(let[,G]of Object.entries(Z))if(p2(G)){let U=h2(G);B.set(U.name,U)}else if(u2(G)){let{index:U,tableName:K}=m2(G);j.push({index:U,tableName:K})}for(let{index:G,tableName:U}of j){let K=B.get(U);if(K)K.indexes.push(G)}J.push(...B.values())}catch(Z){console.warn(`Failed to import ${Q}:`,Z)}}return{tables:J}}import g from"chalk";import{diffLines as w1}from"diff";var l0=3;function L1($,J,Q){let X=[];if(!J){X.push(g.bold.green(`
207
+ +++ ${$} (new file)`)),X.push(g.dim("─".repeat(60)));let j=Q.split(`
208
+ `).slice(0,20);for(let G of j)X.push(g.green(`+ ${G}`));if(Q.split(`
209
+ `).length>20)X.push(g.dim(`... ${Q.split(`
210
+ `).length-20} more lines`));return X.push(g.dim("─".repeat(60))),X.join(`
211
+ `)}X.push(g.bold(`
212
+ --- ${$}`)),X.push(g.bold(`+++ ${$}`)),X.push(g.dim("─".repeat(60)));let Z=w1(J,Q),B=s2(Z);if(B.length===0)X.push(g.dim(" (no changes)"));for(let j of B){X.push(g.cyan(`@@ -${j.oldStart},${j.oldLines} +${j.newStart},${j.newLines} @@`));for(let G of j.lines)if(G.type==="added")X.push(g.green(`+ ${G.content}`));else if(G.type==="removed")X.push(g.red(`- ${G.content}`));else X.push(g.dim(` ${G.content}`));X.push("")}return X.push(g.dim("─".repeat(60))),X.join(`
213
+ `)}function s2($){return a2($)}function a2($){let J=[],Q=null,X=[],Z=1,B=1;for(let j of $){if(!j)continue;let G=j.value.split(`
214
+ `);if(G[G.length-1]==="")G.pop();for(let U of G){let K=j.added?"added":j.removed?"removed":"context";if(X.push({type:K,content:U,oldLine:K!=="added"?Z:void 0,newLine:K!=="removed"?B:void 0}),K!=="added")Z++;if(K!=="removed")B++}}for(let j=0;j<X.length;j++){let G=X[j];if(!G)continue;if(G.type==="added"||G.type==="removed"){if(!Q){let U=Math.max(0,j-l0),K=X.slice(U,j),W=K[0],A=W?.oldLine??G.oldLine??1,q=W?.newLine??G.newLine??1;Q={oldStart:A,newStart:q,oldLines:0,newLines:0,lines:[]};for(let H of K)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 U=-1;for(let W=j+1;W<X.length;W++){let A=X[W];if(A&&A.type!=="context"){U=W;break}}if(U!==-1){if(U-j<=l0*2){Q.lines.push({type:"context",content:G.content}),Q.oldLines++,Q.newLines++;continue}}if(Q.lines.slice().reverse().findIndex((W)=>W.type!=="context")<l0)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 N1($,J){if(!$)return`New file (${J.split(`
215
+ `).length} lines)`;let Q=w1($,J),X=0,Z=0;for(let j of Q){let G=j.value.split(`
216
+ `).length-1;if(j.added)X+=G;else if(j.removed)Z+=G}if(X===0&&Z===0)return"No changes";let B=[];if(X>0)B.push(g.green(`+${X}`));if(Z>0)B.push(g.red(`-${Z}`));return B.join(" ")}c();var S1=new i2().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("--log-level <level>","Log output level: silent, normal, debug","normal").option("-y, --yes","Skip confirmation prompt").action(async($)=>{Y.header("UnrealORM Pull","Introspect database and generate schema"),z0(),N("Loading config");let J=await i(),Q=await J0({cliOutput:$.schemaDir,config:J}),X=$.url||$.username||$.password||$.namespace||$.database||$.authLevel||$.embedded;N("Resolving database connection");let Z=await n({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);N("Introspecting database schema");let B=Y.spin("Introspecting database schema..."),j;try{j=await B0(Z),B.succeed(`Found ${j.tables.length} table(s)`)}catch(_){B.fail("Failed to introspect database"),Y.error(_ instanceof Error?_.message:String(_)),await Z.close(),process.exit(1)}N("Planning file changes"),B.start("Planning file changes...");let G=new Map;if(r0(Q))try{let _=$4(Q).filter((z)=>z.endsWith(".ts"));for(let z of _){let E=e2(v1(Q,z),"utf-8");G.set(z,E)}}catch(_){}let U;if(r0(Q))try{U=await Y0(Q)}catch{}let K;try{K=F1(j,G,U),B.succeed("File changes planned")}catch(_){B.fail("Failed to plan file changes"),Y.error(_ instanceof Error?_.message:String(_)),await Z.close(),process.exit(1)}if(K.length===0)Y.success("All files are up to date!"),await Z.close(),Z0(),process.exit(0);let W=K.filter((_)=>_.type==="create").length,A=K.filter((_)=>_.type==="delete").length,q=K.filter((_)=>_.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(K.length))}`),W>0)Y.printer.log(` ${Y.theme.success("+")} New files: ${W}`);if(A>0)Y.printer.log(` ${Y.theme.error("-")} Deleted files: ${A}`);if(q>0)Y.printer.log(` ${Y.theme.warning("~")} Updated files: ${q}`);Y.newline();for(let _ of K){let z=_.type==="create"?Y.theme.success("+"):_.type==="delete"?Y.theme.error("-"):Y.theme.warning("~");Y.printer.log(` ${z} ${_.filename}`)}Y.newline();let H=[];if(!$.yes){let _=!1;Y.divider(),Y.info("FILE REVIEW"),Y.divider(),Y.newline();for(let z of K){if(!z)continue;if(_){H.push(z);continue}Y.printer.clear();let E=z.type==="create"?Y.theme.success("CREATE"):z.type==="delete"?Y.theme.error("DELETE"):Y.theme.warning("UPDATE");Y.printer.log(Y.bold(`[${K.indexOf(z)+1}/${K.length}] ${E}: ${z.filename}`)),Y.printer.log(Y.dim(` ${N1(z.oldContent,z.newContent)}`)),Y.printer.log(L1(z.filename,z.oldContent,z.newContent));let O=await W0(z.filename,K.indexOf(z)+1,K.length);if(O==="cancel")Y.newline(),Y.warn("Operation cancelled."),await Z.close(),process.exit(0);if(O==="all"){_=!0,H.push(z);for(let V of K.slice(K.indexOf(z)+1))if(V)H.push(V);break}if(O==="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 ${K.length} file changes`),Y.newline()}else Y.divider(),Y.success("APPLYING ALL CHANGES (--yes flag)"),Y.divider(),Y.info(`Applying all ${K.length} file changes`),Y.newline(),H.push(...K);N(`Applying ${H.length} file change(s)`),B.start("Applying file changes...");try{if(!r0(Q))n2(Q,{recursive:!0});for(let _ of H){let z=v1(Q,_.filename);if(_.type==="delete")Q4(z);else t2(z,_.newContent,"utf-8")}B.succeed(`Applied ${H.length} file change(s) to ${Q}`)}catch(_){B.fail("Failed to apply file changes"),Y.error(_ instanceof Error?_.message:String(_)),await Z.close(),process.exit(1)}await Z.close(),Z0(),Y.header("Schema pull complete!"),Y.dim("Changes applied:");for(let _ of H){let z=_.type==="create"?"+":_.type==="delete"?"-":"~";console.log(Y.dim(` ${z} ${_.filename}`))}Y.newline()});import{Command as Z4}from"@commander-js/extra-typings";import{existsSync as B4}from"node:fs";_0();import{compareSchemas as Y4}from"unreal-orm";function a0($,J,Q){return J4($,J,Q)}function J4($,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 X4(X)}case"table_removed":return`REMOVE TABLE ${$.table};`;case"table_type_changed":{if(!X)return null;return k1(X,!0)}case"field_added":{if(!X||!$.field)return null;let B=X.fields.find((j)=>j.name===$.field);if(!B)return null;return o0($.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((j)=>j.name===$.field);if(!B)return null;return o0($.table,B,!0)}case"index_added":{if(!X||!$.index)return null;let B=X.indexes.find((j)=>j.name===$.index);if(!B)return null;return s0($.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((j)=>j.name===$.index);if(!B)return null;return s0($.table,B,!0)}default:return null}}function X4($){let J=[];J.push(k1($));for(let Q of $.fields){if(Q.name.includes("[*]"))continue;let X=$.type==="RELATION"&&(Q.name==="in"||Q.name==="out");J.push(o0($.name,Q,X))}for(let Q of $.indexes)J.push(s0($.name,Q));return J.join(`
217
+ `)}function k1($,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 o0($,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 s0($,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(" ")};`}c();var T1=new Z4().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("--log-level <level>","Log output level: silent, normal, debug","normal").option("-y, --yes","Skip confirmation prompt").action(async($)=>{Y.header("UnrealORM Push","Apply code schema to database"),z0(),N("Loading config");let J=await i(),Q=await J0({cliOutput:$.schemaDir,config:J});if(N(`Schema dir resolved: ${Q}`),!B4(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;N("Resolving database connection");let Z=await n({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);N("Loading code schema");let B=Y.spin("Loading code schema..."),j;try{j=await Y0(Q),B.succeed(`Loaded ${j.tables.length} table(s) from ${Q}`)}catch(_){B.fail("Failed to load code schema"),Y.error(_ instanceof Error?_.message:String(_)),process.exit(1)}N("Introspecting database schema"),B=Y.spin("Introspecting database schema...");let G;try{G=await B0(Z),B.succeed(`Found ${G.tables.length} table(s) in database`)}catch(_){B.fail("Failed to introspect database"),Y.error(_ instanceof Error?_.message:String(_)),await Z.close(),process.exit(1)}N("Comparing schemas"),B.start("Comparing schemas...");let U=Y4(j,G,!0);if(B.succeed("Comparison complete"),U.length===0)Y.success("Schemas are identical. Nothing to push."),await Z.close(),Z0(),process.exit(0);let K=U.filter((_)=>_.type.includes("added")).length,W=U.filter((_)=>_.type.includes("removed")).length,A=U.length-K-W;if(Y.divider(),Y.info("CHANGE SUMMARY (Code -> Database)"),Y.divider(),Y.newline(),Y.printer.log(` Total changes: ${Y.bold(String(U.length))}`),K>0)Y.printer.log(` ${Y.theme.success("+")} Additions: ${K}`);if(W>0)Y.printer.log(` ${Y.theme.error("-")} Removals: ${W}`);if(A>0)Y.printer.log(` ${Y.theme.warning("~")} Modifications: ${A}`);Y.newline();for(let _ of U){let z=_.type.includes("added")?Y.theme.success("+"):_.type.includes("removed")?Y.theme.error("-"):Y.theme.warning("~");Y.printer.log(` ${z} ${_.description}`)}Y.newline();let q=[];if(!$.yes){let _=!1;Y.divider(),Y.info("CHANGE REVIEW"),Y.divider(),Y.newline();for(let z=0;z<U.length;z++){let E=U[z];if(!E)continue;if(_){q.push(E);continue}Y.printer.clear();let O=E.type.includes("added")?Y.theme.success("ADD"):E.type.includes("removed")?Y.theme.error("REMOVE"):Y.theme.warning("MODIFY");Y.printer.log(Y.bold(`[${z+1}/${U.length}] ${O}: ${E.description}`));let V=a0(E,j,G);if(V)Y.printer.log(Y.dim(`
218
+ \uD83D\uDCDD SurrealQL Statement:`)),Y.printer.log(Y.theme.secondary(` ${V}
219
219
  `));else Y.printer.log(Y.dim(`
220
220
  ⚠️ No SurrealQL generated for this change
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=d0(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 l0,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(!l0(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(l0(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(`
221
+ `));let D=await W0("this change",z+1,U.length);if(D==="cancel")Y.newline(),Y.warn("Operation cancelled."),await Z.close(),process.exit(0);if(D==="all"){_=!0,q.push(E);for(let L=z+1;L<U.length;L++){let R=U[L];if(R)q.push(R)}break}if(D==="yes")q.push(E)}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 ${U.length} change(s)`),Y.newline()}else Y.divider(),Y.success("APPLYING ALL CHANGES (--yes flag)"),Y.divider(),Y.info(`Applying all ${U.length} change(s)`),Y.newline(),q.push(...U);let H=[];for(let _ of q){let z=a0(_,j,G);if(z)H.push(z)}N(`Applying ${H.length} SQL statement(s)`),B.start("Applying schema changes...");try{let _=H.flatMap((z)=>z.split(`
222
+ `).filter((E)=>E.trim())).join("");await Z.query(`BEGIN;${_}COMMIT;`),B.succeed("Schema changes applied successfully")}catch(_){B.fail("Failed to apply schema changes"),Y.error(_ instanceof Error?_.message:String(_)),await Z.close(),process.exit(1)}await Z.close(),Z0(),Y.header("Schema push complete!"),Y.dim(`Applied ${q.length} of ${U.length} change(s) to database`),Y.newline()});import{Command as j4}from"@commander-js/extra-typings";import{existsSync as i0,readFileSync as U4,readdirSync as K4}from"node:fs";import{join as _4}from"node:path";import d from"chalk";function C1($,J=!1){if($.length===0)return d.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(d.bold(`
223
+ ${Z}:`));for(let j of B){let G=G4(j.type),U=j.description;if(j.type.includes("added"))U=d.green(j.description);else if(j.type.includes("removed"))U=d.red(j.description);else U=d.yellow(j.description);if(Q.push(` ${G} ${U}`),J&&(j.oldValue!==void 0||j.newValue!==void 0)){if(j.oldValue!==void 0)Q.push(d.dim(" Old: ")+d.red(x1(j.oldValue)));if(j.newValue!==void 0)Q.push(d.dim(" New: ")+d.green(x1(j.newValue)))}}}return Q.join(`
224
+ `)}function G4($){if($.includes("added"))return d.green("+");if($.includes("removed"))return d.red("-");return d.yellow("~")}function x1($){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($)}c();import{compareSchemas as z4}from"unreal-orm";function q4($,J){let Q={added:[],removed:[],modified:[],unchanged:[]};for(let[X,Z]of $){let B=_4(J,X);if(!i0(B))Q.added.push(X);else{let j=U4(B,"utf-8");if(j.trim()!==Z.trim())Q.modified.push({filename:X,databaseContent:Z,codeContent:j});else Q.unchanged.push(X)}}if(i0(J)){let X=K4(J).filter((Z)=>Z.endsWith(".ts"));for(let Z of X)if(!$.has(Z))Q.removed.push(Z)}return Q}function H4($){let J=$.databaseContent.split(`
225
225
  `).length,Q=$.codeContent.split(`
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(l0(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=P0(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 r0 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 M0("Output file path:",Q?r0.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 k0("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 M0("Path to .surql file:","./schema.surql");let U=r0.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=r0.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",o0="\x1B[?25h";function h1(){process.stdout.write("\x1B[?1049h\x1B[?7l\x1B[H\x1B[J")}function s0(){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 i0="\x1BCANCEL";async function F0($,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"||_===`
226
+ `).length,X=J-Q;if(X>0)return`+${X} lines`;if(X<0)return`${X} lines`;return"content changed"}function W4($){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 A4($){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 j of J)console.log(` + ${j}`);Y.newline()}if(Q.length>0){console.log(Y.theme.error(`- Removed (${Q.length}):`));for(let j of Q)console.log(` - ${j}`);Y.newline()}if(X.length>0){console.log(Y.theme.warning(`~ Modified (${X.length}):`));for(let j of X)console.log(` ~ ${j.filename}`),console.log(Y.dim(` Database: from database (${H4(j)})`)),console.log(Y.dim(" Code: current file"));Y.newline()}if(Z.length>0){console.log(Y.theme.dim(`= Unchanged (${Z.length}):`));let j=Z.join(", ");console.log(Y.dim(` ${j}`)),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 y1=new j4().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").option("--log-level <level>","Log output level: silent, normal, debug","normal").action(async($)=>{try{Y.header("UnrealORM Diff","Compare code vs database schema"),N("Loading config");let J=await i(),Q=await J0({cliOutput:$.schemaDir,config:J});N("Resolving database connection");let X=await n({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);N("Introspecting database schema");let Z=Y.spin("Introspecting database schema"),B=await B0(X);Z.succeed("Introspected database schema"),N("Parsing code schema");let j=null;if(i0(Q)){let G=Y.spin("Parsing code schema");try{j=await Y0(Q),G.succeed("Parsed code schema")}catch(U){G.fail("Could not parse code schema"),Y.warn(`${U instanceof Error?U.message:String(U)}`),Y.dim("Falling back to file-based comparison"),Y.newline()}}if(j){N("Comparing schemas (semantic)");let G=z4(B,j);if(G.length===0){Y.success("No schema differences detected. Code and database schemas are in sync."),await X.close();return}let U=W4(G),K=C1(G,$.detailed);Y.divider(),Y.info("Schema Changes"),Y.divider(),Y.newline(),console.log(K);let W=[];if(U.fields>0)W.push(Y.theme.warning(`${U.fields} field(s)`));if(U.indexes>0)W.push(Y.theme.info(`${U.indexes} index(es)`));if(U.tables>0)W.push(Y.theme.primary(`${U.tables} table(s)`));if(Y.newline(),console.log(Y.bold(`${U.total} change(s): ${W.join(", ")}`)),!$.detailed&&U.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=S0(B),U=q4(G,Q);A4(U)}await X.close()}catch(J){Y.error("Error:",J),process.exit(1)}});import{Command as I4}from"@commander-js/extra-typings";import{promises as P4,existsSync as F4}from"node:fs";import n0 from"node:path";import{promises as V4}from"node:fs";import{parseTableDefinition as O4,parseFieldDefinition as E4,parseIndexDefinition as M4}from"unreal-orm";var g1={};function b1($){return{name:$,type:"NORMAL",schemafull:!0,drop:!1,permissions:g1,fields:[],indexes:[],events:[]}}async function f1($){let J=await V4.readFile($,"utf-8");return R4(J)}function D4($){let J=$.replace(/--.*$/gm,"");return J=J.replace(/\/\*[\s\S]*?\*\//g,""),J}function R4($){let J=new Map,X=D4($).split(";").map((Z)=>Z.trim()).filter((Z)=>Z.length>0);for(let Z of X){let j=Z.replace(/\s+/g," ").trim().toUpperCase();try{if(j.startsWith("DEFINE TABLE")){let G=O4(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??g1,viewQuery:G.viewQuery,fields:[],indexes:[],events:[]});else y("DEFINE TABLE","Could not extract table name",`Statement: ${Z.slice(0,80)}...`)}else if(j.startsWith("DEFINE FIELD")){let G=E4(Z),U=Z.match(/\bON\s+(?:TABLE\s+)?(\w+)/i);if(U?.[1]){let K=U[1],W=J.get(K);if(!W)W=b1(K),J.set(K,W);W.fields.push(G)}else y("DEFINE FIELD","Could not extract table name from field definition",`Statement: ${Z.slice(0,80)}...`)}else if(j.startsWith("DEFINE INDEX")){let G=M4(Z),U=Z.match(/\bON\s+(?:TABLE\s+)?(\w+)/i);if(U?.[1]){let K=U[1],W=J.get(K);if(!W)W=b1(K),J.set(K,W);W.indexes.push(G)}else y("DEFINE INDEX","Could not extract table name from index definition",`Statement: ${Z.slice(0,80)}...`)}else if(j.startsWith("DEFINE EVENT"))y("DEFINE EVENT","Events are not yet supported","Event definitions will be skipped");else if(j.startsWith("DEFINE ANALYZER"));else if(j.startsWith("DEFINE FUNCTION"))y("DEFINE FUNCTION","Custom functions are not yet supported","Function definitions will be skipped");else if(j.startsWith("DEFINE PARAM"))y("DEFINE PARAM","Database parameters are not yet supported","Parameter definitions will be skipped");else if(j.startsWith("DEFINE USER"));else if(j.startsWith("DEFINE ACCESS"));else if(j.startsWith("OPTION"));}catch(G){let U=G instanceof Error?G.message:String(G);y("Parse error",U,`Statement: ${Z.slice(0,80)}${Z.length>80?"...":""}`)}}return{tables:Array.from(J.values())}}_0();c();var m1=new I4("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)").option("--log-level <level>","Log output level: silent, normal, debug","normal").action(async($)=>{Y.header("Mermaid ERD Generator","Visualize your schema"),z0();let J=Y.spin("Loading configuration...");try{N("Loading config");let Q=await i($.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 w0("Output file path:",Q?n0.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 b0("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 j;if(B==="code"){J.stop();let U=await J0({cliOutput:$.schemaDir,config:Q});J.start(`Extracting schema from ${U}...`),N("Extracting code schema"),j=await Y0(U),J.succeed(`Found ${j.tables.length} tables from TypeScript schema`)}else if(B==="database"){J.stop();let U=await n({cliOptions:{url:$.url,username:$.username,password:$.password,namespace:$.namespace,database:$.database,authLevel:$.authLevel,embedded:$.embedded},config:Q,skipAutoConfig:!0});if(!U)Y.error("Failed to establish database connection."),process.exit(1);N("Introspecting database schema"),J.start("Introspecting database schema...");try{j=await B0(U),J.succeed(`Found ${j.tables.length} tables from database`)}finally{await U.close()}}else{let U=typeof $.surql==="string"?$.surql:"";if(!U)J.stop(),U=await w0("Path to .surql file:","./schema.surql");let K=n0.resolve(process.cwd(),U);if(!F4(K))J.fail(`File not found: ${K}`),process.exit(1);J.start(`Parsing ${U}...`),j=await f1(K),J.succeed(`Found ${j.tables.length} tables from .surql file`)}N("Generating Mermaid diagram"),J.start("Generating Mermaid diagram...");let G=w4(j);if(J.succeed("Diagram generated"),$.stdout)console.log(`
227
+ ${G}`);else{let U=n0.resolve(process.cwd(),X||"./unreal/schema.mermaid");await P4.writeFile(U,G),Y.success(`Saved to ${U}`),Y.dim(`Tip: Preview with VS Code Mermaid extension,
228
+ https://mermiko.com, or https://mermaid.live`)}Z0()}catch(Q){J.fail("Failed to generate diagram"),Y.error(Q instanceof Error?Q.message:String(Q)),process.exit(1)}});function w4($){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=[],j=new Map;for(let G of $.tables){let U=new Set;for(let K of G.indexes){let W=K.columns[0];if(K.unique&&K.columns.length===1&&W)U.add(W)}if(U.size>0&&G.name)j.set(G.name,U)}if(Q.length>0){J.push(" %% === TABLES ===");for(let G of Q){let U=h1(G,j);J.push(...U.lines),B.push(...U.relationships)}}if(X.length>0){J.push(" %% === RELATIONS (Graph Edges) ===");for(let G of X){let U=L4(G,j);J.push(...U.lines),B.push(...U.relationships)}}if(Z.length>0){J.push(" %% === VIEWS ===");for(let G of Z){let U=h1(G,j);J.push(...U.lines)}}if(B.length>0)J.push(""),J.push(" %% === RELATIONSHIPS ==="),J.push(...B);return J.join(`
229
+ `)}function h1($,J){let Q=[],X=[],Z=$.fields.filter((G)=>!G.name.includes(".")&&!G.name.includes("[")),B=l($.name),j=J.get($.name)??new Set;Q.push(` ${B} {`);for(let G of Z){let U=E0(G.type),K=l(G.name),W=p1(G,j),q=G.name==="id"||G.assert?.includes("!= NONE")?`*${K}`:K,H=` ${U} ${q}`;if(W)H+=` ${W}`;Q.push(H);let _=G.type.match(/^record<(\w+)>$/);if(_?.[1]){let z=l(_[1]),E=G.assert?.includes("!= NONE"),O=j.has(G.name),V=E?"--":"..",R=`${O?"|":"}"}${E?"|":"o"}`,P="||";X.push(` ${B} ${R}${V}|| ${z} : "${G.name}"`)}}return Q.push(" }"),Q.push(""),{lines:Q,relationships:X}}function L4($,J){let Q=[],X=[],Z=l($.name),B=J.get($.name)??new Set,j=$.fields.find((A)=>A.name==="in"),G=$.fields.find((A)=>A.name==="out"),U=j?.type.match(/^record<(\w+)>$/)?.[1],K=G?.type.match(/^record<(\w+)>$/)?.[1],W=$.fields.filter((A)=>A.name!=="in"&&A.name!=="out"&&!A.name.includes(".")&&!A.name.includes("["));if(W.length===0){if(U&&K){let A=l(U),q=l(K);X.push(` ${A} }|--|{ ${q} : "${$.name}"`)}return{lines:[],relationships:X}}if(Q.push(` ${Z} {`),j&&U)Q.push(` ${l(U)} *in FK`);if(G&&K)Q.push(` ${l(K)} *out FK`);for(let A of W){let q=E0(A.type),H=l(A.name),_=p1(A,B),E=A.name==="id"||A.assert?.includes("!= NONE")?`*${H}`:H,O=` ${q} ${E}`;if(_)O+=` ${_}`;Q.push(O)}if(Q.push(" }"),Q.push(""),U&&K){let A=l(U),q=l(K);X.push(` ${A} ||--o{ ${Z} : "in"`),X.push(` ${Z} }o--|| ${q} : "out"`)}return{lines:Q,relationships:X}}function l($){return $.replace(/[^a-zA-Z0-9_]/g,"_")}function E0($){if($.startsWith("record<"))return"record";if($==="record")return"record";if($.startsWith("array<")){let Q=$.slice(6,-1);return`array_${E0(Q)}`}if($==="array")return"array";if($.startsWith("option<")){let Q=$.slice(7,-1);return E0(Q)}if($.startsWith("set<")){let Q=$.slice(4,-1);return`set_${E0(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 p1($,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(",")}c();import{Command as N4}from"@commander-js/extra-typings";var u1="https://github.com/Jimpex/unreal-orm",c1=new N4("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} ${u1}`,(X)=>{if(X)Y.info(`Visit: ${u1}`)})});c();import{Command as v4}from"@commander-js/extra-typings";var d1="https://unreal-orm.jimpex.dev",l1=new v4("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} ${d1}`,(X)=>{if(X)Y.info(`Visit: ${d1}`)})});import{Command as b4}from"@commander-js/extra-typings";c();var r1="\x1B[?25l",t0="\x1B[?25h";function o1(){process.stdout.write("\x1B[?1049h\x1B[?7l\x1B[H\x1B[J")}function e0(){process.stdout.write("\x1B[?7h\x1B[?1049l")}function r(){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 o(){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 $1="\x1BCANCEL";async function k0($,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=(j)=>{if(j==="\x03")process.stdout.write("\x1B[?25h"),process.exit(0);if(j==="\r"||j===`
230
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(i0);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 w0($){return $===i0}async function L0($,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(i0);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=v0($);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 v0($){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 F0(" > ")===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 a0($){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 L0(Q,{title:`Edit: ${$}`,subtitle:"Arrows to move • Type to edit • Ctrl+S save • Esc cancel"});if(w0(X))return;return a0(X)}async function N4(){let $=await L0("",{title:"Add Field - Enter Name",subtitle:"Type field name • Ctrl+S confirm • Esc cancel"});if(w0($)||!$.trim())return null;let J=await L0("",{title:`Add Field: ${$.trim()}`,subtitle:"Type value (JSON for objects/arrays) • Ctrl+S confirm • Esc cancel"});if(w0(J))return null;return{key:$.trim(),value:a0(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,v0(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(v0(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");if(Q=Object.keys(W.tables).sort().map((q)=>({name:q,count:"?"})),X=Q,Z=!1,G(),!$.skipCount)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 F0(D.highlight(" Filter: ")),j(),G()}}var C4=15,n0=5,i1=100,t0=3,e0=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 (${n0}-${i1}, default: auto)`).option("--timeout <seconds>",`Query timeout in seconds (default: ${t0})`).option("--concurrency <count>",`Max concurrent count queries (default: ${e0})`).option("--no-count","Skip fetching table record counts").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(n0,Math.min(i1,j))}else Z=Math.max(n0,Math.min(X-10,30));let B=$.timeout?Math.max(1,Number.parseInt($.timeout,10)||t0):t0,_=$.concurrency?Math.max(1,Number.parseInt($.concurrency,10)||e0):e0,G={db:Q,pageSize:Z,terminalHeight:X,timeout:B,concurrency:_,skipCount:!$.count};h1(),process.stdout.write(f1);try{await s1(G)}catch(j){if(j instanceof Error&&j.message==="EXIT");else{process.stdout.write(o0),s0(),Y.error(j instanceof Error?j.message:String(j)),await Q.close();return}}process.stdout.write(o0),s0(),await Q.close()});u();import{createRequire as x4}from"node:module";var O0=x4(import.meta.url);function y4(){try{let $=O0.resolve("@unreal-orm/cli/package.json");return O0($).version}catch{try{return O0("../../package.json").version}catch{return"unknown"}}}var $1=y4(),b4="https://registry.npmjs.org";async function g4($,J="latest"){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="latest"){let X=await g4($,Q);if(!X)return null;return{current:J,latest:X,isOutdated:X!==J}}function f4(){try{let $=O0.resolve("unreal-orm/package.json",{paths:[process.cwd()]});return O0($).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,"latest"),(async()=>{let X=f4();if(!X)return null;return n1("unreal-orm",X,"latest")})()]),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();
231
+ `),process.stdout.write("\x1B[?25l"),X(Q);else if(j==="\x1B")Z.setRawMode(!1),Z.pause(),Z.removeListener("data",B),process.stdout.write(`
232
+ `),process.stdout.write("\x1B[?25l"),X($1);else if(j===""||j==="\b"){if(Q.length>0)Q=Q.slice(0,-1),process.stdout.write("\b \b")}else if(j>=" "&&j<="~")Q+=j,process.stdout.write(j)};Z.on("data",B)})}function T0($){return $===$1}async function x0($,J){let Q=$.split(`
233
+ `),X=0,Z=0,B=0,j=-1,G=process.stdout.rows||24,U=process.stdout.columns||80,K=G-6,W=3,A=(O,V)=>{process.stdout.write(`\x1B[${O};${V}H`)},q=(O,V)=>{A(O,1),process.stdout.write(`\x1B[2K${V}`)},H=()=>{j0(),console.log(` \x1B[1m${J.title}\x1B[0m`),console.log(` \x1B[90m${J.subtitle}\x1B[0m`),console.log(`\x1B[90m${"─".repeat(Math.min(U,80))}\x1B[0m`);let O=Math.min(B+K,Q.length);for(let V=B;V<O;V++)_(V);for(let V=O-B;V<K;V++)console.log("\x1B[90m ~\x1B[0m");E(),j=B},_=(O)=>{let V=Q[O]??"",D=String(O+1).padStart(3," "),L=O===X,R=V;if(R.length>U-8)R=`${R.slice(0,U-11)}...`;if(L){let P=R.slice(0,Z),I=R[Z]??" ",F=R.slice(Z+1);console.log(`\x1B[90m${D}\x1B[0m \x1B[36m${P}\x1B[7m${I}\x1B[0m${F}`)}else console.log(`\x1B[90m${D}\x1B[0m ${R}`)},z=(O)=>{let V=B;if(X<B)B=X;else if(X>=B+K)B=X-K+1;if(B!==V||B!==j){H();return}if(O!==void 0&&O!==X&&O>=B&&O<B+K){let v=W+1+(O-B),k=Q[O]??"",x=String(O+1).padStart(3," "),S=k;if(S.length>U-8)S=`${S.slice(0,U-11)}...`;q(v,`\x1B[90m${x}\x1B[0m ${S}`)}let D=W+1+(X-B),L=Q[X]??"",R=String(X+1).padStart(3," "),P=L;if(P.length>U-8)P=`${P.slice(0,U-11)}...`;let I=P.slice(0,Z),F=P[Z]??" ",w=P.slice(Z+1);q(D,`\x1B[90m${R}\x1B[0m \x1B[36m${I}\x1B[7m${F}\x1B[0m${w}`),E()},E=()=>{let O=W+K+1,V=Math.min(B+K,Q.length),D=`Ln ${X+1}, Col ${Z+1}`,L=Q.length>K?` | ${B+1}-${V}/${Q.length}`:"";q(O,`\x1B[90m ${D}${L} | Ctrl+S save | Esc cancel\x1B[0m`)};return process.stdout.write("\x1B[?25h"),H(),new Promise((O)=>{let V=process.stdin;V.setRawMode(!0),V.resume(),V.setEncoding("utf8");let D=(R)=>{V.setRawMode(!1),V.pause(),V.removeListener("data",L),process.stdout.write("\x1B[?25l"),O(R)},L=(R)=>{let P=X,I=Q[X]??"",F=!1;if(R==="\x03")process.stdout.write("\x1B[?25h"),process.exit(0);if(R==="\x13"){D(Q.join(`
234
+ `));return}if(R==="\x1B"&&R.length===1){D($1);return}if(R==="\x1B[A"){if(X>0)X--,Z=Math.min(Z,(Q[X]??"").length)}else if(R==="\x1B[B"){if(X<Q.length-1)X++,Z=Math.min(Z,(Q[X]??"").length)}else if(R==="\x1B[C"){if(Z<I.length)Z++;else if(X<Q.length-1)X++,Z=0}else if(R==="\x1B[D"){if(Z>0)Z--;else if(X>0)X--,Z=(Q[X]??"").length}else if(R==="\x1B[H"||R==="\x1B[1~")Z=0;else if(R==="\x1B[F"||R==="\x1B[4~")Z=I.length;else if(R==="\x1B[5~")X=Math.max(0,X-K),Z=Math.min(Z,(Q[X]??"").length);else if(R==="\x1B[6~")X=Math.min(Q.length-1,X+K),Z=Math.min(Z,(Q[X]??"").length);else if(R==="\r"||R===`
235
+ `){let w=I.slice(0,Z),v=I.slice(Z);Q[X]=w,Q.splice(X+1,0,v),X++,Z=0,F=!0}else if(R===""||R==="\b"){if(Z>0)Q[X]=I.slice(0,Z-1)+I.slice(Z),Z--;else if(X>0){let w=Q[X-1]??"";Z=w.length,Q[X-1]=w+I,Q.splice(X,1),X--,F=!0}}else if(R==="\x1B[3~"){if(Z<I.length)Q[X]=I.slice(0,Z)+I.slice(Z+1);else if(X<Q.length-1)Q[X]=`${I}${Q[X+1]??""}`,Q.splice(X+1,1),F=!0}else if(R==="\t")Q[X]=`${I.slice(0,Z)} ${I.slice(Z)}`,Z+=2;else if(R.length===1&&R>=" "&&R<="~")Q[X]=`${I.slice(0,Z)}${R}${I.slice(Z)}`,Z++;if(F)H();else z(P)};V.on("data",L)})}import q0 from"chalk";var M={primary:q0.hex("#FF00A0"),dim:q0.gray,highlight:q0.cyan,success:q0.green,warning:q0.yellow,error:q0.red},T={topLeft:"┌",topRight:"┐",bottomLeft:"└",bottomRight:"┘",horizontal:"─",vertical:"│",teeRight:"├",teeLeft:"┤",teeDown:"┬",teeUp:"┴",cross:"┼"};import S4 from"chalk";function t($,J){let Q=Math.min(process.stdout.columns||80,80);if(console.log(M.primary.bold(` ${$}`)),J)console.log(M.dim(` ${J}`));console.log(M.dim(T.horizontal.repeat(Q)))}function a1($,J,Q,X){console.log(M.dim(` ${T.topLeft}${Q.map((B)=>T.horizontal.repeat(B)).join(T.teeDown)}${T.topRight}`));let Z=$.map((B,j)=>s1(B,Q[j]??10)).join(M.dim(T.vertical));console.log(`${M.dim(` ${T.vertical}`)}${S4.bold(Z)}${M.dim(T.vertical)}`),console.log(M.dim(` ${T.teeRight}${Q.map((B)=>T.horizontal.repeat(B)).join(T.cross)}${T.teeLeft}`));for(let B=0;B<J.length;B++){let j=J[B];if(!j)continue;let U=B===X?M.primary("▸ "):" ",K=j.map((W,A)=>s1(W,Q[A]??10)).join(M.dim(T.vertical));console.log(`${U}${M.dim(T.vertical)}${K}${M.dim(T.vertical)}`)}console.log(M.dim(` ${T.bottomLeft}${Q.map((B)=>T.horizontal.repeat(B)).join(T.teeUp)}${T.bottomRight}`))}function s1($,J){let Q=C0($);if(Q.length>=J)return`${k4($,J-1)}…`;return $+" ".repeat(J-Q.length)}function k4($,J){let Q=0,X=0,Z=/\x1b\[[0-9;]*m/g;while(X<$.length&&Q<J){Z.lastIndex=X;let j=Z.exec($);if(j&&j.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 C0($){return $.replace(/\x1b\[[0-9;]*m/g,"")}async function M0($){r(),t("Confirm",""),console.log(""),console.log(M.warning(` ${$}`)),console.log(""),console.log(M.dim(" y yes • n no"));let J=await o();return J==="y"||J==="Y"}async function i1($,J){return r(),t("Confirm Action",""),console.log(""),console.log(M.warning(` ${$}`)),console.log(""),await k0(" > ")===J}async function D0($){r(),t("Error",""),console.log(""),console.log(M.error(` ${$}`)),console.log(""),console.log(M.dim(" Press any key to continue...")),await o()}async function n1($){r(),t("Success",""),console.log(""),console.log(M.success(` ${$}`)),console.log(""),console.log(M.dim(" Press any key to continue...")),await o()}function e1($){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 R0($,J=40){if($===void 0||$===null)return M.dim("null");if(Array.isArray($)){if($.length===0)return M.dim("[]");if($.length<=5){let Z=`[${$.map((B)=>t1(B)).join(", ")}]`;if(Z.length>J)return M.dim(`[${$.length} items]`);return M.dim(Z)}return M.dim(`[${$.length} items]`)}if(typeof $==="object"){let X=String($);if(X!=="[object Object]"){if(X.length>J)return M.dim(`${X.slice(0,J-3)}...`);return M.dim(X)}let Z=Object.keys($);if(Z.length===0)try{let B=JSON.stringify($);if(B.length>J)return M.dim(`${B.slice(0,J-3)}...`);return M.dim(B)}catch{return M.dim("{}")}if(Z.length<=5){let j=`{${Z.map((G)=>`${G}: ${t1($[G])}`).join(", ")}}`;if(j.length>J)return M.dim(`{${Z.length} fields}`);return M.dim(j)}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>J)return`${Q.slice(0,J-3)}...`;return Q}function t1($){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 Q1($){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 $2($,J,Q){let X=Q.id?String(Q.id):"unknown",Z=0,B={...Q},j={...Q},G=[],U=()=>Object.keys(j).sort((q,H)=>{if(q==="id")return-1;if(H==="id")return 1;return q.localeCompare(H)}),K=(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,A=(q=!1)=>{if(q)r();else j0();let H=process.stdout.rows||24,_=process.stdout.columns||80,z=Math.max(3,H-5),E=G.length,O=E>0?`${E} changes • s save • x discard`:J;t(`Record: ${X}`,O);let V=U(),D=Math.min(Math.max(...V.map((F)=>F.length),8),20),L=_-D-6,R=0;if(Z>=z)R=Z-z+1;let P=Math.min(R+z,V.length);for(let F=R;F<P;F++){let w=V[F];if(!w)continue;let v=j[w],k=F===Z,x=K(w),S=k?M.primary("▸ "):" ",u;if(x==="added")u=M.success(`+ ${w.slice(0,D-2).padEnd(D-2)}`);else if(x==="edited")u=M.warning(`~ ${w.slice(0,D-2).padEnd(D-2)}`);else if(x==="removed")u=M.error(`- ${w.slice(0,D-2).padEnd(D-2)}`);else if(k)u=M.primary.bold(w.slice(0,D).padEnd(D));else u=M.highlight(w.slice(0,D).padEnd(D));let s=R0(v,L);console.log(`${S}${u} ${s}`)}let I=V.length>z?`${R+1}-${P}/${V.length} • `:"";console.log(M.dim(` ${I}↑↓ nav • e edit • + add • - del • d delete • b back • q quit`))};A(!0);while(!0){let q=await o(),H=U();if(q==="q"){if(W()){if(!await M0("Discard unsaved changes?")){A();continue}}throw Error("EXIT")}if(q==="b"||q==="\x1B"){if(W()){if(!await M0("Discard unsaved changes?")){A();continue}}return"back"}if(q==="\x1B[A"||q==="k")Z=Math.max(0,Z-1),A();else if(q==="\x1B[B"||q==="j")Z=Math.min(H.length-1,Z+1),A();else if(q==="e"||q==="\r"||q===`
236
+ `){let _=H[Z];if(_&&_!=="id"){let z=j[_],E=await T4(_,z);if(E!==void 0){let O=B[_];if(JSON.stringify(E)!==JSON.stringify(O)){let V=G.findIndex((D)=>D.type==="edit"&&D.key===_);if(V>=0)G.splice(V,1);G.push({type:"edit",key:_,oldValue:O,newValue:E})}else{let V=G.findIndex((D)=>D.type==="edit"&&D.key===_);if(V>=0)G.splice(V,1)}j[_]=E}A()}else if(_==="id")await D0("Cannot edit the id field"),A()}else if(q==="+"||q==="="){let _=await x4();if(_)j[_.key]=_.value,G.push({type:"add",key:_.key,value:_.value});A()}else if(q==="-"||q==="_"){let _=H[Z];if(_&&_!=="id"){if(K(_)==="added"){let E=G.findIndex((O)=>O.type==="add"&&O.key===_);if(E>=0)G.splice(E,1);delete j[_]}else G.push({type:"remove",key:_,oldValue:B[_]}),delete j[_];Z=Math.min(Z,H.length-2),A()}else if(_==="id")await D0("Cannot remove the id field"),A()}else if(q==="u"||q==="U"){let _=G.pop();if(_){if(_.type==="edit")j[_.key]=_.oldValue;else if(_.type==="add")delete j[_.key];else if(_.type==="remove")j[_.key]=_.oldValue}A()}else if(q==="x"||q==="X"){if(W()){if(await M0("Discard all changes?")){G.length=0;for(let z of Object.keys(j))delete j[z];Object.assign(j,B)}A()}}else if(q==="s"||q==="S"){if(W()){if(await M0(`Save ${G.length} change${G.length>1?"s":""}?`))try{let z=[],E=[],O={};for(let D of G)if(D.type==="edit"||D.type==="add"){let L=`p_${D.key.replace(/[^a-zA-Z0-9]/g,"_")}`;z.push(`\`${D.key}\` = $${L}`),O[L]=D.type==="edit"?D.newValue:D.value}else if(D.type==="remove")E.push(`\`${D.key}\``);let V=`UPDATE ${X}`;if(z.length>0)V+=` SET ${z.join(", ")}`;if(E.length>0)V+=` UNSET ${E.join(", ")}`;V+=` TIMEOUT ${$.timeout}s`,await $.db.query(V,O).collect(),G.length=0;for(let D of Object.keys(B))delete B[D];Object.assign(B,j),await n1("Changes saved successfully")}catch(z){await D0(`Failed to save: ${z instanceof Error?z.message:String(z)}`)}A()}}else if(q==="d"||q==="D")if(await i1(`Delete record ${X}? Type "delete" to confirm:`,"delete"))try{return await $.db.query(`DELETE ${X} TIMEOUT ${$.timeout}s`).collect(),"deleted"}catch(z){await D0(`Failed to delete: ${z instanceof Error?z.message:String(z)}`),A()}else A()}}async function T4($,J){let Q=typeof J==="object"?JSON.stringify(J,null,2):String(J??""),X=await x0(Q,{title:`Edit: ${$}`,subtitle:"Arrows to move • Type to edit • Ctrl+S save • Esc cancel"});if(T0(X))return;return Q1(X)}async function x4(){let $=await x0("",{title:"Add Field - Enter Name",subtitle:"Type field name • Ctrl+S confirm • Esc cancel"});if(T0($)||!$.trim())return null;let J=await x0("",{title:`Add Field: ${$.trim()}`,subtitle:"Type value (JSON for objects/arrays) • Ctrl+S confirm • Esc cancel"});if(T0(J))return null;return{key:$.trim(),value:Q1(J)}}async function Q2($,J,Q){let X=0,Z=0,B=[],j=[],G=!0,U=!0,K=Q,W=async()=>{G=!0,A(U),U=!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 _ of B)for(let z of Object.keys(_))H.add(z);j=Array.from(H),Z=Math.min(Z,Math.max(0,B.length-1)),G=!1,A()},A=(q=!1)=>{if(q)r();else j0();let H=process.stdout.rows||24,_=Math.max(3,H-9),z=B.slice(0,_),E=K!==void 0?` (${K} records)`:"",O=Math.floor(X/$.pageSize)+1,V=K!==void 0?Math.ceil(K/$.pageSize):"?";if(t(`Table: ${J}${E}`,`Page ${O}/${V}`),G){console.log(M.dim(" Loading records..."));return}if(B.length===0){console.log(M.dim(" No records found.")),console.log(M.dim(" b back • q quit"));return}let D=process.stdout.columns||80,L=Math.floor(D/j.length)-1,R=j.map((v)=>{let k=v.length;for(let x of z){let S=R0(x[v]);k=Math.max(k,C0(S).length)}return Math.min(k+2,L)}),P=z.map((v,k)=>j.map((x)=>{let S=R0(v[x]);return k===Z?M.primary(C0(S)):S}));a1(j,P,R,Z);let I=X+z.length,F=K!==void 0?`/${K}`:"",w=X+Z+1;console.log(M.dim(` ${w}${F} • ${X+1}-${I} • ↑↓ select • Enter view • ←→ page • b back • q quit`))};await W();while(!0){let q=await o();if(q==="q")throw Error("EXIT");if(q==="b"||q==="\x1B")return;if(q==="\x1B[A"||q==="k"){if(Z>0)Z--,A();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++,A();else if(K===void 0||X+B.length<K)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(K===void 0||X+$.pageSize<K)X+=$.pageSize,Z=0,await W()}else if(q==="\r"||q===`
237
+ `){let H=B[Z];if(H)if(await $2($,J,H)==="deleted")await W();else await W()}else if(q==="g")X=0,Z=0,await W();else if(q==="G"&&K!==void 0)X=Math.max(0,Math.floor((K-1)/$.pageSize)*$.pageSize),Z=0,await W()}}async function C4($,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 y4($,J,Q,X,Z){let B=0,j=async()=>{while(B<J.length){let U=B++,K=J[U];if(!K)continue;K.count=await C4($,K.name,Q),Z()}},G=Array.from({length:Math.min(X,J.length)},()=>j());await Promise.all(G)}async function J2($){let J=0,Q=[],X=[],Z=!0,B="",j=async()=>{Z=!0,G(!0);let[K]=await $.db.query("INFO FOR DB").collect(),W=K;if(!W?.tables)throw Error("Failed to retrieve database info");if(Q=Object.keys(W.tables).sort().map((q)=>({name:q,count:"?"})),X=Q,Z=!1,G(),!$.skipCount)await y4($.db,Q,$.timeout,$.concurrency,G)},G=(K=!1)=>{if(K)r();else j0();let W=process.stdout.rows||24,A=Math.max(5,W-4),q=B?` ${M.highlight(`[filter: ${B}]`)}`:"";if(t(`Tables${q}`,`${X.length} tables`),Z){console.log(M.dim(" Loading tables..."));return}if(X.length===0){if(B)console.log(M.warning(` No tables matching "${B}"`)),console.log(M.dim(" Press Esc to clear filter"));else console.log(M.warning(" No tables found in database."));return}let H=0;if(J>=A)H=J-A+1;let _=Math.min(H+A,X.length);for(let E=H;E<_;E++){let O=X[E];if(!O)continue;let V=E===J,D=V?M.primary("▸ "):" ",L=V?M.primary.bold(O.name):O.name,R=e1(O.count);console.log(`${D}${L} ${M.dim("(")}${R}${M.dim(")")}`)}let z=X.length>A?`${H+1}-${_}/${X.length} • `:"";console.log(M.dim(` ${z}↑↓ nav • Enter select • / filter • r refresh • q quit`))};if(await j(),X.length===0&&!B){await o();return}let U=()=>{if(B){let K=B.toLowerCase();X=Q.filter((W)=>W.name.toLowerCase().includes(K))}else X=Q;J=Math.min(J,Math.max(0,X.length-1))};while(!0){let K=await o();if(K==="q")throw Error("EXIT");if(K==="\x1B"){if(B)B="",U(),G();else throw Error("EXIT");continue}if(K==="\x1B[A"||K==="k")J=Math.max(0,J-1),G();else if(K==="\x1B[B"||K==="j")J=Math.min(X.length-1,J+1),G();else if(K==="\r"||K===`
238
+ `){let W=X[J];if(W){let A=typeof W.count==="number"?W.count:void 0;await Q2($,W.name,A),G(!0)}}else if(K==="g")J=0,G();else if(K==="G")J=X.length-1,G();else if(K==="r"||K==="R")B="",J=0,await j();else if(K==="/")G(),B=await k0(M.highlight(" Filter: ")),U(),G()}}var g4=15,J1=5,X2=100,X1=3,Z1=5,Z2=new b4("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 (${J1}-${X2}, default: auto)`).option("--timeout <seconds>",`Query timeout in seconds (default: ${X1})`).option("--concurrency <count>",`Max concurrent count queries (default: ${Z1})`).option("--no-count","Skip fetching table record counts").action(async($)=>{Y.header("Database Viewer","Interactive table browser");let J=await i(),Q=await n({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=g4;if($.pageSize){let U=Number.parseInt($.pageSize,10);if(!Number.isNaN(U))Z=Math.max(J1,Math.min(X2,U))}else Z=Math.max(J1,Math.min(X-10,30));let B=$.timeout?Math.max(1,Number.parseInt($.timeout,10)||X1):X1,j=$.concurrency?Math.max(1,Number.parseInt($.concurrency,10)||Z1):Z1,G={db:Q,pageSize:Z,terminalHeight:X,timeout:B,concurrency:j,skipCount:!$.count};o1(),process.stdout.write(r1);try{await J2(G)}catch(U){if(U instanceof Error&&U.message==="EXIT");else{process.stdout.write(t0),e0(),Y.error(U instanceof Error?U.message:String(U)),await Q.close();return}}process.stdout.write(t0),e0(),await Q.close()});c();import{createRequire as f4}from"node:module";var I0=f4(import.meta.url);function h4(){try{let $=I0.resolve("@unreal-orm/cli/package.json");return I0($).version}catch{try{return I0("../../package.json").version}catch{return"unknown"}}}var B1=h4(),m4="https://registry.npmjs.org";async function p4($,J="latest"){try{let Q=await fetch(`${m4}/${$}`);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 B2($,J,Q="latest"){let X=await p4($,Q);if(!X)return null;return{current:J,latest:X,isOutdated:X!==J}}function u4(){try{let $=I0.resolve("unreal-orm/package.json",{paths:[process.cwd()]});return I0($).version}catch{return null}}async function Y2(){if(process.env.CI||process.env.UNREAL_SKIP_UPDATE_CHECK)return;try{let[$,J]=await Promise.all([B2("@unreal-orm/cli",B1,"latest"),(async()=>{let X=u4();if(!X)return null;return B2("unreal-orm",X,"latest")})()]),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{}}H0();var $0=new c4().name("unreal").description("UnrealORM CLI for SurrealDB").version(B1).hook("preAction",($,J)=>{let Q=J.getOptionValue("logLevel");if(Q)Y1(Q);N("Debug logging enabled")}).hook("postAction",async()=>{if(!f())await Y2();process.exit(0)});$0.addCommand(q1);$0.addCommand(S1);$0.addCommand(T1);$0.addCommand(y1);$0.addCommand(m1);$0.addCommand(l1);$0.addCommand(Z2);$0.addCommand(c1);$0.parse();
package/package.json CHANGED
@@ -1,52 +1,64 @@
1
1
  {
2
- "name": "@unreal-orm/cli",
3
- "version": "1.0.0-alpha.7",
4
- "description": "CLI tools for UnrealORM - schema introspection, diffing, and migrations for SurrealDB",
5
- "type": "module",
6
- "main": "dist/index.js",
7
- "bin": {
8
- "unreal": "dist/index.js"
9
- },
10
- "publishConfig": {
11
- "access": "public",
12
- "tag": "latest"
13
- },
14
- "scripts": {
15
- "build": "bun build ./src/index.ts --outdir ./dist --target node --format esm --packages external --minify",
16
- "prepublishOnly": "bun run build",
17
- "publish:flow": "bun run build && bun publish"
18
- },
19
- "dependencies": {
20
- "@commander-js/extra-typings": "^14.0.0",
21
- "chalk": "^5.6.2",
22
- "commander": "^14.0.2",
23
- "diff": "^8.0.2",
24
- "dotenv": "^17.2.3",
25
- "jiti": "^2.6.1",
26
- "ora": "^9.0.0",
27
- "prompts": "^2.4.2",
28
- "unreal-orm": "1.0.0-alpha.3"
29
- },
30
- "devDependencies": {
31
- "@types/bun": "latest",
32
- "@types/diff": "^8.0.0",
33
- "@types/prompts": "^2.4.9"
34
- },
35
- "peerDependencies": {
36
- "surrealdb": "^2.0.0-alpha.14",
37
- "typescript": "^5"
38
- },
39
- "keywords": ["surrealdb", "orm", "cli", "schema", "migrations", "unreal-orm"],
40
- "author": "Jimpex <contact@jimpex.dev> (https://jimpex.dev)",
41
- "license": "ISC",
42
- "repository": {
43
- "type": "git",
44
- "url": "git+https://github.com/jimpex/unreal-orm.git",
45
- "directory": "packages/unreal-cli"
46
- },
47
- "bugs": {
48
- "url": "https://github.com/jimpex/unreal-orm/issues"
49
- },
50
- "homepage": "https://unreal-orm.jimpex.dev",
51
- "files": ["dist", "package.json", "README.md", "LICENSE"]
52
- }
2
+ "name": "@unreal-orm/cli",
3
+ "version": "1.0.0-alpha.9",
4
+ "description": "CLI tools for UnrealORM - schema introspection, diffing, and migrations for SurrealDB",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "bin": {
8
+ "unreal": "dist/index.js"
9
+ },
10
+ "publishConfig": {
11
+ "access": "public",
12
+ "tag": "latest"
13
+ },
14
+ "dependencies": {
15
+ "@commander-js/extra-typings": "^14.0.0",
16
+ "chalk": "^5.6.2",
17
+ "commander": "^14.0.2",
18
+ "diff": "^8.0.2",
19
+ "dotenv": "^17.2.3",
20
+ "jiti": "^2.6.1",
21
+ "ora": "^9.0.0",
22
+ "prompts": "^2.4.2",
23
+ "unreal-orm": "1.0.0-alpha.9"
24
+ },
25
+ "devDependencies": {
26
+ "@types/bun": "latest",
27
+ "@types/diff": "^8.0.0",
28
+ "@types/prompts": "^2.4.9",
29
+ "@surrealdb/node": "^3.0.1"
30
+ },
31
+ "peerDependencies": {
32
+ "surrealdb": "^2.0.0",
33
+ "typescript": "^5"
34
+ },
35
+ "keywords": [
36
+ "surrealdb",
37
+ "orm",
38
+ "cli",
39
+ "schema",
40
+ "migrations",
41
+ "unreal-orm"
42
+ ],
43
+ "author": "Jimpex <contact@jimpex.dev> (https://jimpex.dev)",
44
+ "license": "ISC",
45
+ "repository": {
46
+ "type": "git",
47
+ "url": "git+https://github.com/jimpex/unreal-orm.git",
48
+ "directory": "packages/unreal-cli"
49
+ },
50
+ "bugs": {
51
+ "url": "https://github.com/jimpex/unreal-orm/issues"
52
+ },
53
+ "homepage": "https://unreal-orm.jimpex.dev",
54
+ "files": [
55
+ "dist",
56
+ "package.json",
57
+ "README.md",
58
+ "LICENSE"
59
+ ],
60
+ "scripts": {
61
+ "build": "bun build ./src/index.ts --outdir ./dist --target node --format esm --packages external --minify",
62
+ "publish:flow": "bun run build && bun publish"
63
+ }
64
+ }