bun-query-builder 0.2.60 → 0.2.62
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/cli.js +2 -2
- package/dist/{chunk-bbz0pmj9.js → chunk-1nqz3kbp.js} +1 -1
- package/dist/{chunk-mvk2rcqm.js → chunk-3s6cme8m.js} +2 -2
- package/dist/{chunk-vw813qrt.js → chunk-5k4j9sg4.js} +55 -55
- package/dist/{chunk-mjedm810.js → chunk-79cr4zy3.js} +1 -1
- package/dist/{chunk-fn0m2c0v.js → chunk-w49dhqgq.js} +1 -1
- package/dist/{chunk-kjkkmrp8.js → chunk-y0ff2jm5.js} +1 -1
- package/dist/orm.d.ts +19 -0
- package/dist/src/browser.js +1 -1
- package/dist/src/dynamodb/index.js +1 -1
- package/dist/src/index.js +1 -1
- package/package.json +1 -1
package/dist/bin/cli.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
import{Aa as Ne,D as ae,E as oe,F as le,G as ce,H as ue,I as de,J as me,K as he,L as pe,M as fe,N as ge,O as be,P as ye,Q as $e,R as we,S as ve,T as xe,X as Ce,Y as Se,ea as W,fa as F,ga as z,ka as Oe,la as Ie,ma as Ee,n as ne,na as ke,oa as _e,pa as qe,qa as Me,ra as Be,sa as U,ta as G,ua as Te,va as je,wa as Re,xa as Ve,ya as Ae,za as Le}from"../chunk-
|
|
3
|
+
import{Aa as Ne,D as ae,E as oe,F as le,G as ce,H as ue,I as de,J as me,K as he,L as pe,M as fe,N as ge,O as be,P as ye,Q as $e,R as we,S as ve,T as xe,X as Ce,Y as Se,ea as W,fa as F,ga as z,ka as Oe,la as Ie,ma as Ee,n as ne,na as ke,oa as _e,pa as qe,qa as Me,ra as Be,sa as U,ta as G,ua as Te,va as je,wa as Re,xa as Ve,ya as Ae,za as Le}from"../chunk-5k4j9sg4.js";import"../chunk-3s6cme8m.js";import"../chunk-79cr4zy3.js";import{tc as h}from"../chunk-w49dhqgq.js";import{existsSync as De}from"fs";import T from"fs/promises";import K from"os";import j from"path";import C from"process";import{EventEmitter as Pe}from"events";import v from"process";import Y from"process";import A from"process";import M from"process";import I from"process";import Z from"tty";import _t,{stdin as Zt,stdout as ei}from"process";class ee{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let e=K.homedir(),t=j.join(e,".config","clapp");this.configPath=j.join(t,"telemetry.json")}async isEnabled(){if(C.env.DO_NOT_TRACK==="1"||C.env.DO_NOT_TRACK==="true")return!1;if(C.env.NO_TELEMETRY==="1"||C.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let e=await this.loadConfig();if(e.enabled=!0,!e.userId)e.userId=this.generateUserId();await this.saveConfig(e)}async disable(){let e=await this.loadConfig();e.enabled=!1,await this.saveConfig(e)}async track(e,t){if(!await this.isEnabled())return;let s={event:e,...t,timestamp:Date.now(),platform:K.platform(),nodeVersion:C.version};if(this.events.push(s),this.events.length>=10)await this.send()}async trackCommand(e,t){await this.track("command",{command:e,duration:t})}async trackError(e,t){await this.track("error",{error:e,command:t})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let t=await this.loadConfig();return t.lastSent=Date.now(),await this.saveConfig(t),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let t=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep(t),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep(e){return new Promise((t)=>setTimeout(t,e))}async status(){let e=await this.loadConfig();return{enabled:e.enabled,doNotTrack:C.env.DO_NOT_TRACK==="1"||C.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:e.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(De(this.configPath)){let e=await T.readFile(this.configPath,"utf-8");return this.config=JSON.parse(e),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig(e){this.config=e;try{let t=j.dirname(this.configPath);await T.mkdir(t,{recursive:!0}),await T.writeFile(this.configPath,JSON.stringify(e,null,2),"utf-8")}catch{}}generateUserId(){let e=Math.random().toString(36).substring(2,15),t=Date.now().toString(36);return`${e}-${t}`}}var Dt=new ee;function V(e){return e.replace(/[<[].+/,"").trim()}function We(e){let t=/<([^>]+)>/g,i=/\[([^\]]+)\]/g,s=[],r=(l)=>{let n=!1,a=l[1];if(a.startsWith("..."))a=a.slice(3),n=!0;return{required:l[0].startsWith("<"),value:a,variadic:n}},o;while(o=t.exec(e))s.push(r(o));let d;while(d=i.exec(e))s.push(r(d));return s}function Fe(e){let t={alias:{},boolean:[]};for(let[i,s]of e.entries()){if(s.names.length>1)t.alias[s.names[0]]=s.names.slice(1);if(s.isBoolean)if(s.negated){if(!e.some((o,d)=>d!==i&&o.names.some((l)=>s.names.includes(l))&&typeof o.required==="boolean"))t.boolean.push(s.names[0])}else t.boolean.push(s.names[0])}return t}function Q(e){return e.reduce((t,i)=>t.length>=i.length?t:i,"")}function R(e,t){return e.length>=t?e:`${e}${" ".repeat(t-e.length)}`}function q(e){return e.replace(/([a-z])-([a-z])/g,(t,i,s)=>i+s.toUpperCase())}function ze(e,t,i){let s=0,r=t.length,o=e,d;for(;s<r;++s)d=o[t[s]],o=o[t[s]]=s===r-1?i:d!=null?d:!!~t[s+1].indexOf(".")||!(+t[s+1]>-1)?{}:[]}function Ue(e,t){for(let i of Object.keys(t)){let s=t[i];if(s.shouldTransform){if(e[i]=Array.prototype.concat.call([],e[i]),typeof s.transformFunction==="function")e[i]=e[i].map(s.transformFunction)}}}function Ge(e){let t=/([^\\/]+)$/.exec(e);return t?t[1]:""}function E(e){return e.split(".").map((t,i)=>i===0?q(t):t).join(".")}class k extends Error{exitCode=2;isUsageError=!0;usage;constructor(e,t){super(e);if(this.name=this.constructor.name,t!==void 0)this.usage=t;if(typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error(e).stack}format(e=!1){if(e&&this.stack)return`${this.message}
|
|
4
4
|
|
|
5
5
|
Stack trace:
|
|
6
6
|
${this.stack}`;return this.message}}function He(e){if(e instanceof k)return!0;return!!e&&typeof e==="object"&&e.name==="ClappError"&&typeof e.message==="string"}function Ke(){let{env:e}=Y,{TERM:t,TERM_PROGRAM:i}=e;if(Y.platform!=="win32")return t!=="linux";return Boolean(e.WT_SESSION)||Boolean(e.TERMINUS_SUBLIME)||e.ConEmuTask==="{cmd::Cmder}"||i==="Terminus-Sublime"||i==="vscode"||t==="xterm-256color"||t==="alacritty"||t==="rxvt-unicode"||t==="rxvt-unicode-256color"||e.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var B="\x1B",b=`${B}[`;var J={to(e,t){if(!t)return`${b}${e+1}G`;return`${b}${t+1};${e+1}H`},move(e,t){let i="";if(e<0)i+=`${b}${-e}D`;else if(e>0)i+=`${b}${e}C`;if(t<0)i+=`${b}${-t}A`;else if(t>0)i+=`${b}${t}B`;return i},up:(e=1)=>`${b}${e}A`,down:(e=1)=>`${b}${e}B`,forward:(e=1)=>`${b}${e}C`,backward:(e=1)=>`${b}${e}D`,nextLine:(e=1)=>`${b}E`.repeat(e),prevLine:(e=1)=>`${b}F`.repeat(e),left:`${b}G`,hide:`${b}?25l`,show:`${b}?25h`,save:`${B}7`,restore:`${B}8`};var zt={screen:`${b}2J`,up:(e=1)=>`${b}1J`.repeat(e),down:(e=1)=>`${b}J`.repeat(e),line:`${b}2K`,lineEnd:`${b}K`,lineStart:`${b}1K`,lines(e){let t="";for(let i=0;i<e;i++)t+=this.line+(i<e-1?J.up():"");if(e)t+=J.left;return t}},Ut={screen:`${B}c`};function Ye(e,t){let i=[];for(let s=0;s<=t.length;s++)i[s]=[s];for(let s=0;s<=e.length;s++)i[0][s]=s;for(let s=1;s<=t.length;s++)for(let r=1;r<=e.length;r++)if(t.charAt(s-1)===e.charAt(r-1))i[s][r]=i[s-1][r-1];else i[s][r]=Math.min(i[s-1][r-1]+1,i[s][r-1]+1,i[s-1][r]+1);return i[t.length][e.length]}function te(e,t,i=2,s=3){return t.map((r)=>({cmd:r,distance:Ye(e,r)})).filter(({distance:r})=>r<=i).sort((r,o)=>r.distance-o.distance).slice(0,s).map(({cmd:r})=>r)}function Qe(e,t={}){let i={_:[]},s=t.alias||{},r=new Set(t.boolean||[]),o={};for(let l of Object.keys(s))for(let n of s[l])o[n]=l;for(let l of r)if(s[l])for(let n of s[l])r.add(n);function d(l,n){let a=o[l]||l;if(i[a]=n,s[a])for(let c of s[a])i[c]=n;if(o[l]&&s[o[l]])for(let c of s[o[l]])i[c]=n;i[l]=n}for(let l=0;l<e.length;l++){let n=e[l];if(n==="--"){i._.push(...e.slice(l+1));break}if(n.startsWith("--")){let a=n.indexOf("=");if(a!==-1){let c=q(n.slice(2,a)),m=n.slice(a+1);d(c,m)}else{let c=n.slice(2);if(c.startsWith("no-")){let w=q(c.slice(3));d(w,!1);continue}let m=q(c),p=o[m]||m;if(r.has(p)||r.has(m))d(m,!0);else{let w=e[l+1];if(w!==void 0&&!w.startsWith("-"))d(m,w),l++;else d(m,!0)}}}else if(n.startsWith("-")&&n.length>1){let a=n.slice(1);for(let c=0;c<a.length;c++){let m=a[c],p=o[m]||m;if(c===a.length-1&&!r.has(p)&&!r.has(m)){let w=e[l+1];if(w!==void 0&&!w.startsWith("-"))d(m,w),l++;else d(m,!0)}else d(m,!0)}}else i._.push(n)}return i}class ie{rawName;description;name;names;isBoolean;required;config;negated;constructor(e,t,i){if(this.rawName=e,this.description=t,this.config=Object.assign({},i),e=e.replace(/\.\*/g,""),this.negated=!1,this.names=V(e).split(",").map((s)=>{let r=s.trim().replace(/^-{1,2}/,"");if(r.startsWith("no-"))this.negated=!0,r=r.replace(/^no-/,"");return E(r)}).sort((s,r)=>s.length>r.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if(e.includes("<"))this.required=!0;else if(e.includes("["))this.required=!1;else this.isBoolean=!0}}var Ht=A.argv,Je=`${A.platform}-${A.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,X=M.argv,Xe=`${M.platform}-${M.arch} node-${M.version}`;class L{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor(e,t,i,s){this.rawName=e,this.description=t,this.config=i,this.cli=s,this.options=[],this.aliasNames=[],this.name=V(e);let r=V(e),o=r.indexOf(":");if(o>0)this.namespace=r.substring(0,o),this.name=r.substring(o+1);if(this.args=We(e),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!i)this.config={}}usage(e){return this.usageText=e,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version(e,t="-v, --version"){return this.versionNumber=e,this.option(t,"Display version number"),this}example(e){return this.examples.push(e),this}option(e,t,i){let s=new ie(e,t,i);return this.options.push(s),this}alias(e){return this.aliasNames.push(e),this}action(e){return this.commandAction=e,this}before(e){return this.beforeHooks.push(e),this}after(e){return this.afterHooks.push(e),this}use(e){return this.middleware.push(e),this}isMatched(e){if(this.aliasNames.includes(e))return!0;if(this.namespace)return`${this.namespace}:${this.name}`===e;return this.name===e}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof N}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption(e){let t=E(e.split(".")[0]);return!!this.options.find((i)=>i.names.some((s)=>E(s)===t))}outputHelp(){let{name:e,commands:t}=this.cli,{versionNumber:i,options:s,helpCallback:r}=this.cli.globalCommand,o=[{body:`${e}${i?`/${i}`:""}`}];if(o.push({title:"Usage",body:` $ ${e} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&t.length>0){let a=Q(t.map((y)=>y.rawName)),c=new Map,m=[];for(let y of t)if(y.namespace){if(!c.has(y.namespace))c.set(y.namespace,[]);c.get(y.namespace).push(y)}else m.push(y);let p="";if(m.sort((y,_)=>y.rawName<_.rawName?-1:y.rawName>_.rawName?1:0),m.length>0)p+=m.map((y)=>` ${R(y.rawName,a.length)} ${y.description}`).join(`
|
|
@@ -29,7 +29,7 @@ Received ${i}, cleaning up...`),e)try{await e()}catch(s){console.error("Error du
|
|
|
29
29
|
`)),this.enableDidYouMean){let t=[];for(let s of this.commands){if(s.displayName)t.push(s.displayName);if(s.aliasNames)t.push(...s.aliasNames)}let i=te(e,t);if(i.length>0)console.log(O.yellow("Did you mean one of these?")),i.forEach((s)=>console.log(` ${O.dim("\u2022")} ${this.name} ${s}`)),console.log("")}console.log(O.dim("Run"),`${this.name} --help`,O.dim("to see all available commands")),v.exit(1)}async parse(e=X,t={}){let{run:i=!0,exitOnError:s=!1}=t;if(s)try{return await this.parse(e,{run:i})}catch(n){throw this.handleUsageError(n),n}if(this.rawArgs=e,!this.name)this.name=e[1]?Ge(e[1]):"cli";let r=!0,o=e.slice(2),d=o[0];if(d&&!d.startsWith("-")){for(let n of this.commands)if(n.isMatched(d)){let a=this.mri(o,n);r=!1;let c={...a,args:a.args.slice(1)};this.setParsedInfo(c,n,d),this.emit(`command:${d}`,n);break}if(r){let n=o[1];if(n&&!n.startsWith("-")){let a=`${d}:${n}`;for(let c of this.commands)if(c.isMatched(a)){let m=this.mri(o,c);r=!1;let p={...m,args:m.args.slice(2)};this.setParsedInfo(p,c,a),this.emit(`command:${a}`,c);break}}}}if(r){for(let n of this.commands)if(n.name===""){r=!1;let a=this.mri(o,n);this.setParsedInfo(a,n),this.emit("command:!",n);break}}if(r){let n=this.mri(e.slice(2));this.setParsedInfo(n)}if(this.options.verbose)this.isVerbose=!0;if(this.options.quiet)this.isQuiet=!0;if(this.options.debug)this.isDebug=!0;if(this.options.noInteraction||this.options.interaction===!1)this.isNoInteraction=!0;if(this.options.env)this.environment=String(this.options.env);if(this.options.dryRun)this.isDryRun=!0;if(this.options.force)this.isForce=!0;if(this.options.noEmoji||this.options.emoji===!1)this.useEmoji=!1;if(this.options.theme)this.theme=String(this.options.theme);if(this.options.noCache||this.options.cache===!1)this.isNoCache=!0;if(this.options.help&&this.showHelpOnExit)this.outputHelp(),i=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),i=!1,this.unsetMatchedCommand();let l={args:this.args,options:this.options};if(i)await this.runMatchedCommand();if(!this.matchedCommand&&this.args[0]){if(this.emit("command:*"),!(this.listenerCount("command:*")>0))this.showCommandNotFound(this.args[0])}return l}mri(e,t){let i=[...this.globalCommand.options,...t?t.options:[]],s=Fe(i),r=[],o=e.indexOf("--");if(o>-1)r=e.slice(o+1),e=e.slice(0,o);let d=Qe(e,s),l={_:d._};for(let p of Object.keys(d))if(p!=="_")l[E(p)]=d[p];let n=l._,a={"--":r},c=t&&t.config.ignoreOptionDefaultValue?t.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,m=Object.create(null);for(let p of i){if(!c&&p.config.default!==void 0)for(let w of p.names)a[w]=p.config.default;if(Array.isArray(p.config.type)){if(m[p.name]===void 0)m[p.name]={shouldTransform:!0,transformFunction:p.config.type[0]}}}for(let p of Object.keys(l))if(p!=="_"){let w=p.split(".");ze(a,w,l[p]),Ue(a,m)}return{args:n,options:a}}async run(e=X){return this.parse(e,{run:!0,exitOnError:!0})}handleUsageError(e){if(!He(e)||e.isUsageError===!1)return;let t=e.message||"command-line error",i=this.name?`${this.name}: `:"",s=/--help/.test(t)?"":e.usage?`
|
|
30
30
|
Usage: ${e.usage}`:`
|
|
31
31
|
Run \`${this.name??"cli"} --help\` for usage.`;v.stderr.write(`${i}${t}${s}
|
|
32
|
-
`),v.exit(e.exitCode??2)}async runMatchedCommand(){let{args:e,options:t,matchedCommand:i}=this;if(!i||!i.commandAction)return;i.checkUnknownOptions(),i.checkOptionValue(),i.checkRequiredArgs();let s=[];i.args.forEach((l,n)=>{if(l.variadic)s.push(e.slice(n));else s.push(e[n])}),s.push(t);let r={command:i,args:s,options:t};for(let l of i.beforeHooks)await l(r);let o,d=async()=>{let l=i.commandAction.apply(this,s);if(l instanceof Promise)o=await l;else o=l;return o};if(i.middleware.length>0){let l=0,n=async()=>{if(l<i.middleware.length){let a=i.middleware[l++];await a({...r,next:n})}else await d()};await n()}else await d();for(let l of i.afterHooks)await l(r);return o}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return v.removeAllListeners("SIGINT"),v.removeAllListeners("SIGTERM"),this.signalHandlersSet=!1,this}destroy(){this.removeSignalHandlers(),this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.matchedCommand=void 0,this.matchedCommandName=void 0,this.removeAllListeners()}}class se{cache;enabled;cleanupInterval=null;hits=0;misses=0;constructor(){this.cache=new Map,this.enabled=!0,this.startCleanupInterval()}startCleanupInterval(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanup()},30000),this.cleanupInterval.unref()}stopCleanup(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}isEnabled(){return this.enabled}get(e){if(!this.enabled){this.misses++;return}let t=this.cache.get(e);if(!t){this.misses++;return}if(Date.now()-t.timestamp>t.ttl){this.cache.delete(e),this.misses++;return}return this.hits++,t.value}set(e,t,i=5000){if(!this.enabled)return;this.cache.set(e,{value:t,timestamp:Date.now(),ttl:i})}has(e){if(!this.enabled)return!1;let t=this.cache.get(e);if(!t)return!1;if(Date.now()-t.timestamp>t.ttl)return this.cache.delete(e),!1;return!0}delete(e){this.cache.delete(e)}clear(){this.cache.clear()}disable(){this.enabled=!1,this.clear()}enable(){this.enabled=!0}stats(){return{size:this.cache.size,enabled:this.enabled,hits:this.hits,misses:this.misses}}resetStats(){this.hits=0,this.misses=0}keys(){return Array.from(this.cache.keys())}cleanup(){let e=Date.now();for(let[t,i]of this.cache.entries())if(e-i.timestamp>i.ttl)this.cache.delete(t)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var Yt=new se;function it(){if("FORCE_COLOR"in I.env)return I.env.FORCE_COLOR!=="0";if("NO_COLOR"in I.env||I.env.TERM==="dumb")return!1;if(I.platform==="win32")return!0;return Z.isatty(1)&&Z.isatty(2)}var re=it();function g(e,t){if(!re)return(i)=>i;return(i)=>e+i+t}var st=g("\x1B[0m","\x1B[0m"),rt=g("\x1B[31m","\x1B[39m"),nt=g("\x1B[32m","\x1B[39m"),at=g("\x1B[33m","\x1B[39m"),ot=g("\x1B[34m","\x1B[39m"),lt=g("\x1B[35m","\x1B[39m"),ct=g("\x1B[36m","\x1B[39m"),ut=g("\x1B[37m","\x1B[39m"),dt=g("\x1B[90m","\x1B[39m"),mt=g("\x1B[1m","\x1B[22m"),ht=g("\x1B[3m","\x1B[23m"),pt=g("\x1B[4m","\x1B[24m"),ft=g("\x1B[2m","\x1B[22m"),gt=g("\x1B[7m","\x1B[27m"),bt=g("\x1B[8m","\x1B[28m"),yt=g("\x1B[9m","\x1B[29m"),$t=g("\x1B[41m","\x1B[49m"),wt=g("\x1B[42m","\x1B[49m"),vt=g("\x1B[43m","\x1B[49m"),xt=g("\x1B[44m","\x1B[49m"),Ct=g("\x1B[45m","\x1B[49m"),St=g("\x1B[46m","\x1B[49m"),Ot=g("\x1B[47m","\x1B[49m"),It=re,Et={reset:st,red:rt,green:nt,yellow:at,blue:ot,magenta:lt,cyan:ct,white:ut,gray:dt,bold:mt,italic:ht,underline:pt,dim:ft,inverse:gt,hidden:bt,strikethrough:yt,bgRed:$t,bgGreen:wt,bgYellow:vt,bgBlue:xt,bgMagenta:Ct,bgCyan:St,bgWhite:Ot,isColorSupported:It},kt=Et,qt=["up","down","left","right","space","enter","cancel"],ti={actions:new Set(qt),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};var ii=_t.platform.startsWith("win"),si=Symbol("clapp:cancel");var Mt=Ke();var f=(e,t)=>Mt?e:t,ri=f("\u25C6","*"),ni=f("\u25A0","x"),ai=f("\u25B2","x"),oi=f("\u25C7","o"),li=f("\u250C","T"),Bt=f("\u2502","|"),ci=f("\u2514","\u2014"),ui=f("\u25CF",">"),di=f("\u25CB"," "),mi=f("\u25FB","[\u2022]"),hi=f("\u25FC","[+]"),pi=f("\u25FB","[ ]"),fi=f("\u25AA","\u2022"),gi=f("\u2500","-"),bi=f("\u256E","+"),yi=f("\u251C","+"),$i=f("\u256F","+"),wi=f("\u25CF","\u2022"),vi=f("\u25C6","*"),xi=f("\u25B2","!"),Ci=f("\u25A0","x");var Si={light:f("\u2500","-"),heavy:f("\u2501","="),block:f("\u2588","#")};function Tt(){return`${kt.gray(Bt)} `}var Oi=Tt();var P="0.2.
|
|
32
|
+
`),v.exit(e.exitCode??2)}async runMatchedCommand(){let{args:e,options:t,matchedCommand:i}=this;if(!i||!i.commandAction)return;i.checkUnknownOptions(),i.checkOptionValue(),i.checkRequiredArgs();let s=[];i.args.forEach((l,n)=>{if(l.variadic)s.push(e.slice(n));else s.push(e[n])}),s.push(t);let r={command:i,args:s,options:t};for(let l of i.beforeHooks)await l(r);let o,d=async()=>{let l=i.commandAction.apply(this,s);if(l instanceof Promise)o=await l;else o=l;return o};if(i.middleware.length>0){let l=0,n=async()=>{if(l<i.middleware.length){let a=i.middleware[l++];await a({...r,next:n})}else await d()};await n()}else await d();for(let l of i.afterHooks)await l(r);return o}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return v.removeAllListeners("SIGINT"),v.removeAllListeners("SIGTERM"),this.signalHandlersSet=!1,this}destroy(){this.removeSignalHandlers(),this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.matchedCommand=void 0,this.matchedCommandName=void 0,this.removeAllListeners()}}class se{cache;enabled;cleanupInterval=null;hits=0;misses=0;constructor(){this.cache=new Map,this.enabled=!0,this.startCleanupInterval()}startCleanupInterval(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanup()},30000),this.cleanupInterval.unref()}stopCleanup(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}isEnabled(){return this.enabled}get(e){if(!this.enabled){this.misses++;return}let t=this.cache.get(e);if(!t){this.misses++;return}if(Date.now()-t.timestamp>t.ttl){this.cache.delete(e),this.misses++;return}return this.hits++,t.value}set(e,t,i=5000){if(!this.enabled)return;this.cache.set(e,{value:t,timestamp:Date.now(),ttl:i})}has(e){if(!this.enabled)return!1;let t=this.cache.get(e);if(!t)return!1;if(Date.now()-t.timestamp>t.ttl)return this.cache.delete(e),!1;return!0}delete(e){this.cache.delete(e)}clear(){this.cache.clear()}disable(){this.enabled=!1,this.clear()}enable(){this.enabled=!0}stats(){return{size:this.cache.size,enabled:this.enabled,hits:this.hits,misses:this.misses}}resetStats(){this.hits=0,this.misses=0}keys(){return Array.from(this.cache.keys())}cleanup(){let e=Date.now();for(let[t,i]of this.cache.entries())if(e-i.timestamp>i.ttl)this.cache.delete(t)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var Yt=new se;function it(){if("FORCE_COLOR"in I.env)return I.env.FORCE_COLOR!=="0";if("NO_COLOR"in I.env||I.env.TERM==="dumb")return!1;if(I.platform==="win32")return!0;return Z.isatty(1)&&Z.isatty(2)}var re=it();function g(e,t){if(!re)return(i)=>i;return(i)=>e+i+t}var st=g("\x1B[0m","\x1B[0m"),rt=g("\x1B[31m","\x1B[39m"),nt=g("\x1B[32m","\x1B[39m"),at=g("\x1B[33m","\x1B[39m"),ot=g("\x1B[34m","\x1B[39m"),lt=g("\x1B[35m","\x1B[39m"),ct=g("\x1B[36m","\x1B[39m"),ut=g("\x1B[37m","\x1B[39m"),dt=g("\x1B[90m","\x1B[39m"),mt=g("\x1B[1m","\x1B[22m"),ht=g("\x1B[3m","\x1B[23m"),pt=g("\x1B[4m","\x1B[24m"),ft=g("\x1B[2m","\x1B[22m"),gt=g("\x1B[7m","\x1B[27m"),bt=g("\x1B[8m","\x1B[28m"),yt=g("\x1B[9m","\x1B[29m"),$t=g("\x1B[41m","\x1B[49m"),wt=g("\x1B[42m","\x1B[49m"),vt=g("\x1B[43m","\x1B[49m"),xt=g("\x1B[44m","\x1B[49m"),Ct=g("\x1B[45m","\x1B[49m"),St=g("\x1B[46m","\x1B[49m"),Ot=g("\x1B[47m","\x1B[49m"),It=re,Et={reset:st,red:rt,green:nt,yellow:at,blue:ot,magenta:lt,cyan:ct,white:ut,gray:dt,bold:mt,italic:ht,underline:pt,dim:ft,inverse:gt,hidden:bt,strikethrough:yt,bgRed:$t,bgGreen:wt,bgYellow:vt,bgBlue:xt,bgMagenta:Ct,bgCyan:St,bgWhite:Ot,isColorSupported:It},kt=Et,qt=["up","down","left","right","space","enter","cancel"],ti={actions:new Set(qt),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};var ii=_t.platform.startsWith("win"),si=Symbol("clapp:cancel");var Mt=Ke();var f=(e,t)=>Mt?e:t,ri=f("\u25C6","*"),ni=f("\u25A0","x"),ai=f("\u25B2","x"),oi=f("\u25C7","o"),li=f("\u250C","T"),Bt=f("\u2502","|"),ci=f("\u2514","\u2014"),ui=f("\u25CF",">"),di=f("\u25CB"," "),mi=f("\u25FB","[\u2022]"),hi=f("\u25FC","[+]"),pi=f("\u25FB","[ ]"),fi=f("\u25AA","\u2022"),gi=f("\u2500","-"),bi=f("\u256E","+"),yi=f("\u251C","+"),$i=f("\u256F","+"),wi=f("\u25CF","\u2022"),vi=f("\u25C6","*"),xi=f("\u25B2","!"),Ci=f("\u25A0","x");var Si={light:f("\u2500","-"),heavy:f("\u2501","="),block:f("\u2588","#")};function Tt(){return`${kt.gray(Bt)} `}var Oi=Tt();var P="0.2.62";var u=new D("query-builder");u.command("introspect <dir>","Load models and print inferred schema").option("--verbose","Enable verbose logging").example("query-builder introspect ./app/Models --verbose").action(async(e,t)=>{await xe(e,t)});u.command("introspect:db","Reverse-introspect the live database into defineModel() source (#1047)").option("--table <table>","Limit to a single table (repeatable)").example("query-builder introspect:db > app/Models/generated.ts").action(async(e)=>{let t=e?.table,i=t?Array.isArray(t)?t:[t]:void 0,s=await Ce({tables:i});console.log(`import { defineModel } from 'bun-query-builder'
|
|
33
33
|
|
|
34
34
|
${s.map((r)=>r.source).join(`
|
|
35
35
|
`)}`)});u.command("sql <dir> <table>","Build a sample query for a table").option("--limit <n>","Limit rows",{default:10}).example("query-builder sql ./app/Models users --limit 5").action(async(e,t,i)=>{await Re(e,t,i)});u.command("ping","Test database connectivity (uses environment variables)").example("query-builder ping").action(async()=>{await qe()});u.command("wait-ready","Wait for database to become ready").option("--attempts <n>","Number of attempts",{default:10}).option("--delay <ms>","Delay between attempts",{default:100}).example("query-builder wait-ready --attempts 30 --delay 250").action(async(e)=>{try{await Ne(e)}catch{let t=await import("process");t.default.exitCode=1}});u.command("unsafe <sql>","Execute an unsafe SQL string (one statement with params)").option("--params <json>","JSON array of parameters").example('query-builder unsafe "SELECT * FROM users WHERE id = $1" --params "[1]"').action(async(e,t)=>{await Ve(e,t)});u.command("file <path>","Execute a SQL file (supports $1, $2 params)").option("--params <json>","JSON array of parameters").example("query-builder file ./migrations/seed.sql").example('query-builder file ./reports/top.sql --params "[30]"').action(async(e,t)=>{await $e(e,t)});u.command("migrate <dir>","Generate SQL migrations from models").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--state <path>","Path to migration state file (defaults to <dir>/.qb-migrations.<dialect>.json)").option("--apply","Execute the generated SQL against the database").option("--full","Force full migration SQL instead of incremental diff").example("query-builder migrate ./app/Models --dialect postgres").action(async(e,t)=>{try{await W(e,{dialect:t.dialect,state:t.state,apply:t.apply,full:t.full}),await F()}catch(i){console.error("-- Migration failed:",i);let s=await import("process");s.default.exitCode=1}});u.command("explain <sql>","Explain a query").example('query-builder explain "SELECT * FROM users WHERE active = true"').action(async(e)=>{await ye(e)});u.command("query:explain-all <path>","Run EXPLAIN on all SQL files in a directory").option("--verbose","Enable verbose output").option("--json","Output as JSON").example("query-builder query:explain-all ./queries").example("query-builder query:explain-all ./queries/users.sql").action(async(e,t)=>{try{await Me(e,{verbose:t.verbose,json:t.json})}catch(i){console.error("-- Explain all failed:",i);let s=await import("process");s.default.exitCode=1}});u.command("relation:diagram","Generate relationship diagram from models").option("--dir <path>","Models directory (defaults to app/Models)").option("--format <fmt>","Output format (mermaid|dot)",{default:"mermaid"}).option("--output <path>","Output file path").option("--verbose","Enable verbose output").example("query-builder relation:diagram").example("query-builder relation:diagram --format dot --output schema.dot").example("query-builder relation:diagram --output schema.mmd").action(async(e)=>{try{await Be({dir:e.dir,format:e.format,output:e.output,verbose:e.verbose})}catch(t){console.error("-- Diagram generation failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("migrate:fresh <dir>","Reset database and run all migrations").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--state <path>","Path to migration state file (defaults to <dir>/.qb-migrations.<dialect>.json)").option("--full","Force full migration SQL instead of incremental diff").example("query-builder migrate:fresh ./app/Models --dialect postgres").action(async(e,t)=>{try{console.log("-- Resetting database..."),await z(e,{dialect:t.dialect,state:t.state}),console.log("-- Generating fresh migrations..."),await W(e,{dialect:t.dialect,state:t.state,full:t.full}),console.log("-- Executing migrations..."),await F()}catch(i){console.error("-- Migrate fresh failed:",i);let s=await import("process");s.default.exitCode=1}});u.command("reset <dir>","Drop all tables and reset database").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--state <path>","Path to migration state file (defaults to <dir>/.qb-migrations.<dialect>.json)").example("query-builder reset ./app/Models --dialect postgres").action(async(e,t)=>{try{await z(e,{dialect:t.dialect,state:t.state})}catch(i){console.error("-- Reset failed:",i);let s=await import("process");s.default.exitCode=1}});u.command("seed","Run database seeders").option("--dir <path>","Path to seeders directory (defaults to database/seeders)").option("--class <name>","Run a specific seeder class").option("--verbose","Enable verbose logging").example("query-builder seed").example("query-builder seed --class UserSeeder").example("query-builder seed --dir ./database/seeders").action(async(e)=>{try{if(e.class)await G(e.class,{verbose:e.verbose});else await U({seedersDir:e.dir,verbose:e.verbose})}catch(t){console.error("-- Seeding failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("db:seed","Run database seeders (alias for seed)").option("--dir <path>","Path to seeders directory (defaults to database/seeders)").option("--class <name>","Run a specific seeder class").option("--verbose","Enable verbose logging").example("query-builder db:seed").example("query-builder db:seed --class UserSeeder").action(async(e)=>{try{if(e.class)await G(e.class,{verbose:e.verbose});else await U({seedersDir:e.dir,verbose:e.verbose})}catch(t){console.error("-- Seeding failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("make:seeder <name>","Create a new seeder file").example("query-builder make:seeder User").example("query-builder make:seeder UserSeeder").action(async(e)=>{try{await Te(e)}catch(t){console.error("-- Failed to create seeder:",t);let i=await import("process");i.default.exitCode=1}});u.command("db:fresh","Drop all tables, re-run migrations and seed the database").option("--models <path>","Path to models directory (defaults to app/Models)").option("--seeders <path>","Path to seeders directory (defaults to database/seeders)").option("--verbose","Enable verbose logging").example("query-builder db:fresh").example("query-builder db:fresh --models ./app/Models --seeders ./database/seeders").action(async(e)=>{try{await je({modelsDir:e.models,seedersDir:e.seeders,verbose:e.verbose})}catch(t){console.error("-- Database fresh failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("make:model <name>","Create a new model file").option("--table <name>","Table name (defaults to plural of model name)").option("--dir <path>","Models directory (defaults to app/Models)").option("--timestamps","Include timestamp fields (default: true)").example("query-builder make:model User").example("query-builder make:model Post --table=blog_posts").action(async(e,t)=>{try{await Se(e,{table:t.table,dir:t.dir,timestamps:t.timestamps})}catch(i){console.error("-- Failed to create model:",i);let s=await import("process");s.default.exitCode=1}});u.command("model:show <name>","Show detailed model information").option("--dir <path>","Models directory (defaults to app/Models)").option("--json","Output as JSON").option("--verbose","Enable verbose output").example("query-builder model:show User").example("query-builder model:show Post --json").action(async(e,t)=>{try{await _e(e,{dir:t.dir,json:t.json,verbose:t.verbose})}catch(i){console.error("-- Failed to show model:",i);let s=await import("process");s.default.exitCode=1}});u.command("migrate:status","Show migration status").example("query-builder migrate:status").action(async()=>{try{await Ee()}catch(e){console.error("-- Failed to get migration status:",e);let t=await import("process");t.default.exitCode=1}});u.command("migrate:list","List all migrations (alias for migrate:status)").example("query-builder migrate:list").action(async()=>{try{await ke()}catch(e){console.error("-- Failed to list migrations:",e);let t=await import("process");t.default.exitCode=1}});u.command("migrate:rollback","Rollback migrations").option("--steps <n>","Number of migrations to rollback",{default:1}).option("--no-reverse-schema","Only remove the migration records; leave the schema alone").option("--delete-files","Also delete the rolled-back migration files from disk").example("query-builder migrate:rollback").example("query-builder migrate:rollback --steps 2").example("query-builder migrate:rollback --no-reverse-schema").action(async(e)=>{try{await Ie({steps:Number(e.steps),reverseSchema:e.reverseSchema,deleteFiles:Boolean(e.deleteFiles)})}catch(t){console.error("-- Rollback failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("migrate:generate [dir]","Generate migration from model changes").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--state <path>","Path to migration state file").option("--apply","Execute the generated SQL").option("--full","Force full migration SQL").example("query-builder migrate:generate").example("query-builder migrate:generate ./app/Models --dialect postgres").action(async(e,t)=>{try{await Oe(e,{dialect:t?.dialect,state:t?.state,apply:t?.apply,full:t?.full})}catch(i){console.error("-- Generate migration failed:",i);let s=await import("process");s.default.exitCode=1}});u.command("db:info","Show database information and statistics").example("query-builder db:info").action(async()=>{try{await pe()}catch(e){console.error("-- Failed to get database info:",e);let t=await import("process");t.default.exitCode=1}});u.command("db:stats","Show database statistics (alias for db:info)").example("query-builder db:stats").action(async()=>{try{await fe()}catch(e){console.error("-- Failed to get database stats:",e);let t=await import("process");t.default.exitCode=1}});u.command("db:wipe","Drop all tables from the database").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--force","Skip confirmation prompt").option("--verbose","Enable verbose output").example("query-builder db:wipe").example("query-builder db:wipe --force").action(async(e)=>{try{await be({dialect:e.dialect,force:e.force,verbose:e.verbose})}catch(t){console.error("-- Wipe failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("db:optimize","Optimize database tables (VACUUM, ANALYZE, OPTIMIZE)").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--aggressive","Use aggressive optimization (VACUUM FULL for postgres)").option("--tables <tables>","Comma-separated list of tables to optimize").option("--verbose","Enable verbose output").example("query-builder db:optimize").example("query-builder db:optimize --aggressive").example("query-builder db:optimize --tables users,posts").action(async(e)=>{try{await ge({dialect:e.dialect,aggressive:e.aggressive,tables:e.tables?e.tables.split(","):void 0,verbose:e.verbose})}catch(t){console.error("-- Optimize failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("console","Start interactive query console").example("query-builder console").action(async()=>{try{await ce()}catch(e){console.error("-- Console failed:",e);let t=await import("process");t.default.exitCode=1}});u.command("tinker","Start interactive query console (alias for console)").example("query-builder tinker").action(async()=>{try{await ue()}catch(e){console.error("-- Tinker failed:",e);let t=await import("process");t.default.exitCode=1}});u.command("inspect <table>","Inspect a table structure").option("--verbose","Enable verbose output",{default:!0}).example("query-builder inspect users").action(async(e,t)=>{try{await we(e,{verbose:t.verbose})}catch(i){console.error("-- Failed to inspect table:",i);let s=await import("process");s.default.exitCode=1}});u.command("table:info <table>","Show table information (alias for inspect)").option("--verbose","Enable verbose output",{default:!0}).example("query-builder table:info users").action(async(e,t)=>{try{await ve(e,{verbose:t.verbose})}catch(i){console.error("-- Failed to get table info:",i);let s=await import("process");s.default.exitCode=1}});u.command("cache:clear","Clear the query cache").example("query-builder cache:clear").action(async()=>{try{await ae()}catch(e){console.error("-- Failed to clear cache:",e);let t=await import("process");t.default.exitCode=1}});u.command("cache:stats","Show cache statistics").example("query-builder cache:stats").action(async()=>{try{await oe()}catch(e){console.error("-- Failed to get cache stats:",e);let t=await import("process");t.default.exitCode=1}});u.command("cache:config","Configure cache settings").option("--size <n>","Set maximum cache size").example("query-builder cache:config --size 500").action(async(e)=>{try{await le({size:e.size})}catch(t){console.error("-- Failed to configure cache:",t);let i=await import("process");i.default.exitCode=1}});u.command("benchmark","Run performance benchmarks").option("--operations <ops>","Comma-separated list of operations (select,insert,update,delete,count)").option("--iterations <n>","Number of iterations per operation",{default:1000}).example("query-builder benchmark").example("query-builder benchmark --operations select,insert --iterations 5000").action(async(e)=>{try{await ne({operations:e.operations,iterations:e.iterations?Number(e.iterations):void 0})}catch(t){console.error("-- Benchmark failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("validate:schema [dir]","Validate models against database schema").example("query-builder validate:schema").example("query-builder validate:schema ./app/Models").action(async(e)=>{try{await Ae(e)}catch(t){console.error("-- Validation failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("check [dir]","Validate schema (alias for validate:schema)").example("query-builder check").action(async(e)=>{try{await Le(e)}catch(t){console.error("-- Check failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("export <table>","Export data from a table").option("--format <fmt>","Export format (json|csv|sql)",{default:"json"}).option("--output <path>","Output file path").option("--limit <n>","Limit number of rows").example("query-builder export users").example("query-builder export users --format csv --output users.csv").example("query-builder export users --format sql --limit 100").action(async(e,t)=>{try{await de(e,{format:t.format,output:t.output,limit:t.limit?Number(t.limit):void 0})}catch(i){console.error("-- Export failed:",i);let s=await import("process");s.default.exitCode=1}});u.command("import <table> <file>","Import data into a table").option("--format <fmt>","Import format (json|csv)").option("--truncate","Truncate table before import").example("query-builder import users users.json").example("query-builder import users users.csv --truncate").action(async(e,t,i)=>{try{await me(e,t,{format:i.format,truncate:i.truncate})}catch(s){console.error("-- Import failed:",s);let r=await import("process");r.default.exitCode=1}});u.command("dump","Dump database to SQL file").option("--tables <tables>","Comma-separated list of tables to dump").option("--output <path>","Output file path").example("query-builder dump").example("query-builder dump --tables users,posts").example("query-builder dump --output backup.sql").action(async(e)=>{try{await he({tables:e.tables,output:e.output})}catch(t){console.error("-- Dump failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("version","Show the version of the CLI").action(()=>{console.log(P)});u.version(P);u.help();u.parse();
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{rc as xt,sc as V}from"./chunk-fn0m2c0v.js";import{existsSync as rr}from"fs";import{join as ar}from"path";import ir from"process";import{existsSync as dt,statSync as ft}from"fs";import{join as nr,relative as or,resolve as gt}from"path";import ke from"process";import{Buffer as M}from"buffer";import{createCipheriv as sr,createDecipheriv as lr,randomBytes as Ie}from"crypto";import{closeSync as Je,createReadStream as pt,createWriteStream as cr,existsSync as ye,fsyncSync as yt,openSync as bt,writeFileSync as hr}from"fs";import{access as mr,constants as wt,mkdir as ur,readdir as be,rename as Ct,stat as F,unlink as we,writeFile as ze}from"fs/promises";import{isAbsolute as dr,join as D,resolve as fr}from"path";import g from"process";import{pipeline as gr}from"stream/promises";import{createGzip as vt}from"zlib";import H from"process";import T from"process";import Ce from"process";import{existsSync as ve}from"fs";import{resolve as _e}from"path";import{existsSync as pr}from"fs";import{existsSync as qe,mkdirSync as yr,readdirSync as br,readFileSync as wr,writeFileSync as Cr}from"fs";import{homedir as O}from"os";import{dirname as St,resolve as w}from"path";import L from"process";import{existsSync as vr,readdirSync as Sr}from"fs";import{extname as Be,resolve as Et}from"path";import Er from"process";import{spawnSync as ga}from"child_process";import{existsSync as j,readFileSync as pa}from"fs";import{join as G}from"path";import Zt from"process";function Mr(e,t){this[e]=Ar.bind(null,t)}class it{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,a])=>r.timestamp.getTime()-a.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,a){if(!this.options.enabled)return;let i=this.generateKey(e,r),n=a??this.options.ttl,o=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:n,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),a=this.cache.get(r);if(!a){this.totalMisses++;return}if(this.isExpired(a)){this.cache.delete(r),this.totalMisses++;return}return a.hits++,this.totalHits++,a.value}isFileModified(e,t){try{if(!dt(e))return!0;return ft(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,a){try{let i=dt(r)?ft(r):null,n=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:n},r,a)}catch{this.set(e,t,r,a)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((a,i)=>a+i.size,0),r=e.map((a)=>a.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let a=r;this.cache.set(t,{value:a.value,timestamp:new Date(a.timestamp),ttl:a.ttl,hits:a.hits,size:a.size})}}}class nt{metrics=[];maxMetrics=1000;async track(e,t,r={}){let a=performance.now(),i=new Date;try{let n=await t(),o=performance.now()-a;return this.recordMetric({operation:e,duration:o,timestamp:i,...r}),n}catch(n){let o=performance.now()-a;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:i,...r}),n}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),a=r.reduce((i,n)=>i+n,0);return{count:t.length,averageDuration:a/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:a,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function Pr(e,t={}){let r=Object.keys(t).sort().map((a)=>`${a}:${t[a]}`).join("|");return r?`${e}:${r}`:e}function Nr(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function xr(e){return e.getStats().size*2}function Rr(e,t={}){let r=ke.cwd();while(r.includes("storage"))r=gt(r,"..");let a=gt(r,e||"");if(t?.relative)return or(ke.cwd(),a);return a}function p(){if(T.env.NODE_ENV==="test"||T.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Lr(){if(T.env.NODE_ENV==="test"||T.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof T<"u"){let e=T.type;if(e==="renderer"||e==="worker")return!1;return!!(T.versions&&(T.versions.node||T.versions.bun))}return!1}class Lt{async format(e){let t=await Lr(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:H.pid,hostname:t(),environment:H.env.NODE_ENV||"development",platform:H.platform,version:H.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:H.env.NODE_ENV||H.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Oe{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...U},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Lt,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??g.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},a=t.timestamp!==void 0;if(a)delete r.timestamp;if(this.config={...this.config,...r,timestamp:a||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),n=this.generateKey();this.currentKeyId=i,this.keys.set(i,n),this.encryptionKeys.set(i,{key:n,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Ee,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Ee};return{...Ee,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:U.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,a])=>a!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!p()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let a,i=0,n=3,o=1000;while(i<n)try{try{try{await mr(this.config.logDirectory,wt.F_OK|wt.W_OK)}catch(s){if(s instanceof Error&&"code"in s)if(s.code==="ENOENT")await ur(this.config.logDirectory,{recursive:!0,mode:493});else if(s.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw s;else throw s}}catch(s){throw console.error("Debug: [writeToFile] Failed to create log directory:",s),s}let l=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:M.from(e);try{if(!ye(this.currentLogFile))await ze(this.currentLogFile,"",{mode:420});if(a=bt(this.currentLogFile,"a",420),hr(a,l,{flag:"a"}),yt(a),a!==void 0)Je(a),a=void 0;if((await F(this.currentLogFile)).size===0){if(await ze(this.currentLogFile,l,{flag:"w",mode:420}),(await F(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(s){let c=s;if(c.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(c.code)){if(i<n-1){let h=typeof c.message==="string"?c.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${n}:`,h);let m=o*2**i;await new Promise((u)=>setTimeout(u,m)),i++;continue}}if(c?.code&&["ENOSPC","EDQUOT"].includes(c.code))throw Error(`Disk quota exceeded or no space left on device: ${c.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",c),c}finally{if(a!==void 0)try{Je(a)}catch(s){console.error("Debug: [writeToFile] Error closing file descriptor:",s)}}}catch(l){if(i===n-1){let c=l,h=typeof c.message==="string"?c.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),l}i++;let s=o*2**(i-1);await new Promise((c)=>setTimeout(c,s))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(a){throw console.error("Debug: [writeToFile] Error in operation:",a),a}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return D(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return D(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return D(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(p())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((a)=>{console.error("Error rotating keys:",a)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let a=Array.from(this.encryptionKeys.entries()).sort(([,o],[,l])=>l.createdAt.getTime()-o.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,n=Math.max(1,i);if(a.length>n)for(let[o]of a.slice(n))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return Ie(16).toString("hex")}generateKey(){return Ie(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=Ie(16),a=sr("aes-256-gcm",t,r),i=M.isBuffer(e)?e:M.from(e,"utf8"),n=a.update(i),o=a.final(),l=n.length+o.length,s=a.getAuthTag(),c=M.allocUnsafe(16+l+16);return r.copy(c,0),n.copy(c,16),o.copy(c,16+n.length),s.copy(c,16+l),{encrypted:c,iv:r}}async compressData(e){return new Promise((t,r)=>{let a=vt(),i=[];a.on("data",(n)=>i.push(n)),a.on("end",()=>t(M.from(M.concat(i)))),a.on("error",r),a.write(e),a.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(p())return;if(!this.shouldWriteToFile())return;let e=await F(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,a=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await be(this.config.logDirectory),n=i.filter((s)=>s.startsWith(this.name)&&/\.log\.\d+$/.test(s)).sort((s,c)=>{let h=Number.parseInt(s.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),o=n.length>0?Number.parseInt(n[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${r}.${o}`;if(await F(r).catch(()=>null))try{if(await Ct(r,l),t.compress)try{let s=`${l}.gz`;await this.compressLogFile(l,s),await we(l)}catch(s){console.error("Error compressing rotated file:",s)}if(n.length===0&&!i.some((s)=>s.endsWith(".log.1")))try{let s=`${r}.1`;await ze(s,"")}catch(s){console.error("Error creating backup file:",s)}}catch(s){console.error(`Error during rotation: ${s instanceof Error?s.message:String(s)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),n=r.replace(/\.log$/,`-${i}.log`);if(await F(r).catch(()=>null))await Ct(r,n)}if(this.currentLogFile=a,t.maxFiles){let i=(await be(this.config.logDirectory)).filter((n)=>n.startsWith(this.name)).sort((n,o)=>o.localeCompare(n));for(let n of i.slice(t.maxFiles))await we(D(this.config.logDirectory,n))}}}async compressLogFile(e,t){let r=pt(e),a=cr(t),i=vt();await gr(r,i,a)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let a=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(a);console.log(a)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),ye(this.currentLogFile))try{let e=bt(this.currentLogFile,"r+");yt(e),Je(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!p()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await be(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await we(D(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?f.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||p())return!1;let e=typeof g.env.NO_COLOR<"u",t=g.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof g.stderr<"u"&&g.stderr.isTTY||typeof g.stdout<"u"&&g.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:a="",message:i,level:n,showTimestamp:o=!0}=e,l=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(n==="warning")d.push("WARN");else if(n==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(a)d.push(a.replace(/[[\]]/g,""));return d.push(i),d.join(" ")}let s=g.stdout.columns||120,c="";if(n==="warning"||n==="error")c=`${r} ${i}`;else if(n==="info"||n==="success")c=`${r} ${a} ${i}`;else c=`${r} ${a} ${f.cyan(i)}`;if(!o)return c.trim();let h=l(c).trim().length,m=l(t).length,u=Math.max(1,s-2-h-m);return`${c.trim()}${" ".repeat(u)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(n,o)=>{let l=Number.parseInt(o,10);return l<t[0].length?String(t[0][l]):n});let r=/%([sdijfo%])/g,a=0,i=e.replace(r,(n,o)=>{if(o==="%")return"%";if(a>=t.length)return n;let l=t[a++];switch(o){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return n}});if(a<t.length)i+=` ${t.slice(a).map((n)=>typeof n==="object"?JSON.stringify(n,null,2):String(n)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,a,i)=>{let n=f.underline(f.blue(a)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(o)}`,s="\x1B]8;;",c="\x1B\\";return`\x1B]8;;${l}\x1B\\${n}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${n}\x1B]8;;\x1B\\`;return n}),t=t.replace(/`([^`]+)`/g,(r,a)=>f.bgGray(a)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,a)=>f.bold(a)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,a)=>f.italic(a)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,a)=>f.italic(a)),t=t.replace(/~([^~]+)~/g,(r,a)=>f.strikethrough(a)),t}supportsHyperlinks(){if(p())return!1;let e=g.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=g.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(dr(t)||t.startsWith("./")||t.startsWith("../"))t=fr(t);else return null;return ye(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let a=new Date,i=this.formatConsoleTimestamp(a),n=this.formatFileTimestamp(a),o,l;if(t instanceof Error)o=t.message,l=t.stack;else o=this.formatMessage(t,r);let{consoleText:s,fileText:c}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let m=this.options.showIcons===!1?"":Ft[e],u=this.options.showTags!==!1&&this.name?f.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:i,icon:m,tag:u,message:f.gray(s),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:i,icon:m,tag:u,message:s,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:i,icon:m,tag:u,message:f.green(s),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:i,icon:m,tag:u,message:s,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:i,icon:m,tag:u,message:s,level:e}),console.error(d),l){let S=l.split(`
|
|
2
|
+
import{sc as xt,tc as V}from"./chunk-w49dhqgq.js";import{existsSync as rr}from"fs";import{join as ar}from"path";import ir from"process";import{existsSync as dt,statSync as ft}from"fs";import{join as nr,relative as or,resolve as gt}from"path";import ke from"process";import{Buffer as M}from"buffer";import{createCipheriv as sr,createDecipheriv as lr,randomBytes as Ie}from"crypto";import{closeSync as Je,createReadStream as pt,createWriteStream as cr,existsSync as ye,fsyncSync as yt,openSync as bt,writeFileSync as hr}from"fs";import{access as mr,constants as wt,mkdir as ur,readdir as be,rename as Ct,stat as F,unlink as we,writeFile as ze}from"fs/promises";import{isAbsolute as dr,join as D,resolve as fr}from"path";import g from"process";import{pipeline as gr}from"stream/promises";import{createGzip as vt}from"zlib";import H from"process";import T from"process";import Ce from"process";import{existsSync as ve}from"fs";import{resolve as _e}from"path";import{existsSync as pr}from"fs";import{existsSync as qe,mkdirSync as yr,readdirSync as br,readFileSync as wr,writeFileSync as Cr}from"fs";import{homedir as O}from"os";import{dirname as St,resolve as w}from"path";import L from"process";import{existsSync as vr,readdirSync as Sr}from"fs";import{extname as Be,resolve as Et}from"path";import Er from"process";import{spawnSync as ga}from"child_process";import{existsSync as j,readFileSync as pa}from"fs";import{join as G}from"path";import Zt from"process";function Mr(e,t){this[e]=Ar.bind(null,t)}class it{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,a])=>r.timestamp.getTime()-a.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,a){if(!this.options.enabled)return;let i=this.generateKey(e,r),n=a??this.options.ttl,o=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:n,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),a=this.cache.get(r);if(!a){this.totalMisses++;return}if(this.isExpired(a)){this.cache.delete(r),this.totalMisses++;return}return a.hits++,this.totalHits++,a.value}isFileModified(e,t){try{if(!dt(e))return!0;return ft(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,a){try{let i=dt(r)?ft(r):null,n=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:n},r,a)}catch{this.set(e,t,r,a)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((a,i)=>a+i.size,0),r=e.map((a)=>a.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let a=r;this.cache.set(t,{value:a.value,timestamp:new Date(a.timestamp),ttl:a.ttl,hits:a.hits,size:a.size})}}}class nt{metrics=[];maxMetrics=1000;async track(e,t,r={}){let a=performance.now(),i=new Date;try{let n=await t(),o=performance.now()-a;return this.recordMetric({operation:e,duration:o,timestamp:i,...r}),n}catch(n){let o=performance.now()-a;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:i,...r}),n}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),a=r.reduce((i,n)=>i+n,0);return{count:t.length,averageDuration:a/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:a,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function Pr(e,t={}){let r=Object.keys(t).sort().map((a)=>`${a}:${t[a]}`).join("|");return r?`${e}:${r}`:e}function Nr(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function xr(e){return e.getStats().size*2}function Rr(e,t={}){let r=ke.cwd();while(r.includes("storage"))r=gt(r,"..");let a=gt(r,e||"");if(t?.relative)return or(ke.cwd(),a);return a}function p(){if(T.env.NODE_ENV==="test"||T.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Lr(){if(T.env.NODE_ENV==="test"||T.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof T<"u"){let e=T.type;if(e==="renderer"||e==="worker")return!1;return!!(T.versions&&(T.versions.node||T.versions.bun))}return!1}class Lt{async format(e){let t=await Lr(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:H.pid,hostname:t(),environment:H.env.NODE_ENV||"development",platform:H.platform,version:H.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:H.env.NODE_ENV||H.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Oe{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...U},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Lt,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??g.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},a=t.timestamp!==void 0;if(a)delete r.timestamp;if(this.config={...this.config,...r,timestamp:a||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),n=this.generateKey();this.currentKeyId=i,this.keys.set(i,n),this.encryptionKeys.set(i,{key:n,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Ee,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Ee};return{...Ee,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:U.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,a])=>a!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!p()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let a,i=0,n=3,o=1000;while(i<n)try{try{try{await mr(this.config.logDirectory,wt.F_OK|wt.W_OK)}catch(s){if(s instanceof Error&&"code"in s)if(s.code==="ENOENT")await ur(this.config.logDirectory,{recursive:!0,mode:493});else if(s.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw s;else throw s}}catch(s){throw console.error("Debug: [writeToFile] Failed to create log directory:",s),s}let l=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:M.from(e);try{if(!ye(this.currentLogFile))await ze(this.currentLogFile,"",{mode:420});if(a=bt(this.currentLogFile,"a",420),hr(a,l,{flag:"a"}),yt(a),a!==void 0)Je(a),a=void 0;if((await F(this.currentLogFile)).size===0){if(await ze(this.currentLogFile,l,{flag:"w",mode:420}),(await F(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(s){let c=s;if(c.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(c.code)){if(i<n-1){let h=typeof c.message==="string"?c.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${n}:`,h);let m=o*2**i;await new Promise((u)=>setTimeout(u,m)),i++;continue}}if(c?.code&&["ENOSPC","EDQUOT"].includes(c.code))throw Error(`Disk quota exceeded or no space left on device: ${c.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",c),c}finally{if(a!==void 0)try{Je(a)}catch(s){console.error("Debug: [writeToFile] Error closing file descriptor:",s)}}}catch(l){if(i===n-1){let c=l,h=typeof c.message==="string"?c.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),l}i++;let s=o*2**(i-1);await new Promise((c)=>setTimeout(c,s))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(a){throw console.error("Debug: [writeToFile] Error in operation:",a),a}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return D(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return D(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return D(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(p())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((a)=>{console.error("Error rotating keys:",a)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let a=Array.from(this.encryptionKeys.entries()).sort(([,o],[,l])=>l.createdAt.getTime()-o.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,n=Math.max(1,i);if(a.length>n)for(let[o]of a.slice(n))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return Ie(16).toString("hex")}generateKey(){return Ie(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=Ie(16),a=sr("aes-256-gcm",t,r),i=M.isBuffer(e)?e:M.from(e,"utf8"),n=a.update(i),o=a.final(),l=n.length+o.length,s=a.getAuthTag(),c=M.allocUnsafe(16+l+16);return r.copy(c,0),n.copy(c,16),o.copy(c,16+n.length),s.copy(c,16+l),{encrypted:c,iv:r}}async compressData(e){return new Promise((t,r)=>{let a=vt(),i=[];a.on("data",(n)=>i.push(n)),a.on("end",()=>t(M.from(M.concat(i)))),a.on("error",r),a.write(e),a.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(p())return;if(!this.shouldWriteToFile())return;let e=await F(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,a=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await be(this.config.logDirectory),n=i.filter((s)=>s.startsWith(this.name)&&/\.log\.\d+$/.test(s)).sort((s,c)=>{let h=Number.parseInt(s.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),o=n.length>0?Number.parseInt(n[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${r}.${o}`;if(await F(r).catch(()=>null))try{if(await Ct(r,l),t.compress)try{let s=`${l}.gz`;await this.compressLogFile(l,s),await we(l)}catch(s){console.error("Error compressing rotated file:",s)}if(n.length===0&&!i.some((s)=>s.endsWith(".log.1")))try{let s=`${r}.1`;await ze(s,"")}catch(s){console.error("Error creating backup file:",s)}}catch(s){console.error(`Error during rotation: ${s instanceof Error?s.message:String(s)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),n=r.replace(/\.log$/,`-${i}.log`);if(await F(r).catch(()=>null))await Ct(r,n)}if(this.currentLogFile=a,t.maxFiles){let i=(await be(this.config.logDirectory)).filter((n)=>n.startsWith(this.name)).sort((n,o)=>o.localeCompare(n));for(let n of i.slice(t.maxFiles))await we(D(this.config.logDirectory,n))}}}async compressLogFile(e,t){let r=pt(e),a=cr(t),i=vt();await gr(r,i,a)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let a=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(a);console.log(a)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),ye(this.currentLogFile))try{let e=bt(this.currentLogFile,"r+");yt(e),Je(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!p()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await be(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await we(D(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?f.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||p())return!1;let e=typeof g.env.NO_COLOR<"u",t=g.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof g.stderr<"u"&&g.stderr.isTTY||typeof g.stdout<"u"&&g.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:a="",message:i,level:n,showTimestamp:o=!0}=e,l=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(n==="warning")d.push("WARN");else if(n==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(a)d.push(a.replace(/[[\]]/g,""));return d.push(i),d.join(" ")}let s=g.stdout.columns||120,c="";if(n==="warning"||n==="error")c=`${r} ${i}`;else if(n==="info"||n==="success")c=`${r} ${a} ${i}`;else c=`${r} ${a} ${f.cyan(i)}`;if(!o)return c.trim();let h=l(c).trim().length,m=l(t).length,u=Math.max(1,s-2-h-m);return`${c.trim()}${" ".repeat(u)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(n,o)=>{let l=Number.parseInt(o,10);return l<t[0].length?String(t[0][l]):n});let r=/%([sdijfo%])/g,a=0,i=e.replace(r,(n,o)=>{if(o==="%")return"%";if(a>=t.length)return n;let l=t[a++];switch(o){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return n}});if(a<t.length)i+=` ${t.slice(a).map((n)=>typeof n==="object"?JSON.stringify(n,null,2):String(n)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,a,i)=>{let n=f.underline(f.blue(a)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(o)}`,s="\x1B]8;;",c="\x1B\\";return`\x1B]8;;${l}\x1B\\${n}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${n}\x1B]8;;\x1B\\`;return n}),t=t.replace(/`([^`]+)`/g,(r,a)=>f.bgGray(a)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,a)=>f.bold(a)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,a)=>f.italic(a)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,a)=>f.italic(a)),t=t.replace(/~([^~]+)~/g,(r,a)=>f.strikethrough(a)),t}supportsHyperlinks(){if(p())return!1;let e=g.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=g.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(dr(t)||t.startsWith("./")||t.startsWith("../"))t=fr(t);else return null;return ye(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let a=new Date,i=this.formatConsoleTimestamp(a),n=this.formatFileTimestamp(a),o,l;if(t instanceof Error)o=t.message,l=t.stack;else o=this.formatMessage(t,r);let{consoleText:s,fileText:c}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let m=this.options.showIcons===!1?"":Ft[e],u=this.options.showTags!==!1&&this.name?f.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:i,icon:m,tag:u,message:f.gray(s),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:i,icon:m,tag:u,message:s,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:i,icon:m,tag:u,message:f.green(s),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:i,icon:m,tag:u,message:s,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:i,icon:m,tag:u,message:s,level:e}),console.error(d),l){let S=l.split(`
|
|
3
3
|
`);for(let b of S)if(b.trim()&&!b.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:f.gray(` ${b}`),level:e,showTimestamp:!1}))}break}}else if(!p()){if(console.error(`${n} ${this.environment}.${e.toUpperCase()}: ${o}`),l)console.error(l)}let h=`${n} ${this.environment}.${e.toUpperCase()}: ${c}
|
|
4
4
|
`;if(l)h+=`${l}
|
|
5
5
|
`;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(e,t=""){let r={update:(i,n)=>{},finish:(i)=>{},interrupt:(i,n)=>{}};if(!this.enabled)return r;let a=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:a,lastRenderedLine:""},this.shouldStyleConsole()&&!p()&&g.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(i,n)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,i),this.activeProgressBar.total),n!==void 0)this.activeProgressBar.message=n;if(this.shouldStyleConsole()&&!p()&&g.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(i)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,i)},interrupt:(i,n="info")=>{if(!p()&&g.stdout.isTTY)g.stdout.write(`
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{rc as p}from"./chunk-fn0m2c0v.js";function D(e){n={...n,...e}}function k(){return n}function B(){return typeof window<"u"&&typeof document<"u"}async function y(){if(n.getToken){let e=n.getToken();return e instanceof Promise?e:e}if(typeof localStorage<"u")return localStorage.getItem("auth_token");return null}async function l(){let e={"Content-Type":"application/json",Accept:"application/json",...n.headers},t=await y();if(t)e.Authorization=`Bearer ${t}`;return e}async function u(e){if(e.status===401)throw n.onUnauthorized?.(),new d("Unauthorized",401);if(!e.ok){let r=await e.json().catch(()=>({message:"Request failed"}));throw new d(r.message||`HTTP ${e.status}`,e.status)}let t=await e.json();if(n.transformResponse)return n.transformResponse(t);return t}class m{state;constructor(e){this.state={table:e,wheres:[],orderBy:[],selectColumns:["*"],withRelations:[]}}select(...e){return this.state.selectColumns=e,this}where(e,t,r){if(r===void 0)this.state.wheres.push({column:e,operator:"=",value:t,boolean:"and"});else this.state.wheres.push({column:e,operator:t,value:r,boolean:"and"});return this}orWhere(e,t,r){throw TypeError("[browser] orWhere() is not supported by this client. The query-param format it builds has no spelling for a disjunction, so the term would be sent as a plain filter and the server would read it as AND \u2014 silently returning a superset of the rows you asked for. Express the alternatives as a single filter (whereIn), or issue one request per branch and merge the results.")}andWhere(e,t,r){return r===void 0?this.where(e,t):this.where(e,t,r)}whereNull(e){return this.where(e,"is",null)}whereNotNull(e){return this.where(e,"is not",null)}whereIn(e,t){return this.where(e,"in",t)}whereNotIn(e,t){return this.where(e,"not in",t)}orderBy(e,t="asc"){return this.state.orderBy.push({column:e,direction:t}),this}orderByDesc(e){return this.orderBy(e,"desc")}latest(e="created_at"){return this.orderBy(e,"desc")}oldest(e="created_at"){return this.orderBy(e,"asc")}limit(e){return this.state.limitValue=e,this}offset(e){return this.state.offsetValue=e,this}skip(e){return this.offset(e)}take(e){return this.limit(e)}with(...e){return this.state.withRelations.push(...e),this}buildQueryParams(){let e=new URLSearchParams;for(let t of this.state.wheres)if(t.operator==="=")e.append(t.column,String(t.value));else if(t.operator==="in"&&Array.isArray(t.value))e.append(`${t.column}[]`,t.value.join(","));else if(t.operator==="is"&&t.value===null)e.append(`filter[${t.column}][is]`,"null");else if(t.operator==="is not"&&t.value===null)e.append(`filter[${t.column}][is_not]`,"null");else e.append(`filter[${t.column}][${t.operator}]`,String(t.value));if(this.state.orderBy.length>0){let t=this.state.orderBy.map((r)=>`${r.direction==="desc"?"-":""}${r.column}`).join(",");e.append("sort",t)}if(this.state.limitValue!==void 0)e.append("limit",String(this.state.limitValue));if(this.state.offsetValue!==void 0)e.append("offset",String(this.state.offsetValue));if(this.state.selectColumns.length>0&&!this.state.selectColumns.includes("*"))e.append("fields",this.state.selectColumns.join(","));if(this.state.withRelations.length>0)e.append("include",this.state.withRelations.join(","));return e}buildUrl(e){let t=`${n.baseUrl}/${this.state.table}`;if(e!==void 0)return`${t}/${e}`;let s=this.buildQueryParams().toString();return s?`${t}?${s}`:t}async get(){let e=this.buildUrl(),t=await fetch(e,{method:"GET",headers:await l()}),r=await u(t);return Array.isArray(r)?r:r.data}async first(){return this.limit(1),(await this.get())[0]??null}async firstOrFail(){let e=await this.first();if(!e)throw new d(`No ${this.state.table} found`,404);return e}async find(e){let t=this.buildUrl(e);try{let r=await fetch(t,{method:"GET",headers:await l()});if(r.status===404)return null;let s=await u(r);return"data"in s&&!Array.isArray(s.data)?s.data:s}catch{return null}}async findOrFail(e){let t=await this.find(e);if(!t)throw new d(`${this.state.table} with id ${e} not found`,404);return t}async count(){let e=this.buildQueryParams();e.append("count","true");let t=`${n.baseUrl}/${this.state.table}?${e.toString()}`,r=await fetch(t,{method:"GET",headers:await l()});return(await u(r)).count}async exists(){return await this.count()>0}async create(e){let t=`${n.baseUrl}/${this.state.table}`,r=n.transformRequest?n.transformRequest(e):e,s=await fetch(t,{method:"POST",headers:await l(),body:JSON.stringify(r)}),a=await u(s);return"data"in a&&!Array.isArray(a.data)?a.data:a}async insert(e){return this.create(e)}async update(e,t){let r=`${n.baseUrl}/${this.state.table}/${e}`,s=n.transformRequest?n.transformRequest(t):t,a=await fetch(r,{method:"PATCH",headers:await l(),body:JSON.stringify(s)}),i=await u(a);return"data"in i&&!Array.isArray(i.data)?i.data:i}async delete(e){let t=`${n.baseUrl}/${this.state.table}/${e}`;return(await fetch(t,{method:"DELETE",headers:await l()})).ok}async destroy(e){return this.delete(e)}async paginate(e=1,t=15){this.limit(t).offset((e-1)*t);let r=this.buildQueryParams();r.append("paginate","true");let s=`${n.baseUrl}/${this.state.table}?${r.toString()}`,a=await fetch(s,{method:"GET",headers:await l()});return u(a)}toState(){return{...this.state}}}function T(e){return new m(e)}function K(){return new Proxy({},{get:(e,t)=>()=>T(t)})}class w{_attributes;_definition;constructor(e,t={}){this._definition=e,this._attributes={...t}}get(e){return this._attributes[e]}set(e,t){this._attributes[e]=t}get attributes(){return{...this._attributes}}get id(){let e=this._definition.primaryKey||"id";return this._attributes[e]}toJSON(){let e=new Set;for(let[r,s]of Object.entries(this._definition.attributes))if(s.hidden)e.add(r);let t={};for(let[r,s]of Object.entries(this._attributes))if(!e.has(r))t[r]=s;return t}}class o{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];constructor(e){this._definition=e}getTablePath(){return typeof this._definition.traits?.useApi==="object"&&this._definition.traits.useApi?.uri||this._definition.table}where(e,t,r){if(r===void 0)this._wheres.push({column:e,operator:"=",value:t,boolean:"and"});else this._wheres.push({column:e,operator:t,value:r,boolean:"and"});return this}orWhere(e,t,r){throw TypeError("[browser] orWhere() is not supported by this client. The query-param format it builds has no spelling for a disjunction, so the term would be sent as a plain filter and the server would read it as AND \u2014 silently returning a superset of the rows you asked for. Express the alternatives as a single filter (whereIn), or issue one request per branch and merge the results.")}whereIn(e,t){return this._wheres.push({column:e,operator:"in",value:t,boolean:"and"}),this}whereNotIn(e,t){return this._wheres.push({column:e,operator:"not in",value:t,boolean:"and"}),this}whereNull(e){return this._wheres.push({column:e,operator:"is",value:null,boolean:"and"}),this}whereNotNull(e){return this._wheres.push({column:e,operator:"is not",value:null,boolean:"and"}),this}whereLike(e,t){return this._wheres.push({column:e,operator:"like",value:t,boolean:"and"}),this}orderBy(e,t="asc"){return this._orderBy.push({column:e,direction:t}),this}orderByDesc(e){return this.orderBy(e,"desc")}orderByAsc(e){return this.orderBy(e,"asc")}limit(e){return this._limit=e,this}take(e){return this.limit(e)}offset(e){return this._offset=e,this}skip(e){return this.offset(e)}select(...e){return this._select=e,this}with(...e){return this._withRelations.push(...e),this}latest(e="created_at"){return this.orderByDesc(e)}oldest(e="created_at"){return this.orderByAsc(e)}buildQueryParams(){let e=new URLSearchParams;for(let t of this._wheres)if(t.operator==="=")e.append(t.column,String(t.value));else if(t.operator==="in"&&Array.isArray(t.value))e.append(`${t.column}[]`,t.value.join(","));else if(t.operator==="is"&&t.value===null)e.append(`filter[${t.column}][is]`,"null");else if(t.operator==="is not"&&t.value===null)e.append(`filter[${t.column}][is_not]`,"null");else e.append(`filter[${t.column}][${t.operator}]`,String(t.value));if(this._orderBy.length>0){let t=this._orderBy.map((r)=>`${r.direction==="desc"?"-":""}${r.column}`).join(",");e.append("sort",t)}if(this._limit!==void 0)e.append("limit",String(this._limit));if(this._offset!==void 0)e.append("offset",String(this._offset));if(this._select.length>0&&!this._select.includes("*"))e.append("fields",this._select.join(","));if(this._withRelations.length>0)e.append("include",this._withRelations.join(","));return e}buildUrl(e){let t=`${n.baseUrl}/${this.getTablePath()}`;if(e!==void 0)return`${t}/${e}`;let s=this.buildQueryParams().toString();return s?`${t}?${s}`:t}async get(){let e=this.buildUrl(),t=await fetch(e,{method:"GET",headers:await l()}),r=await u(t);return(Array.isArray(r)?r:r.data).map((a)=>new w(this._definition,a))}async first(){return this._limit=1,(await this.get())[0]??null}async firstOrFail(){let e=await this.first();if(!e)throw new d(`No ${this._definition.name} found`,404);return e}async find(e){let t=this.buildUrl(e);try{let r=await fetch(t,{method:"GET",headers:await l()});if(r.status===404)return null;let s=await u(r),a="data"in s&&!Array.isArray(s.data)?s.data:s;return new w(this._definition,a)}catch{return null}}async findOrFail(e){let t=await this.find(e);if(!t)throw new d(`${this._definition.name} with id ${e} not found`,404);return t}async count(){let e=this.buildQueryParams();e.append("count","true");let t=`${n.baseUrl}/${this.getTablePath()}?${e.toString()}`,r=await fetch(t,{method:"GET",headers:await l()});return(await u(r)).count}async exists(){return await this.count()>0}async pluck(e){return this._select=[e],(await this.get()).map((r)=>r.get(e))}async paginate(e=1,t=15){this._limit=t,this._offset=(e-1)*t;let r=this.buildQueryParams();r.append("paginate","true");let s=`${n.baseUrl}/${this.getTablePath()}?${r.toString()}`,a=await fetch(s,{method:"GET",headers:await l()}),i=await u(a);return{...i,data:i.data.map((c)=>new w(this._definition,c))}}}function x(e){return new Proxy({query:()=>new o(e),where(r,s,a){return new o(e).where(r,s,a)},orWhere(r,s,a){return new o(e).orWhere(r,s,a)},whereIn(r,s){return new o(e).whereIn(r,s)},whereNotIn(r,s){return new o(e).whereNotIn(r,s)},whereNull(r){return new o(e).whereNull(r)},whereNotNull(r){return new o(e).whereNotNull(r)},whereLike(r,s){return new o(e).whereLike(r,s)},orderBy(r,s="asc"){return new o(e).orderBy(r,s)},orderByDesc(r){return new o(e).orderByDesc(r)},select(...r){return new o(e).select(...r)},limit:(r)=>new o(e).limit(r),take:(r)=>new o(e).take(r),skip:(r)=>new o(e).skip(r),latest:(r="created_at")=>new o(e).latest(r),oldest:(r="created_at")=>new o(e).oldest(r),async find(r){return new o(e).find(r)},async findOrFail(r){return new o(e).findOrFail(r)},async all(){return new o(e).get()},async first(){return new o(e).first()},async firstOrFail(){return new o(e).firstOrFail()},async count(){return new o(e).count()},async exists(){return new o(e).exists()},async paginate(r,s){return new o(e).paginate(r,s)},async pluck(r){return new o(e).pluck(r)},async create(r){let s=typeof e.traits?.useApi==="object"&&e.traits.useApi?.uri||e.table,a=`${n.baseUrl}/${s}`,i=n.transformRequest?n.transformRequest(r):r,c=await fetch(a,{method:"POST",headers:await l(),body:JSON.stringify(i)}),f=await u(c),h="data"in f&&!Array.isArray(f.data)?f.data:f;return new w(e,h)},async update(r,s){let a=typeof e.traits?.useApi==="object"&&e.traits.useApi?.uri||e.table,i=`${n.baseUrl}/${a}/${r}`,c=n.transformRequest?n.transformRequest(s):s,f=await fetch(i,{method:"PATCH",headers:await l(),body:JSON.stringify(c)}),h=await u(f),b="data"in h&&!Array.isArray(h.data)?h.data:h;return new w(e,b)},async delete(r){let s=typeof e.traits?.useApi==="object"&&e.traits.useApi?.uri||e.table,a=`${n.baseUrl}/${s}/${r}`;return(await fetch(a,{method:"DELETE",headers:await l()})).ok},async destroy(r){return this.delete(r)},getDefinition:()=>e,getTable:()=>e.table},{get(r,s){if(typeof s==="string"&&s.startsWith("where")&&s.length>5){let a=s.slice(5),i=a.charAt(0).toLowerCase()+a.slice(1);if(i in e.attributes||i==="id"||i===e.primaryKey)return(c)=>new o(e).where(i,c)}return Reflect.get(r,s)}})}var n,d,A,_;var g=p(()=>{n={baseUrl:""};d=class d extends Error{status;constructor(e,t){super(e);this.name="BrowserQueryError",this.status=t}};A={async login(e){let t=await fetch(`${n.baseUrl}/login`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...n.headers},body:JSON.stringify(e)});if(!t.ok){let a=await t.json().catch(()=>({message:"Login failed"}));throw new d(a.message||"Login failed",t.status)}let r=await t.json(),s=r.data||r;if(typeof localStorage<"u"&&s.token)localStorage.setItem("auth_token",s.token);return s},async register(e){let t=await fetch(`${n.baseUrl}/register`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...n.headers},body:JSON.stringify(e)});if(!t.ok){let a=await t.json().catch(()=>({message:"Registration failed"}));throw new d(a.message||"Registration failed",t.status)}let r=await t.json(),s=r.data||r;if(typeof localStorage<"u"&&s.token)localStorage.setItem("auth_token",s.token);return s},async logout(){if(await y())try{await fetch(`${n.baseUrl}/logout`,{method:"POST",headers:await l()})}catch{}if(typeof localStorage<"u")localStorage.removeItem("auth_token")},async user(){if(!await y())return null;try{let t=await fetch(`${n.baseUrl}/user`,{method:"GET",headers:await l()});if(t.status===401)return n.onUnauthorized?.(),null;if(!t.ok)return null;let r=await t.json();return r.user||r}catch{return null}},async check(){return await this.user()!==null},getToken:y},_=T});
|
|
3
|
-
export{D as
|
|
2
|
+
import{sc as p}from"./chunk-w49dhqgq.js";function D(e){n={...n,...e}}function k(){return n}function B(){return typeof window<"u"&&typeof document<"u"}async function y(){if(n.getToken){let e=n.getToken();return e instanceof Promise?e:e}if(typeof localStorage<"u")return localStorage.getItem("auth_token");return null}async function l(){let e={"Content-Type":"application/json",Accept:"application/json",...n.headers},t=await y();if(t)e.Authorization=`Bearer ${t}`;return e}async function u(e){if(e.status===401)throw n.onUnauthorized?.(),new d("Unauthorized",401);if(!e.ok){let r=await e.json().catch(()=>({message:"Request failed"}));throw new d(r.message||`HTTP ${e.status}`,e.status)}let t=await e.json();if(n.transformResponse)return n.transformResponse(t);return t}class m{state;constructor(e){this.state={table:e,wheres:[],orderBy:[],selectColumns:["*"],withRelations:[]}}select(...e){return this.state.selectColumns=e,this}where(e,t,r){if(r===void 0)this.state.wheres.push({column:e,operator:"=",value:t,boolean:"and"});else this.state.wheres.push({column:e,operator:t,value:r,boolean:"and"});return this}orWhere(e,t,r){throw TypeError("[browser] orWhere() is not supported by this client. The query-param format it builds has no spelling for a disjunction, so the term would be sent as a plain filter and the server would read it as AND \u2014 silently returning a superset of the rows you asked for. Express the alternatives as a single filter (whereIn), or issue one request per branch and merge the results.")}andWhere(e,t,r){return r===void 0?this.where(e,t):this.where(e,t,r)}whereNull(e){return this.where(e,"is",null)}whereNotNull(e){return this.where(e,"is not",null)}whereIn(e,t){return this.where(e,"in",t)}whereNotIn(e,t){return this.where(e,"not in",t)}orderBy(e,t="asc"){return this.state.orderBy.push({column:e,direction:t}),this}orderByDesc(e){return this.orderBy(e,"desc")}latest(e="created_at"){return this.orderBy(e,"desc")}oldest(e="created_at"){return this.orderBy(e,"asc")}limit(e){return this.state.limitValue=e,this}offset(e){return this.state.offsetValue=e,this}skip(e){return this.offset(e)}take(e){return this.limit(e)}with(...e){return this.state.withRelations.push(...e),this}buildQueryParams(){let e=new URLSearchParams;for(let t of this.state.wheres)if(t.operator==="=")e.append(t.column,String(t.value));else if(t.operator==="in"&&Array.isArray(t.value))e.append(`${t.column}[]`,t.value.join(","));else if(t.operator==="is"&&t.value===null)e.append(`filter[${t.column}][is]`,"null");else if(t.operator==="is not"&&t.value===null)e.append(`filter[${t.column}][is_not]`,"null");else e.append(`filter[${t.column}][${t.operator}]`,String(t.value));if(this.state.orderBy.length>0){let t=this.state.orderBy.map((r)=>`${r.direction==="desc"?"-":""}${r.column}`).join(",");e.append("sort",t)}if(this.state.limitValue!==void 0)e.append("limit",String(this.state.limitValue));if(this.state.offsetValue!==void 0)e.append("offset",String(this.state.offsetValue));if(this.state.selectColumns.length>0&&!this.state.selectColumns.includes("*"))e.append("fields",this.state.selectColumns.join(","));if(this.state.withRelations.length>0)e.append("include",this.state.withRelations.join(","));return e}buildUrl(e){let t=`${n.baseUrl}/${this.state.table}`;if(e!==void 0)return`${t}/${e}`;let s=this.buildQueryParams().toString();return s?`${t}?${s}`:t}async get(){let e=this.buildUrl(),t=await fetch(e,{method:"GET",headers:await l()}),r=await u(t);return Array.isArray(r)?r:r.data}async first(){return this.limit(1),(await this.get())[0]??null}async firstOrFail(){let e=await this.first();if(!e)throw new d(`No ${this.state.table} found`,404);return e}async find(e){let t=this.buildUrl(e);try{let r=await fetch(t,{method:"GET",headers:await l()});if(r.status===404)return null;let s=await u(r);return"data"in s&&!Array.isArray(s.data)?s.data:s}catch{return null}}async findOrFail(e){let t=await this.find(e);if(!t)throw new d(`${this.state.table} with id ${e} not found`,404);return t}async count(){let e=this.buildQueryParams();e.append("count","true");let t=`${n.baseUrl}/${this.state.table}?${e.toString()}`,r=await fetch(t,{method:"GET",headers:await l()});return(await u(r)).count}async exists(){return await this.count()>0}async create(e){let t=`${n.baseUrl}/${this.state.table}`,r=n.transformRequest?n.transformRequest(e):e,s=await fetch(t,{method:"POST",headers:await l(),body:JSON.stringify(r)}),a=await u(s);return"data"in a&&!Array.isArray(a.data)?a.data:a}async insert(e){return this.create(e)}async update(e,t){let r=`${n.baseUrl}/${this.state.table}/${e}`,s=n.transformRequest?n.transformRequest(t):t,a=await fetch(r,{method:"PATCH",headers:await l(),body:JSON.stringify(s)}),i=await u(a);return"data"in i&&!Array.isArray(i.data)?i.data:i}async delete(e){let t=`${n.baseUrl}/${this.state.table}/${e}`;return(await fetch(t,{method:"DELETE",headers:await l()})).ok}async destroy(e){return this.delete(e)}async paginate(e=1,t=15){this.limit(t).offset((e-1)*t);let r=this.buildQueryParams();r.append("paginate","true");let s=`${n.baseUrl}/${this.state.table}?${r.toString()}`,a=await fetch(s,{method:"GET",headers:await l()});return u(a)}toState(){return{...this.state}}}function T(e){return new m(e)}function K(){return new Proxy({},{get:(e,t)=>()=>T(t)})}class w{_attributes;_definition;constructor(e,t={}){this._definition=e,this._attributes={...t}}get(e){return this._attributes[e]}set(e,t){this._attributes[e]=t}get attributes(){return{...this._attributes}}get id(){let e=this._definition.primaryKey||"id";return this._attributes[e]}toJSON(){let e=new Set;for(let[r,s]of Object.entries(this._definition.attributes))if(s.hidden)e.add(r);let t={};for(let[r,s]of Object.entries(this._attributes))if(!e.has(r))t[r]=s;return t}}class o{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];constructor(e){this._definition=e}getTablePath(){return typeof this._definition.traits?.useApi==="object"&&this._definition.traits.useApi?.uri||this._definition.table}where(e,t,r){if(r===void 0)this._wheres.push({column:e,operator:"=",value:t,boolean:"and"});else this._wheres.push({column:e,operator:t,value:r,boolean:"and"});return this}orWhere(e,t,r){throw TypeError("[browser] orWhere() is not supported by this client. The query-param format it builds has no spelling for a disjunction, so the term would be sent as a plain filter and the server would read it as AND \u2014 silently returning a superset of the rows you asked for. Express the alternatives as a single filter (whereIn), or issue one request per branch and merge the results.")}whereIn(e,t){return this._wheres.push({column:e,operator:"in",value:t,boolean:"and"}),this}whereNotIn(e,t){return this._wheres.push({column:e,operator:"not in",value:t,boolean:"and"}),this}whereNull(e){return this._wheres.push({column:e,operator:"is",value:null,boolean:"and"}),this}whereNotNull(e){return this._wheres.push({column:e,operator:"is not",value:null,boolean:"and"}),this}whereLike(e,t){return this._wheres.push({column:e,operator:"like",value:t,boolean:"and"}),this}orderBy(e,t="asc"){return this._orderBy.push({column:e,direction:t}),this}orderByDesc(e){return this.orderBy(e,"desc")}orderByAsc(e){return this.orderBy(e,"asc")}limit(e){return this._limit=e,this}take(e){return this.limit(e)}offset(e){return this._offset=e,this}skip(e){return this.offset(e)}select(...e){return this._select=e,this}with(...e){return this._withRelations.push(...e),this}latest(e="created_at"){return this.orderByDesc(e)}oldest(e="created_at"){return this.orderByAsc(e)}buildQueryParams(){let e=new URLSearchParams;for(let t of this._wheres)if(t.operator==="=")e.append(t.column,String(t.value));else if(t.operator==="in"&&Array.isArray(t.value))e.append(`${t.column}[]`,t.value.join(","));else if(t.operator==="is"&&t.value===null)e.append(`filter[${t.column}][is]`,"null");else if(t.operator==="is not"&&t.value===null)e.append(`filter[${t.column}][is_not]`,"null");else e.append(`filter[${t.column}][${t.operator}]`,String(t.value));if(this._orderBy.length>0){let t=this._orderBy.map((r)=>`${r.direction==="desc"?"-":""}${r.column}`).join(",");e.append("sort",t)}if(this._limit!==void 0)e.append("limit",String(this._limit));if(this._offset!==void 0)e.append("offset",String(this._offset));if(this._select.length>0&&!this._select.includes("*"))e.append("fields",this._select.join(","));if(this._withRelations.length>0)e.append("include",this._withRelations.join(","));return e}buildUrl(e){let t=`${n.baseUrl}/${this.getTablePath()}`;if(e!==void 0)return`${t}/${e}`;let s=this.buildQueryParams().toString();return s?`${t}?${s}`:t}async get(){let e=this.buildUrl(),t=await fetch(e,{method:"GET",headers:await l()}),r=await u(t);return(Array.isArray(r)?r:r.data).map((a)=>new w(this._definition,a))}async first(){return this._limit=1,(await this.get())[0]??null}async firstOrFail(){let e=await this.first();if(!e)throw new d(`No ${this._definition.name} found`,404);return e}async find(e){let t=this.buildUrl(e);try{let r=await fetch(t,{method:"GET",headers:await l()});if(r.status===404)return null;let s=await u(r),a="data"in s&&!Array.isArray(s.data)?s.data:s;return new w(this._definition,a)}catch{return null}}async findOrFail(e){let t=await this.find(e);if(!t)throw new d(`${this._definition.name} with id ${e} not found`,404);return t}async count(){let e=this.buildQueryParams();e.append("count","true");let t=`${n.baseUrl}/${this.getTablePath()}?${e.toString()}`,r=await fetch(t,{method:"GET",headers:await l()});return(await u(r)).count}async exists(){return await this.count()>0}async pluck(e){return this._select=[e],(await this.get()).map((r)=>r.get(e))}async paginate(e=1,t=15){this._limit=t,this._offset=(e-1)*t;let r=this.buildQueryParams();r.append("paginate","true");let s=`${n.baseUrl}/${this.getTablePath()}?${r.toString()}`,a=await fetch(s,{method:"GET",headers:await l()}),i=await u(a);return{...i,data:i.data.map((c)=>new w(this._definition,c))}}}function x(e){return new Proxy({query:()=>new o(e),where(r,s,a){return new o(e).where(r,s,a)},orWhere(r,s,a){return new o(e).orWhere(r,s,a)},whereIn(r,s){return new o(e).whereIn(r,s)},whereNotIn(r,s){return new o(e).whereNotIn(r,s)},whereNull(r){return new o(e).whereNull(r)},whereNotNull(r){return new o(e).whereNotNull(r)},whereLike(r,s){return new o(e).whereLike(r,s)},orderBy(r,s="asc"){return new o(e).orderBy(r,s)},orderByDesc(r){return new o(e).orderByDesc(r)},select(...r){return new o(e).select(...r)},limit:(r)=>new o(e).limit(r),take:(r)=>new o(e).take(r),skip:(r)=>new o(e).skip(r),latest:(r="created_at")=>new o(e).latest(r),oldest:(r="created_at")=>new o(e).oldest(r),async find(r){return new o(e).find(r)},async findOrFail(r){return new o(e).findOrFail(r)},async all(){return new o(e).get()},async first(){return new o(e).first()},async firstOrFail(){return new o(e).firstOrFail()},async count(){return new o(e).count()},async exists(){return new o(e).exists()},async paginate(r,s){return new o(e).paginate(r,s)},async pluck(r){return new o(e).pluck(r)},async create(r){let s=typeof e.traits?.useApi==="object"&&e.traits.useApi?.uri||e.table,a=`${n.baseUrl}/${s}`,i=n.transformRequest?n.transformRequest(r):r,c=await fetch(a,{method:"POST",headers:await l(),body:JSON.stringify(i)}),f=await u(c),h="data"in f&&!Array.isArray(f.data)?f.data:f;return new w(e,h)},async update(r,s){let a=typeof e.traits?.useApi==="object"&&e.traits.useApi?.uri||e.table,i=`${n.baseUrl}/${a}/${r}`,c=n.transformRequest?n.transformRequest(s):s,f=await fetch(i,{method:"PATCH",headers:await l(),body:JSON.stringify(c)}),h=await u(f),b="data"in h&&!Array.isArray(h.data)?h.data:h;return new w(e,b)},async delete(r){let s=typeof e.traits?.useApi==="object"&&e.traits.useApi?.uri||e.table,a=`${n.baseUrl}/${s}/${r}`;return(await fetch(a,{method:"DELETE",headers:await l()})).ok},async destroy(r){return this.delete(r)},getDefinition:()=>e,getTable:()=>e.table},{get(r,s){if(typeof s==="string"&&s.startsWith("where")&&s.length>5){let a=s.slice(5),i=a.charAt(0).toLowerCase()+a.slice(1);if(i in e.attributes||i==="id"||i===e.primaryKey)return(c)=>new o(e).where(i,c)}return Reflect.get(r,s)}})}var n,d,A,_;var g=p(()=>{n={baseUrl:""};d=class d extends Error{status;constructor(e,t){super(e);this.name="BrowserQueryError",this.status=t}};A={async login(e){let t=await fetch(`${n.baseUrl}/login`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...n.headers},body:JSON.stringify(e)});if(!t.ok){let a=await t.json().catch(()=>({message:"Login failed"}));throw new d(a.message||"Login failed",t.status)}let r=await t.json(),s=r.data||r;if(typeof localStorage<"u"&&s.token)localStorage.setItem("auth_token",s.token);return s},async register(e){let t=await fetch(`${n.baseUrl}/register`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...n.headers},body:JSON.stringify(e)});if(!t.ok){let a=await t.json().catch(()=>({message:"Registration failed"}));throw new d(a.message||"Registration failed",t.status)}let r=await t.json(),s=r.data||r;if(typeof localStorage<"u"&&s.token)localStorage.setItem("auth_token",s.token);return s},async logout(){if(await y())try{await fetch(`${n.baseUrl}/logout`,{method:"POST",headers:await l()})}catch{}if(typeof localStorage<"u")localStorage.removeItem("auth_token")},async user(){if(!await y())return null;try{let t=await fetch(`${n.baseUrl}/user`,{method:"GET",headers:await l()});if(t.status===401)return n.onUnauthorized?.(),null;if(!t.ok)return null;let r=await t.json();return r.user||r}catch{return null}},async check(){return await this.user()!==null},getToken:y},_=T});
|
|
3
|
+
export{D as Nb,k as Ob,B as Pb,d as Qb,m as Rb,T as Sb,K as Tb,x as Ub,A as Vb,_ as Wb,g as Xb};
|